Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

feat(wwebjs): report a session whose call hook never installed

Yudhi Armyndharisa2db9ab3c281
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 889862535..858361d13 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -18,6 +18,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed
+- A whatsapp-web.js session that comes up without its page-side call hook says so in the log instead of silently never reporting an incoming call. The hook is installed last in the same page evaluate as the message listeners, so the session stays healthy for messages either way ([#1655](https://github.com/rmyndharis/OpenWA/issues/1655)).
- Stopping, unlinking or force-killing a session announces `session.status: disconnected` after the engine is released, not while it is still tearing down, so a dashboard tab or a webhook consumer no longer learns the session is down in the one moment the API still reports its engine as loaded. On whatsapp-web.js that window lasted as long as Chromium took to close, and left an open QR modal on a dead code with the started actions still offered ([#1649](https://github.com/rmyndharis/OpenWA/issues/1649)).
- The dashboard blanks a session's displayed QR code as soon as the session disconnects, so a code minted by a connection that is gone is never left on screen to be scanned ([#1649](https://github.com/rmyndharis/OpenWA/issues/1649)).
- A pairing-code request whose retry budget runs out on a reloading WhatsApp Web page answers `503` instead of `500`, so a client can tell a retryable transport failure from a broken gateway ([#1654](https://github.com/rmyndharis/OpenWA/issues/1654)).
diff --git a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
index 6c38e37b7..93890841c 100644
--- a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
+++ b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
@@ -2351,6 +2351,62 @@ describe('WhatsAppWebJsAdapter ready reconciliation (#251/#273)', () => {
rmSpy.mockRestore();
});
+ // #1655: a session can be perfectly healthy for messages and unable to see a single incoming call,
+ // because whatsapp-web.js installs the call hook last in the same page evaluate as the message
+ // listeners. The page read that settles it is one line, so ready says it instead of staying quiet.
+ it('warns at ready when the page carries no call hook', async () => {
+ const adapter = newAdapter();
+ const logger = (adapter as unknown as { logger: { warn: jest.Mock } }).logger;
+ const warnSpy = jest.spyOn(logger, 'warn').mockImplementation(() => undefined);
+ // The probe stringifies the collection's Map.set; an untouched one reports native code.
+ const lifecycle = (
+ adapter as unknown as {
+ lifecycle: { client: unknown; status: EngineStatus; markReadyFromClientInfo: () => void };
+ }
+ ).lifecycle;
+ // The promotion early-returns from a terminal status, and a fresh adapter starts DISCONNECTED.
+ lifecycle.status = EngineStatus.AUTHENTICATING;
+ lifecycle.client = {
+ info: { wid: { user: '628123' }, pushname: 'Tester' },
+ pupPage: { evaluate: jest.fn().mockResolvedValue(false) },
+ };
+
+ lifecycle.markReadyFromClientInfo();
+ await new Promise(resolve => setImmediate(resolve));
+
+ const missing = warnSpy.mock.calls.find(
+ ([, meta]) => (meta as { action?: string })?.action === 'call_hook_missing',
+ );
+ expect(missing).toBeDefined();
+ expect(missing?.[1]).toMatchObject({ sessionId: 'sess-1' });
+ warnSpy.mockRestore();
+ });
+
+ it('stays quiet at ready when the call hook is installed', async () => {
+ const adapter = newAdapter();
+ const logger = (adapter as unknown as { logger: { warn: jest.Mock } }).logger;
+ const warnSpy = jest.spyOn(logger, 'warn').mockImplementation(() => undefined);
+ const lifecycle = (
+ adapter as unknown as {
+ lifecycle: { client: unknown; status: EngineStatus; markReadyFromClientInfo: () => void };
+ }
+ ).lifecycle;
+ // The promotion early-returns from a terminal status, and a fresh adapter starts DISCONNECTED.
+ lifecycle.status = EngineStatus.AUTHENTICATING;
+ lifecycle.client = {
+ info: { wid: { user: '628123' }, pushname: 'Tester' },
+ pupPage: { evaluate: jest.fn().mockResolvedValue(true) },
+ };
+
+ lifecycle.markReadyFromClientInfo();
+ await new Promise(resolve => setImmediate(resolve));
+
+ expect(
+ warnSpy.mock.calls.find(([, meta]) => (meta as { action?: string })?.action === 'call_hook_missing'),
+ ).toBeUndefined();
+ warnSpy.mockRestore();
+ });
+
// #981: clearing the auth dir destroys the ONLY copy of the session's WhatsApp credentials, and the
// loss is permanent — every later start finds an empty profile and can only show a QR. Until now the
// adapter logged only the FAILURE to delete, so a successful wipe left no trace at all and triage
diff --git a/src/engine/adapters/wwebjs-call-hook-check.spec.ts b/src/engine/adapters/wwebjs-call-hook-check.spec.ts
new file mode 100644
index 000000000..b0f102a80
--- /dev/null
+++ b/src/engine/adapters/wwebjs-call-hook-check.spec.ts
@@ -0,0 +1,46 @@
+import { reportMissingCallHook } from './wwebjs-call-hook-check';
+
+/**
+ * whatsapp-web.js detects an incoming call by patching ONE page function: the call collection's
+ * internal `Map.set`. It installs that patch in the same `evaluate` as the message listeners, with
+ * no try/catch, so anything that throws earlier in that evaluate leaves messages working and calls
+ * undetectable, with nothing in the log to say so. This check turns that silence into a warning.
+ */
+describe('reportMissingCallHook', () => {
+ const makeLogger = (): { warn: jest.Mock; debug: jest.Mock } => ({ warn: jest.fn(), debug: jest.fn() });
+
+ it('warns when the page still has the untouched set', async () => {
+ const logger = makeLogger();
+ const page = { evaluate: jest.fn().mockResolvedValue(false) };
+ await reportMissingCallHook(page, logger as never, 'sess-1');
+ expect(logger.warn).toHaveBeenCalledTimes(1);
+ expect((logger.warn.mock.calls[0] as [string, Record<string, unknown>])[1]).toMatchObject({
+ sessionId: 'sess-1',
+ action: 'call_hook_missing',
+ });
+ });
+
+ it('stays silent when the hook is installed', async () => {
+ const logger = makeLogger();
+ const page = { evaluate: jest.fn().mockResolvedValue(true) };
+ await reportMissingCallHook(page, logger as never, 'sess-1');
+ expect(logger.warn).not.toHaveBeenCalled();
+ });
+
+ // An inconclusive read is not evidence of a missing hook: the collection may not be in the page's
+ // module graph at all. Saying "calls are broken" on that would send operators after a non-problem.
+ it('stays silent when the probe cannot decide', async () => {
+ const logger = makeLogger();
+ const page = { evaluate: jest.fn().mockResolvedValue(null) };
+ await reportMissingCallHook(page, logger as never, 'sess-1');
+ expect(logger.warn).not.toHaveBeenCalled();
+ });
+
+ it('never throws when the page is gone or the read fails', async () => {
+ const logger = makeLogger();
+ await reportMissingCallHook(undefined, logger as never, 'sess-1');
+ const dead = { evaluate: jest.fn().mockRejectedValue(new Error('Session closed')) };
+ await reportMissingCallHook(dead, logger as never, 'sess-1');
+ expect(logger.warn).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/engine/adapters/wwebjs-call-hook-check.ts b/src/engine/adapters/wwebjs-call-hook-check.ts
new file mode 100644
index 000000000..8d3cf3c42
--- /dev/null
+++ b/src/engine/adapters/wwebjs-call-hook-check.ts
@@ -0,0 +1,63 @@
+import { type createLogger } from '../../common/services/logger.service';
+
+/** The narrow slice of the Puppeteer page this check needs, so nothing here depends on puppeteer. */
+export interface EvaluatablePage {
+ evaluate<T>(fn: () => T): Promise<T>;
+}
+
+/**
+ * Page-side probe: is whatsapp-web.js' incoming-call hook installed on this page?
+ *
+ * The library detects a call by replacing ONE function, the call collection's internal `Map.set`
+ * (`Client.js`, attachEventListeners). A patched `set` is a JS function; an untouched one stringifies
+ * with `[native code]`. Returns `null` when the collection is not in the page's module graph at all,
+ * which is not the same answer as "the hook is missing".
+ */
+function readCallHookState(): boolean | null {
+ const w = window as unknown as { require?: (name: string) => Record<string, unknown> | undefined };
+ if (typeof w.require !== 'function') return null;
+ let collection: Record<string, unknown> | undefined;
+ try {
+ collection = w.require('WAWebCallCollection');
+ } catch {
+ return null;
+ }
+ if (!collection) return null;
+ const owned = collection;
+ const mapKey = Object.keys(owned).find(key => owned[key] instanceof Map);
+ if (!mapKey) return null;
+ const setter = (owned[mapKey] as { set: unknown }).set;
+ return !String(setter).includes('[native code]');
+}
+
+/**
+ * Warn when a ready session's page carries no call hook.
+ *
+ * whatsapp-web.js installs the call hook in the same `evaluate` as its message listeners, and that
+ * evaluate has no `try`/`catch`: a module that stops resolving earlier in it leaves the message
+ * bridge registered and the call hook silently absent. The session then looks completely healthy,
+ * keeps delivering messages, and never reports a single incoming call. Operators have no way to see
+ * that from the outside, so say it in the log.
+ *
+ * Deliberately advisory: it never changes the session's status. Detection is the only thing lost,
+ * and a false alarm on an inconclusive read would send operators after a problem they do not have.
+ */
+export async function reportMissingCallHook(
+ page: EvaluatablePage | undefined,
+ logger: ReturnType<typeof createLogger>,
+ sessionId: string,
+): Promise<void> {
+ if (!page) return;
+ let installed: boolean | null;
+ try {
+ installed = await page.evaluate(readCallHookState);
+ } catch {
+ return; // a page that died mid-read says nothing about the hook
+ }
+ if (installed !== false) return;
+ logger.warn(
+ 'Incoming calls cannot be detected on this session: the page-side call hook is not installed. ' +
+ 'Messages are unaffected; restart the session to reinject it.',
+ { sessionId, action: 'call_hook_missing' },
+ );
+}
diff --git a/src/engine/adapters/wwebjs-lifecycle.ts b/src/engine/adapters/wwebjs-lifecycle.ts
index 607bd5c7e..0c6aee180 100644
--- a/src/engine/adapters/wwebjs-lifecycle.ts
+++ b/src/engine/adapters/wwebjs-lifecycle.ts
@@ -17,6 +17,7 @@ import { killOrphanedChromiumProcesses, removeStaleSingletonFiles } from './chro
import { isSupportedProxyUrl, buildProxyLaunchConfig } from './wwebjs-proxy';
import { BACKPORT_MISSING_MESSAGE, isBackportMissing } from './wwebjs-backport-check';
import { unappliedPatches, unappliedPatchesMessage } from './engine-patch-status';
+import { reportMissingCallHook } from './wwebjs-call-hook-check';
import { type WhatsAppWebJsConfig } from './whatsapp-web-js.adapter';
import { AUTH_FAILURE_REASON, STALE_PROFILE_ADVICE } from '../terminal-engine-failure';
import { wwjsAuthDir } from '../auth-dir-paths';
@@ -787,6 +788,17 @@ export class WwebjsLifecycle {
// gets the companion unlinked (~5m later → disconnected: LOGOUT, #982). Dismiss it best-effort
// and fall back to ACTION_REQUIRED. Started after READY so a non-ready session never arms it.
this.host.startOnboardingWatcher();
+ // whatsapp-web.js installs its incoming-call hook as the LAST statement of the same page
+ // evaluate that registers the message listeners, and that evaluate has no try/catch: a module
+ // that stops resolving earlier in it leaves the message bridge live and the call hook absent.
+ // The session then looks healthy, keeps delivering messages, and reports no call at all. Warn
+ // once per ready rather than leaving that silent; nothing else changes, since only detection is
+ // lost. Fire-and-forget: a diagnostic must never delay or fail the promotion to READY.
+ void reportMissingCallHook(
+ (this.client as unknown as { pupPage?: { evaluate: <T>(fn: () => T) => Promise<T> } } | null)?.pupPage,
+ this.host.logger,
+ this.host.config.sessionId,
+ );
}
/** The single status-transition funnel: latches disconnectReported, fires the callback, re-emits