Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(logger): keep third-party ids out of info-level lines
Yudhi Armyndharis103c258480b6
diff --git a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts b/src/engine/adapters/whatsapp-web-js.adapter.spec.tsindex 308e0f0f9..67fcf40d1 100644--- a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts+++ b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts@@ -8464,3 +8464,83 @@ describe('WhatsAppWebJsAdapter raw-id extraction hardening', () => {expect(info.participantCount).toBe(3);});});++// A chat, contact or group id belongs to a third party, and a serialized message id embeds the chat JID:+// the per-action lines keep them out of info-level output and carry them as debug metadata only.+describe('WhatsAppWebJsAdapter per-action log lines', () => {+ const CHAT = '[email protected]';+ const MESSAGE_ID = `false_${CHAT}_3EB0ABC`;+ const GROUP = '[email protected]';++ 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;+ };++ it.each<[string, () => unknown, (a: WhatsAppWebJsAdapter) => Promise<unknown>, string, string, object]>([+ [+ 'deleteContact',+ () => ({ deleteAddressbookContact: jest.fn().mockResolvedValue(undefined) }),+ a => a.deleteContact(CHAT),+ '628123',+ 'Deleted addressbook contact',+ { contactId: CHAT },+ ],+ [+ 'blockContact',+ () => ({ getContactById: jest.fn().mockResolvedValue({ block: jest.fn().mockResolvedValue(true) }) }),+ a => a.blockContact(CHAT),+ '628123',+ 'Blocked contact',+ { contactId: CHAT },+ ],+ [+ 'reactToMessage',+ () => ({+ getChatById: jest.fn().mockResolvedValue({+ fetchMessages: jest+ .fn()+ .mockResolvedValue([{ id: { _serialized: MESSAGE_ID }, react: jest.fn().mockResolvedValue(undefined) }]),+ }),+ }),+ a => a.reactToMessage(CHAT, MESSAGE_ID, 'x'),+ '628123',+ 'Reacted to message',+ { messageId: MESSAGE_ID },+ ],+ [+ 'addLabelToChat',+ () => ({+ getChatById: jest.fn().mockResolvedValue({ getLabels: jest.fn().mockResolvedValue([]) }),+ getLabels: jest.fn().mockResolvedValue([{ id: 'L1', name: 'L1', hexColor: '#fff' }]),+ addOrRemoveLabels: jest.fn().mockResolvedValue(undefined),+ }),+ a => a.addLabelToChat(CHAT, 'L1'),+ '628123',+ 'Added label to chat',+ { labelId: 'L1', chatId: CHAT },+ ],+ [+ 'getGroupInviteCode',+ () => ({+ getChatById: jest.fn().mockResolvedValue({ isGroup: true, getInviteCode: jest.fn().mockResolvedValue('C0DE') }),+ }),+ a => a.getGroupInviteCode(GROUP),+ '120363777000',+ 'Got group invite code',+ { groupId: GROUP },+ ],+ ])('%s logs the id at debug only', async (_name, client, call, id, message, meta) => {+ const adapter = readyAdapter(client());+ const logger = (adapter as unknown as { logger: { log: () => void; debug: () => void } }).logger;+ const log = jest.spyOn(logger, 'log');+ const debug = jest.spyOn(logger, 'debug').mockImplementation(() => undefined);++ await call(adapter);++ expect(JSON.stringify(log.mock.calls)).not.toContain(id);+ expect(debug).toHaveBeenCalledWith(message, expect.objectContaining(meta));+ });+});diff --git a/src/engine/adapters/wwebjs-channels.ts b/src/engine/adapters/wwebjs-channels.tsindex 45a342561..1e8f31adb 100644--- a/src/engine/adapters/wwebjs-channels.ts+++ b/src/engine/adapters/wwebjs-channels.ts@@ -206,7 +206,7 @@ export class WwebjsChannels {if (!ok) {throw new EngineRefusedError(`Failed to unsubscribe from channel ${channelId}`);}- this.host.logger.log(`Unsubscribed from channel: ${channelId}`);+ this.host.logger.debug('Unsubscribed from channel', { channelId });}async getChannelMessages(channelId: string, limit: number = 50): Promise<ChannelMessage[]> {diff --git a/src/engine/adapters/wwebjs-contacts.ts b/src/engine/adapters/wwebjs-contacts.tsindex 605c8ba76..41b3ff4b3 100644--- a/src/engine/adapters/wwebjs-contacts.ts+++ b/src/engine/adapters/wwebjs-contacts.ts@@ -245,13 +245,13 @@ export class WwebjsContacts {await withPage(this.host, 'upsertContact', () =>this.client().saveOrEditAddressbookContact(userPart(contactId), firstName, lastName),);- this.host.logger.log(`Saved addressbook contact ${contactId}`);+ this.host.logger.debug('Saved addressbook contact', { contactId });}async deleteContact(contactId: string): Promise<void> {this.host.ensureReady();await withPage(this.host, 'deleteContact', () => this.client().deleteAddressbookContact(userPart(contactId)));- this.host.logger.log(`Deleted addressbook contact ${contactId}`);+ this.host.logger.debug('Deleted addressbook contact', { contactId });}async blockContact(contactId: string): Promise<void> {@@ -260,7 +260,7 @@ export class WwebjsContacts {const contact = await this.client().getContactById(contactId);await contact.block();});- this.host.logger.log(`Blocked contact ${contactId}`);+ this.host.logger.debug('Blocked contact', { contactId });}/**@@ -280,7 +280,7 @@ export class WwebjsContacts {const contact = await this.client().getContactById(contactId);await contact.unblock();});- this.host.logger.log(`Unblocked contact ${contactId}`);+ this.host.logger.debug('Unblocked contact', { contactId });}async getProfilePicture(contactId: string): Promise<string | null> {diff --git a/src/engine/adapters/wwebjs-groups.ts b/src/engine/adapters/wwebjs-groups.tsindex 2afde2d34..ee9b7989b 100644--- a/src/engine/adapters/wwebjs-groups.ts+++ b/src/engine/adapters/wwebjs-groups.ts@@ -344,7 +344,7 @@ export class WwebjsGroups {if (!inviteCode) {throw new EngineRefusedError(`Failed to get the invite code for group ${groupId} — admin rights required`);}- this.host.logger.log(`Got invite code for group ${groupId}`);+ this.host.logger.debug('Got group invite code', { groupId });return inviteCode;}@@ -354,7 +354,7 @@ export class WwebjsGroups {if (!newCode) {throw new EngineRefusedError(`Failed to revoke the invite code for group ${groupId} — admin rights required`);}- this.host.logger.log(`Revoked invite code for group ${groupId}, new code generated`);+ this.host.logger.debug('Revoked group invite code, new code generated', { groupId });return newCode;}@@ -450,7 +450,7 @@ export class WwebjsGroups {if (!groupId) {throw new InvalidInviteCodeError();}- this.host.logger.log(`Joined group ${groupId} via invite code`);+ this.host.logger.debug('Joined group via invite code', { groupId });return groupId;}diff --git a/src/engine/adapters/wwebjs-labels.ts b/src/engine/adapters/wwebjs-labels.tsindex 49c5ce790..c66322f01 100644--- a/src/engine/adapters/wwebjs-labels.ts+++ b/src/engine/adapters/wwebjs-labels.ts@@ -194,6 +194,6 @@ export class WwebjsLabels {if (add && !(await this.getLabels()).some(label => label.id === labelId)) {throw new LabelNotFoundError(labelId);}- this.host.logger.log(`${add ? 'Added' : 'Removed'} label ${labelId} ${add ? 'to' : 'from'} chat ${chatId}`);+ this.host.logger.debug(add ? 'Added label to chat' : 'Removed label from chat', { labelId, chatId });}}diff --git a/src/engine/adapters/wwebjs-messaging.ts b/src/engine/adapters/wwebjs-messaging.tsindex 8ca35faa2..b0c272569 100644--- a/src/engine/adapters/wwebjs-messaging.ts+++ b/src/engine/adapters/wwebjs-messaging.ts@@ -704,7 +704,7 @@ export class WwebjsMessaging {}await (message as MessageWithReactions).react(emoji);});- this.host.logger.log(`Reacted to message ${messageId} with ${emoji || '(removed)'}`);+ this.host.logger.debug('Reacted to message', { messageId, emoji: emoji || '(removed)' });}async getMessageReactions(chatId: string, messageId: string): Promise<MessageReaction[]> {@@ -882,7 +882,7 @@ export class WwebjsMessaging {}await message.delete(forEveryone);});- this.host.logger.log(`Deleted message ${messageId} from chat ${chatId} (forEveryone: ${forEveryone})`);+ this.host.logger.debug('Deleted message', { chatId, messageId, forEveryone });}async editMessage(chatId: string, messageId: string, body: string, mentions?: string[]): Promise<MessageResult> {@@ -914,7 +914,7 @@ export class WwebjsMessaging {`the edit of message ${messageId} was rejected — only the account's own text messages can be edited`,);}- this.host.logger.log(`Edited message ${messageId} in chat ${chatId}`);+ this.host.logger.debug('Edited message', { chatId, messageId });return toMessageResult(edited);}@@ -955,7 +955,7 @@ export class WwebjsMessaging {}throw error;}- this.host.logger.log(`Voted on poll ${pollMessageId} in chat ${chatId} (${options.length} option(s))`);+ this.host.logger.debug('Voted on poll', { chatId, pollMessageId, options: options.length });}async pinMessage(chatId: string, messageId: string, durationSeconds: number): Promise<void> {@@ -972,7 +972,7 @@ export class WwebjsMessaging {`the pin of message ${messageId} was rejected — in a group only admins may pin, and the duration must be 24h, 7d or 30d`,);}- this.host.logger.log(`Pinned message ${messageId} in chat ${chatId} for ${durationSeconds}s`);+ this.host.logger.debug('Pinned message', { chatId, messageId, durationSeconds });}async starMessage(chatId: string, messageId: string, star: boolean): Promise<void> {@@ -984,7 +984,7 @@ export class WwebjsMessaging {const message = await this.findInFetchWindow(chatId, messageId);await (star ? message.star() : message.unstar());});- this.host.logger.log(`${star ? 'Starred' : 'Unstarred'} message ${messageId} in chat ${chatId}`);+ this.host.logger.debug(star ? 'Starred message' : 'Unstarred message', { chatId, messageId });}async unpinMessage(chatId: string, messageId: string): Promise<void> {@@ -998,6 +998,6 @@ export class WwebjsMessaging {if (!unpinned) {throw new EngineRefusedError(`the unpin of message ${messageId} was rejected — in a group only admins may unpin`);}- this.host.logger.log(`Unpinned message ${messageId} in chat ${chatId}`);+ this.host.logger.debug('Unpinned message', { chatId, messageId });}}diff --git a/src/modules/automation/automation-rules.service.spec.ts b/src/modules/automation/automation-rules.service.spec.tsindex 8acf9a389..3ddf29d53 100644--- a/src/modules/automation/automation-rules.service.spec.ts+++ b/src/modules/automation/automation-rules.service.spec.ts@@ -142,6 +142,19 @@ describe('AutomationRulesService', () => {expect(sends).toEqual([{ sessionId: 'sessA', chatId: '[email protected]', text: 'welcome!' }]);});+ // The chat id is a third party's number: the reply line carries it as debug metadata only.+ it('logs the reply at debug and keeps the chat id out of info-level lines', async () => {+ await service.create('sessA', { name: 'any', replyText: 'hi' });+ const logger = (service as unknown as { logger: { log: () => void; debug: () => void } }).logger;+ const log = jest.spyOn(logger, 'log');+ const debug = jest.spyOn(logger, 'debug').mockImplementation(() => undefined);++ await service.evaluateInbound('sessA', inbound());++ expect(debug).toHaveBeenCalledWith('Automation rule replied', expect.objectContaining({ chatId: '[email protected]' }));+ expect(JSON.stringify(log.mock.calls)).not.toContain('628111');+ });+it('a rule without conditions matches every inbound message', async () => {await service.create('sessA', { name: 'all', replyText: 'ack' });diff --git a/src/modules/automation/automation-rules.service.ts b/src/modules/automation/automation-rules.service.tsindex 32ecd8797..5e6ef546f 100644--- a/src/modules/automation/automation-rules.service.ts+++ b/src/modules/automation/automation-rules.service.ts@@ -183,7 +183,7 @@ export class AutomationRulesService {const messagePort = this.resolveMessagePort();if (!messagePort) return;await messagePort.sendText(sessionId, { chatId, text: rule.replyText });- this.logger.log('Automation rule replied', { sessionId, ruleId: rule.id, chatId });+ this.logger.debug('Automation rule replied', { sessionId, ruleId: rule.id, chatId });} catch (error) {// The send path already persisted/audited its own failure; here it only must not propagate.this.logger.warn('Automation rule reply failed', {diff --git a/src/modules/session/session-engine-event-wiring.ts b/src/modules/session/session-engine-event-wiring.tsindex 875db8794..cad341612 100644--- a/src/modules/session/session-engine-event-wiring.ts+++ b/src/modules/session/session-engine-event-wiring.ts@@ -282,7 +282,7 @@ export class SessionEngineEventWiring {},onCall: (event: IncomingCallEvent): void => {if (!host.isLiveEngine(id, engine)) return;- this.logger.log(`Incoming call from ${event.from}`, {+ this.logger.log('Incoming call', {sessionId: id,callId: event.callId,isVideo: event.isVideo,diff --git a/src/modules/session/session-engine-lifecycle.service.ts b/src/modules/session/session-engine-lifecycle.service.tsindex 27441bfd2..846a4c69c 100644--- a/src/modules/session/session-engine-lifecycle.service.ts+++ b/src/modules/session/session-engine-lifecycle.service.ts@@ -803,7 +803,7 @@ export class SessionEngineLifecycle {/** Engine callback body, lifted out of initializeEngine so the wiring table stays readable. */private handleEngineReady(id: string, engine: IWhatsAppEngine, phone: string, pushName: string): void {if (!this.isLiveEngine(id, engine)) return;- this.logger.log(`Session ready: ${phone}`, {+ this.logger.log('Session ready', {sessionId: id,phone,pushName,diff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.tsindex 134ea654a..44b6376d2 100644--- a/src/modules/session/session.service.spec.ts+++ b/src/modules/session/session.service.spec.ts@@ -2131,6 +2131,23 @@ describe('SessionService', () => {}});+ it('keeps the account number out of the ready line message, in its metadata only', () => {+ const i = internals();+ (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });+ const engine = { getStatus: jest.fn().mockReturnValue(EngineStatus.READY) };+ i.engines.set('sess-uuid-1', engine);+ const logger = (lifecycle as unknown as { logger: { log: () => void } }).logger;+ const log = jest.spyOn(logger, 'log');++ try {+ i.handleEngineReady('sess-uuid-1', engine, '628123', 'Tester');++ expect(log).toHaveBeenCalledWith('Session ready', expect.objectContaining({ phone: '628123' }));+ } finally {+ log.mockRestore();+ }+ });+it('resets the attempt budget only after a stable READY, never because time passed between attempts', () => {jest.useFakeTimers();try {@@ -7516,6 +7533,22 @@ describe('SessionService', () => {}});+ // The caller is a third party; callId already ties the log line to the call.received event.+ it("logs the incoming call without the caller's number", async () => {+ const onCall = await startAndCaptureCallCallback();+ const logger = (lifecycle as unknown as { logger: { log: () => void } }).logger;+ const log = jest.spyOn(logger, 'log');++ try {+ onCall(callEvent({ from: '[email protected]' }));++ expect(log).toHaveBeenCalledWith('Incoming call', expect.objectContaining({ callId: 'CALL1' }));+ expect(JSON.stringify(log.mock.calls)).not.toContain('628111');+ } finally {+ log.mockRestore();+ }+ });+it('drops the event when it arrives from a stale (superseded) engine', async () => {const onCall = await startAndCaptureCallCallback({ autoRejectCalls: true });// A newer engine now owns the id (restart/reconnect window): the captured callback is stale.