Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(engine): gate the wwjs pairing code on QR readiness, not on the client existing
Yudhi Armyndharisa5f640010763
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 6b151eb79..e752cbddc 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -33,6 +33,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0- The engine parity check no longer skips optional interface members. `probeLiveness?()` did not match its member pattern, so the capability matrix could omit any optional method while the check reported green; it now has a row recording that wwjs probes with a real round trip and Baileys with a local check.- `.env.example` and the troubleshooting FAQ no longer name a specific WhatsApp Web build to pin with `WWEBJS_WEB_VERSION`. The build they named has since been withdrawn from the registry, and a build the registry no longer serves is fetched, missed and silently ignored — so an operator following the FAQ's own workaround got the default behaviour while the log claimed the pin had been applied. Both now point at the registry's `html/` folder for a build that is currently served.- A WhatsApp Web build that cannot be resolved from the wa-version registry is now reported (`web_version_resolve_failed`) with the reason, the registry URL and the remedy. A host that cannot reach the registry — a proxy, a firewalled VPS, regional blocking — silently continued without a pin and let whatsapp-web.js pick the build itself, which is the "authenticates then never reaches ready" class the pin exists to prevent; nothing was logged, so there was nothing to grep for. The existing one-minute backoff already bounds how often the warning can repeat.+- `POST /sessions/:id/pairing-code` answers `409` while a whatsapp-web.js session is still starting up, instead of a `500` carrying a raw `TypeError`. The engine stored its client before launching Chromium, so for the whole launch — seconds on a modest host — the route passed its only guard and reached into a browser page that did not exist yet. Requesting a code straight after `POST /start`, which is what the dashboard's linking modal invites, landed in exactly that window. The request is now accepted only once the session reaches `qr_ready`, the state the pairing flow needs anyway.### Securitydiff --git a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts b/src/engine/adapters/whatsapp-web-js.adapter.spec.tsindex 640769595..cc475420b 100644--- a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts+++ b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts@@ -551,6 +551,58 @@ describe('WhatsAppWebJsAdapter readiness guard (#100)', () => {});});+describe('WhatsAppWebJsAdapter.requestPairingCode readiness', () => {+ /**+ * A whatsapp-web.js Client as it exists between `new Client(...)` and the browser being up: the+ * adapter has already stored it (`this.client = client` runs before `client.initialize()`), but+ * `pupPage` is still null. Calling requestPairingCode on it reaches+ * `exposeFunctionIfAbsent(this.pupPage, ...)` → `page.evaluate(...)` and throws — the fixture+ * reproduces the library's own rejection rather than inventing one.+ */+ const clientBeforeItsPageExists = () => ({+ pupPage: null,+ requestPairingCode: jest.fn(() =>+ Promise.reject(new TypeError("Cannot read properties of null (reading 'evaluate')")),+ ),+ });++ const adapterWith = (status: EngineStatus, client: unknown): WhatsAppWebJsAdapter => {+ const adapter = new WhatsAppWebJsAdapter({ sessionId: 's', sessionDataPath: './data/sessions', puppeteer: {} });+ (adapter as unknown as { status: EngineStatus }).status = status;+ (adapter as unknown as { client: unknown }).client = client;+ return adapter;+ };++ it('rejects with EngineNotReadyError while the client exists but its page does not', async () => {+ const client = clientBeforeItsPageExists();+ const adapter = adapterWith(EngineStatus.INITIALIZING, client);++ await expect(adapter.requestPairingCode('628123456789')).rejects.toBeInstanceOf(EngineNotReadyError);+ });++ it('does not reach into the library while the page is still absent', async () => {+ const client = clientBeforeItsPageExists();+ const adapter = adapterWith(EngineStatus.INITIALIZING, client);++ await expect(adapter.requestPairingCode('628123456789')).rejects.toThrow();+ expect(client.requestPairingCode).not.toHaveBeenCalled();+ });++ it('delegates to the client once the session is showing a QR', async () => {+ const client = { pupPage: {}, requestPairingCode: jest.fn().mockResolvedValue('ABCD1234') };+ const adapter = adapterWith(EngineStatus.QR_READY, client);++ await expect(adapter.requestPairingCode('628123456789')).resolves.toBe('ABCD1234');+ expect(client.requestPairingCode).toHaveBeenCalledWith('628123456789');+ });++ it('still rejects when there is no client at all', async () => {+ const adapter = adapterWith(EngineStatus.DISCONNECTED, null);++ await expect(adapter.requestPairingCode('628123456789')).rejects.toBeInstanceOf(EngineNotReadyError);+ });+});+describe('WhatsAppWebJsAdapter.getChatHistory enrichment (parity with the live path)', () => {const readyAdapter = (client: unknown): WhatsAppWebJsAdapter => {const adapter = new WhatsAppWebJsAdapter({ sessionId: 's', sessionDataPath: './data/sessions', puppeteer: {} });diff --git a/src/engine/adapters/whatsapp-web-js.adapter.ts b/src/engine/adapters/whatsapp-web-js.adapter.tsindex 976411eb5..ee2ddfa1e 100644--- a/src/engine/adapters/whatsapp-web-js.adapter.ts+++ b/src/engine/adapters/whatsapp-web-js.adapter.ts@@ -1745,12 +1745,19 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin/*** Request an 8-char pairing code so the user can link via "Link with phone number" instead of- * scanning the QR. Must be called after the engine has started (the client is initialized and- * waiting to link); whatsapp-web.js throws if called before it is ready or after authentication.+ * scanning the QR.+ *+ * Gated on QR_READY, not on the client merely existing. `this.client` is assigned before+ * `client.initialize()` (see runInitAttempt), so for the whole Chromium launch — seconds on a+ * modest host — a client is present while its `pupPage` is still null, and whatsapp-web.js's+ * requestPairingCode reaches `exposeFunctionIfAbsent(this.pupPage, …)` and throws a raw TypeError+ * that surfaces as a 500. QR_READY is the precise window this can work in anyway: the library+ * emits 'qr' only once the Store is injected and the in-page socket reports UNPAIRED, which are+ * the same preconditions the pairing flow needs.*/async requestPairingCode(phoneNumber: string): Promise<string> {- if (!this.client) {- throw new EngineNotReadyError();+ if (!this.client || this.status !== EngineStatus.QR_READY) {+ throw new EngineNotReadyError('Session is not waiting to be linked. Start it and wait for the QR stage.');}return this.client.requestPairingCode(phoneNumber);}