Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(session): auto-start sessions after the listener binds, not before it

Yudhi Armyndharisfdd762e689e2
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 761d120dd..51eaacc6a 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -45,6 +45,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- `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.
- A burst of inbound media messages no longer loses the media of everything past the eighth. The Baileys adapter capped the download queue at its active slots, and an upsert is submitted in one synchronous pass, so admission was a constant 8 whatever the batch size — a 40-message upsert arrived with 32 of its files replaced by an omitted-media marker. The queue is now unbounded and a burst parks instead of shedding; the concurrent-download bound is unchanged.
+- Auto-starting previously authenticated sessions no longer delays the HTTP listener. NestJS binds the port only after every bootstrap hook has finished, and the auto-start loop launches one engine at a time with a 2s throttle, each bounded only by the engine-init timeout of at least 60 seconds — so a host with several sessions kept the port closed, not merely unhealthy, for minutes. The Helm chart's liveness budget is roughly 50 seconds and the Docker `HEALTHCHECK` encodes the same expectation, so a restart could be killed before it ever answered, and no probe budget can cover a bound that grows with the session count. The launches now run after the port is open; a shutdown that lands mid-run stops the remaining launches and waits for the one in flight. A failure of the session scan itself is now logged instead of aborting startup.
+
### Security
- An advisory usage-statistics write no longer persists the whole API-key row. A key deleted while a request that had already loaded it was in flight was re-inserted with its original hash and authenticated again; a revocation or a narrowing of role, allowlist, IP allowlist or expiry was likewise reverted to the values that request loaded. The write is now scoped to the two usage columns and affects nothing if the row is gone.
diff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.ts
index 14a3cfc62..9124307f9 100644
--- a/src/modules/session/session.service.spec.ts
+++ b/src/modules/session/session.service.spec.ts
@@ -1956,7 +1956,7 @@ describe('SessionService', () => {
seedReadySession(engine);
const scheduleSpy = jest.spyOn(internals(), 'scheduleReconnect');
- await service.onApplicationBootstrap();
+ service.onApplicationBootstrap();
// Tick 1: the first failure stays below the 2-consecutive-failures threshold — nothing happens.
await jest.advanceTimersByTimeAsync(SESSION_WATCHDOG_INTERVAL_MS);
@@ -1998,7 +1998,7 @@ describe('SessionService', () => {
seedReadySession(engine);
const scheduleSpy = jest.spyOn(internals(), 'scheduleReconnect');
- await service.onApplicationBootstrap();
+ service.onApplicationBootstrap();
await jest.advanceTimersByTimeAsync(SESSION_WATCHDOG_INTERVAL_MS * 3);
expect(engine.probeLiveness).toHaveBeenCalledTimes(3);
@@ -2026,7 +2026,7 @@ describe('SessionService', () => {
internals().engines.set('sess-not-ready', notReady);
internals().engines.set('sess-no-probe', noProbe);
- await service.onApplicationBootstrap();
+ service.onApplicationBootstrap();
await jest.advanceTimersByTimeAsync(SESSION_WATCHDOG_INTERVAL_MS * 2);
expect(notReady.probeLiveness).not.toHaveBeenCalled();
@@ -2053,7 +2053,7 @@ describe('SessionService', () => {
seedReadySession(engine);
const scheduleSpy = jest.spyOn(internals(), 'scheduleReconnect');
- await service.onApplicationBootstrap();
+ service.onApplicationBootstrap();
// Well past the 2-failure threshold that would disconnect a READY session.
await jest.advanceTimersByTimeAsync(SESSION_WATCHDOG_INTERVAL_MS * 4);
@@ -2095,7 +2095,7 @@ describe('SessionService', () => {
'warn',
);
- await service.onApplicationBootstrap();
+ service.onApplicationBootstrap();
await jest.advanceTimersByTimeAsync(SESSION_WATCHDOG_INTERVAL_MS * 5);
const observeWarnings = warnSpy.mock.calls.filter(
@@ -2120,7 +2120,7 @@ describe('SessionService', () => {
};
seedReadySession(engine);
- await service.onApplicationBootstrap();
+ service.onApplicationBootstrap();
await jest.advanceTimersByTimeAsync(SESSION_WATCHDOG_INTERVAL_MS); // tick 1: probe hangs
expect(livenessFailures().get('sess-uuid-1')).toBeUndefined(); // not counted yet
await jest.advanceTimersByTimeAsync(SESSION_WATCHDOG_PROBE_TIMEOUT_MS); // 15s → timeout failure
@@ -2137,7 +2137,7 @@ describe('SessionService', () => {
it('clears the watchdog timer in onModuleDestroy (idempotent, no open handle)', async () => {
jest.useFakeTimers();
try {
- await service.onApplicationBootstrap();
+ service.onApplicationBootstrap();
expect(internals().watchdog.timer).not.toBeNull();
expect(jest.getTimerCount()).toBe(1); // the interval itself
@@ -5654,6 +5654,11 @@ describe('SessionService', () => {
// ── onApplicationBootstrap (auto-start) ───────────────────────────
describe('onApplicationBootstrap', () => {
+ // The launch loop is detached from the hook so the HTTP listener binds without waiting for
+ // it; every assertion about what it did has to await the run, or it reads a loop that has
+ // not started yet and passes for the wrong reason.
+ const autoStartRun = (): Promise<void> => (service as unknown as { autoStartRun: Promise<void> }).autoStartRun;
+
const originalFlag = process.env.AUTO_START_SESSIONS;
afterEach(async () => {
@@ -5668,7 +5673,8 @@ describe('SessionService', () => {
delete process.env.AUTO_START_SESSIONS;
const startSpy = jest.spyOn(service, 'start').mockResolvedValue(undefined as never);
- await service.onApplicationBootstrap();
+ service.onApplicationBootstrap();
+ await autoStartRun();
expect(repository.find).not.toHaveBeenCalled();
expect(startSpy).not.toHaveBeenCalled();
@@ -5679,7 +5685,8 @@ describe('SessionService', () => {
(repository.find as jest.Mock).mockResolvedValue([]);
const startSpy = jest.spyOn(service, 'start').mockResolvedValue(undefined as never);
- await service.onApplicationBootstrap();
+ service.onApplicationBootstrap();
+ await autoStartRun();
expect(startSpy).not.toHaveBeenCalled();
});
@@ -5693,7 +5700,8 @@ describe('SessionService', () => {
jest.spyOn(service as unknown as { delay: () => Promise<void> }, 'delay').mockResolvedValue(undefined);
const startSpy = jest.spyOn(service, 'start').mockResolvedValue(undefined as never);
- await service.onApplicationBootstrap();
+ service.onApplicationBootstrap();
+ await autoStartRun();
expect(startSpy).toHaveBeenCalledTimes(2);
expect(startSpy).toHaveBeenCalledWith('a');
@@ -5712,10 +5720,80 @@ describe('SessionService', () => {
.mockRejectedValueOnce(new Error('boom'))
.mockResolvedValueOnce(undefined as never);
- await service.onApplicationBootstrap();
+ service.onApplicationBootstrap();
+ await autoStartRun();
expect(startSpy).toHaveBeenCalledTimes(2);
});
+
+ // Nest binds the HTTP listener only after every bootstrap hook settles, and a launch is a
+ // Chromium start bounded by resolveEngineInitTimeoutMs (>= 60s) with a 2s throttle between
+ // sessions. Awaiting the loop here kept the port CLOSED for that whole time, so every liveness
+ // probe in the window was a connection refusal — the chart's budget is ~50s.
+ it('returns without waiting for a launch that has not finished', async () => {
+ process.env.AUTO_START_SESSIONS = 'true';
+ (repository.find as jest.Mock).mockResolvedValue([{ id: 'a', name: 'A' }]);
+ let releaseLaunch: () => void = () => undefined;
+ jest
+ .spyOn(service, 'start')
+ .mockImplementation(() => new Promise<never>(resolve => (releaseLaunch = () => resolve(undefined as never))));
+
+ const settled = await Promise.race([
+ Promise.resolve(service.onApplicationBootstrap()).then(() => 'returned' as const),
+ new Promise<'still waiting'>(resolve => setTimeout(() => resolve('still waiting'), 250)),
+ ]);
+
+ expect(settled).toBe('returned');
+ releaseLaunch();
+ await autoStartRun();
+ });
+
+ it('stops launching the rest once a shutdown lands mid-run', async () => {
+ process.env.AUTO_START_SESSIONS = 'true';
+ (repository.find as jest.Mock).mockResolvedValue([
+ { id: 'a', name: 'A' },
+ { id: 'b', name: 'B' },
+ { id: 'c', name: 'C' },
+ ]);
+ jest.spyOn(service as unknown as { delay: () => Promise<void> }, 'delay').mockResolvedValue(undefined);
+ const startSpy = jest.spyOn(service, 'start').mockImplementation(() => {
+ (service as unknown as { shuttingDown: boolean }).shuttingDown = true;
+ return Promise.resolve(undefined as never);
+ });
+
+ service.onApplicationBootstrap();
+ await autoStartRun();
+
+ expect(startSpy).toHaveBeenCalledTimes(1);
+ });
+
+ // The other half of detaching it: a SIGTERM during boot must not leave a browser being launched
+ // behind, so the teardown waits for the one in flight rather than racing it.
+ it('waits for a launch already in flight before completing shutdown', async () => {
+ process.env.AUTO_START_SESSIONS = 'true';
+ (repository.find as jest.Mock).mockResolvedValue([{ id: 'a', name: 'A' }]);
+ let releaseLaunch: () => void = () => undefined;
+ let launchStarted: () => void = () => undefined;
+ const launching = new Promise<void>(resolve => (launchStarted = resolve));
+ jest.spyOn(service, 'start').mockImplementation(() => {
+ launchStarted();
+ return new Promise<never>(resolve => (releaseLaunch = () => resolve(undefined as never)));
+ });
+ service.onApplicationBootstrap();
+ // Not a tick count: wait until the launch is genuinely in flight. Shut down any earlier and
+ // the loop's own guard stops it before the first start, which is a different behaviour.
+ await launching;
+
+ const destroy = service.onModuleDestroy();
+ const blocked = await Promise.race([
+ destroy.then(() => 'completed' as const),
+ new Promise<'blocked'>(resolve => setTimeout(() => resolve('blocked'), 250)),
+ ]);
+
+ expect(blocked).toBe('blocked');
+ releaseLaunch();
+ await destroy;
+ });
});
// ── pre-initialize retirement race (lifecycle control during the INITIALIZING DB write) ──
diff --git a/src/modules/session/session.service.ts b/src/modules/session/session.service.ts
index 28580f1a0..63d801459 100644
--- a/src/modules/session/session.service.ts
+++ b/src/modules/session/session.service.ts
@@ -61,6 +61,11 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
return this.engineRegistry;
}
+ /** The detached auto-start run; see onApplicationBootstrap. Awaited by onModuleDestroy. */
+ private autoStartRun: Promise<void> = Promise.resolve();
+ /** Set at the top of onModuleDestroy so the detached run stops launching further sessions. */
+ private shuttingDown = false;
+
constructor(
@InjectRepository(Session, 'data')
private readonly sessionRepository: Repository<Session>,
@@ -115,7 +120,7 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
}
}
- async onApplicationBootstrap(): Promise<void> {
+ onApplicationBootstrap(): void {
// Start the liveness watchdog FIRST: it must run even when auto-start is disabled (sessions can
// be started via the API at any time), so it can't sit behind the auto-start early-return below.
// The watchdog owns the probe cadence and failure counting; a session it proves dead comes
@@ -137,6 +142,29 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
if (!resolveFeatureFlags(this.configService).autoStartSessions) return;
+ // DETACHED, deliberately. Nest binds the HTTP listener only after every onApplicationBootstrap
+ // hook has settled, and this loop's duration is unbounded: one engine initialization is at least
+ // 60s (resolveEngineInitTimeoutMs) and there is a 2s throttle between sessions, so a host with
+ // ten authenticated sessions kept the port CLOSED — not unhealthy, closed — for ten minutes.
+ // Every liveness probe in that window is a connection refusal, and no probe budget can cover a
+ // bound that scales with the session count: the chart's is ~50s and the Dockerfile HEALTHCHECK
+ // encodes the same expectation. Awaited on shutdown so a launch in flight is accounted for.
+ this.autoStartRun = this.autoStartSessions().catch((error: unknown) => {
+ // Previously this rejected out of the hook and aborted boot, so a transient database error
+ // during the session scan took the whole gateway down rather than the auto-start.
+ this.logger.error('Auto-start scan failed', error instanceof Error ? error.message : String(error), {
+ action: 'auto_start_scan_failed',
+ });
+ });
+ }
+
+ /**
+ * Launch every previously authenticated session this node may claim, one at a time.
+ *
+ * Sequential with a throttle by design — these are Chromium launches — which is exactly why it
+ * cannot run inside the bootstrap hook. See onApplicationBootstrap.
+ */
+ private async autoStartSessions(): Promise<void> {
// Restricted to sessions this node may claim. Without it every replica scans the same rows and
// races to launch the same engines, which is a WhatsApp account being opened twice, not merely
// duplicated work.
@@ -153,6 +181,14 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
});
for (let i = 0; i < sessions.length; i++) {
+ // A shutdown landing mid-run must not launch anything further: onModuleDestroy tears down what
+ // exists, and a browser launched after that point is never destroyed.
+ if (this.shuttingDown) {
+ this.logger.log(`Auto-start stopped at ${i} of ${sessions.length} session(s): shutting down`, {
+ action: 'auto_start_aborted',
+ });
+ return;
+ }
const session = sessions[i];
try {
await this.start(session.id);
@@ -177,8 +213,14 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
async onModuleDestroy(): Promise<void> {
// Stop the watchdog FIRST (before any teardown below can hang): no new probe/disconnect handling
// may start mid-shutdown. stop() is idempotent, so a second onModuleDestroy call stays safe.
+ this.shuttingDown = true;
this.watchdog.stop();
this.ownership?.stopHeartbeat();
+ // A SIGTERM during boot can land while the detached auto-start is mid-launch. Let that one
+ // settle — the flag above stops the loop taking another — so the engine it registers is torn
+ // down below instead of outliving the process as an orphaned browser. Bounded by the launch
+ // already in flight, never by the whole run.
+ await this.autoStartRun;
// Reconnect timers + engine teardown belong to the lifecycle owner.
await this.engineLifecycle.shutdown();
// Released only after the engines are actually down, so a peer never claims a session this