Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(wwjs): survive undefined label-chat entries and the $1 serialized-property rename

Yudhi Armyndharis90569e4f4b15
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 408ad004d..c23e25044 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -35,6 +35,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- A media-storage root the app cannot write to is caught at boot with a clear error, instead of failing on the first write (#1066).
- The bundled `docker-compose.yml` now forwards the `SEND_PACING_*`, `MEDIA_CONVERSION_*`/`FFMPEG_PATH` and session-ownership (`NODE_ID`, `NODE_URL`, lease/sweep) variables — previously these features could not be enabled from `.env` in a compose deployment at all.
- The four label write tools (`LabelUpsert`, `LabelDelete`, `LabelAddToChat`, `LabelRemoveFromChat`) answered `Internal error` over MCP even though the write had succeeded on WhatsApp, prompting agents to retry a completed operation; they now return `{ success: true }`.
+- **whatsapp-web.js raw-id extraction hardening:** listing a label's chats no longer 500s when a labelled chat was deleted, and the channel list, channel creation and group-invite preview now read the `$1` fallback for the WA Web property rename — previously a renamed build returned channel ids as the literal string `"undefined"` and turned every valid invite preview into a false 404.
- **Baileys refusals now answer their documented statuses instead of 500:** an invalid/expired group invite previews as 404, admin-refused group writes (subject, description, announce/locked, picture, member-add mode) and refused channel writes (create/delete/mute) answer 403 — matching the whatsapp-web.js engine. Transport failures still propagate unchanged.
- **Multi-node request routing hardening:** forwarded requests now carry the client address in `x-forwarded-for` (so `allowedIps` keys and per-IP throttling see the real client once peer nodes are listed in `TRUSTED_PROXIES`), a malformed session id no longer 500s on Postgres in routed mode, and the client-settable forwarded marker is verified — a marked request landing on a live non-owner answers 409 instead of executing there.
- **Send pacing accounting:** forwards now pass through the cold-reachout gate (they were ungated while still draining the budget), replying to someone who wrote first today no longer spends the cold budget, and a pacing 429 inside a bulk batch is recorded as `SEND_PACING_LIMITED` instead of a generic `SEND_FAILED`.
diff --git a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
index 506376a31..5b49bfea8 100644
--- a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
+++ b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
@@ -6054,3 +6054,64 @@ describe('WhatsAppWebJsAdapter voice status', () => {
expect(options.sendAudioAsVoice).toBeUndefined();
});
});
+
+// WA Web's minifier periodically renames the page-context `_serialized` property to `$1` (#747),
+// 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".
+describe('WhatsAppWebJsAdapter raw-id extraction hardening', () => {
+ 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('getChatsByLabel skips an undefined entry (deleted chat behind the label) instead of a 500', async () => {
+ const getChatsByLabelId = jest
+ .fn()
+ .mockResolvedValue([undefined, { id: { _serialized: '[email protected]' }, name: 'Kept', isGroup: false }, { id: {} }]);
+
+ const result = await readyAdapter({ getChatsByLabelId }).getChatsByLabel('7');
+
+ expect(result).toHaveLength(1);
+ expect(result[0].id).toBe('[email protected]');
+ });
+
+ it('getSubscribedChannels reads $1 on a renamed build, never the literal "undefined"', async () => {
+ const getChannels = jest.fn().mockResolvedValue([{ id: { $1: '120363@newsletter' }, name: 'Renamed' }]);
+
+ const result = await readyAdapter({ getChannels }).getSubscribedChannels();
+
+ expect(result[0].id).toBe('120363@newsletter');
+ });
+
+ it('createChannel reads nid.$1 on a renamed build instead of returning id "undefined"', async () => {
+ const createChannel = jest.fn().mockResolvedValue({ title: 'C', nid: { $1: '120363@newsletter' } });
+
+ const channel = await readyAdapter({ createChannel }).createChannel('C');
+
+ expect(channel.id).toBe('120363@newsletter');
+ });
+
+ it('createChannel refuses when no id is readable rather than minting "undefined"', async () => {
+ const createChannel = jest.fn().mockResolvedValue({ title: 'C', nid: {} });
+
+ await expect(readyAdapter({ createChannel }).createChannel('C')).rejects.toBeInstanceOf(EngineRefusedError);
+ });
+
+ it('getGroupJoinInfo reads id/owner via $1 on a renamed build instead of a false 404', async () => {
+ const getInviteInfo = jest.fn().mockResolvedValue({
+ id: { $1: '[email protected]' },
+ subject: 'G',
+ owner: { $1: '[email protected]' },
+ size: 3,
+ });
+
+ const info = await readyAdapter({ getInviteInfo }).getGroupJoinInfo('CODE');
+
+ expect(info.id).toBe('[email protected]');
+ expect(info.owner).toBe('[email protected]');
+ expect(info.participantCount).toBe(3);
+ });
+});
diff --git a/src/engine/adapters/wwebjs-channels.ts b/src/engine/adapters/wwebjs-channels.ts
index e5b59e1ae..f271911d2 100644
--- a/src/engine/adapters/wwebjs-channels.ts
+++ b/src/engine/adapters/wwebjs-channels.ts
@@ -26,7 +26,9 @@ export class WwebjsChannels {
return [];
}
return channels.map((ch: WwjsChannelData) => ({
- id: String(typeof ch.id === 'object' ? ch.id._serialized : ch.id),
+ // Read `$1` before giving up (#747: WA Web's minifier renamed the serialized property), and
+ // never String() the object branch — that manufactures the literal "undefined" as an id.
+ id: (typeof ch.id === 'object' ? (ch.id._serialized ?? ch.id.$1) : String(ch.id)) || '',
name: String(ch.name || ''),
description: ch.description ? String(ch.description) : undefined,
inviteCode: ch.inviteCode ? String(ch.inviteCode) : undefined,
@@ -52,8 +54,15 @@ export class WwebjsChannels {
if (typeof result === 'string' || !result?.nid) {
throw new EngineRefusedError(typeof result === 'string' ? result : `Failed to create the channel '${name}'`);
}
+ // The nid crosses the puppeteer boundary as a raw page-context Wid, exactly the object class
+ // WA Web's minifier rename hits (#747): read `$1` before giving up, and never String() an
+ // absent id — a channel with the literal id "undefined" is unusable for every follow-up call.
+ const channelId = result.nid._serialized ?? result.nid.$1;
+ if (!channelId) {
+ throw new EngineRefusedError(`Channel '${name}' was created but its id was unreadable — refusing to return it`);
+ }
return {
- id: String(result.nid._serialized),
+ id: String(channelId),
name: String(result.title ?? name),
...(description === undefined ? {} : { description }),
// The library hands back a full invite LINK; the neutral shape carries the code, which is what
diff --git a/src/engine/adapters/wwebjs-groups.ts b/src/engine/adapters/wwebjs-groups.ts
index 31d1b0bf5..1a42d56e6 100644
--- a/src/engine/adapters/wwebjs-groups.ts
+++ b/src/engine/adapters/wwebjs-groups.ts
@@ -340,20 +340,22 @@ export class WwebjsGroups {
async getGroupJoinInfo(inviteCode: string): Promise<GroupJoinInfo> {
this.host.ensureReady();
const raw = (await this.client().getInviteInfo(inviteCode)) as {
- id?: { _serialized?: string } | string;
+ id?: { _serialized?: string; $1?: string } | string;
subject?: string;
desc?: string;
- owner?: { _serialized?: string } | string;
+ owner?: { _serialized?: string; $1?: string } | string;
creation?: number;
size?: number;
participants?: unknown[];
} | null;
- const id = typeof raw?.id === 'string' ? raw.id : raw?.id?._serialized;
+ // 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);
if (!id) {
throw new GroupNotFoundError(inviteCode);
}
- const owner = typeof raw?.owner === 'string' ? raw.owner : raw?.owner?._serialized;
+ const owner = typeof raw?.owner === 'string' ? raw.owner : (raw?.owner?._serialized ?? raw?.owner?.$1);
// `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.ts
index 903f7878b..6873ab402 100644
--- a/src/engine/adapters/wwebjs-labels.ts
+++ b/src/engine/adapters/wwebjs-labels.ts
@@ -42,7 +42,10 @@ export class WwebjsLabels {
const chats = await (this.client() as unknown as BusinessClient).getChatsByLabelId(labelId);
const summaries: ChatSummary[] = [];
for (const chat of chats ?? []) {
- const id = chat.id?._serialized;
+ // The library builds this list via getChatById per label item and yields UNDEFINED entries
+ // for chats that no longer resolve (Client.js getChatsByLabelId → ChatFactory) — the whole
+ // entry, not just the id, so the optional chain must start at the entry itself.
+ const id = chat?.id?._serialized;
if (!id) continue;
summaries.push({
id,
diff --git a/src/engine/types/whatsapp-web-js.types.ts b/src/engine/types/whatsapp-web-js.types.ts
index d5331a346..4c2d3a6e4 100644
--- a/src/engine/types/whatsapp-web-js.types.ts
+++ b/src/engine/types/whatsapp-web-js.types.ts
@@ -122,7 +122,10 @@ export interface BusinessClient extends Omit<
getChatsByLabelId(
labelId: string,
): Promise<
- Array<{ id?: { _serialized?: string }; name?: string; isGroup?: boolean; unreadCount?: number; timestamp?: number }>
+ Array<
+ | { id?: { _serialized?: string }; name?: string; isGroup?: boolean; unreadCount?: number; timestamp?: number }
+ | undefined
+ >
>;
getChannels(): Promise<WwjsChannelData[]>;
/** Takes a channel ID (`…@newsletter`), NOT an invite code; resolves true only on success. */
@@ -134,7 +137,7 @@ export interface BusinessClient extends Omit<
createChannel(
title: string,
options?: { description?: string },
- ): Promise<{ title?: string; nid: { _serialized: string }; inviteLink?: string } | string>;
+ ): Promise<{ title?: string; nid: { _serialized?: string; $1?: string }; inviteLink?: string } | string>;
/** False when the channel was not found or the server refused. */
deleteChannel(channelId: string): Promise<boolean>;
/** Resolves true only when the unsubscription completed. */
@@ -145,7 +148,7 @@ export interface BusinessClient extends Omit<
* WhatsApp Channel/Newsletter data.
*/
export interface WwjsChannelData {
- id: { _serialized: string } | string;
+ id: { _serialized?: string; $1?: string } | string;
name?: string;
description?: string;
inviteCode?: string;