Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
feat(engine): engine-neutral WhatsApp identities for Baileys inbound (#342)
Tobias Strebitzer8edecdfcc51d
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 2b775446a..9f44ebacf 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,21 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]+### Fixed++- **Baileys engine: inbound message ids are now engine-neutral (`@c.us`).** The Baileys adapter emitted+ its native `<phone>@s.whatsapp.net` / `<lid>@lid` ids in message payloads (`from` / `to` / `chatId` /+ `author`, plus revoked and reaction events), while the whatsapp-web.js engine and the rest of the+ system use the `<phone>@c.us` convention - so the same contact was addressed under a different id+ depending on the engine, and `@lid` (privacy-id) contacts could not be resolved to a phone. Baileys+ now canonicalizes these to the neutral dialect (resolving a `@lid` to its phone when the mapping is+ known, keeping it as `@lid` otherwise), matching whatsapp-web.js. Group participant and owner ids are+ canonicalized through the same path, so admin/controller recognition (e.g. the translation plugin)+ keeps working. **Consumer-visible:** `message.received` / `revoked` / `reaction` webhook and WebSocket+ payloads from a Baileys session now carry `@c.us` ids where they previously carried+ `@s.whatsapp.net` (or a resolved `@lid`); a consumer that stored or compared the old ids will see the+ new value. Outbound sending and contact/chat list ids are unchanged for now.+## [0.4.4] - 2026-06-20A reliability and correctness patch. Engine: Baileys reconnect no longer leaks its socket, and a sessiondiff --git a/docs/03-system-architecture.md b/docs/03-system-architecture.mdindex 0bc233776..fd5df9e72 100644--- a/docs/03-system-architecture.md+++ b/docs/03-system-architecture.md@@ -157,6 +157,33 @@ flowchart LRIC -.-> Cache```+### WhatsApp Identity Contract (engine-neutral ids)++WhatsApp addresses the same entity through several id dialects, and each engine speaks a different one:+whatsapp-web.js uses `<phone>@c.us`, while Baileys speaks the raw protocol forms `<phone>@s.whatsapp.net`+and `<lid>@lid` (a privacy id whose number is **not** a phone number). To keep application code, the+REST/webhook payloads, and plugins free of that, the **engine boundary is an anti-corruption layer**:+every WhatsApp id an engine emits in a neutral field (`from` / `to` / `chatId` / `author`, contact and+chat `id`) is reduced to one small **neutral dialect**:++| Neutral form | Meaning |+| --- | --- |+| `<phone>@c.us` | a user, by phone (the raw `@s.whatsapp.net` form folds into this) |+| `<id>@g.us` | a group |+| `<lid>@lid` | a user known **only** by privacy id - phone genuinely unknown (a first-class state) |+| `status@broadcast`, `<id>@newsletter`, `<id>@broadcast` | special channels |++Never `@s.whatsapp.net`, never a `:device` suffix. **Resolution rule:** prefer `@c.us` (resolve a lid+to its phone when the mapping is known), and fall back to `@lid` only when it can't be resolved - an+unresolved lid is never faked into a phone number.++The shared implementation lives in `src/engine/identity/wa-id.ts` (`parseWaId` / `toNeutralJid`); the+contract is documented on the `IWhatsAppEngine` interface.++> **Rollout status:** the contract is applied per-engine. It currently covers the **Baileys inbound+> read path** (message / revoked / reaction payloads). Outbound id de-normalization (neutral -> engine+> dialect on send) and contact/chat list ids are tracked follow-ups.+### Adapter Lifecycle State MachineEach adapter follows a consistent lifecycle:diff --git a/docs/21-glossary.md b/docs/21-glossary.mdindex d0f1f2992..8da4a6871 100644--- a/docs/21-glossary.md+++ b/docs/21-glossary.md@@ -107,13 +107,16 @@ Data stored in RAM. Fast but non-persistent. Used for cache in minimal deploymen## J### JID (Jabber ID)-Identifier format in the XMPP protocol used by WhatsApp. Same as Chat ID.+WhatsApp's id format, inherited from XMPP; the user-facing "Chat ID" is a JID. The same entity can be addressed in more than one dialect: `<phone>@c.us` (whatsapp-web.js, and OpenWA's neutral form), `<phone>@s.whatsapp.net` (Baileys' raw form for the same user), `<id>@g.us` (a group), or `<lid>@lid` (a LID, a privacy id). OpenWA normalizes engine ids to a single neutral dialect at the engine boundary - see *System Architecture > WhatsApp Identity Contract*.### Job QueueQueueing system for asynchronous task processing. Used for webhook delivery and message scheduling.## L+### LID (Linked ID)+A WhatsApp **privacy identifier** (`<number>@lid`) that addresses a user without exposing their phone number - increasingly used in groups and communities. Its number is **not** a phone number; a separate `lid -> phone` mapping (supplied by WhatsApp via history sync / contacts) resolves it when known. OpenWA keeps an unresolved LID as-is rather than guessing a phone. See *System Architecture > WhatsApp Identity Contract*.+### Linked DeviceWhatsApp feature that allows up to 4 additional devices to be linked to one account without requiring an active phone connection.diff --git a/src/engine/adapters/baileys-group-mapper.spec.ts b/src/engine/adapters/baileys-group-mapper.spec.tsindex 12a1bc2bc..74a6c97eb 100644--- a/src/engine/adapters/baileys-group-mapper.spec.ts+++ b/src/engine/adapters/baileys-group-mapper.spec.ts@@ -59,4 +59,30 @@ describe('mapBaileysGroupInfo', () => {{ id: '[email protected]', number: '628222', name: undefined, isAdmin: true, isSuperAdmin: false },]);});++ it('canonicalizes participant ids and owner through the supplied normalizer (lid -> resolved phone)', () => {+ // A lid-addressed group: participants/owner arrive as @lid. The normalizer (the adapter's+ // session-store) resolves the known lid to its phone so both sides of the admin check share a dialect.+ const m = meta({+ owner: '111@lid',+ participants: [+ { id: '111@lid', admin: 'superadmin' },+ { id: '222@lid', admin: null },+ ],+ });+ const normalize = (jid: string) => (jid === '111@lid' ? '[email protected]' : jid);+ const info = mapBaileysGroupInfo(m, normalize);+ expect(info.owner).toBe('[email protected]');+ expect(info.participants).toEqual([+ { id: '[email protected]', number: '628111', name: undefined, isAdmin: true, isSuperAdmin: true },+ { id: '222@lid', number: '222', name: undefined, isAdmin: false, isSuperAdmin: false }, // unresolved: kept raw+ ]);+ });++ it('mapBaileysGroup flags self-admin across the dialect split via the normalizer', () => {+ const m = meta({ participants: [{ id: '111@lid', admin: 'admin' }] });+ // Self is reported in the raw protocol dialect; the normalizer folds both onto @c.us so they match.+ const normalize = (jid: string) => (jid === '111@lid' || jid === '[email protected]' ? '[email protected]' : jid);+ expect(mapBaileysGroup(m, '[email protected]', normalize).isAdmin).toBe(true);+ });});diff --git a/src/engine/adapters/baileys-group-mapper.ts b/src/engine/adapters/baileys-group-mapper.tsindex 138b32eb5..0052a6198 100644--- a/src/engine/adapters/baileys-group-mapper.ts+++ b/src/engine/adapters/baileys-group-mapper.ts@@ -1,41 +1,54 @@import type { GroupMetadata } from '@whiskeysockets/baileys';import { Group, GroupInfo, GroupParticipant } from '../interfaces/whatsapp-engine.interface';+import { userPart } from '../identity/wa-id';-/** `628xxx:[email protected]` / `628xxx@lid` -> `628xxx` (the user part, device + scheme stripped). */-function userPart(jid: string): string {- return jid.split('@')[0].split(':')[0];-}+/**+ * Canonicalizes participant/owner JIDs to the neutral dialect (see wa-id.ts). Defaults to identity so+ * the pure-shape behaviour is unchanged; the adapter supplies the session-store-backed normalizer so+ * group ids share the dialect of inbound message authors (admin/controller recognition relies on this).+ */+type NormalizeJid = (jid: string) => string;+const identity: NormalizeJid = jid => jid;-function isSelfAdmin(metadata: GroupMetadata, selfJid: string): boolean {- const self = userPart(selfJid);- return metadata.participants.some(p => userPart(p.id) === self && (p.admin === 'admin' || p.admin === 'superadmin'));+function isSelfAdmin(metadata: GroupMetadata, selfJid: string, normalizeJid: NormalizeJid): boolean {+ const self = userPart(normalizeJid(selfJid));+ return metadata.participants.some(+ p => userPart(normalizeJid(p.id)) === self && (p.admin === 'admin' || p.admin === 'superadmin'),+ );}/** Map a Baileys GroupMetadata to the neutral summary {@link Group}. `selfJid` flags whether WE are an admin. */-export function mapBaileysGroup(metadata: GroupMetadata, selfJid: string): Group {+export function mapBaileysGroup(+ metadata: GroupMetadata,+ selfJid: string,+ normalizeJid: NormalizeJid = identity,+): Group {return {id: metadata.id,name: metadata.subject,participantsCount: metadata.participants.length,- isAdmin: isSelfAdmin(metadata, selfJid),+ isAdmin: isSelfAdmin(metadata, selfJid, normalizeJid),linkedParentJID: metadata.linkedParent ?? null,};}/** Map a Baileys GroupMetadata to the neutral {@link GroupInfo} (full participant list). */-export function mapBaileysGroupInfo(metadata: GroupMetadata): GroupInfo {- const participants: GroupParticipant[] = metadata.participants.map(p => ({- id: p.id,- number: userPart(p.id),- name: p.name,- isAdmin: p.admin === 'admin' || p.admin === 'superadmin',- isSuperAdmin: p.admin === 'superadmin',- }));+export function mapBaileysGroupInfo(metadata: GroupMetadata, normalizeJid: NormalizeJid = identity): GroupInfo {+ const participants: GroupParticipant[] = metadata.participants.map(p => {+ const id = normalizeJid(p.id);+ return {+ id,+ number: userPart(id),+ name: p.name,+ isAdmin: p.admin === 'admin' || p.admin === 'superadmin',+ isSuperAdmin: p.admin === 'superadmin',+ };+ });return {id: metadata.id,name: metadata.subject,description: metadata.desc,- owner: metadata.owner,+ owner: metadata.owner ? normalizeJid(metadata.owner) : metadata.owner,createdAt: metadata.creation,participants,// WhatsApp "announce" = only admins can post; surface as both isAnnounce and (members') isReadOnly (best-effort).diff --git a/src/engine/adapters/baileys-message-mapper.spec.ts b/src/engine/adapters/baileys-message-mapper.spec.tsindex 9eabe1120..7c007f4ab 100644--- a/src/engine/adapters/baileys-message-mapper.spec.ts+++ b/src/engine/adapters/baileys-message-mapper.spec.ts@@ -71,6 +71,25 @@ describe('buildIncomingMessageFromBaileys', () => {expect(r.to).toBe('[email protected]'); // chat});+ it('applies the supplied normalizer to from/to/chatId on a 1:1 message', () => {+ const normalize = (jid: string) => jid.replace('@s.whatsapp.net', '@c.us');+ const r = buildIncomingMessageFromBaileys(base, normalize);+ expect(r.from).toBe('[email protected]');+ expect(r.to).toBe('[email protected]');+ expect(r.chatId).toBe('[email protected]');+ });++ it('normalizes the group author and self while leaving the group JID intact', () => {+ const normalize = (jid: string) => jid.replace('@s.whatsapp.net', '@c.us');+ const r = buildIncomingMessageFromBaileys(+ { ...base, remoteJid: '[email protected]', participant: '[email protected]' },+ normalize,+ );+ expect(r.from).toBe('[email protected]'); // group jid untouched by this normalizer+ expect(r.to).toBe('[email protected]'); // self normalized+ expect(r.author).toBe('[email protected]'); // participant normalized+ });+it('sets author to the participant for a group message and flags isGroup', () => {const r = buildIncomingMessageFromBaileys({...base,diff --git a/src/engine/adapters/baileys-message-mapper.ts b/src/engine/adapters/baileys-message-mapper.tsindex c954532b9..6468c8861 100644--- a/src/engine/adapters/baileys-message-mapper.ts+++ b/src/engine/adapters/baileys-message-mapper.ts@@ -91,10 +91,18 @@ export interface BaileysIncomingFields {* sender lives in `participant` (exposed as `author`), matching the wwjs convention where `from`* is the group JID.*/-export function buildIncomingMessageFromBaileys(fields: BaileysIncomingFields): IncomingMessage {- const chatId = fields.remoteJid;- const isGroup = chatId.endsWith('@g.us');- const self = fields.selfJid ?? '';+export function buildIncomingMessageFromBaileys(+ fields: BaileysIncomingFields,+ // Canonicalizes the emitted JIDs (from/to/chatId/author) to the neutral @c.us convention. Defaults+ // to identity so the pure-shape behaviour (and its tests) is unchanged; the adapter supplies the+ // session-store-backed normalizer that resolves @lid / @s.whatsapp.net.+ normalizeJid: (jid: string) => string = jid => jid,+): IncomingMessage {+ const rawChatId = fields.remoteJid;+ const isGroup = rawChatId.endsWith('@g.us');+ const isStatusBroadcast = rawChatId === 'status@broadcast';+ const chatId = normalizeJid(rawChatId);+ const self = normalizeJid(fields.selfJid ?? '');const incoming: IncomingMessage = {id: fields.id,@@ -106,15 +114,15 @@ export function buildIncomingMessageFromBaileys(fields: BaileysIncomingFields):timestamp: fields.timestamp,fromMe: fields.fromMe,isGroup,- isStatusBroadcast: chatId === 'status@broadcast',+ isStatusBroadcast,};if (isGroup && fields.participant) {- incoming.author = fields.participant;+ incoming.author = normalizeJid(fields.participant);}- // The real sender for an @lid check is the participant in a group, else the chat JID itself.- const senderJid = fields.participant ?? chatId;+ // The lid check uses the RAW sender (participant in a group, else the chat JID) before normalization.+ const senderJid = fields.participant ?? rawChatId;if (senderJid.endsWith('@lid')) {incoming.isLidSender = true;}diff --git a/src/engine/adapters/baileys-session-store.spec.ts b/src/engine/adapters/baileys-session-store.spec.tsindex 706d7c479..a0a58c047 100644--- a/src/engine/adapters/baileys-session-store.spec.ts+++ b/src/engine/adapters/baileys-session-store.spec.ts@@ -83,4 +83,39 @@ describe('BaileysSessionStore', () => {expect(store.resolvePhone('222@lid')).toBe('628222');expect(store.resolvePhone('333@lid')).toBeNull();});++ it('returns the user-part of an already-neutral @c.us id (a resolved-lid sender arrives as @c.us)', () => {+ // Once inbound ids are canonicalized, a resolved lid reaches resolvePhone as <phone>@c.us. Without+ // this branch senderPhone regresses to null for exactly the case the feature exists to surface.+ expect(store.resolvePhone('[email protected]')).toBe('628111');+ expect(store.resolvePhone('628111:[email protected]')).toBe('628111');+ });++ it('resolves a :device-suffixed lid via the device-stripped mapping', () => {+ store.addLidMappings([{ lid: '111@lid', pn: '[email protected]' }]);+ expect(store.resolvePhone('111:7@lid')).toBe('628999');+ });++ describe('toNeutralJid', () => {+ it('maps @s.whatsapp.net to @c.us and strips the device suffix', () => {+ expect(store.toNeutralJid('[email protected]')).toBe('[email protected]');+ expect(store.toNeutralJid('628111:[email protected]')).toBe('[email protected]');+ });++ it('keeps groups as @g.us and passes status@broadcast / empty through', () => {+ expect(store.toNeutralJid('[email protected]')).toBe('[email protected]');+ expect(store.toNeutralJid('status@broadcast')).toBe('status@broadcast');+ expect(store.toNeutralJid('')).toBe('');+ });++ it('resolves a @lid to <phone>@c.us when known, else keeps the raw lid', () => {+ expect(store.toNeutralJid('111@lid')).toBe('111@lid'); // no mapping yet+ store.addLidMappings([{ lid: '111@lid', pn: '[email protected]' }]);+ expect(store.toNeutralJid('111@lid')).toBe('[email protected]');+ });++ it('is idempotent on an already-neutral @c.us id', () => {+ expect(store.toNeutralJid('[email protected]')).toBe('[email protected]');+ });+ });});diff --git a/src/engine/adapters/baileys-session-store.ts b/src/engine/adapters/baileys-session-store.tsindex 9ba3703fe..9f80e6215 100644--- a/src/engine/adapters/baileys-session-store.ts+++ b/src/engine/adapters/baileys-session-store.ts@@ -1,5 +1,6 @@import type { Chat, Contact as BaileysContact, WAMessage, WAMessageKey } from '@whiskeysockets/baileys';import { ChatSummary, Contact } from '../interfaces/whatsapp-engine.interface';+import { parseWaId, toNeutralJid as canonicalizeWaId, userPart } from '../identity/wa-id';/*** Baileys `Contact` does not include a `phoneNumber` field, but WhatsApp Business events may supply@@ -90,26 +91,35 @@ export class BaileysSessionStore {}resolvePhone(id: string): string | null {- if (id.endsWith('@s.whatsapp.net')) {- return this.userPart(id);+ const parsed = parseWaId(id);+ // A user id (@c.us / @s.whatsapp.net) already carries the phone as its user-part. The @c.us case+ // matters once inbound ids are canonicalized: a resolved-lid sender arrives as <phone>@c.us.+ if (parsed.kind === 'user') {+ return parsed.userPart;}- if (id.endsWith('@lid')) {- const pn = this.lidToPn.get(id);+ if (parsed.kind === 'lid') {+ // Look up by the device-stripped lid; mappings/contacts are keyed without a :device suffix.+ const lidJid = `${parsed.userPart}@lid`;+ const pn = this.lidToPn.get(lidJid) ?? this.lidToPn.get(id);if (pn) {- return this.userPart(pn);+ return userPart(pn);}- const contactPhone = this.contacts.get(id)?.phoneNumber;- return contactPhone ? this.userPart(contactPhone) : null;+ const contactPhone = (this.contacts.get(lidJid) ?? this.contacts.get(id))?.phoneNumber;+ return contactPhone ? userPart(contactPhone) : null;}return null;}+ /**+ * Canonicalize a Baileys JID to the neutral dialect (see {@link canonicalizeWaId} / wa-id.ts),+ * resolving a lid to its phone via this session's lid->pn map when the mapping is known.+ */+ toNeutralJid(jid: string): string {+ return canonicalizeWaId(jid, id => this.resolvePhone(id));+ }+private toNeutralContact(c: BaileysContactWithPhone): Contact {- const number = c.phoneNumber- ? this.userPart(c.phoneNumber)- : c.id.endsWith('@s.whatsapp.net')- ? this.userPart(c.id)- : '';+ const number = c.phoneNumber ? userPart(c.phoneNumber) : c.id.endsWith('@s.whatsapp.net') ? userPart(c.id) : '';return {id: c.id,name: c.name ?? c.verifiedName,@@ -125,7 +135,7 @@ export class BaileysSessionStore {const last = this.lastMessages.get(c.id);return {id: c.id,- name: c.name ?? this.userPart(c.id),+ name: c.name ?? userPart(c.id),isGroup: c.id.endsWith('@g.us'),unreadCount: c.unreadCount ?? 0,timestamp: last?.timestamp ?? this.toUnixSeconds(c.conversationTimestamp),@@ -133,10 +143,6 @@ export class BaileysSessionStore {};}- private userPart(jid: string): string {- return jid.split('@')[0].split(':')[0];- }-private toUnixSeconds(ts: number | { toNumber(): number } | null | undefined): number {if (ts == null) {return 0;diff --git a/src/engine/adapters/baileys.adapter.spec.ts b/src/engine/adapters/baileys.adapter.spec.tsindex 207cec859..828ebec14 100644--- a/src/engine/adapters/baileys.adapter.spec.ts+++ b/src/engine/adapters/baileys.adapter.spec.ts@@ -565,6 +565,73 @@ describe('BaileysAdapter inbound fan-out', () => {expect(msg).toMatchObject({ id: 'IN1', body: 'hi there', type: 'text', fromMe: false });});+ it('canonicalizes an inbound message JID from @s.whatsapp.net to @c.us', async () => {+ const onMessage = jest.fn();+ const adapter = newAdapter();+ await adapter.initialize({ onMessage });+ fakeSock.fire('messages.upsert', {+ type: 'notify',+ messages: [+ {+ key: { remoteJid: '[email protected]', fromMe: false, id: 'IN_C' },+ message: { conversation: 'hi' },+ messageTimestamp: 1700000002,+ },+ ],+ });+ await new Promise(r => setImmediate(r));+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access+ const msg = onMessage.mock.calls[0][0] as { from: string; to: string; chatId: string };+ expect(msg.from).toBe('[email protected]');+ expect(msg.to).toBe('[email protected]'); // self (fakeSock.user is 628999)+ expect(msg.chatId).toBe('[email protected]');+ });++ it('resolves an @lid sender to <phone>@c.us using a history-sync lid->pn mapping', async () => {+ const onMessage = jest.fn();+ const adapter = newAdapter();+ await adapter.initialize({ onMessage });+ // History sync supplies the lid -> phone mapping the resolver needs.+ fakeSock.fire('messaging-history.set', { lidPnMappings: [{ lid: '111@lid', pn: '[email protected]' }] });+ fakeSock.fire('messages.upsert', {+ type: 'notify',+ messages: [+ {+ key: { remoteJid: '111@lid', fromMe: false, id: 'IN_LID' },+ message: { conversation: 'hi from lid' },+ messageTimestamp: 1700000005,+ },+ ],+ });+ await new Promise(r => setImmediate(r));+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access+ const msg = onMessage.mock.calls[0][0] as { from: string; isLidSender?: boolean };+ expect(msg.from).toBe('[email protected]'); // lid resolved to phone, neutral dialect+ expect(msg.isLidSender).toBe(true); // still flagged: the raw sender was a lid+ });++ it('keeps an unresolved @lid sender as @lid end-to-end (no mapping known)', async () => {+ const onMessage = jest.fn();+ const adapter = newAdapter();+ await adapter.initialize({ onMessage });+ fakeSock.fire('messages.upsert', {+ type: 'notify',+ messages: [+ {+ key: { remoteJid: '111@lid', fromMe: false, id: 'IN_LID_RAW' },+ message: { conversation: 'hi from unknown lid' },+ messageTimestamp: 1700000005,+ },+ ],+ });+ await new Promise(r => setImmediate(r));+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access+ const msg = onMessage.mock.calls[0][0] as { from: string; chatId: string; isLidSender?: boolean };+ expect(msg.from).toBe('111@lid'); // unresolved: kept as a privacy id, not faked into a phone+ expect(msg.chatId).toBe('111@lid');+ expect(msg.isLidSender).toBe(true);+ });+it('routes a fromMe message to onMessageCreate (outgoing), not onMessage', async () => {const onMessage = jest.fn();const onMessageCreate = jest.fn();@@ -799,7 +866,7 @@ describe('BaileysAdapter inbound fan-out', () => {body: string;};expect(revoked.id).toBe('ORIGINAL_ID');- expect(revoked.chatId).toBe('[email protected]');+ expect(revoked.chatId).toBe('[email protected]'); // canonicalized to the neutral dialectexpect(revoked.type).toBe('revoked');expect(revoked.body).toBe('');});@@ -845,9 +912,9 @@ describe('BaileysAdapter inbound fan-out', () => {senderId: string;};expect(event.messageId).toBe('TARGET_MSG_ID');- expect(event.chatId).toBe('[email protected]');+ expect(event.chatId).toBe('[email protected]'); // canonicalized to the neutral dialectexpect(event.reaction).toBe('👍');- expect(event.senderId).toBe('[email protected]');+ expect(event.senderId).toBe('[email protected]'); // canonicalized to the neutral dialect});it('media download failure: logs the error and emits the message without media (no throw)', async () => {@@ -1114,6 +1181,26 @@ describe('BaileysAdapter group management', () => {expect(await adapter.getGroupInfo('[email protected]')).toBeNull();});+ it('getGroupInfo canonicalizes participant + owner ids through the session store (lid -> phone)', async () => {+ const adapter = await ready();+ // History sync supplies the lid -> phone mapping; the adapter passes the store's canonicalizer in.+ fakeSock.fire('messaging-history.set', { lidPnMappings: [{ lid: '111@lid', pn: '[email protected]' }] });+ fakeSock.groupMetadata.mockResolvedValueOnce({+ id: '[email protected]',+ subject: 'G',+ owner: '111@lid',+ participants: [+ { id: '111@lid', admin: 'superadmin' },+ { id: '222@lid', admin: null },+ ],+ });+ const info = await adapter.getGroupInfo('[email protected]');+ // Owner + the known admin fold to <phone>@c.us, so they share the dialect of canonicalized authors.+ expect(info?.owner).toBe('[email protected]');+ expect(info?.participants[0]).toMatchObject({ id: '[email protected]', number: '628111', isSuperAdmin: true });+ expect(info?.participants[1]).toMatchObject({ id: '222@lid', number: '222' }); // unresolved kept raw+ });+it('createGroup returns the mapped new group', async () => {fakeSock.groupCreate.mockResolvedValue(META);const adapter = await ready();diff --git a/src/engine/adapters/baileys.adapter.ts b/src/engine/adapters/baileys.adapter.tsindex c9f391937..4040c3fbf 100644--- a/src/engine/adapters/baileys.adapter.ts+++ b/src/engine/adapters/baileys.adapter.ts@@ -466,14 +466,16 @@ export class BaileysAdapter implements IWhatsAppEngine {this.ensureReady();const all = await this.sock!.groupFetchAllParticipating();const self = this.normalizedSelfJid();- return Object.values(all).map(metadata => mapBaileysGroup(metadata, self));+ return Object.values(all).map(metadata =>+ mapBaileysGroup(metadata, self, jid => this.sessionStore.toNeutralJid(jid)),+ );}async getGroupInfo(groupId: string): Promise<GroupInfo | null> {this.ensureReady();try {const metadata = await this.sock!.groupMetadata(groupId);- return mapBaileysGroupInfo(metadata);+ return mapBaileysGroupInfo(metadata, jid => this.sessionStore.toNeutralJid(jid));} catch (err) {this.logger.debug('groupMetadata failed; treating as not-found', {groupId,@@ -486,7 +488,7 @@ export class BaileysAdapter implements IWhatsAppEngine {async createGroup(name: string, participants: string[]): Promise<Group> {this.ensureReady();const metadata = await this.sock!.groupCreate(name, participants);- return mapBaileysGroup(metadata, this.normalizedSelfJid());+ return mapBaileysGroup(metadata, this.normalizedSelfJid(), jid => this.sessionStore.toNeutralJid(jid));}async addParticipants(groupId: string, participants: string[]): Promise<void> {@@ -709,9 +711,9 @@ export class BaileysAdapter implements IWhatsAppEngine {const to = msg.key.fromMe === true ? remoteJid : this.normalizedSelfJid();const revoked: RevokedMessage = {id: pm.key?.id ?? '',- chatId: remoteJid,- from,- to,+ chatId: this.sessionStore.toNeutralJid(remoteJid),+ from: this.sessionStore.toNeutralJid(from),+ to: this.sessionStore.toNeutralJid(to),type: 'revoked',body: '',timestamp: this.toUnixSeconds(msg.messageTimestamp),@@ -728,9 +730,9 @@ export class BaileysAdapter implements IWhatsAppEngine {const rm = msg.message?.reactionMessage;const event: ReactionEvent = {messageId: rm?.key?.id ?? '',- chatId: remoteJid,+ chatId: this.sessionStore.toNeutralJid(remoteJid),reaction: rm?.text ?? '',- senderId: msg.key.participant ?? remoteJid,+ senderId: this.sessionStore.toNeutralJid(msg.key.participant ?? remoteJid),};this.callbacks.onMessageReaction?.(event);return;@@ -883,21 +885,24 @@ export class BaileysAdapter implements IWhatsAppEngine {quotedMessage = { id: contextInfo.stanzaId, body: qBody };}- return buildIncomingMessageFromBaileys({- id: msg.key.id ?? '',- remoteJid: msg.key.remoteJid!,- fromMe: msg.key.fromMe === true,- participant: msg.key.participant ?? undefined,- body,- contentType,- isPtt: content.audioMessage?.ptt === true,- timestamp: this.toUnixSeconds(msg.messageTimestamp),- pushName: msg.pushName ?? undefined,- selfJid: this.normalizedSelfJid(),- media,- location,- quotedMessage,- });+ return buildIncomingMessageFromBaileys(+ {+ id: msg.key.id ?? '',+ remoteJid: msg.key.remoteJid!,+ fromMe: msg.key.fromMe === true,+ participant: msg.key.participant ?? undefined,+ body,+ contentType,+ isPtt: content.audioMessage?.ptt === true,+ timestamp: this.toUnixSeconds(msg.messageTimestamp),+ pushName: msg.pushName ?? undefined,+ selfJid: this.normalizedSelfJid(),+ media,+ location,+ quotedMessage,+ },+ jid => this.sessionStore.toNeutralJid(jid),+ );}private normalizedSelfJid(): string {diff --git a/src/engine/identity/wa-id.spec.ts b/src/engine/identity/wa-id.spec.tsnew file mode 100644index 000000000..f4a7a6b95--- /dev/null+++ b/src/engine/identity/wa-id.spec.ts@@ -0,0 +1,60 @@+import { parseWaId, toNeutralJid, userPart } from './wa-id';++describe('wa-id', () => {+ describe('userPart', () => {+ it('strips the domain and the device suffix', () => {+ expect(userPart('[email protected]')).toBe('628111');+ expect(userPart('628111:[email protected]')).toBe('628111');+ expect(userPart('[email protected]')).toBe('120363-456');+ });+ });++ describe('parseWaId', () => {+ it('classifies each dialect, folding @s.whatsapp.net and @c.us into one user kind', () => {+ expect(parseWaId('[email protected]')).toMatchObject({ kind: 'user', userPart: '628111' });+ expect(parseWaId('[email protected]')).toMatchObject({ kind: 'user', userPart: '628111' });+ expect(parseWaId('628111:[email protected]')).toMatchObject({ kind: 'user', userPart: '628111', device: '3' });+ expect(parseWaId('[email protected]')).toMatchObject({ kind: 'group' });+ expect(parseWaId('111@lid')).toMatchObject({ kind: 'lid', userPart: '111' });+ expect(parseWaId('status@broadcast')).toMatchObject({ kind: 'status' });+ expect(parseWaId('abc@newsletter')).toMatchObject({ kind: 'newsletter' });+ expect(parseWaId('not-a-jid')).toMatchObject({ kind: 'unknown' });+ });++ it('classifies broadcast and lowercases the parsed parts', () => {+ expect(parseWaId('123@broadcast')).toMatchObject({ kind: 'broadcast', userPart: '123' });+ expect(parseWaId('ABC@NEWSLETTER')).toMatchObject({ kind: 'newsletter', userPart: 'abc' });+ expect(parseWaId('AbCd@LID')).toMatchObject({ kind: 'lid', userPart: 'abcd' });+ });+ });++ describe('toNeutralJid', () => {+ it('maps @s.whatsapp.net (and device suffixes) to @c.us, idempotent on @c.us', () => {+ expect(toNeutralJid('[email protected]')).toBe('[email protected]');+ expect(toNeutralJid('628111:[email protected]')).toBe('[email protected]');+ expect(toNeutralJid('[email protected]')).toBe('[email protected]');+ });++ it('keeps groups as @g.us and passes status / empty through', () => {+ expect(toNeutralJid('[email protected]')).toBe('[email protected]');+ expect(toNeutralJid('status@broadcast')).toBe('status@broadcast');+ expect(toNeutralJid('')).toBe('');+ });++ it('resolves a lid to <phone>@c.us when the resolver knows it, else keeps the raw lid', () => {+ const resolve = (jid: string) => (jid === '111@lid' ? '628999' : null);+ expect(toNeutralJid('111@lid', resolve)).toBe('[email protected]');+ expect(toNeutralJid('222@lid', resolve)).toBe('222@lid'); // unresolved: kept as a privacy id+ expect(toNeutralJid('111@lid')).toBe('111@lid'); // no resolver supplied+ });++ it('keeps newsletter and broadcast channels in their own dialect', () => {+ expect(toNeutralJid('120363-abc@newsletter')).toBe('120363-abc@newsletter');+ expect(toNeutralJid('120363-def@broadcast')).toBe('120363-def@broadcast');+ });++ it('passes an unrecognized format through unchanged', () => {+ expect(toNeutralJid('weird-thing')).toBe('weird-thing');+ });+ });+});diff --git a/src/engine/identity/wa-id.ts b/src/engine/identity/wa-id.tsnew file mode 100644index 000000000..3ed4b35ee--- /dev/null+++ b/src/engine/identity/wa-id.ts@@ -0,0 +1,101 @@+/**+ * Engine-neutral WhatsApp identity handling.+ *+ * WhatsApp addresses the same entity through several dialects:+ * - `<phone>@c.us` a user, addressed by phone (whatsapp-web.js dialect)+ * - `<phone>@s.whatsapp.net` the SAME user, in the raw protocol dialect (Baileys)+ * - `<lid>@lid` a user addressed by a privacy id (LID); the number is NOT a phone+ * - `<id>@g.us` a group+ * - `status@broadcast` the status/stories pseudo-JID+ * - `<id>@newsletter` a channel; `<id>@broadcast` a broadcast list+ * - any of the above may carry a `:<device>` multi-device suffix+ *+ * The engine boundary is an anti-corruption layer: adapters reduce all of that to the NEUTRAL dialect+ * the application layer sees, so app code never has to know which engine produced an id. The neutral+ * dialect is intentionally small:+ * - `<phone>@c.us` a user known by phone (the common case; @s.whatsapp.net folds into this)+ * - `<id>@g.us` a group+ * - `<lid>@lid` a user known ONLY by privacy id - phone genuinely unknown (a first-class state)+ * - `status@broadcast` / `<id>@newsletter` / `<id>@broadcast` special channels+ * - never `@s.whatsapp.net`, never a `:device` suffix+ *+ * Resolution rule: prefer `@c.us` (resolve a lid to its phone when the mapping is known); fall back to+ * `@lid` only when it can't be resolved. An unresolved lid is NOT pretended to be a phone.+ */++export type WaIdKind = 'user' | 'group' | 'lid' | 'status' | 'newsletter' | 'broadcast' | 'unknown';++/** Domains that denote a phone-addressed user (the two are the same entity, different dialects). */+const USER_DOMAINS = new Set(['c.us', 's.whatsapp.net']);++export interface ParsedWaId {+ kind: WaIdKind;+ /** The local part with the device suffix and domain stripped (phone digits, lid number, or group id). */+ userPart: string;+ /** The multi-device suffix (`:N`), when present. */+ device?: string;+ /** The original JID, verbatim. */+ raw: string;+}++/** The local part of a JID: domain and `:device` suffix stripped (`628:[email protected]` -> `628`). */+export function userPart(jid: string): string {+ return jid.split('@')[0].split(':')[0];+}++/** Classify any WhatsApp JID into its neutral kind + parts, without resolving anything. */+export function parseWaId(jid: string): ParsedWaId {+ const raw = jid;+ const lower = jid.trim().toLowerCase();+ if (lower === 'status@broadcast') {+ return { kind: 'status', userPart: 'status', raw };+ }+ const at = lower.lastIndexOf('@');+ if (at === -1) {+ return { kind: 'unknown', userPart: lower, raw };+ }+ const domain = lower.slice(at + 1);+ const [local, device] = lower.slice(0, at).split(':');+ const kind: WaIdKind = USER_DOMAINS.has(domain)+ ? 'user'+ : domain === 'g.us'+ ? 'group'+ : domain === 'lid'+ ? 'lid'+ : domain === 'newsletter'+ ? 'newsletter'+ : domain === 'broadcast'+ ? 'broadcast'+ : 'unknown';+ return { kind, userPart: local, device, raw };+}++/**+ * Reduce any WhatsApp JID to the neutral dialect (see the module contract above). `resolvePhone` maps a+ * lid to its phone user-part when the engine knows the mapping; an unresolvable lid is kept as+ * `<lid>@lid`. Idempotent on an already-neutral id. An unrecognized format is passed through unchanged.+ */+export function toNeutralJid(jid: string, resolvePhone?: (jid: string) => string | null): string {+ if (!jid) {+ return jid;+ }+ const parsed = parseWaId(jid);+ switch (parsed.kind) {+ case 'user':+ return `${parsed.userPart}@c.us`;+ case 'group':+ return `${parsed.userPart}@g.us`;+ case 'lid': {+ const phone = resolvePhone?.(jid);+ return phone ? `${phone}@c.us` : `${parsed.userPart}@lid`;+ }+ case 'status':+ return 'status@broadcast';+ case 'newsletter':+ return `${parsed.userPart}@newsletter`;+ case 'broadcast':+ return `${parsed.userPart}@broadcast`;+ default:+ return jid;+ }+}diff --git a/src/engine/interfaces/whatsapp-engine.interface.ts b/src/engine/interfaces/whatsapp-engine.interface.tsindex 9c539f577..395524e9a 100644--- a/src/engine/interfaces/whatsapp-engine.interface.ts+++ b/src/engine/interfaces/whatsapp-engine.interface.ts@@ -1,4 +1,18 @@// WhatsApp Engine Interface - Abstract layer for WA engines+//+// Identity contract (the engine boundary is an anti-corruption layer for WhatsApp's id dialects):+// every JID an engine EMITS in a neutral field (`from` / `to` / `chatId` / `author` / contact + chat+// `id`, etc.) is in the NEUTRAL dialect, so application code never has to know which engine produced+// it. The neutral dialect is small:+// - `<phone>@c.us` a user known by phone (the raw `@s.whatsapp.net` form folds into this)+// - `<id>@g.us` a group+// - `<lid>@lid` a user known ONLY by privacy id - phone genuinely unknown (a first-class state)+// - `status@broadcast` / `<id>@newsletter` / `<id>@broadcast` special channels+// - never `@s.whatsapp.net`, never a `:device` suffix+// Resolution rule: prefer `@c.us` (resolve a lid to its phone when the mapping is known), fall back to+// `@lid` only when it can't be resolved. See `engine/identity/wa-id.ts` for the shared implementation.+// (Ids the engine ACCEPTS - e.g. `sendTextMessage(chatId)` - may be neutral; the adapter de-normalizes+// to its own dialect. Full inbound + outbound conformance is being rolled out per-engine.)export enum EngineStatus {DISCONNECTED = 'disconnected',diff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.tsindex f11198490..20e6a089f 100644--- a/src/modules/session/session.service.spec.ts+++ b/src/modules/session/session.service.spec.ts@@ -10,6 +10,7 @@ import { EventsGateway } from '../events/events.gateway';import { WebhookService } from '../webhook/webhook.service';import { HookManager } from '../../core/hooks';import { IncomingMessage, EngineEventCallbacks, EngineStatus } from '../../engine/interfaces/whatsapp-engine.interface';+import { BaileysSessionStore } from '../../engine/adapters/baileys-session-store';function createMockSession(overrides: Partial<Session> = {}): Session {return {@@ -863,6 +864,33 @@ describe('SessionService', () => {}});+ it('resolves senderPhone from a canonicalized @c.us author for a resolved-lid sender (#263)', async () => {+ // After JID canonicalization a resolved lid reaches the service as <phone>@c.us while isLidSender+ // stays true. Wire resolveContactPhone to the real store so the @c.us branch is genuinely exercised:+ // if resolvePhone regressed to null for @c.us, senderPhone would be null here.+ process.env.RESOLVE_LID_TO_PHONE = 'true';+ try {+ echoHook();+ const store = new BaileysSessionStore();+ store.addLidMappings([{ lid: '111@lid', pn: '[email protected]' }]);+ mockEngine.resolveContactPhone.mockImplementation((id: string) => Promise.resolve(store.resolvePhone(id)));+ const callbacks = await startAndCaptureCallbacks();++ // Group lid author resolved to <phone>@c.us by the engine boundary.+ callbacks.onMessage!(+ makeMessage({ from: '[email protected]', chatId: '[email protected]', author: '[email protected]', 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('[email protected]');+ } 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();diff --git a/src/plugins/extensions/translation/core/translation.coordinator.spec.ts b/src/plugins/extensions/translation/core/translation.coordinator.spec.tsindex 15b5adb2f..3f0802a70 100644--- a/src/plugins/extensions/translation/core/translation.coordinator.spec.ts+++ b/src/plugins/extensions/translation/core/translation.coordinator.spec.ts@@ -102,6 +102,30 @@ describe('TranslationCoordinator', () => {expect(saved.at(-1)?.active).toBe(true);});+ it('recognizes a resolved-lid admin once group ids share the @c.us dialect', async () => {+ // In a lid-addressed group the author is canonicalized to <phone>@c.us; the admin list must be+ // canonicalized through the same path so widEquals (which does NOT bridge lid<->phone) can match.+ const state = freshState({ announced: true });+ const { store, gateway, translator, saved, mocks } = makeDeps(state);+ mocks.getGroupAdmins.mockResolvedValue(['[email protected]']); // resolved-lid admin, neutral dialect+ const c = new TranslationCoordinator(translator, store, gateway, OPTS);+ const res = await c.handleMessage('s', msg({ author: '[email protected]', body: '/tr on' }));+ expect(res).toEqual({ swallow: true });+ expect(saved.at(-1)?.active).toBe(true);+ });++ it('regression guard: a raw @lid admin list does NOT match a resolved @c.us author', async () => {+ // The pre-fix one-sided state: author canonicalized but the admin list left raw. widEquals compares+ // user-parts (111 vs 628111) and deliberately won't bridge the namespaces, so the admin is denied.+ const state = freshState({ announced: true });+ const { store, gateway, translator, saved, mocks } = makeDeps(state);+ mocks.getGroupAdmins.mockResolvedValue(['111@lid']); // un-canonicalized+ const c = new TranslationCoordinator(translator, store, gateway, OPTS);+ const res = await c.handleMessage('s', msg({ author: '[email protected]', body: '/tr on' }));+ expect(res).toEqual({ swallow: true });+ expect(saved.at(-1)?.active ?? false).toBe(false);+ });+it('rejects activation from a non-admin (silent by default)', async () => {const state = freshState({ announced: true });const { store, gateway, translator, saved, mocks } = makeDeps(state);