Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(engine): use the phone-dialect twins in Baileys group metadata
Yudhi Armyndharisf482c7b5e6cf
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex e372270fc..426915a38 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -13,6 +13,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Fixed+- Baileys group metadata now uses the phone-dialect twins the payload already carries (`ownerPn`, `participants[].phoneNumber`). Reading only the LID left `owner` and `participants[].id` as `<lid>@lid`, made `number` the LID digits presented as a phone number, and reported `isAdmin: false` for groups the account actually administers — ids that then failed to join against the `@c.us` the same session's contacts and message webhooks emit for the same person. It was only correct once the lid→phone mapping had been learned; the twin is available immediately. Where WhatsApp withholds the twin, as it does for non-contacts, the previous behaviour stands.+- On the Baileys engine, `isBlocked` on a contact read is now the account's real blocklist state rather than a literal `false`. Nothing derived it, while the same session's `/contacts/blocked` endpoint returned the real ids — so automation that skips blocked contacts before sending messaged people the account had explicitly blocked. A blocklist query that fails leaves the field at its default and logs a warning rather than failing the contact read or selling a transport failure as "nobody is blocked". `isMyContact` is unchanged: Baileys has no addressbook signal to derive it from, and inventing one would repeat the mistake.- Five whatsapp-web.js chat operations — mark-as-read, clear, archive, mark-unread and delete — no longer report a dead browser as a refusal. Each caught every error and resolved `false`, so the caller got `200 {"success": false}` ("WhatsApp declined a valid request") while the session's page was actually dead, and retried against it instead of receiving the documented 503. The early death signal was lost too, so the session kept reporting READY until the slower watchdog noticed. They now split transport failure out into `EngineTransportError` and report it, exactly as `getChats` and the other sibling reads in the same adapter already did. An ordinary page-side refusal still resolves `false`, unchanged.diff --git a/src/engine/adapters/baileys-contacts.ts b/src/engine/adapters/baileys-contacts.tsindex e8b191bb4..a07e8a0fa 100644--- a/src/engine/adapters/baileys-contacts.ts+++ b/src/engine/adapters/baileys-contacts.ts@@ -162,7 +162,6 @@ export class BaileysContacts {await this.confirmed(this.sock().removeProfilePicture(selfJid), 'the profile picture removal');}- // eslint-disable-next-line @typescript-eslint/require-awaitasync getContacts(): Promise<Contact[]> {this.host.ensureReady();return this.withBlockedState(this.host.listContacts());diff --git a/src/engine/adapters/baileys-group-lid-twins.spec.ts b/src/engine/adapters/baileys-group-lid-twins.spec.tsnew file mode 100644index 000000000..fcbabfcc9--- /dev/null+++ b/src/engine/adapters/baileys-group-lid-twins.spec.ts@@ -0,0 +1,59 @@+import type { GroupMetadata } from '@whiskeysockets/baileys';+import { mapBaileysGroup, mapBaileysGroupInfo } from './baileys-group-mapper';++/**+ * The mappers read only `metadata.owner` and `participant.id` and discarded the phone-dialect twins+ * the SAME payload carries (`ownerPn`, `participant.phoneNumber`). For a LID-addressed group that+ * left `owner` and `participants[].id` as `<lid>@lid`, made `participants[].number` the LID digits+ * presented as a phone number, and made `isAdmin` false for the account that administers the group.+ *+ * The old behaviour was only correct once the lid→pn mapping had been LEARNED — the normalizer+ * resolves it then. These pin the cold arm, where nothing has been learned yet and the twin the+ * server already sent is the only phone-dialect source available.+ */+const identity = (jid: string): string => jid;++const lidGroup = (withTwins: boolean): GroupMetadata =>+ ({+ id: '[email protected]',+ subject: 'Ops',+ owner: '111222333@lid',+ ownerPn: withTwins ? '[email protected]' : undefined,+ creation: 1,+ participants: [+ {+ id: '111222333@lid',+ phoneNumber: withTwins ? '[email protected]' : undefined,+ admin: 'superadmin',+ },+ { id: '444555666@lid', phoneNumber: withTwins ? '[email protected]' : undefined, admin: null },+ ],+ }) as unknown as GroupMetadata;++describe('LID group metadata uses the phone-dialect twins the payload already carries', () => {+ it('maps the owner from ownerPn', () => {+ expect(mapBaileysGroupInfo(lidGroup(true), identity).owner).toBe('[email protected]');+ });++ it('maps participant ids and numbers from phoneNumber', () => {+ const info = mapBaileysGroupInfo(lidGroup(true), identity);++ expect(info.participants.map(p => p.id)).toEqual(['[email protected]', '[email protected]']);+ // The whole point: `number` must be an MSISDN, not the LID digits dressed up as one.+ expect(info.participants.map(p => p.number)).toEqual(['628111', '628222']);+ });++ it('recognises the account as admin through its phone-dialect twin', () => {+ expect(mapBaileysGroup(lidGroup(true), '[email protected]', identity).isAdmin).toBe(true);+ });++ // Negative twin: WhatsApp withholds phone_number for non-contacts as a privacy default. With no+ // twin there is nothing to prefer, and the previous behaviour must stand rather than the mapper+ // inventing an MSISDN.+ it('falls back to the lid when the server sent no twin', () => {+ const info = mapBaileysGroupInfo(lidGroup(false), identity);++ expect(info.owner).toBe('111222333@lid');+ expect(info.participants.map(p => p.id)).toEqual(['111222333@lid', '444555666@lid']);+ });+});diff --git a/src/engine/adapters/baileys-group-mapper.ts b/src/engine/adapters/baileys-group-mapper.tsindex f7d55429e..72ef67071 100644--- a/src/engine/adapters/baileys-group-mapper.ts+++ b/src/engine/adapters/baileys-group-mapper.ts@@ -10,10 +10,27 @@ import { userPart } from '../identity/wa-id';type NormalizeJid = (jid: string) => string;const identity: NormalizeJid = jid => jid;+/**+ * The phone-dialect identity for a participant or owner.+ *+ * A LID-addressed group hands us `<lid>@lid` in `id`/`owner`, and the SAME payload carries the phone+ * twin alongside it (`participant.phoneNumber`, `metadata.ownerPn`). Reading only the lid left the+ * neutral output correct ONLY once the lid→pn mapping had been learned — before that, ids did not+ * match the `@c.us` the session's own contacts and message webhooks emit for the same person, and+ * `number` presented LID digits as an MSISDN. Prefer the twin the server already sent; fall back to+ * the normalizer, which still resolves a learned mapping. WhatsApp withholds `phone_number` for+ * non-contacts, so the fallback is the ordinary case, not an error path.+ */+function preferPhoneDialect(jid: string, phoneTwin: string | undefined, normalizeJid: NormalizeJid): string {+ return normalizeJid(phoneTwin ?? jid);+}+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'),+ p =>+ userPart(preferPhoneDialect(p.id, p.phoneNumber, normalizeJid)) === self &&+ (p.admin === 'admin' || p.admin === 'superadmin'),);}@@ -35,7 +52,7 @@ export function mapBaileysGroup(/** Map a Baileys GroupMetadata to the neutral {@link GroupInfo} (full participant list). */export function mapBaileysGroupInfo(metadata: GroupMetadata, normalizeJid: NormalizeJid = identity): GroupInfo {const participants: GroupParticipant[] = metadata.participants.map(p => {- const id = normalizeJid(p.id);+ const id = preferPhoneDialect(p.id, p.phoneNumber, normalizeJid);return {id,number: userPart(id),@@ -48,7 +65,7 @@ export function mapBaileysGroupInfo(metadata: GroupMetadata, normalizeJid: Normaid: metadata.id,name: metadata.subject,description: metadata.desc,- owner: metadata.owner ? normalizeJid(metadata.owner) : metadata.owner,+ owner: metadata.owner ? preferPhoneDialect(metadata.owner, metadata.ownerPn, normalizeJid) : metadata.owner,createdAt: metadata.creation,participants,// WhatsApp "announce" = only admins can post; surface as both isAnnounce and (members') isReadOnly (best-effort).