Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
feat(contacts): resolve @lid privacy ids to phone numbers (#263) (#277)
Yudhi Armyndharis8e342fe8ee4d
diff --git a/.env.example b/.env.exampleindex 8e95be4e3..bd750e210 100644--- a/.env.example+++ b/.env.example@@ -80,6 +80,13 @@ PUPPETEER_ARGS=--no-sandbox,--disable-setuid-sandbox,--disable-dev-shm-usage,--d# SIMULATE_TYPING=false# SIMULATE_TYPING_MAX_MS=5000+# Inline @lid -> phone resolution (#263). When a sender is identified by a WhatsApp privacy id+# (@lid) instead of a phone number, attach a best-effort `senderPhone` (MSISDN digits, or null when+# the engine can't map it) to the message.received webhook + websocket payload. OFF by default —+# it adds a per-sender lookup (cached). The on-demand endpoint GET /sessions/:id/contacts/:id/phone+# works regardless of this flag.+# RESOLVE_LID_TO_PHONE=true+# Observability — Prometheus scrape endpoint at GET /api/metrics.# Disabled by default; set a token to enable. Scrapers must send `Authorization: Bearer <token>`.# METRICS_TOKEN=change-me-to-a-long-random-stringdiff --git a/CHANGELOG.md b/CHANGELOG.mdindex 162168a0d..0a9ba5287 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]+### Added++- **Resolve a `@lid` privacy id to a phone number** (#263), engine-neutral via a new+ `IWhatsAppEngine.resolveContactPhone`. On-demand endpoint `GET /sessions/:id/contacts/:contactId/phone`+ → `{ contactId, phone }` (MSISDN digits, or `null` when the engine can't map it — best-effort, since+ `@lid` exists to hide numbers). Optional **inline** resolution: set `RESOLVE_LID_TO_PHONE=true` to attach+ a best-effort `senderPhone` to the `message.received` webhook + websocket payload for `@lid` senders+ (off by default; per-sender lookups are cached). A non-whatsapp-web.js engine implements its own mapping.+### Changed- **Message delivery status is now engine-agnostic** (engine-pluggability decoupling, #265). The raw whatsapp-web.jsdiff --git a/docs/06-api-specification.md b/docs/06-api-specification.mdindex 2384df31a..7e185c8b6 100644--- a/docs/06-api-specification.md+++ b/docs/06-api-specification.md@@ -1099,6 +1099,30 @@ GET /api/sessions/:sessionId/contacts/:contactId/profile-picture}```+#### Resolve a contact id to a phone number++Resolve a contact identified by a WhatsApp privacy id (`@lid`) to its phone number. Pass the `@lid`+JID as `:contactId`.++```http+GET /api/sessions/:sessionId/contacts/:contactId/phone+```++**Response (200 OK):**+```json+{+ "contactId": "123456789@lid",+ "phone": "628123456789"+}+```++> **Best-effort.** `phone` is MSISDN digits when the account knows the mapping, or `null` otherwise —+> `@lid` exists specifically to hide phone numbers, so a stranger you've never interacted with (or a+> privacy-protected sender) won't resolve. This is a WhatsApp-engine limitation, not an OpenWA one.++To get this resolved automatically on each incoming message instead of calling the endpoint, see+`RESOLVE_LID_TO_PHONE` under [message.received](#messagereceived).+---### 6.4.5 Groups@@ -1455,6 +1479,12 @@ flowchart TB}```+> **Optional `senderPhone` (`@lid` resolution).** When a sender is identified by a WhatsApp privacy id+> (`from`/`author` ends in `@lid`) and `RESOLVE_LID_TO_PHONE=true` is set, the payload also carries a+> best-effort `senderPhone` (MSISDN digits, or `null` when the engine can't map it). Off by default+> because it adds a per-sender lookup (results are cached). See also the on-demand+> [resolve endpoint](#resolve-a-contact-id-to-a-phone-number). (#263)+### message.ack```jsondiff --git a/src/engine/adapters/message-mapper.spec.ts b/src/engine/adapters/message-mapper.spec.tsindex a597fed77..b3d4a88ac 100644--- a/src/engine/adapters/message-mapper.spec.ts+++ b/src/engine/adapters/message-mapper.spec.ts@@ -20,6 +20,22 @@ describe('buildIncomingMessageBase', () => {expect(r.isStatusBroadcast).toBe(false);expect(r.author).toBeUndefined();expect(r.contact).toBeUndefined();+ expect(r.isLidSender).toBeUndefined(); // a normal @c.us sender is not flagged+ });++ it('flags a 1:1 sender identified by an @lid privacy id (#263)', () => {+ const r = buildIncomingMessageBase({ ...base, from: '111@lid' });+ expect(r.isLidSender).toBe(true);+ });++ it('flags an @lid group participant via author, not the group JID (#263)', () => {+ const r = buildIncomingMessageBase({ ...base, from: '[email protected]', author: '222@lid' });+ expect(r.isLidSender).toBe(true);+ });++ it('does not flag a group whose participant is a normal number', () => {+ const r = buildIncomingMessageBase({ ...base, from: '[email protected]', author: '[email protected]' });+ expect(r.isLidSender).toBeUndefined();});it('flags a status/story broadcast via isStatusBroadcast (engine pseudo-JID stays in the adapter)', () => {diff --git a/src/engine/adapters/message-mapper.ts b/src/engine/adapters/message-mapper.tsindex 326144a20..a6ebc48a9 100644--- a/src/engine/adapters/message-mapper.ts+++ b/src/engine/adapters/message-mapper.ts@@ -82,6 +82,13 @@ export function buildIncomingMessageBase(msg: RawMessageFields): IncomingMessageincoming.author = msg.author;}+ // Flag senders identified by a WhatsApp privacy id (`@lid`) so engine-neutral code can opt to+ // resolve a phone number without matching the engine-specific JID scheme itself (#263).+ const senderJid = msg.author ?? msg.from;+ if (senderJid.endsWith('@lid')) {+ incoming.isLidSender = true;+ }+// Push name is available synchronously on the raw payload — no contact lookup needed.const pushName = msg._data?.notifyName;if (pushName) {diff --git a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts b/src/engine/adapters/whatsapp-web-js.adapter.spec.tsindex 0c403d31f..3519d676a 100644--- a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts+++ b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts@@ -7,6 +7,7 @@ import {wwebjsAckToDeliveryStatus,} from './whatsapp-web-js.adapter';import { EngineNotReadyError } from '../../common/errors/engine-not-ready.error';+import { EngineStatus } from '../interfaces/whatsapp-engine.interface';import { SsrfBlockedError } from '../../common/security/ssrf-guard';describe('wwebjsAckToDeliveryStatus (engine ack-int -> neutral DeliveryStatus boundary, #265)', () => {@@ -119,6 +120,7 @@ describe('WhatsAppWebJsAdapter readiness guard (#100)', () => {await expect(adapter.getGroups()).rejects.toBeInstanceOf(EngineNotReadyError);await expect(adapter.checkNumberExists('628123')).rejects.toBeInstanceOf(EngineNotReadyError);await expect(adapter.getNumberId('628123')).rejects.toBeInstanceOf(EngineNotReadyError);+ await expect(adapter.resolveContactPhone('123@lid')).rejects.toBeInstanceOf(EngineNotReadyError);});it('carries HTTP 409 so NestJS returns "session not connected" (not 500) without a custom filter', () => {@@ -126,6 +128,33 @@ describe('WhatsAppWebJsAdapter readiness guard (#100)', () => {});});+describe('WhatsAppWebJsAdapter.resolveContactPhone (@lid -> phone, #263)', () => {+ // Stub a "ready" adapter with a fake client so we exercise the mapping without a real browser.+ const readyAdapter = (getContactLidAndPhone: jest.Mock): WhatsAppWebJsAdapter => {+ const adapter = new WhatsAppWebJsAdapter({ sessionId: 's', sessionDataPath: './data/sessions', puppeteer: {} });+ (adapter as unknown as { status: EngineStatus }).status = EngineStatus.READY;+ (adapter as unknown as { client: unknown }).client = { getContactLidAndPhone };+ return adapter;+ };++ it('returns the phone JID stripped to MSISDN digits', async () => {+ const adapter = readyAdapter(jest.fn().mockResolvedValue([{ lid: '123@lid', pn: '[email protected]' }]));+ await expect(adapter.resolveContactPhone('123@lid')).resolves.toBe('628123456789');+ });++ it('returns null when the engine has no mapping (empty result or empty pn)', async () => {+ await expect(readyAdapter(jest.fn().mockResolvedValue([])).resolveContactPhone('123@lid')).resolves.toBeNull();+ await expect(+ readyAdapter(jest.fn().mockResolvedValue([{ lid: '123@lid', pn: '' }])).resolveContactPhone('123@lid'),+ ).resolves.toBeNull();+ });++ it('is best-effort: a thrown engine error resolves to null, not a rejection', async () => {+ const adapter = readyAdapter(jest.fn().mockRejectedValue(new Error('Evaluation failed')));+ await expect(adapter.resolveContactPhone('123@lid')).resolves.toBeNull();+ });+});+describe('resolveWebVersionPin (#251 — opt-in WA-Web version pin)', () => {const orig = { v: process.env.WWEBJS_WEB_VERSION, p: process.env.WWEBJS_WEB_VERSION_REMOTE_PATH };afterEach(() => {diff --git a/src/engine/adapters/whatsapp-web-js.adapter.ts b/src/engine/adapters/whatsapp-web-js.adapter.tsindex 7f2415912..281182a62 100644--- a/src/engine/adapters/whatsapp-web-js.adapter.ts+++ b/src/engine/adapters/whatsapp-web-js.adapter.ts@@ -556,6 +556,23 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEnginreturn (await this.getNumberId(number)) !== null;}+ async resolveContactPhone(contactId: string): Promise<string | null> {+ this.ensureReady();+ try {+ // Queried one id at a time: the batch form is prone to "Evaluation failed" and rate-limiting+ // (whatsapp-web.js #3857/#3969). `pn` is the phone JID (`<digits>@c.us`) when the account knows+ // the mapping; best-effort, so a missing mapping or any failure resolves to null.+ const [result] = await this.client!.getContactLidAndPhone([contactId]);+ const pn = result?.pn;+ return pn ? pn.replace(/@c\.us$/i, '').replace(/\D/g, '') || null : null;+ } catch (error) {+ this.logger.debug(`resolveContactPhone failed for ${contactId}`, {+ error: error instanceof Error ? error.message : String(error),+ });+ return null;+ }+ }+async getGroups(): Promise<Group[]> {this.ensureReady();const chats = await this.client!.getChats();diff --git a/src/engine/interfaces/whatsapp-engine.interface.ts b/src/engine/interfaces/whatsapp-engine.interface.tsindex e7a5230b2..607c4c356 100644--- a/src/engine/interfaces/whatsapp-engine.interface.ts+++ b/src/engine/interfaces/whatsapp-engine.interface.ts@@ -58,6 +58,18 @@ export interface IncomingMessage {isStatusBroadcast?: boolean;/** For group messages, the WID of the participant who actually sent it (`from` is the group JID there). */author?: string;+ /**+ * Set by the adapter when the sender is identified by a privacy id (e.g. a WhatsApp `@lid`) rather+ * than a phone number, so engine-neutral code can decide whether to attempt phone resolution without+ * matching an engine-specific JID scheme.+ */+ isLidSender?: boolean;+ /**+ * Best-effort phone number (MSISDN digits) of the sender, resolved from a privacy id when inline+ * resolution is enabled (`RESOLVE_LID_TO_PHONE`). `null` when the engine cannot map it. Only+ * populated for `isLidSender` messages.+ */+ senderPhone?: string | null;/** Sender display info, best-effort from the WhatsApp Web contact cache. */contact?: {name?: string;@@ -357,6 +369,12 @@ export interface IWhatsAppEngine {* number is not registered. The engine owns the JID scheme, so callers never build it themselves.*/getNumberId(number: string): Promise<string | null>;+ /**+ * Best-effort resolution of a contact id to a phone number (MSISDN digits), or `null` when the+ * engine cannot map it (e.g. a privacy `@lid` the account has never seen). The contact id is the+ * engine's native scheme; the adapter decides how to resolve it.+ */+ resolveContactPhone(contactId: string): Promise<string | null>;// Groups - BasicgetGroups(): Promise<Group[]>;diff --git a/src/modules/contact/contact.controller.ts b/src/modules/contact/contact.controller.tsindex 9f1d994a8..f56b7dd65 100644--- a/src/modules/contact/contact.controller.ts+++ b/src/modules/contact/contact.controller.ts@@ -67,6 +67,19 @@ export class ContactController {return { url };}+ @Get(':contactId/phone')+ @ApiOperation({ summary: 'Resolve a contact id (e.g. an @lid) to a phone number — best-effort' })+ @ApiParam({ name: 'sessionId', description: 'Session ID' })+ @ApiParam({ name: 'contactId', description: 'Contact ID / JID to resolve (e.g., an @lid)' })+ @ApiResponse({+ status: 200,+ description: 'Resolved phone number (MSISDN digits), or null when the engine cannot map it',+ })+ async resolvePhone(@Param('sessionId') sessionId: string, @Param('contactId') contactId: string) {+ const phone = await this.contactService.resolveContactPhone(sessionId, contactId);+ return { contactId, phone };+ }+@Post(':contactId/block')@HttpCode(HttpStatus.OK)@ApiOperation({ summary: 'Block a contact' })diff --git a/src/modules/contact/contact.service.spec.ts b/src/modules/contact/contact.service.spec.tsindex 7b5fffd57..292ded452 100644--- a/src/modules/contact/contact.service.spec.ts+++ b/src/modules/contact/contact.service.spec.ts@@ -29,4 +29,12 @@ describe('ContactService', () => {await expect(makeService({ getNumberId }).getNumberId('s1', '628123')).resolves.toBe('[email protected]');expect(getNumberId).toHaveBeenCalledWith('628123');});++ it('delegates resolveContactPhone to the engine', async () => {+ const resolveContactPhone = jest.fn().mockResolvedValue('628123456789');+ await expect(makeService({ resolveContactPhone }).resolveContactPhone('s1', '123@lid')).resolves.toBe(+ '628123456789',+ );+ expect(resolveContactPhone).toHaveBeenCalledWith('123@lid');+ });});diff --git a/src/modules/contact/contact.service.ts b/src/modules/contact/contact.service.tsindex 1c95022b4..710e22264 100644--- a/src/modules/contact/contact.service.ts+++ b/src/modules/contact/contact.service.ts@@ -38,6 +38,10 @@ export class ContactService {return this.getEngine(sessionId).getNumberId(number);}+ resolveContactPhone(sessionId: string, contactId: string) {+ return this.getEngine(sessionId).resolveContactPhone(contactId);+ }+getProfilePicture(sessionId: string, contactId: string) {return this.getEngine(sessionId).getProfilePicture(contactId);}diff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.tsindex c1a817cbe..a650b7304 100644--- a/src/modules/session/session.service.spec.ts+++ b/src/modules/session/session.service.spec.ts@@ -79,6 +79,7 @@ describe('SessionService', () => {sendSeen: jest.fn().mockResolvedValue(true),deleteChat: jest.fn().mockResolvedValue(true),sendChatState: jest.fn().mockResolvedValue(undefined),+ resolveContactPhone: jest.fn().mockResolvedValue('628111222333'),};engineFactory = {@@ -538,6 +539,79 @@ describe('SessionService', () => {expect(dispatchedEvents('message.sent')).toHaveLength(0);});+ // The default hookManager mock returns an empty `data: {}`; echo the message through so the+ // engine-set fields (isLidSender) survive the hook and reach the inline-resolution branch.+ const echoHook = () =>+ (hookManager.execute as jest.Mock).mockImplementation((_event: string, data: unknown) =>+ Promise.resolve({ continue: true, data }),+ );++ it('attaches senderPhone inline for an @lid sender when RESOLVE_LID_TO_PHONE is on (#263)', async () => {+ process.env.RESOLVE_LID_TO_PHONE = 'true';+ try {+ echoHook();+ mockEngine.resolveContactPhone.mockResolvedValue('628111222333');+ const callbacks = await startAndCaptureCallbacks();++ callbacks.onMessage!(makeMessage({ from: '111@lid', chatId: '111@lid', isLidSender: true }));+ await flush();++ const received = dispatchedEvents('message.received');+ expect(received).toHaveLength(1);+ expect((received[0][2] as IncomingMessage).senderPhone).toBe('628111222333');+ expect(mockEngine.resolveContactPhone).toHaveBeenCalledWith('111@lid');+ } finally {+ delete process.env.RESOLVE_LID_TO_PHONE;+ }+ });++ it('does not resolve senderPhone when RESOLVE_LID_TO_PHONE is unset (default off)', async () => {+ delete process.env.RESOLVE_LID_TO_PHONE;+ echoHook();+ const callbacks = await startAndCaptureCallbacks();++ callbacks.onMessage!(makeMessage({ from: '111@lid', chatId: '111@lid', isLidSender: true }));+ await flush();++ const received = dispatchedEvents('message.received');+ expect(received).toHaveLength(1);+ expect((received[0][2] as IncomingMessage).senderPhone).toBeUndefined();+ expect(mockEngine.resolveContactPhone).not.toHaveBeenCalled();+ });++ it('does not resolve for a normal (non-lid) sender even when the flag is on', async () => {+ process.env.RESOLVE_LID_TO_PHONE = 'true';+ try {+ echoHook();+ const callbacks = await startAndCaptureCallbacks();++ callbacks.onMessage!(makeMessage({ from: '[email protected]', chatId: '[email protected]' })); // no isLidSender+ await flush();++ expect(mockEngine.resolveContactPhone).not.toHaveBeenCalled();+ } finally {+ delete process.env.RESOLVE_LID_TO_PHONE;+ }+ });++ it('caches @lid resolution so the same sender is queried only once (#263)', async () => {+ process.env.RESOLVE_LID_TO_PHONE = 'true';+ try {+ echoHook();+ mockEngine.resolveContactPhone.mockResolvedValue('628111222333');+ const callbacks = await startAndCaptureCallbacks();++ callbacks.onMessage!(makeMessage({ id: 'm1', from: '111@lid', chatId: '111@lid', isLidSender: true }));+ await flush();+ callbacks.onMessage!(makeMessage({ id: 'm2', from: '111@lid', chatId: '111@lid', isLidSender: true }));+ await flush();++ expect(mockEngine.resolveContactPhone).toHaveBeenCalledTimes(1);+ } finally {+ delete process.env.RESOLVE_LID_TO_PHONE;+ }+ });+it('dispatches the message.revoked webhook and WS event on a revoke (#152)', async () => {const callbacks = await startAndCaptureCallbacks();expect(typeof callbacks.onMessageRevoked).toBe('function');diff --git a/src/modules/session/session.service.ts b/src/modules/session/session.service.tsindex 27a56b1b3..af7d4aa06 100644--- a/src/modules/session/session.service.ts+++ b/src/modules/session/session.service.ts@@ -44,6 +44,11 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat// In-memory map of active engine instancesprivate engines: Map<string, IWhatsAppEngine> = new Map();+ // Bounded cache for inline @lid -> phone resolution (#263), keyed `${sessionId}:${lid}`. Caches+ // misses (null) too, so a chatty unmapped sender isn't re-queried on every message (which also+ // reduces engine rate-limit pressure). Best-effort feature, so staleness is acceptable.+ private readonly lidPhoneCache = new Map<string, string | null>();+ private static readonly LID_PHONE_CACHE_MAX = 5000;// Transient, human-readable reason for the most recent terminal engine failure,// keyed by session id. Surfaced on read so the dashboard can explain a FAILED// status; cleared when the session re-initializes or becomes ready.@@ -386,7 +391,7 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicatsessionId: id,source: 'Engine',})- .then(({ continue: shouldContinue, data: finalMessage }) => {+ .then(async ({ continue: shouldContinue, data: finalMessage }) => {if (!shouldContinue) {// Plugin stopped processing (e.g., auto-reply handled it)return;@@ -394,6 +399,14 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat// Persist the incoming message so the dashboard chats view can render history.const incoming: IncomingMessage = finalMessage;++ // Inline @lid -> phone resolution (#263), opt-in via RESOLVE_LID_TO_PHONE. Best-effort:+ // attaches senderPhone (digits or null) before persist/dispatch so webhook/ws consumers+ // get it in a single pass. Only for privacy-id senders, so no lookup for normal numbers.+ if (process.env.RESOLVE_LID_TO_PHONE === 'true' && incoming.isLidSender && !incoming.fromMe) {+ incoming.senderPhone = await this.resolveSenderPhone(id, incoming.author ?? incoming.from);+ }+const metadata: Record<string, unknown> = {};if (incoming.media) {metadata.media = incoming.media;@@ -789,6 +802,34 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicatreturn this.engines.get(id);}+ /**+ * Best-effort resolution of a privacy-id sender (`@lid`) to a phone number for inline attachment on+ * incoming messages (#263). Cached per session (incl. misses). Never throws — returns null on any+ * failure or when the engine isn't available. Gated by the caller on `RESOLVE_LID_TO_PHONE`.+ */+ private async resolveSenderPhone(sessionId: string, contactId: string): Promise<string | null> {+ const key = `${sessionId}:${contactId}`;+ const cached = this.lidPhoneCache.get(key);+ if (cached !== undefined) {+ return cached;+ }+ let phone: string | null;+ try {+ phone = (await this.getEngine(sessionId)?.resolveContactPhone(contactId)) ?? null;+ } catch {+ phone = null;+ }+ // Bounded FIFO eviction: Map preserves insertion order, so the first key is the oldest.+ if (this.lidPhoneCache.size >= SessionService.LID_PHONE_CACHE_MAX) {+ for (const oldest of this.lidPhoneCache.keys()) {+ this.lidPhoneCache.delete(oldest);+ break;+ }+ }+ this.lidPhoneCache.set(key, phone);+ return phone;+ }+async getGroups(id: string): Promise<{ id: string; name: string; linkedParentJID?: string | null }[]> {await this.findOne(id); // Verify session existsconst engine = this.engines.get(id);