Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
feat(audit): record a WhatsApp-initiated unlink in the audit log
Yudhi Armyndharis62a2aed0fafe
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 9e1d4bad3..35f53a640 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -9,6 +9,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Added+- **A WhatsApp-initiated unlink now leaves a durable audit record** — the disconnect reason previously reached only the log, the webhook and the socket, so once the process restarted an unlink was indistinguishable over the API from an ordinary network drop; transient drops stay unaudited, so a reconnect storm still writes nothing.- **The Go SDK has its first semantic version, `sdk/go/v0.2.0`** — until now the module proxy only served pseudo-versions, so callers could not pin a release at all.- **`rmyndharis-openwa` 0.2.0 on PyPI** — the first release through the trusted-publishing workflow, carrying everything the Python SDK gained since 0.1.0 in June.- **`rmyndharis/openwa` 0.2.0 on Packagist** — the first versioned PHP release since June; Composer users on a stable constraint were pinned to 0.1.0 while only `dev-main` moved.diff --git a/src/modules/audit/intentionally-unemitted-actions.ts b/src/modules/audit/intentionally-unemitted-actions.tsindex 10652aa75..cb61a430c 100644--- a/src/modules/audit/intentionally-unemitted-actions.ts+++ b/src/modules/audit/intentionally-unemitted-actions.ts@@ -18,8 +18,6 @@ export const INTENTIONALLY_UNEMITTED_ACTIONS: Partial<Record<AuditAction, string'Not emitted: would fire on every authenticated request, which is too high-volume for the audit log. Authentication failures are audited (API_KEY_AUTH_FAILED); successful authentication is intentionally not.',[AuditAction.SESSION_CONNECTED]:'Not emitted: an engine-level lifecycle transition, redundant with sessions.status and the SessionEngineLifecycle lastDispatchedStatus map. User-initiated lifecycle (SESSION_STARTED / SESSION_STOPPED) is audited.',- [AuditAction.SESSION_DISCONNECTED]:- 'Not emitted: an engine-level lifecycle transition, redundant with sessions.status and the SessionEngineLifecycle lastDispatchedStatus map; reconnect storms would flood the audit log.',[AuditAction.MESSAGE_SENT]:'Not emitted: per outbound message, fully redundant with the messages table, which persists every send with its outcome.',[AuditAction.MESSAGE_FAILED]:diff --git a/src/modules/session/session-engine-lifecycle.service.ts b/src/modules/session/session-engine-lifecycle.service.tsindex 14977c400..cf75c7651 100644--- a/src/modules/session/session-engine-lifecycle.service.ts+++ b/src/modules/session/session-engine-lifecycle.service.ts@@ -116,6 +116,19 @@ function isAuthTimeoutRejection(err: unknown): boolean {return err === ENGINE_AUTH_TIMEOUT || (err instanceof Error && err.message === ENGINE_AUTH_TIMEOUT);}+/**+ * Disconnect reasons that mean WhatsApp revoked this device, as opposed to a link that merely+ * dropped. Only these are audited (#1107): they are one-shot and terminal — no reconnect can+ * restore the link, only a fresh QR can — so they cannot produce the per-attempt flood that keeps+ * the rest of the disconnect transitions out of the audit log.+ *+ * Deliberately not CONFLICT (another device took over, and takeover is recoverable), not+ * DEPRECATED_VERSION (our own client is too old), and not TIMEOUT (a fault, and the single most+ * common reconnect-storm reason). Mirrors how the whatsapp-web.js adapter classifies the same+ * states; the Baileys adapter reports its own logout through the same callback.+ */+const TERMINAL_UNLINK_REASONS = new Set(['LOGOUT', 'UNPAIRED', 'UNPAIRED_IDLE']);+/*** Owns the live WhatsApp engines and every state machine around them: start/stop/logout/forceKill,* delete's engine retirement, reconnect backoff, engine-event wiring, and the credential-teardown /@@ -760,6 +773,21 @@ export class SessionEngineLifecycle {action: 'disconnected',});+ // #1107: everything else this method does with `reason` is ephemeral — a log line, a webhook, a+ // socket emit, a plugin hook — and the only DB write below is the status. So once the process+ // restarts, a WhatsApp unlink is indistinguishable over the API from a network drop: both read+ // `disconnected` with a null `lastError`. Audit the unlinks, and only those. That is the same+ // test SESSION_RESTRICTED already passes next door — rare, not reconnect noise, no other durable+ // record — and it keeps the objection that keeps the rest unemitted intact, since a flapping+ // connection retries with TIMEOUT/NAVIGATION and never with one of these.+ if (TERMINAL_UNLINK_REASONS.has(reason)) {+ void this.auditService?.logWarn(AuditAction.SESSION_DISCONNECTED, {+ sessionId: id,+ metadata: { reason },+ errorMessage: `WhatsApp unlinked this device (${reason}); the session must be re-paired with a fresh QR`,+ });+ }+void this.webhookService.dispatch(id, 'session.disconnected', { sessionId: id, reason });this.eventsGateway.emitSessionDisconnected(id, { reason });diff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.tsindex e4639d3e4..935cf0c95 100644--- a/src/modules/session/session.service.spec.ts+++ b/src/modules/session/session.service.spec.ts@@ -2637,6 +2637,82 @@ describe('SessionService', () => {expect(eventsGateway.emitSessionDisconnected).toHaveBeenCalledWith('sess-uuid-1', { reason: 'socket closed' });});+ // #1107: the reason reaches the log, the webhook, the socket and the plugin hook, and stops+ // there — the only DB write on this path is the status. So an operator reading the session+ // afterwards cannot tell a WhatsApp unlink from a network drop: both are `disconnected` with a+ // null `lastError`. An unlink is rare, is not reconnect noise, and has no other durable record,+ // which is the same test that already earns SESSION_RESTRICTED its audit row.+ const disconnectAndFlush = async (callbacks: EngineEventCallbacks, reason: string): Promise<void> => {+ callbacks.onDisconnected?.(reason);+ // The handler re-reads the session row before publishing, so the audit lands after the findOne.+ await new Promise(resolve => setImmediate(resolve));+ };++ it.each(['LOGOUT', 'UNPAIRED', 'UNPAIRED_IDLE'])(+ 'writes a durable audit record for a terminal unlink (%s)',+ async reason => {+ const callbacks = await startAndCapture();+ jest+ .spyOn(lifecycle as unknown as { scheduleReconnect: (id: string, s: unknown) => void }, 'scheduleReconnect')+ .mockImplementation(() => {});+ auditService.logWarn.mockClear();++ await disconnectAndFlush(callbacks, reason);++ // Assert the call before destructuring it: an absent call would otherwise surface as an+ // unreadable TypeError on the array pattern rather than as the missing audit row.+ expect(auditService.logWarn).toHaveBeenCalledTimes(1);+ const [action, context] = auditCall(auditService.logWarn);+ expect(action).toBe('session_disconnected');+ expect(context.sessionId).toBe('sess-uuid-1');+ expect(context.metadata).toMatchObject({ reason });+ },+ );++ // The reason this action was left unemitted until now: a flapping connection retries forever,+ // and a row per attempt would bury the one that matters. Filtering to the unlinks keeps that+ // objection answered — a storm is TIMEOUT/NAVIGATION, never LOGOUT.+ it.each(['TIMEOUT', 'NAVIGATION', 'socket closed'])('does not audit a transient drop (%s)', async reason => {+ const callbacks = await startAndCapture();+ jest+ .spyOn(lifecycle as unknown as { scheduleReconnect: (id: string, s: unknown) => void }, 'scheduleReconnect')+ .mockImplementation(() => {});+ auditService.logWarn.mockClear();++ await disconnectAndFlush(callbacks, reason);++ expect(auditService.logWarn).not.toHaveBeenCalled();+ });++ // The audit row is a disconnect side effect like the webhook and the socket emit, so it belongs+ // behind the SAME post-await identity fence. Superseding before the call would only exercise the+ // wiring's entry check, which would pass wherever the emit sat — so supersede the engine while+ // the handler is parked on its session reload, the one window that discriminates the placement.+ it('does not audit an unlink from an engine superseded during the async session reload', async () => {+ const callbacks = await startAndCapture();+ jest+ .spyOn(lifecycle as unknown as { scheduleReconnect: (id: string, s: unknown) => void }, 'scheduleReconnect')+ .mockImplementation(() => {});+ let resolveReload!: (value: Session | null) => void;+ (repository.findOne as jest.Mock).mockImplementation(+ () =>+ new Promise<Session | null>(resolve => {+ resolveReload = resolve;+ }),+ );+ auditService.logWarn.mockClear();++ // Still the live owner here, so the handler proceeds past its entry fence and parks.+ const handled = Promise.resolve(callbacks.onDisconnected?.('LOGOUT'));+ enginesOf().set('sess-uuid-1', { marker: 'engine-B' });+ await Promise.resolve();+ await Promise.resolve();+ resolveReload(createMockSession({ status: SessionStatus.READY }));+ await handled;++ expect(auditService.logWarn).not.toHaveBeenCalled();+ });+it('ignores onReady from an engine that was torn down (post-stop window)', async () => {const callbacks = await startAndCapture();enginesOf().delete('sess-uuid-1'); // stop()/forceKill() removes the engine from the live map