Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
feat(session): warn when a linked session comes back asking for a QR
Yudhi Armyndharis0d260985aa7d
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex b96cf09a0..1812b77c8 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]+### Added++- A previously linked session that comes back asking for a QR now logs a warning (`relink_required`) naming the+ likely causes, since an unlink that happened while the engine was down can leave no other trace.+### Changed- `POST /sessions/{sessionId}/pairing-code`: the 409 description in the OpenAPI contract and API referencediff --git a/src/modules/session/session-engine-event-wiring.ts b/src/modules/session/session-engine-event-wiring.tsindex 48ef9751f..ebe5e2895 100644--- a/src/modules/session/session-engine-event-wiring.ts+++ b/src/modules/session/session-engine-event-wiring.ts@@ -85,12 +85,20 @@ export class SessionEngineEventWiring {this.logger = deps.logger;}+ /**+ * `previouslyLinked` is whether the session row carried a phone when this engine started, i.e.+ * it had completed a link before. A QR from such an engine means the stored credentials are gone+ * or no longer accepted, and when that happened while the engine was down nothing else in the+ * log says so, hence the one-shot warning below.+ */buildCallbacks(id: string,engine: IWhatsAppEngine,sessionName: string,host: SessionEngineWiringHost,+ previouslyLinked = false,): EngineEventCallbacks {+ let relinkWarned = false;/*** Persist an engine-driven status, but only while this node still owns the session.*@@ -119,6 +127,22 @@ export class SessionEngineEventWiring {sessionId: id,action: 'qr_generated',});+ // A whatsapp-web.js revocation that happened while the engine was down leaves no other trace:+ // the engine simply boots into the QR screen, with no LOGOUT, no auth failure and no audit+ // row. The paths where OpenWA itself discarded the credentials (a LOGOUT close, the+ // stuck-auth recovery) also end here, but each of those has already logged its own warning,+ // and starting a session under a different ENGINE_TYPE than it was linked with lands here too.+ if (previouslyLinked && !relinkWarned) {+ relinkWarned = true;+ this.logger.warn(+ 'Previously linked session is asking for a QR again: its stored credentials are missing or no ' ++ 'longer accepted. Unless an earlier warning for this session (LOGOUT, auth_cleared) or a changed ' ++ 'ENGINE_TYPE explains it, WhatsApp dropped the link while the engine was down (unlinked from the ' ++ "phone, expired while offline, or the engine's stored auth state was lost). Check Linked devices " ++ 'on the phone before re-pairing.',+ { sessionId: id, action: 'relink_required' },+ );+ }void host.webhookService.dispatch(id, 'session.qr', { sessionId: id, qr });diff --git a/src/modules/session/session-engine-lifecycle.service.ts b/src/modules/session/session-engine-lifecycle.service.tsindex 3b44e6016..8be6f79a1 100644--- a/src/modules/session/session-engine-lifecycle.service.ts+++ b/src/modules/session/session-engine-lifecycle.service.ts@@ -597,7 +597,9 @@ export class SessionEngineLifecycle {// order, and the synchronous one-shot stuck-auth claim are preserved there, reaching the// lifecycle's live methods/state through the wiringHost built in the constructor.// `session.name` is handed over as the immutable snapshot onCredentialTeardownStarted keys on.- const initPromise = engine.initialize(this.eventWiring.buildCallbacks(id, engine, session.name, this.wiringHost));+ const initPromise = engine.initialize(+ this.eventWiring.buildCallbacks(id, engine, session.name, this.wiringHost, Boolean(session.phone)),+ );// engine.initialize() launches Chromium and navigates to WhatsApp Web with no internal timeout:// whatsapp-web.js calls page.goto(..., { timeout: 0 }) and its web-version-cache fetch has nonediff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.tsindex 73713e650..a13d10183 100644--- a/src/modules/session/session.service.spec.ts+++ b/src/modules/session/session.service.spec.ts@@ -4275,6 +4275,39 @@ describe('SessionService', () => {expect(qr[0][2]).toMatchObject({ sessionId: 'sess-uuid-1', qr: 'qr-data-abc' });});+ // An unlink that happened while the engine was down leaves no LOGOUT, no auth failure and no+ // audit row: the engine just boots into the QR screen. The warning is the only trace of it.+ const relinkWarnings = (warn: jest.SpyInstance): unknown[][] =>+ (warn.mock.calls as unknown[][]).filter(+ ([, ctx]) => (ctx as { action?: string } | undefined)?.action === 'relink_required',+ );++ it('warns once (relink_required) when a previously linked session comes back asking for a QR', async () => {+ const warn = jest.spyOn((lifecycle as unknown as { logger: { warn: (...a: unknown[]) => void } }).logger, 'warn');+ (repository.findOne as jest.Mock).mockResolvedValue(createMockSession({ phone: '628123' }));+ (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });+ await service.start('sess-uuid-1');+ const callbacks = (mockEngine.initialize.mock.calls as [EngineEventCallbacks][])[0][0];++ callbacks.onQRCode!('qr-1');+ callbacks.onQRCode!('qr-2'); // periodic refresh: not a second warning+ await flush();++ const warned = relinkWarnings(warn);+ expect(warned).toHaveLength(1);+ expect(warned[0][1]).toMatchObject({ sessionId: 'sess-uuid-1', action: 'relink_required' });+ });++ it('does not warn about relinking when the session had never been linked', async () => {+ const warn = jest.spyOn((lifecycle as unknown as { logger: { warn: (...a: unknown[]) => void } }).logger, 'warn');+ const callbacks = await startAndCaptureCallbacks(); // fixture row has phone: null++ callbacks.onQRCode!('qr-1');+ await flush();++ expect(relinkWarnings(warn)).toHaveLength(0);+ });+it('dispatches session.authenticated with phone/pushName when the engine reports ready', async () => {const callbacks = await startAndCaptureCallbacks();expect(typeof callbacks.onReady).toBe('function');