Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(engine): read every raw Wid through one helper, split transport deaths from not-found, record resolved LIDs, publish API rejections
Yudhi Armyndharis765f844de63e
diff --git a/src/engine/adapters/baileys-events.ts b/src/engine/adapters/baileys-events.tsindex aee4ad4bf..6c5e190ac 100644--- a/src/engine/adapters/baileys-events.ts+++ b/src/engine/adapters/baileys-events.ts@@ -125,7 +125,10 @@ export class BaileysEvents {/** Live incoming calls by call id, holding the raw `from` JID sock.rejectCall() needs — the* call event is long gone by the time a reject arrives, so it must be cached at event time.* Readonly reference, owned here; the adapter's lifecycle clears it on teardown. */- readonly liveCalls = new Map<string, { callFrom: string; expiresAt: number }>();+ readonly liveCalls = new Map<+ string,+ { callFrom: string; expiresAt: number; from: string; isVideo: boolean; isGroup: boolean }+ >();constructor(private readonly host: BaileysEventsHost) {}@@ -453,7 +456,12 @@ export class BaileysEvents {// same call-id, so a single call can reach this loop more than once. Cache first and emit// only for an id not already live, otherwise one call surfaces as several `call.received`// events.- if (!this.cacheLiveCall(call.id, call.from)) {+ const published = {+ from: this.host.toNeutralJid(call.callerPn ?? call.from),+ isVideo: call.isVideo === true,+ isGroup: call.isGroup === true,+ };+ if (!this.cacheLiveCall(call.id, call.from, published)) {continue;}const payload: IncomingCallEvent = {@@ -574,7 +582,11 @@ export class BaileysEvents {* once per call rather than once per upstream offer tag. A repeat offer still refreshes the* entry, so a long-ringing call stays rejectable for a full TTL from the most recent signal.*/- private cacheLiveCall(callId: string, callFrom: string): boolean {+ private cacheLiveCall(+ callId: string,+ callFrom: string,+ published: { from: string; isVideo: boolean; isGroup: boolean },+ ): boolean {const now = Date.now();for (const [id, entry] of this.liveCalls) {if (entry.expiresAt <= now) {@@ -582,7 +594,10 @@ export class BaileysEvents {}}const isNewCall = !this.liveCalls.has(callId);- this.liveCalls.set(callId, { callFrom, expiresAt: now + BaileysEvents.LIVE_CALL_TTL_MS });+ // The published identity is cached alongside the raw JID so a rejection issued through the API+ // can report the same shape the engine-observed outcomes do — the call event itself is long+ // gone by then.+ this.liveCalls.set(callId, { callFrom, expiresAt: now + BaileysEvents.LIVE_CALL_TTL_MS, ...published });return isNewCall;}@@ -602,6 +617,18 @@ export class BaileysEvents {throw new EngineNotReadyError('Cannot reject a call before the engine is initialized.');}await sock.rejectCall(callId, entry.callFrom);+ // A rejection made HERE produces no inbound `reject` signal to observe, so without this the+ // one outcome the caller definitely knows about — the one they asked for — was the only one+ // never published. Emitted only after the socket accepted it, and the entry is already evicted,+ // so a server echo arriving later cannot publish a second time.+ this.host.getOnCallOutcome()?.({+ callId,+ from: entry.from,+ outcome: 'rejected',+ isVideo: entry.isVideo,+ isGroup: entry.isGroup,+ timestamp: Math.floor(Date.now() / 1000),+ });}/**diff --git a/src/engine/adapters/baileys-messaging.ts b/src/engine/adapters/baileys-messaging.tsindex e5801e9f6..1d829a7bd 100644--- a/src/engine/adapters/baileys-messaging.ts+++ b/src/engine/adapters/baileys-messaging.ts@@ -44,6 +44,8 @@ export interface BaileysMessagingHost {putStoredMessage(msg: WAMessage): Promise<void> | undefined;/** Look up a previously-seen message from the store (the reply/forward/react/delete handle). */getStoredMessage(messageId: string): Promise<WAMessage | null> | undefined;+ /** Remember a lid<->phone pair the socket resolved, so later reads do not have to ask again. */+ recordLidMapping(lid: string, pn: string): void;/** The currently-registered onMessageCreate callback, if any (assigned at initialize()). */getOnMessageCreate(): EngineEventCallbacks['onMessageCreate'];/** Map a WAMessage to its neutral shape (the adapter's inbound mapper). */@@ -368,6 +370,11 @@ export class BaileysMessaging {try {const pn = this.host.toEngineJid(chatId);const lid = await this.sock().signalRepository?.lidMapping?.getLIDForPN(pn);+ // Record what the socket just told us. This resolution is the one place a cold contact's lid+ // becomes known before any message arrives, and without writing it back the session store+ // still believes the two ids are unrelated — which makes an ownership check comparing the+ // stored key's lid against a phone-dialect chatId reject a message that IS in that chat.+ if (lid) this.host.recordLidMapping(lid, pn);return lid ?? chatId;} catch {return chatId; // resolution is best-effort; an unmapped contact sends to the PN as beforediff --git a/src/engine/adapters/baileys.adapter.spec.ts b/src/engine/adapters/baileys.adapter.spec.tsindex 53afb211b..a20e2506c 100644--- a/src/engine/adapters/baileys.adapter.spec.ts+++ b/src/engine/adapters/baileys.adapter.spec.ts@@ -4804,6 +4804,29 @@ describe('BaileysAdapter call outcomes', () => {expect(onCallOutcome).not.toHaveBeenCalled();});+ // A rejection issued through the API produces no inbound signal to observe, so it was the one+ // outcome never published — the very one the caller knows happened.+ it('publishes call.rejected when the call is rejected through the API', async () => {+ const onCallOutcome = jest.fn();+ const adapter = await ringing({ onCall: jest.fn(), onCallOutcome });++ await adapter.rejectCall(CALL_ID);++ expect(fakeSock.rejectCall).toHaveBeenCalledWith(CALL_ID, CALLER);+ expect(onCallOutcome).toHaveBeenCalledWith(+ expect.objectContaining({ callId: CALL_ID, outcome: 'rejected', from: '[email protected]' }),+ );+ });++ it('publishes nothing when the socket refuses the rejection', async () => {+ const onCallOutcome = jest.fn();+ const adapter = await ringing({ onCall: jest.fn(), onCallOutcome });+ fakeSock.rejectCall.mockRejectedValueOnce(new Error('socket closed'));++ await expect(adapter.rejectCall(CALL_ID)).rejects.toThrow('socket closed');+ expect(onCallOutcome).not.toHaveBeenCalled();+ });+// WhatsApp replays signalling for calls that ended while the session was disconnected. Announcing// those would report last week's declined call as if it had just happened.it('drops an offline-replayed outcome', async () => {diff --git a/src/engine/adapters/baileys.adapter.ts b/src/engine/adapters/baileys.adapter.tsindex d5002aaf7..6573a966c 100644--- a/src/engine/adapters/baileys.adapter.ts+++ b/src/engine/adapters/baileys.adapter.ts@@ -157,6 +157,9 @@ export class BaileysAdapter implements IWhatsAppEngine {loadLib: () => this.loadLib(),putStoredMessage: msg => this.config.messageStore?.put(this.config.dbSessionId, msg),getStoredMessage: messageId => this.config.messageStore?.getMessage(this.config.dbSessionId, messageId),+ // Store the device-stripped lid: that is the key the lid->phone lookup reads.+ recordLidMapping: (lid, pn) =>+ this.sessionStore.addLidMappings([{ lid: `${lid.split('@')[0].split(':')[0]}@lid`, pn }]),getOnMessageCreate: () => this.callbacks.onMessageCreate,mapMessage: (msg, contentType, opts) => this.events.mapMessage(msg, contentType, opts),});diff --git a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts b/src/engine/adapters/whatsapp-web-js.adapter.spec.tsindex 5b49bfea8..f78094170 100644--- a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts+++ b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts@@ -29,6 +29,7 @@ import { EngineRefusedError } from '../../common/errors/engine-refused.error';import { EngineTransportError } from '../../common/errors/engine-transport.error';import { InvalidInviteCodeError } from '../../common/errors/invalid-invite-code.error';import { GroupNotFoundError } from '../../common/errors/group-not-found.error';+import { LabelNotFoundError } from '../../common/errors/label-not-found.error';import { SsrfBlockedError } from '../../common/security/ssrf-guard';import { fetch as undiciFetch } from 'undici';@@ -6059,6 +6060,37 @@ describe('WhatsAppWebJsAdapter voice status', () => {// and getChatsByLabelId yields undefined ENTRIES for label items whose chat no longer resolves.// These raw-id extraction sites must read the rename and skip the hole instead of crashing or// minting the literal id "undefined".+// A dead page and a genuinely-missing resource both reject; only the second is a 404. Folding a+// transport death into "not found" sends operators debugging the wrong layer — the sibling+// joinGroupViaInviteCode already makes this split.+describe('WhatsAppWebJsAdapter transport death is not a not-found', () => {+ const readyAdapter = (client: unknown): 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 = client;+ return adapter;+ };+ const dead = (): Error => new Error('Protocol error (Runtime.callFunctionOn): Target closed');++ it('getGroupJoinInfo answers 503 for a dead page, 404 for a refused invite', async () => {+ const transport = readyAdapter({ getInviteInfo: jest.fn().mockRejectedValue(dead()) });+ await expect(transport.getGroupJoinInfo('CODE')).rejects.toBeInstanceOf(EngineTransportError);++ const refused = readyAdapter({ getInviteInfo: jest.fn().mockRejectedValue(new Error('invite revoked')) });+ await expect(refused.getGroupJoinInfo('CODE')).rejects.toBeInstanceOf(GroupNotFoundError);+ });++ it('getChatsByLabel answers 503 for a dead page, 404 for an unknown label', async () => {+ const transport = readyAdapter({ getChatsByLabelId: jest.fn().mockRejectedValue(dead()) });+ await expect(transport.getChatsByLabel('7')).rejects.toBeInstanceOf(EngineTransportError);++ const unknown = readyAdapter({+ getChatsByLabelId: jest.fn().mockRejectedValue(new TypeError('Cannot read properties of undefined')),+ });+ await expect(unknown.getChatsByLabel('7')).rejects.toBeInstanceOf(LabelNotFoundError);+ });+});+describe('WhatsAppWebJsAdapter raw-id extraction hardening', () => {const readyAdapter = (client: unknown): WhatsAppWebJsAdapter => {const adapter = new WhatsAppWebJsAdapter({ sessionId: 's', sessionDataPath: './data/sessions', puppeteer: {} });diff --git a/src/engine/adapters/wwebjs-contacts.ts b/src/engine/adapters/wwebjs-contacts.tsindex 8e5f83cbc..d13d9b137 100644--- a/src/engine/adapters/wwebjs-contacts.ts+++ b/src/engine/adapters/wwebjs-contacts.ts@@ -2,6 +2,7 @@ import { type Client } from 'whatsapp-web.js';import { Contact } from '../interfaces/whatsapp-engine.interface';import { EngineTransportError } from '../../common/errors/engine-transport.error';import { userPart } from '../identity/wa-id';+import { readWid } from '../types/whatsapp-web-js.types';import { type WwebjsEngineHost } from './wwebjs-host';/**@@ -58,7 +59,9 @@ export class WwebjsContacts {this.host.ensureReady();try {const numberId = await this.client().getNumberId(number);- return numberId?._serialized ?? null;+ // Read both property names: a WA Web build that renamed `_serialized` would otherwise make+ // every number look unregistered — and checkNumberExists below reports exactly that.+ return readWid(numberId) ?? null;} catch (error) {this.host.reportIfPageTransportError(error, 'getNumberId');throw error;diff --git a/src/engine/adapters/wwebjs-groups.ts b/src/engine/adapters/wwebjs-groups.tsindex d84b66c20..935beac06 100644--- a/src/engine/adapters/wwebjs-groups.ts+++ b/src/engine/adapters/wwebjs-groups.ts@@ -8,7 +8,7 @@ import {GroupParticipant,ParticipantOperationResult,} from '../interfaces/whatsapp-engine.interface';-import { GroupChat, GroupMetadataRaw, GroupCreateResult, SerializedWid } from '../types/whatsapp-web-js.types';+import { GroupChat, GroupMetadataRaw, GroupCreateResult, SerializedWid, readWid } from '../types/whatsapp-web-js.types';import { EngineRefusedError } from '../../common/errors/engine-refused.error';import { EngineTransportError } from '../../common/errors/engine-transport.error';import { EngineNotSupportedError } from '../../common/errors/engine-not-supported.error';@@ -30,11 +30,7 @@ export function extractLinkedParentJID(groupMetadata?: GroupMetadataRaw): stringreturn null;}- if (typeof candidate === 'string') {- return candidate;- }-- return candidate._serialized ?? null;+ return readWid(candidate) ?? null;}/**@@ -89,7 +85,9 @@ export class WwebjsGroups {id: g.id._serialized,name: g.name,participantsCount: groupChat.participants?.length,- isAdmin: groupChat.participants?.some(p => p.isAdmin && p.id._serialized === client.info?.wid?._serialized),+ isAdmin: groupChat.participants?.some(+ p => p.isAdmin && readWid(p.id) !== undefined && readWid(p.id) === readWid(client.info?.wid),+ ),linkedParentJID: extractLinkedParentJID(groupChat.groupMetadata),};});@@ -107,19 +105,23 @@ export class WwebjsGroups {return null;}const groupChat = chat as unknown as GroupChat;- const participants: GroupParticipant[] = (groupChat.participants || []).map(p => ({- id: String(p.id._serialized),- number: String(p.id.user),- name: p.name ? String(p.name) : undefined,- isAdmin: Boolean(p.isAdmin),- isSuperAdmin: Boolean(p.isSuperAdmin),- }));+ // Raw page-context Wids: read both property names, and DROP a participant whose id is+ // unreadable rather than emitting the literal string "undefined" as an addressable id.+ const participants: GroupParticipant[] = (groupChat.participants || [])+ .filter(p => readWid(p.id) !== undefined)+ .map(p => ({+ id: readWid(p.id)!,+ number: String(p.id.user),+ name: p.name ? String(p.name) : undefined,+ isAdmin: Boolean(p.isAdmin),+ isSuperAdmin: Boolean(p.isSuperAdmin),+ }));return {id: chat.id._serialized,name: chat.name,description: groupChat.description ? String(groupChat.description) : undefined,- owner: groupChat.owner?._serialized ? String(groupChat.owner._serialized) : undefined,+ owner: readWid(groupChat.owner),createdAt: groupChat.createdAt,participants,isReadOnly: Boolean(groupChat.isReadOnly),@@ -157,7 +159,7 @@ export class WwebjsGroups {throw new Error(result);}const gid = (result as unknown as GroupCreateResult).gid as SerializedWid | undefined;- const groupId = gid?._serialized ?? gid?.$1;+ const groupId = readWid(gid);// A group id is not ack-safe the way a message id is: there is no empty-sentinel equivalent, and any// placeholder would be handed back as a real, addressable group. Fail instead of inventing one.if (!groupId) {@@ -356,6 +358,12 @@ export class WwebjsGroups {try {raw = await this.client().getInviteInfo(inviteCode);} catch (error) {+ // A dead page and a refused invite both land here; only the second is a 404. Folding a+ // transport death into "no such invite" sends operators debugging the wrong layer.+ if (this.host.isPageTransportError(error)) {+ this.host.reportIfPageTransportError(error, 'getGroupJoinInfo');+ throw new EngineTransportError(`Transport died while previewing invite ${inviteCode}`);+ }this.host.logger.debug('getInviteInfo rejected; treating the invite as not found', {error: error instanceof Error ? error.message : String(error),});@@ -364,11 +372,11 @@ export class WwebjsGroups {// Raw page-context Wids: read `$1` before concluding absence (#747, the WA Web minifier// rename) — without the fallback a renamed build turns every VALID invite into a false 404.- const id = typeof raw?.id === 'string' ? raw.id : (raw?.id?._serialized ?? raw?.id?.$1);+ const id = readWid(raw?.id);if (!id) {throw new GroupNotFoundError(inviteCode);}- const owner = typeof raw?.owner === 'string' ? raw.owner : (raw?.owner?._serialized ?? raw?.owner?.$1);+ const owner = readWid(raw?.owner);// `size` is the disclosed count; a participants array is used only as a fallback for builds that// send one instead. Neither is synthesised when both are missing.const count = typeof raw?.size === 'number' ? raw.size : raw?.participants?.length;diff --git a/src/engine/adapters/wwebjs-labels.ts b/src/engine/adapters/wwebjs-labels.tsindex 052de2c38..5a59bf260 100644--- a/src/engine/adapters/wwebjs-labels.ts+++ b/src/engine/adapters/wwebjs-labels.ts@@ -4,6 +4,7 @@ import { GroupChat, BusinessClient } from '../types/whatsapp-web-js.types';import { isChannelJid, chatKind } from '../identity/wa-id';import { ChatLabelsUnsupportedError } from '../../common/errors/chat-labels-unsupported.error';import { LabelNotFoundError } from '../../common/errors/label-not-found.error';+import { EngineTransportError } from '../../common/errors/engine-transport.error';import { type WwebjsEngineHost } from './wwebjs-host';/**@@ -48,6 +49,11 @@ export class WwebjsLabels {try {chats = await (this.client() as unknown as BusinessClient).getChatsByLabelId(labelId);} catch (error) {+ // Same split the group read makes: a dead page is a 503, not "no such label".+ if (this.host.isPageTransportError(error)) {+ this.host.reportIfPageTransportError(error, 'getChatsByLabel');+ throw new EngineTransportError(`Transport died while listing chats for label ${labelId}`);+ }this.host.logger.debug('getChatsByLabelId rejected; treating the label as not found', {labelId,error: error instanceof Error ? error.message : String(error),diff --git a/src/engine/types/whatsapp-web-js.types.ts b/src/engine/types/whatsapp-web-js.types.tsindex 4c2d3a6e4..21eaee3c5 100644--- a/src/engine/types/whatsapp-web-js.types.ts+++ b/src/engine/types/whatsapp-web-js.types.ts@@ -18,6 +18,17 @@ export interface SerializedWid {$1?: string;}+/**+ * Read a page-context Wid's serialized id under either property name, or undefined when neither is+ * present. Every raw-Wid read goes through this: the rename lands on all of them at once, and a+ * site that reads `_serialized` alone silently yields undefined — which `String()` then turns into+ * the literal id `"undefined"`, an id that looks real and addresses nothing.+ */+export function readWid(wid: SerializedWid | string | null | undefined): string | undefined {+ if (typeof wid === 'string') return wid || undefined;+ return wid?._serialized ?? wid?.$1 ?? undefined;+}+/*** Raw group metadata as returned by `chat.groupMetadata.serialize()`.* The field that links a community sub-group to its parent community has