Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
feat(webhook): opt-in WEBHOOK_CONTACT_DETAILS enriches the message contact (#462)
Softronic43dd68850902
diff --git a/.env.example b/.env.exampleindex bbe7bf824..02a45b33b 100644--- a/.env.example+++ b/.env.example@@ -172,6 +172,12 @@ WEBHOOK_RETRY_DELAY=5000 # Delay between retries in ms# refused (at registration AND delivery) and redirects are not followed.# (Server-side media-by-URL fetches are ALWAYS SSRF-guarded, regardless of this flag.)WEBHOOK_SSRF_PROTECT=true++# Expose the FULL sender `contact` field set (id, number, shortName, business flags, isBlocked,+# labels, …) on the message.received webhook + websocket payload. OFF by default — the payload keeps+# the minimal { name, pushName }. Opt in only if your consumer needs the richer data; all fields are+# read from the already-cached contact (no extra WhatsApp API calls).+# WEBHOOK_CONTACT_DETAILS=true# Comma-separated hosts/IPs allowed to bypass SSRF protection for BOTH webhooks# and media — escape-hatch for trusted internal targets (e.g. a localhost media# store or a sidecar webhook receiver).diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 03699a904..f0a6c9cb0 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -23,6 +23,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0- Infrastructure: configuration values saved from the dashboard are now rejected if they contain a line break, which could otherwise write an extra `KEY=value` line into `data/.env.generated` and inject an arbitrary environment variable on the next boot.- Infrastructure: data export/import (the documented backup and SQLite↔PostgreSQL migration flow) is now complete. It previously exported and restored only sessions, webhooks, messages, and message batches — so a restore silently lost all message templates and stored Baileys messages (cascade-deleted with the old sessions and never re-imported) and dropped every webhook's filters, causing a filtered webhook to come back firing on all events. Templates, stored Baileys messages, and webhook filters now round-trip intact.- Engine selection: pinning the engine from the environment works again after the v0.7.1 compose change. The bundled compose files forward `ENGINE_TYPE` into the container again (`- ENGINE_TYPE=${ENGINE_TYPE:-}`) and the app treats a blank value as unset, so an `.env`/host `ENGINE_TYPE=baileys` is honoured while the dashboard's Infrastructure > Engine selection still wins when no engine is pinned. `.env.example` no longer ships `ENGINE_TYPE` pre-pinned. **Upgrade note:** if you relied on `ENGINE_TYPE=baileys` in your `.env`, confirm the active engine after upgrading. (#453 — thanks @ulises2k)+- Webhooks: an opt-in `WEBHOOK_CONTACT_DETAILS` flag enriches the `message.received` payload's sender `contact` object with the free, already-cached WhatsApp contact fields — `id`, `number`, `shortName`, `type`, `isMyContact`, `isWAContact`, `isBusiness`, `isEnterprise`, `verifiedName`, `verifiedLevel`, `isBlocked`, and `labels` (IDs) — alongside the existing `name`/`pushName`. **Off by default** (the payload keeps the minimal `name`/`pushName`). All fields are read synchronously from the contact already fetched per message, so no extra WhatsApp API calls are made (profile picture and about/status are intentionally excluded to avoid rate-limit/ban risk).## [0.7.1] - 2026-06-24diff --git a/docs/06-api-specification.md b/docs/06-api-specification.mdindex 50581f843..ad95cafd9 100644--- a/docs/06-api-specification.md+++ b/docs/06-api-specification.md@@ -1494,13 +1494,34 @@ flowchart TB"isGroup": false,"hasMedia": false,"contact": {+ "id": "[email protected]",+ "number": "628123456789","name": "John Doe",- "pushName": "John"+ "pushName": "John",+ "shortName": "John",+ "type": "in",+ "isMyContact": true,+ "isWAContact": true,+ "isBusiness": false,+ "isEnterprise": false,+ "verifiedName": null,+ "verifiedLevel": 0,+ "isBlocked": false,+ "labels": []}}}```+> **`contact` fields (opt-in via `WEBHOOK_CONTACT_DETAILS`).** By default the `contact` object carries+> only `name` and `pushName`. Set `WEBHOOK_CONTACT_DETAILS=true` to expose the full set shown above+> (`id`, `number`, `shortName`, `type`, the business flags, `isBlocked`, `labels`, …). All fields are+> optional and best-effort, read synchronously from the WhatsApp Web contact cache already fetched for+> the message — **no extra WhatsApp API calls** are made. Profile picture and about/status are+> intentionally not included (they require per-message network calls and risk rate-limiting/ban). For+> an `@lid` privacy-id sender, `number` may be empty; use the top-level `senderPhone` field for the+> resolved phone number.+> **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 defaultdiff --git a/src/engine/adapters/message-mapper.spec.ts b/src/engine/adapters/message-mapper.spec.tsindex 25159670d..88050e8c2 100644--- a/src/engine/adapters/message-mapper.spec.ts+++ b/src/engine/adapters/message-mapper.spec.ts@@ -1,4 +1,10 @@-import { buildIncomingMessageBase, mapWwebjsMessageType, RawMessageFields } from './message-mapper';+import {+ buildIncomingMessageBase,+ mapContactFields,+ mapWwebjsMessageType,+ RawContactFields,+ RawMessageFields,+} from './message-mapper';describe('buildIncomingMessageBase', () => {const base: RawMessageFields = {@@ -102,3 +108,86 @@ describe('mapWwebjsMessageType (engine type-token -> neutral MessageType boundarexpect(mapWwebjsMessageType(raw)).toBe(expected);});});++describe('mapContactFields', () => {+ const businessRaw: RawContactFields = {+ id: { _serialized: '254571402260600@lid' },+ number: '254571402260600',+ name: 'Leo hermano',+ pushname: 'leo',+ shortName: 'Leo',+ type: 'in',+ isMyContact: true,+ isWAContact: true,+ isBusiness: true,+ isEnterprise: false,+ verifiedName: 'Leo Store',+ verifiedLevel: 2,+ isBlocked: false,+ labels: ['L1', 'L2'],+ };++ describe('full mode (WEBHOOK_CONTACT_DETAILS opt-in)', () => {+ it('copies the sync fields for a business contact', () => {+ expect(mapContactFields(businessRaw, true)).toEqual({+ id: '254571402260600@lid',+ number: '254571402260600',+ name: 'Leo hermano',+ pushName: 'leo',+ shortName: 'Leo',+ type: 'in',+ isMyContact: true,+ isWAContact: true,+ isBusiness: true,+ isEnterprise: false,+ verifiedName: 'Leo Store',+ verifiedLevel: 2,+ isBlocked: false,+ labels: ['L1', 'L2'],+ });+ });++ it('omits business fields and empty values for a plain personal contact', () => {+ const r = mapContactFields(+ {+ id: { _serialized: '[email protected]' },+ number: '584145200715',+ pushname: 'Ana',+ isMyContact: false,+ isWAContact: true,+ isBusiness: false,+ },+ true,+ );+ expect(r).toEqual({+ id: '[email protected]',+ number: '584145200715',+ pushName: 'Ana',+ isMyContact: false,+ isWAContact: true,+ isBusiness: false,+ });+ expect('verifiedName' in r).toBe(false);+ expect('name' in r).toBe(false);+ expect('labels' in r).toBe(false);+ });++ it('returns an empty object when nothing is set', () => {+ expect(mapContactFields({}, true)).toEqual({});+ });++ it('drops an empty labels array', () => {+ expect(mapContactFields({ labels: [] }, true)).toEqual({});+ });+ });++ describe('minimal mode (default)', () => {+ it('returns only name and pushName even when the contact has full data', () => {+ expect(mapContactFields(businessRaw)).toEqual({ name: 'Leo hermano', pushName: 'leo' });+ });++ it('omits name/pushName when absent and never includes extended fields', () => {+ expect(mapContactFields({ number: '584145200715', isBusiness: true })).toEqual({});+ });+ });+});diff --git a/src/engine/adapters/message-mapper.ts b/src/engine/adapters/message-mapper.tsindex 4776e74ad..1e6586f6d 100644--- a/src/engine/adapters/message-mapper.ts+++ b/src/engine/adapters/message-mapper.ts@@ -1,4 +1,4 @@-import { IncomingMessage, MessageType } from '../interfaces/whatsapp-engine.interface';+import { IncomingMessage, MessageContact, MessageType } from '../interfaces/whatsapp-engine.interface';/*** Map a whatsapp-web.js `MessageTypes` token to the engine-neutral {@link MessageType}, so no@@ -104,3 +104,53 @@ export function buildIncomingMessageBase(msg: RawMessageFields): IncomingMessagereturn incoming;}++/**+ * The subset of whatsapp-web.js `Contact` properties we read synchronously (already on the resolved+ * contact, no network call). Declared explicitly so {@link mapContactFields} is unit-testable without a+ * full wwebjs `Contact`, and so the async getters stay out by construction.+ */+export interface RawContactFields {+ id?: { _serialized?: string };+ number?: string;+ name?: string;+ pushname?: string;+ shortName?: string;+ type?: string;+ isMyContact?: boolean;+ isWAContact?: boolean;+ isBusiness?: boolean;+ isEnterprise?: boolean;+ verifiedName?: string;+ verifiedLevel?: number;+ isBlocked?: boolean;+ labels?: string[];+}++/**+ * Map the synchronous fields of a wwebjs `Contact` to a {@link MessageContact}, copying only the values+ * that are set. No network calls, which on a per-message path would risk rate-limiting.+ *+ * With `full` false (the default) it returns just `name`/`pushName`, the long-standing payload. With+ * `full` true (operator opt-in via `WEBHOOK_CONTACT_DETAILS`) it returns the complete field set.+ */+export function mapContactFields(contact: RawContactFields, full = false): MessageContact {+ const out: MessageContact = {};+ if (contact.name) out.name = contact.name;+ if (contact.pushname) out.pushName = contact.pushname;+ if (!full) return out;+ const id = contact.id?._serialized;+ if (id) out.id = id;+ if (contact.number) out.number = contact.number;+ if (contact.shortName) out.shortName = contact.shortName;+ if (contact.type) out.type = contact.type;+ if (contact.isMyContact !== undefined) out.isMyContact = contact.isMyContact;+ if (contact.isWAContact !== undefined) out.isWAContact = contact.isWAContact;+ if (contact.isBusiness !== undefined) out.isBusiness = contact.isBusiness;+ if (contact.isEnterprise !== undefined) out.isEnterprise = contact.isEnterprise;+ if (contact.verifiedName) out.verifiedName = contact.verifiedName;+ if (contact.verifiedLevel !== undefined) out.verifiedLevel = contact.verifiedLevel;+ if (contact.isBlocked !== undefined) out.isBlocked = contact.isBlocked;+ if (contact.labels && contact.labels.length > 0) out.labels = contact.labels;+ return out;+}diff --git a/src/engine/adapters/whatsapp-web-js.adapter.ts b/src/engine/adapters/whatsapp-web-js.adapter.tsindex 9c8b866b4..93d5ca9f8 100644--- a/src/engine/adapters/whatsapp-web-js.adapter.ts+++ b/src/engine/adapters/whatsapp-web-js.adapter.ts@@ -46,7 +46,7 @@ import {WwjsChannelData,GroupCreateResult,} from '../types/whatsapp-web-js.types';-import { buildIncomingMessageBase } from './message-mapper';+import { buildIncomingMessageBase, mapContactFields } from './message-mapper';import {capInboundMedia,inboundMediaConcurrency,@@ -360,15 +360,20 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngintry {const incomingMessage: IncomingMessage = buildIncomingMessageBase(msg);- // Enrich the sender contact with the saved name (best-effort, from the WhatsApp Web cache).- // `author`/`from` resolve to the actual sender for group and 1:1 messages respectively.+ // Attach the sender's contact info. getContact() gives the real sender (author in groups, from+ // in 1:1); we read only its synchronous fields and never the async getters (profile pic, about),+ // which would hit WhatsApp on every message.try {const contact = await msg.getContact();- if (contact?.name || contact?.pushname) {- incomingMessage.contact = {- name: contact.name || incomingMessage.contact?.name,- pushName: contact.pushname || incomingMessage.contact?.pushName,- };+ if (contact) {+ // Off by default the payload keeps { name, pushName }; WEBHOOK_CONTACT_DETAILS opts into the+ // full set. Merge over the base so the notifyName pushName isn't lost, and skip an empty+ // result so we don't emit an empty contact object.+ const full = process.env.WEBHOOK_CONTACT_DETAILS === 'true';+ const merged = { ...incomingMessage.contact, ...mapContactFields(contact, full) };+ if (Object.keys(merged).length > 0) {+ incomingMessage.contact = merged;+ }}} catch (error) {this.logger.error('Error getting message contact', String(error));diff --git a/src/engine/interfaces/whatsapp-engine.interface.ts b/src/engine/interfaces/whatsapp-engine.interface.tsindex 77983d6e3..64f0351f2 100644--- a/src/engine/interfaces/whatsapp-engine.interface.ts+++ b/src/engine/interfaces/whatsapp-engine.interface.ts@@ -85,11 +85,8 @@ export interface IncomingMessage {* populated for `isLidSender` messages.*/senderPhone?: string | null;- /** Sender display info, best-effort from the WhatsApp Web contact cache. */- contact?: {- name?: string;- pushName?: string;- };+ /** Sender contact info, best-effort from the WhatsApp Web cache. Sync fields only (no network). */+ contact?: MessageContact;media?: {mimetype: string;filename?: string;@@ -112,6 +109,37 @@ export interface IncomingMessage {};}+/**+ * Synchronous (already-resolved, no network call) fields of a sender contact, surfaced on+ * {@link IncomingMessage}. Async getters (profile pic / about / formatted number) are intentionally+ * NOT included — they hit WhatsApp servers per message and risk rate-limit/ban. All optional; a key+ * is present only when the engine populated it.+ */+export interface MessageContact {+ /** Sender JID (`…@c.us` or a `…@lid` privacy id). */+ id?: string;+ /** Phone digits, best-effort. For `@lid` senders the authoritative number is `IncomingMessage.senderPhone`. */+ number?: string;+ name?: string;+ pushName?: string;+ shortName?: string;+ /** whatsapp-web.js contact type token. */+ type?: string;+ /** Saved in the account's address book. */+ isMyContact?: boolean;+ /** Is a WhatsApp user. */+ isWAContact?: boolean;+ isBusiness?: boolean;+ isEnterprise?: boolean;+ /** Business verified name. */+ verifiedName?: string;+ /** Business verification level. */+ verifiedLevel?: number;+ isBlocked?: boolean;+ /** Label IDs (CRM). Names are not resolved — that would need a network call. */+ labels?: string[];+}+export interface Contact {id: string;name?: string;