Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(baileys): stop channel creation failing after the channel exists
Yudhi Armyndharisbda29787a86e
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 13f5bc805..81813eff1 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -25,6 +25,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Fixed- A group participant id that does not name an individual — free text, a group id, a number too short to be one — is now rejected with `400` naming the offending entries, instead of being handed to the engine. On whatsapp-web.js such an id reached the page-side `createWid`, which threw an error the minified bundle reports without a name, so the caller received a `500` that could not be diagnosed from either end. The check covers group creation and adding, removing, promoting and demoting participants, and it sits in the service rather than the request body so the MCP tools are guarded on the same terms as the REST routes. Refs #1220.+- Creating a channel on the Baileys engine no longer answers `500` while leaving the channel behind. The library's response parser read `thread.picture.id` eagerly, but its create call sends only a name and description and has no picture parameter, so the picture was absent on every create and the parse threw after WhatsApp had already created the newsletter — and because the operation is non-idempotent, a client retrying the `500` leaked one orphan channel per attempt, invisible through the API since `getSubscribedChannels` is not available on that engine. A new install-time patch reads the response defensively so the call succeeds and returns the new channel's id, which is the only place that id appears.- A profile-picture lookup that fails on the whatsapp-web.js engine now answers `503` instead of `{"url": null}`, which is what the route already documented. whatsapp-web.js resolves `undefined` for the only legitimate negative — no picture, or hidden by privacy — so every error reaching the adapter was a failure being reported as "this contact has no avatar". The batch route keeps its best-effort `null`, having no per-id error channel. A dead page during a single-contact lookup likewise stops reading as `404`.- The JavaScript, Python, Go and Java SDKs list `group.join_request`, an event the gateway has accepted and dispatched all along, so a typed client can subscribe to it without casting past its own type.- A webhook's `lastTriggeredAt` is published as a nullable date-time string instead of an object, so a client generated from the contract no longer rejects both of the values the field actually carries. The response itself is unchanged.diff --git a/Dockerfile b/Dockerfileindex 60657795c..0fe0ee653 100644--- a/Dockerfile+++ b/Dockerfile@@ -120,7 +120,7 @@ COPY package*.json ./# scripts/postinstall.js rides along: `npm ci` below runs the hook, which fails# when the file is missing. With the patcher present the hook applies it in# --best-effort mode; the explicit fatal run right after is the real gate.-COPY scripts/postinstall.js scripts/patch-wwebjs-201832.js scripts/wwebjs-201832.patch scripts/patch-wwebjs-newsletter-preview.js scripts/patch-wwebjs-status.js scripts/patch-wwebjs-ready-sync.js scripts/patch-baileys-appstate.js ./scripts/+COPY scripts/postinstall.js scripts/patch-wwebjs-201832.js scripts/wwebjs-201832.patch scripts/patch-wwebjs-newsletter-preview.js scripts/patch-wwebjs-status.js scripts/patch-wwebjs-ready-sync.js scripts/patch-baileys-appstate.js scripts/patch-baileys-newsletter-create.js ./scripts/# Install production dependencies only, then apply the backports. The status patcher runs after# the two patchers it depends on: its transforms were written against the tree they leave behind.@@ -133,6 +133,7 @@ RUN npm ci --omit=dev \&& node scripts/patch-wwebjs-status.js \&& node scripts/patch-wwebjs-ready-sync.js \&& node scripts/patch-baileys-appstate.js \+ && node scripts/patch-baileys-newsletter-create.js \&& npm cache clean --force# Replace the npm the base image bundles. npm is not on the request path — the entrypoint runsdiff --git a/docs/29-engine-capability-matrix.md b/docs/29-engine-capability-matrix.mdindex 05ab2ff49..a03bf1100 100644--- a/docs/29-engine-capability-matrix.md+++ b/docs/29-engine-capability-matrix.md@@ -5,7 +5,7 @@ Three-way comparison of every capability: the **Baileys library** (`@whiskeysockits adapter layer and REST API — including which "supported" cells only work because OpenWA patchesthe installed library. Coverage is total: all 112 `IWhatsAppEngine` methods (29.4), **all 152Baileys + 81 whatsapp-web.js library methods** (29.5), all 34 + 31 library events (29.5.4), and all-5 install-time patches (29.3). If it exists upstream or in OpenWA, it has a row here.+6 install-time patches (29.3). If it exists upstream or in OpenWA, it has a row here.## 29.1 How to read this matrix@@ -124,15 +124,16 @@ OpenWA ships five exact, self-disabling source transforms over the installed engpatcher no-ops once the fix is present upstream, and an unrecognized source shape fails loudlyrather than shipping a silently partial patch.-### 29.3.1 The five patches+### 29.3.1 The six patches-| # | Patcher | Library target | What it repairs | Stand-down predicate |-| --- | ---------------------------------------------------------- | ------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| 🔧¹ | `scripts/patch-wwebjs-201832.js` (+ `wwebjs-201832.patch`) | whatsapp-web.js models | WhatsApp Web 2.3000.x renamed the serialized message-id property `id._serialized` → `id.$1`; 1.34.7 reads the old name in the `Message` constructor and ~40 downstream sites, so message ids, acks, quoted-message resolution and media downloads break. Backports upstream fix #201832 (`Base._normalizeId()`). One known harmless reject on 1.34.7 (a LID-aware `Contact.js` path that does not exist there); any other reject aborts the build. | no-ops once `_normalizeId` exists upstream. Runtime double-check: `src/engine/adapters/wwebjs-backport-check.ts` detects an unpatched install and logs an error naming the fix as the wwjs session starts (`whatsapp-web-js.adapter.ts:430`). It is diagnostic, **not** preventive — startup continues, so a session reaching READY is not evidence the patch landed. |-| 🔧² | `scripts/patch-wwebjs-status.js` | whatsapp-web.js injected status send | Two independent breakages in current WhatsApp Web builds: (1) the `canCheckStatusRankingPosterGating()` helper is gone and its call threw before any status send — now called when present, `false` (pre-gating meaning) when not; (2) `sendStatusMediaMsgAction` changed signature from positional `(msg, mediaUpdate)` to a single options object — adopted from upstream PR #201816. The two edits of the media repair are all-or-nothing. | exact-shape match; unknown shape fails the build. |-| 🔧³ | `scripts/patch-wwebjs-newsletter-preview.js` | whatsapp-web.js `Injected/Utils.js` | Link-preview generation omitted the destination chat, so WhatsApp Web could not select the newsletter preview transport: `getLinkPreview(link)` → `getLinkPreview(link, chat)`. | exact-shape match; unknown shape fails the build. |-| 🔧⁴ | `scripts/patch-wwebjs-ready-sync.js` | whatsapp-web.js readiness pipeline | Two live-observed races: on a warm profile the page can reach `hasSynced=true` before the edge listener attaches (the whole post-auth pipeline silently never runs), and a partial `attachEventListeners` failure was swallowed (message bridge dead while sends still work). Adds an `eventsAttached` completion marker and fires the handler once when the level is already true; double-fire is deduped by the adapter. | exact-shape, one group all-or-nothing; unknown shape fails the build. |-| 🔧⁵ | `scripts/patch-baileys-appstate.js` | Baileys `lib/Socket/chats.js` | `resyncAppState`'s `while (collectionsToHandle.size)` loop: `query()` resolves `undefined` on its own 60s timeout, decoding to `{}`, and every loop exit — including the library's own attempts guard — lives inside `for (const key in decoded)`, which never runs on an empty decode. The loop would burn one 60s query per pass for the life of the socket (~1000 wasted queries/day). The patch adds the missing exit: empty decode → `break`. | exact-shape match; remove once upstream bounds the loop. |+| # | Patcher | Library target | What it repairs | Stand-down predicate |+| --- | ---------------------------------------------------------- | ------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| 🔧¹ | `scripts/patch-wwebjs-201832.js` (+ `wwebjs-201832.patch`) | whatsapp-web.js models | WhatsApp Web 2.3000.x renamed the serialized message-id property `id._serialized` → `id.$1`; 1.34.7 reads the old name in the `Message` constructor and ~40 downstream sites, so message ids, acks, quoted-message resolution and media downloads break. Backports upstream fix #201832 (`Base._normalizeId()`). One known harmless reject on 1.34.7 (a LID-aware `Contact.js` path that does not exist there); any other reject aborts the build. | no-ops once `_normalizeId` exists upstream. Runtime double-check: `src/engine/adapters/wwebjs-backport-check.ts` detects an unpatched install and logs an error naming the fix as the wwjs session starts (`whatsapp-web-js.adapter.ts:430`). It is diagnostic, **not** preventive — startup continues, so a session reaching READY is not evidence the patch landed. |+| 🔧² | `scripts/patch-wwebjs-status.js` | whatsapp-web.js injected status send | Two independent breakages in current WhatsApp Web builds: (1) the `canCheckStatusRankingPosterGating()` helper is gone and its call threw before any status send — now called when present, `false` (pre-gating meaning) when not; (2) `sendStatusMediaMsgAction` changed signature from positional `(msg, mediaUpdate)` to a single options object — adopted from upstream PR #201816. The two edits of the media repair are all-or-nothing. | exact-shape match; unknown shape fails the build. |+| 🔧³ | `scripts/patch-wwebjs-newsletter-preview.js` | whatsapp-web.js `Injected/Utils.js` | Link-preview generation omitted the destination chat, so WhatsApp Web could not select the newsletter preview transport: `getLinkPreview(link)` → `getLinkPreview(link, chat)`. | exact-shape match; unknown shape fails the build. |+| 🔧⁴ | `scripts/patch-wwebjs-ready-sync.js` | whatsapp-web.js readiness pipeline | Two live-observed races: on a warm profile the page can reach `hasSynced=true` before the edge listener attaches (the whole post-auth pipeline silently never runs), and a partial `attachEventListeners` failure was swallowed (message bridge dead while sends still work). Adds an `eventsAttached` completion marker and fires the handler once when the level is already true; double-fire is deduped by the adapter. | exact-shape, one group all-or-nothing; unknown shape fails the build. |+| 🔧⁵ | `scripts/patch-baileys-appstate.js` | Baileys `lib/Socket/chats.js` | `resyncAppState`'s `while (collectionsToHandle.size)` loop: `query()` resolves `undefined` on its own 60s timeout, decoding to `{}`, and every loop exit — including the library's own attempts guard — lives inside `for (const key in decoded)`, which never runs on an empty decode. The loop would burn one 60s query per pass for the life of the socket (~1000 wasted queries/day). The patch adds the missing exit: empty decode → `break`. | exact-shape match; remove once upstream bounds the loop. |+| 🔧⁶ | `scripts/patch-baileys-newsletter-create.js` | Baileys `lib/Socket/newsletter.js` | `parseNewsletterCreateResponse` reads `thread.picture.id` eagerly, but `newsletterCreate` sends only `{ name, description }` — there is no picture parameter anywhere in the chain — so `thread.picture` is null on EVERY create and the parse threw for all of them. WhatsApp creates the newsletter server-side BEFORE the response is parsed, so each call returned 500 while leaving a real channel behind, and `createChannel` is non-idempotent, so a client retrying a 5xx leaked one orphan per attempt (confirmed on the test account). `description` has the same defect whenever the caller omits one. The patch reads every nested field defensively so the response's `id` — the only place the new channel's id appears — always survives. | exact-shape match; remove once upstream tolerates a pictureless newsletter. |### 29.3.2 Which matrix rows depend on which patch@@ -149,6 +150,7 @@ row-level marks.| 🔧³ newsletter link preview | `sendTextMessage` (and any send carrying a link preview) **to a channel JID** on wwjs. Row-marked on `sendTextMessage` as the common case. || 🔧⁴ ready-sync | `initialize` on wwjs (warm-restore readiness race). Row-marked. || 🔧⁵ app-state resync bound | No single row — keeps the Baileys socket's app-state resync from spinning (~1000 wasted 60s queries/day). Connection health under **every baileys cell**; the baileys column header carries `🔧⁵`. |+| 🔧⁶ newsletter-create parse | `createChannel` on **baileys** — without it the call always answers 500 and leaks the channel it just created. Row-marked. |Rows that are ✅ on **both** engines where one side is patch-dependent: `initialize` (🔧⁴ wwjs),`sendTextMessage` (🔧³ wwjs), `postTextStatus` / `postImageStatus` / `postVideoStatus` /@@ -281,7 +283,7 @@ socket is caught by the transport instead. No REST route: the session watchdog p| Method | Baileys adapter 🔧⁵ | wwjs adapter 🔧¹ ⁴ | OpenWA REST || -------------------------- | ------------------- | ------------------ | --------------- |-| `createChannel` | ✅ | ✅ | ✅ |+| `createChannel` | ✅🔧⁶ | ✅ | ✅ || `deleteChannel` | ✅ | ✅ | ✅ || `muteChannel` | ✅ | ✅ | ✅ || `demoteChannelAdmin` | ✅ | ❌ lib | ⚠️ baileys only |@@ -900,7 +902,7 @@ adapter sources — re-derive the same way when anything changes:showed it** — `demoteChannelAdmin`'s page function is gone, and `transferChannelOwnership`'s pagefunction rejects locally against a list it cannot repopulate (both in 29.6.2). Both are Baileys-onlyand both are 501 on wwjs. `.d.ts` presence is not capability.-- **5** install-time patches (4 whatsapp-web.js + 1 Baileys), all exact and self-disabling.+- **6** install-time patches (4 whatsapp-web.js + 2 Baileys), all exact and self-disabling.- **0 phantom-support rows** — every `not-available` cell throws at the adapter boundary.- Remaining adapter-gaps (fixable in this repo, ranked): **#1** `getChannelMessages` (Baileys —fetch is one line, `BinaryNode`→`ChannelMessage` parser is the work); **#2** `subscribeToChannel`diff --git a/package.json b/package.jsonindex 898d0a673..306455ff6 100644--- a/package.json+++ b/package.json@@ -37,7 +37,7 @@"lint": "eslint \"{src,apps,libs,test}/**/*.ts\"","lint:fix": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix","test": "jest",- "test:scripts": "node --test scripts/postinstall.spec.js scripts/patch-wwebjs-newsletter-preview.spec.js scripts/patch-wwebjs-status.spec.js scripts/patch-wwebjs-ready-sync.spec.js scripts/patch-baileys-appstate.spec.js scripts/dockerfile-patchers.spec.js scripts/check-upstream-surface.spec.mjs scripts/check-sdk-docs.spec.mjs",+ "test:scripts": "node --test scripts/postinstall.spec.js scripts/patch-wwebjs-newsletter-preview.spec.js scripts/patch-wwebjs-status.spec.js scripts/patch-wwebjs-ready-sync.spec.js scripts/patch-baileys-appstate.spec.js scripts/patch-baileys-newsletter-create.spec.js scripts/dockerfile-patchers.spec.js scripts/check-upstream-surface.spec.mjs scripts/check-sdk-docs.spec.mjs","test:watch": "jest --watch","test:cov": "jest --coverage","test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",diff --git a/scripts/patch-baileys-newsletter-create.js b/scripts/patch-baileys-newsletter-create.jsnew file mode 100644index 000000000..364046254--- /dev/null+++ b/scripts/patch-baileys-newsletter-create.js@@ -0,0 +1,119 @@+/**+ * Stop Baileys' newsletter-create parser from throwing away a channel it just created.+ *+ * `parseNewsletterCreateResponse` (lib/Socket/newsletter.js) builds its result eagerly and reads+ * `thread.picture.id` unconditionally. But `newsletterCreate` sends `input: { name, description }`+ * and its signature is `(name, description?)` — there is **no picture parameter anywhere in the+ * chain** — so a newly created newsletter has no picture and `thread.picture` is null on EVERY+ * create. The parse therefore throws `TypeError: Cannot read properties of null (reading 'id')` for+ * every single call, not for an unlucky subset.+ *+ * The damage is worse than a failed request. WhatsApp creates the newsletter **server-side first**;+ * the parser dies afterwards, on the response. So the caller receives a 500 believing nothing+ * happened, while a real channel is left behind — and `createChannel` is non-idempotent, so a client+ * that retries a 5xx leaks one orphan channel per attempt. Confirmed on the test account: two failed+ * calls, two orphan channels, found only by looking at the handset. There is no API path to find+ * them on that engine, because `getSubscribedChannels` answers 501 on Baileys.+ *+ * **Recovering the id is the point, not merely not crashing.** `response.id` is the only place the+ * new channel's id ever appears, so a parser that returns without it would convert "500 plus an+ * orphan" into "200 with no handle" — arguably worse, since nothing would look wrong. Every nested+ * read is therefore made defensive: whatever else is absent, the id survives.+ *+ * `description` has the same defect and is reachable through this gateway's own API: the create DTO+ * makes it optional and `newsletterCreate` sends `description ?? null`, so a channel created without+ * one gets `thread.description === null` and `thread.description.text` throws exactly as the picture+ * read does.+ *+ * Exact and self-disabling, like the other patchers: an unknown shape fails rather than silently+ * shipping unpatched.+ *+ * **RETIRE THIS, do not keep it.** It compensates for an upstream bug with an obvious upstream fix,+ * and it is not tied to a WhatsApp Web version the way the whatsapp-web.js patchers are. Delete it+ * once @whiskeysockets/baileys tolerates a pictureless newsletter in this parser.+ */+'use strict';++const fs = require('fs');+const path = require('path');++const DEFAULT_BAILEYS = path.join(__dirname, '..', 'node_modules', '@whiskeysockets', 'baileys');+const NEWSLETTER_PATH = path.join('lib', 'Socket', 'newsletter.js');++const MARKER = 'OpenWA: newsletterCreate cannot supply a picture';++const PARSE_FIND = ` return {+ id: id,+ owner: undefined,+ name: thread.name.text,+ creation_time: parseInt(thread.creation_time, 10),+ description: thread.description.text,+ invite: thread.invite,+ subscribers: parseInt(thread.subscribers_count, 10),+ verification: thread.verification,+ picture: {+ id: thread.picture.id,+ directPath: thread.picture.direct_path+ },+ mute_state: viewer.mute+ };`;++const PARSE_REPLACE = ` // ${MARKER} — its input is { name, description } and nothing else — so+ // \`thread.picture\` is null on every create and this eager read threw for all of them. WhatsApp+ // creates the newsletter BEFORE the response is parsed, so each throw left a real channel behind+ // while the caller saw a 500. \`description\` is null too whenever the caller omitted one+ // (newsletterCreate sends \`description ?? null\`). Read every nested field defensively: \`id\` is+ // the only place the new channel's id appears, so it must survive whatever else is missing.+ return {+ id: id,+ owner: undefined,+ name: thread?.name?.text,+ creation_time: parseInt(thread?.creation_time, 10),+ description: thread?.description?.text,+ invite: thread?.invite,+ subscribers: parseInt(thread?.subscribers_count, 10),+ verification: thread?.verification,+ picture: thread?.picture ? { id: thread.picture.id, directPath: thread.picture.direct_path } : undefined,+ mute_state: viewer?.mute+ };`;++/** Apply the transform. Returns {skipped, reason} or {note} — never a partial write. */+function applyNewsletterCreatePatch(baileysDir = DEFAULT_BAILEYS) {+ const file = path.join(baileysDir, NEWSLETTER_PATH);+ if (!fs.existsSync(file)) {+ return { skipped: true, reason: `${NEWSLETTER_PATH} not found — nothing to patch` };+ }+ const source = fs.readFileSync(file, 'utf8');+ if (source.includes(MARKER)) {+ return { skipped: true, reason: 'already patched' };+ }+ const occurrences = source.split(PARSE_FIND).length - 1;+ if (occurrences !== 1) {+ throw new Error(+ `expected exactly 1 newsletter-create parse site in ${NEWSLETTER_PATH}, found ${occurrences} — ` ++ 'the upstream shape changed; re-check whether a pictureless newsletter still crashes the parser ' ++ 'before removing this patcher',+ );+ }+ fs.writeFileSync(file, source.replace(PARSE_FIND, PARSE_REPLACE), 'utf8');+ return { note: 'made the newsletter-create parse tolerate an absent picture, keeping the new channel id' };+}++function run() {+ const bestEffort = process.argv.includes('--best-effort');+ try {+ const result = applyNewsletterCreatePatch();+ console.log(`patch-baileys-newsletter-create: ${result.skipped ? `skipped — ${result.reason}` : result.note}`);+ } catch (error) {+ if (bestEffort) {+ console.warn(`patch-baileys-newsletter-create: skipped — ${error.message}`);+ return;+ }+ console.error(`patch-baileys-newsletter-create: ${error.message}`);+ process.exitCode = 1;+ }+}++if (require.main === module) run();++module.exports = { applyNewsletterCreatePatch, PARSE_FIND, PARSE_REPLACE, MARKER };diff --git a/scripts/patch-baileys-newsletter-create.spec.js b/scripts/patch-baileys-newsletter-create.spec.jsnew file mode 100644index 000000000..ce5303043--- /dev/null+++ b/scripts/patch-baileys-newsletter-create.spec.js@@ -0,0 +1,132 @@+'use strict';++const test = require('node:test');+const assert = require('node:assert/strict');+const fs = require('fs');+const os = require('os');+const path = require('path');++const { applyNewsletterCreatePatch, PARSE_FIND, MARKER } = require('./patch-baileys-newsletter-create');++/**+ * Same contract as the sibling patcher specs: the patcher rewrites a file this repository does not+ * own, so it must fire only on the exact shape it was written for, refuse loudly on anything else,+ * and be safe to run twice (postinstall runs on every install).+ *+ * This one also EXECUTES the parser either side of the patch, because the defect is behavioural. A+ * text assertion would pass just as happily against a transform that stopped the crash while+ * dropping the new channel's id — which is the one thing the response carries that nothing else can+ * recover.+ */++/** A parser file with the real upstream body, in CommonJS so the test can run it. */+function fakeBaileys() {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'baileys-newsletter-'));+ fs.mkdirSync(path.join(dir, 'lib', 'Socket'), { recursive: true });+ const file = path.join(dir, 'lib', 'Socket', 'newsletter.js');+ fs.writeFileSync(+ file,+ `const parseNewsletterCreateResponse = (response) => {+ const { id, thread_metadata: thread, viewer_metadata: viewer } = response;+${PARSE_FIND}+};+module.exports = { parseNewsletterCreateResponse };+`,+ );+ return { dir, file };+}++function load(file) {+ delete require.cache[require.resolve(file)];+ return require(file).parseNewsletterCreateResponse;+}++/** What WhatsApp actually returns for a channel created through `newsletterCreate`. */+const REAL_RESPONSE = {+ id: '120363428347011596@newsletter',+ thread_metadata: {+ name: { text: 'openwa-probe' },+ creation_time: '1786405315',+ description: null, // the caller omitted one; newsletterCreate sends `description ?? null`+ invite: '0029VbCs400HAdNLkrTlCt0r',+ subscribers_count: '1',+ verification: 'UNVERIFIED',+ picture: null, // there is no picture parameter anywhere in the create chain+ },+ viewer_metadata: { mute: 'off' },+};++test('CONTROL — the unpatched parser throws on the shape every create produces', () => {+ // Without this the tests below could pass against a parser that never had the defect.+ const { dir, file } = fakeBaileys();+ const parse = load(file);+ assert.throws(() => parse(REAL_RESPONSE), /Cannot read properties of null/);+ fs.rmSync(dir, { recursive: true, force: true });+});++test('the patched parser survives an absent picture AND keeps the new channel id', () => {+ const { dir, file } = fakeBaileys();+ const result = applyNewsletterCreatePatch(dir);+ assert.equal(result.skipped, undefined);++ const parsed = load(file)(REAL_RESPONSE);+ // The id is the whole point: it is the only place the created channel's id ever appears, so a+ // patch that merely stopped the crash would leave an orphan nobody can address.+ assert.equal(parsed.id, '120363428347011596@newsletter');+ assert.equal(parsed.picture, undefined);+ assert.equal(parsed.description, undefined);+ assert.equal(parsed.name, 'openwa-probe');+ assert.equal(parsed.invite, '0029VbCs400HAdNLkrTlCt0r');+ assert.equal(parsed.creation_time, 1786405315);+ fs.rmSync(dir, { recursive: true, force: true });+});++test('a channel that DOES have a picture still maps it', () => {+ const { dir, file } = fakeBaileys();+ applyNewsletterCreatePatch(dir);+ const parsed = load(file)({+ ...REAL_RESPONSE,+ thread_metadata: {+ ...REAL_RESPONSE.thread_metadata,+ description: { text: 'notes' },+ picture: { id: 'pic-1', direct_path: '/v/t61/pic' },+ },+ });+ assert.deepEqual(parsed.picture, { id: 'pic-1', directPath: '/v/t61/pic' });+ assert.equal(parsed.description, 'notes');+ fs.rmSync(dir, { recursive: true, force: true });+});++test('is idempotent — a second run does not double-patch', () => {+ const { dir, file } = fakeBaileys();+ applyNewsletterCreatePatch(dir);+ const once = fs.readFileSync(file, 'utf8');+ const second = applyNewsletterCreatePatch(dir);+ assert.equal(second.skipped, true);+ assert.equal(second.reason, 'already patched');+ assert.equal(fs.readFileSync(file, 'utf8'), once);+ fs.rmSync(dir, { recursive: true, force: true });+});++test('refuses an unknown shape rather than shipping unpatched', () => {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'baileys-newsletter-'));+ fs.mkdirSync(path.join(dir, 'lib', 'Socket'), { recursive: true });+ fs.writeFileSync(path.join(dir, 'lib', 'Socket', 'newsletter.js'), 'const x = 1;\n');+ assert.throws(() => applyNewsletterCreatePatch(dir), /expected exactly 1 newsletter-create parse site/);+ fs.rmSync(dir, { recursive: true, force: true });+});++test('skips a tree with no baileys rather than failing the install', () => {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'baileys-newsletter-'));+ const result = applyNewsletterCreatePatch(dir);+ assert.equal(result.skipped, true);+ assert.match(result.reason, /not found/);+ fs.rmSync(dir, { recursive: true, force: true });+});++test('the marker the idempotence check keys on is actually written', () => {+ const { dir, file } = fakeBaileys();+ applyNewsletterCreatePatch(dir);+ assert.ok(fs.readFileSync(file, 'utf8').includes(MARKER));+ fs.rmSync(dir, { recursive: true, force: true });+});diff --git a/scripts/postinstall.js b/scripts/postinstall.jsindex 033b5c23d..091f1bb3a 100644--- a/scripts/postinstall.js+++ b/scripts/postinstall.js@@ -1,7 +1,7 @@/*** Post-install hook (npm `postinstall`).*- * Six conditional steps, each skipped when its target is absent so the hook is a no-op where the+ * Seven conditional steps, each skipped when its target is absent so the hook is a no-op where the* piece is missing (the Docker builder stage copies package*.json long before any source):** 1. `npm ci` inside dashboard/ when dashboard/ exists — the dashboard carries its own lockfile and@@ -22,8 +22,10 @@* 5. `node scripts/patch-wwebjs-ready-sync.js --best-effort` when present — the readiness* marker + hasSynced level-check, gated the same way.* 6. `node scripts/patch-baileys-appstate.js --best-effort` when present — the app-state resync- * bound, gated the same way. This is the one step that is not a whatsapp-web.js patch, so a- * Baileys-only install runs it and skips 2-5.+ * bound, gated the same way.+ * 7. `node scripts/patch-baileys-newsletter-create.js --best-effort` when present — the+ * newsletter-create parse fix. Steps 6-7 are the Baileys patches, so a Baileys-only install+ * runs those and skips 2-5.** Structured like scripts/patch-wwebjs-201832.js: pure planning + injectable spawn, so the spec* (scripts/postinstall.spec.js, node:test) exercises every branch without a real npm run.@@ -112,6 +114,15 @@ function planSteps(root, env = process.env) {options: { stdio: 'inherit', cwd: root, env: cleanEnv },});}+ const baileysNewsletterPatcher = path.join(root, 'scripts', 'patch-baileys-newsletter-create.js');+ if (fs.existsSync(baileysNewsletterPatcher)) {+ steps.push({+ name: 'Baileys newsletter-create parse fix (scripts/patch-baileys-newsletter-create.js --best-effort)',+ command: process.execPath,+ args: [baileysNewsletterPatcher, '--best-effort'],+ options: { stdio: 'inherit', cwd: root, env: cleanEnv },+ });+ }return steps;}