Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(baileys): report a socket torn down mid-send as not ready

Yudhi Armyndharis1cd47d531ac9
diff --git a/src/engine/adapters/baileys.adapter.spec.ts b/src/engine/adapters/baileys.adapter.spec.ts
index 3493abf65..b393613bc 100644
--- a/src/engine/adapters/baileys.adapter.spec.ts
+++ b/src/engine/adapters/baileys.adapter.spec.ts
@@ -651,6 +651,18 @@ describe('BaileysAdapter lifecycle & status', () => {
}
});
+ // A send that passed ensureReady() reads the socket again after its awaits (media fetch, quote lookup,
+ // lid resolution); a stop or logout in between must surface as a 409, not a TypeError that feeds the
+ // send breaker as an account failure.
+ it('a socket torn down after the readiness check reads as not ready, not as a null socket', async () => {
+ const adapter = newAdapter();
+ await adapter.initialize(noopCallbacks({}));
+ const host = (adapter as unknown as { messaging: { host: { getSocket(): unknown } } }).messaging.host;
+ expect(host.getSocket()).toBe(fakeSock);
+ (adapter as unknown as { sock: unknown }).sock = null;
+ expect(() => host.getSocket()).toThrow(EngineNotReadyError);
+ });
+
it('on a recoverable close: reconnects (re-creates the socket) and does NOT fire onDisconnected', async () => {
const onDisconnected = jest.fn();
const adapter = newAdapter();
diff --git a/src/engine/adapters/baileys.adapter.ts b/src/engine/adapters/baileys.adapter.ts
index 511006339..b75594266 100644
--- a/src/engine/adapters/baileys.adapter.ts
+++ b/src/engine/adapters/baileys.adapter.ts
@@ -1,4 +1,5 @@
import { ChatLabelsUnsupportedError } from '../../common/errors/chat-labels-unsupported.error';
+import { EngineNotReadyError } from '../../common/errors/engine-not-ready.error';
import { isChannelJid } from '../identity/wa-id';
import type * as BaileysLib from '@whiskeysockets/baileys';
import type { WASocket } from '@whiskeysockets/baileys';
@@ -120,7 +121,12 @@ export class BaileysAdapter implements IWhatsAppEngine {
// interface, which this literal satisfies structurally - least privilege stays enforceable.
const delegates: { events?: BaileysEvents } = {};
const host: BaileysEngineHost = {
- getSocket: () => this.sock!,
+ // Read after a delegate's awaits too, when a stop or logout may have torn the socket down since
+ // its readiness check: that is a not-ready session (409), not a null dereference (500).
+ getSocket: () => {
+ if (!this.sock) throw new EngineNotReadyError();
+ return this.sock;
+ },
getSocketOrNull: () => this.sock,
logger: this.logger,
toNeutralJid: jid => this.sessionStore.toNeutralJid(jid),