Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(session): lifecycle honesty and guarded-download follow-ups (#1008)

Yudhi Armyndharis4bed23e12fe8
diff --git a/.env.example b/.env.example
index 5d0e00af9..2c93e13dd 100644
--- a/.env.example
+++ b/.env.example
@@ -21,7 +21,9 @@ LOG_LEVEL=info # error | warn | info | debug
# Auto-start previously authenticated sessions on server boot. Recommended `true` for a SINGLE-instance
# production deployment so a crash-restart self-heals authenticated sessions; keep `false` if you run
# multiple replicas behind a scheduler (two replicas resurrecting one session risks a forced logout/ban —
-# see docs/13-horizontal-scaling.md).
+# see docs/13-horizontal-scaling.md). A session whose logout was not confirmed (502) keeps its credentials
+# and will be auto-started again — delete it if it must stay down; a confirmed logout is skipped (its
+# credentials are gone, so it can only ever come back via a fresh QR scan).
AUTO_START_SESSIONS=false
# 0 = unlimited. Set a positive integer to cap concurrently running/initializing sessions.
# Failed sessions still hold a slot until stopped (their engine stays resident); stop them to free capacity.
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 5699426c3..37919db03 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -33,7 +33,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
probe that cannot reach the page — a reload, a teardown, a timeout — is logged and otherwise
ignored: it says nothing about the modal, and taking a working session out of `ready` blocks every
send for a reason the operator cannot act on. The status is deliberately expensive to reach for
- that reason.
+ that reason: five failed dismiss clicks (up from three), so a multi-step "What's new" flow clicked
+ through one screen per tick no longer reads as a stuck modal.
- **`POST /sessions/:id/logout` unlinks the device from the WhatsApp account** (#984, #1003). Both engines
already implemented a real protocol-level unlink — whatsapp-web.js calls `WAWebSocketModel.Socket.logout()`
diff --git a/docs/06-api-specification.md b/docs/06-api-specification.md
index 044c9d895..bfc3e17bd 100644
--- a/docs/06-api-specification.md
+++ b/docs/06-api-specification.md
@@ -536,6 +536,11 @@ which happened:
unlink would. `start` waits for that cleanup to settle before re-creating the profile, so the
outcome is consistent either way — but plan for a re-scan after a deadline-hit 502.
+With `AUTO_START_SESSIONS=true`, a session whose unlink was not confirmed keeps its credentials and
+is auto-started again on boot (the "start and retry" flow, automated) — delete it if it must stay
+down. A confirmed logout is skipped on boot: its credentials are gone, so it can only come back via
+a fresh QR scan.
+
**Auth:** API key (OPERATOR) · **Scope:** session-scoped
**Path parameters**
@@ -601,7 +606,7 @@ No request body.
Returned via `transformSession`.
-**Errors:** `401` · `403` · `404` not found
+**Errors:** `400` session is not started (no live engine to kill) · `401` · `403` · `404` not found
#### POST /api/sessions/:id/pairing-code
@@ -5148,7 +5153,7 @@ These are the events OpenWA actually emits. A webhook is registered with an `eve
| `message.edited` | A message body or media caption is edited | `{ messageId, chatId, body, senderId, from, to, fromMe, isGroup, type, hasMedia, author?, mentionedIds?, timestamp }` — `messageId` is the original message id, `body` is the latest text/caption, and `timestamp` is the edit occurrence time in epoch **seconds** (not the original creation time) |
| `session.qr` | A new pairing QR is generated | `{ sessionId, qr }` (raw QR string) |
| `session.authenticated` | The session pairs and becomes ready | `{ sessionId, phone, pushName }` |
-| `session.disconnected` | The session disconnects | `{ sessionId, reason }` |
+| `session.disconnected` | The session disconnects on the engine or WhatsApp side (drop, conflict, or a phone-initiated unlink). Not fired for API-initiated stop/logout/delete — those are acknowledged by the API response and the `session.status` transition | `{ sessionId, reason }` |
| `session.reconnect_loop` | Every 5th consecutive reconnect attempt is scheduled (attempt 5, 10, 15, …) — the session is failing to come back up | `{ sessionId, attempts, nextDelayMs }` |
| `session.status` | The session status transitions | `{ sessionId, status }` where `status` is one of `created` / `initializing` / `qr_ready` / `authenticating` / `ready` / `disconnected` / `action_required` / `failed` |
| `group.join` | Participant(s) are added to or join a group this session is in | `{ groupId, actorId?, participantIds, timestamp }` — `actorId` is the admin/inviter when known |
diff --git a/docs/07-api-collection.md b/docs/07-api-collection.md
index 35415316b..8d93d8e6f 100644
--- a/docs/07-api-collection.md
+++ b/docs/07-api-collection.md
@@ -148,7 +148,7 @@ curl -X POST "$BASE/api/sessions/8f3c2b1a-9d4e-4c7a-8b2f-1e6d5a4c3b2a/logout" \
#### POST /api/sessions/:id/force-kill
-Force-kill a stuck session (OPERATOR).
+Force-kill a stuck session (OPERATOR). Returns `400` when the session is not started (there is no live engine to kill).
```bash
curl -X POST "$BASE/api/sessions/8f3c2b1a-9d4e-4c7a-8b2f-1e6d5a4c3b2a/force-kill" \
diff --git a/docs/12-troubleshooting-faq.md b/docs/12-troubleshooting-faq.md
index 19305eaba..eb3c944c8 100644
--- a/docs/12-troubleshooting-faq.md
+++ b/docs/12-troubleshooting-faq.md
@@ -456,6 +456,31 @@ Re-creating the session (`DELETE /sessions/<id>`) also purges its profile dir; c
scan. Messages are unaffected — they live in the database, not the browser profile — so nothing is lost
except the WhatsApp pairing, which must be re-scanned.
+`force-kill` requires a started session — it returns `400` when no live engine is registered (there
+is nothing to SIGKILL). A browser left wedged by an earlier teardown is reaped automatically by the
+next `start()` (an orphan sweep keyed on the session's browser marker runs at every engine launch),
+so the stop → start sequence alone is sufficient once the engine is gone.
+
+### Issue: Session stuck at `action_required` ("What's new" onboarding modal)
+
+> **Engine:** This issue applies to the `whatsapp-web.js` engine only (Chromium/Puppeteer-based). It does not affect `ENGINE_TYPE=baileys`.
+
+**Symptoms:** A freshly linked session leaves `ready` for `action_required` within its first minutes,
+every send returns `409` ("session not connected"), and the session's `lastError` says WhatsApp keeps
+showing its onboarding modal after repeated attempts to dismiss it.
+
+**Cause:** New WhatsApp accounts are shown a "What's new" modal after linking that must be
+acknowledged before the companion device is allowed to stay linked. The adapter auto-dismisses it
+and only gives up after five clicks that fail to land — at that point a human must click through it
+once, so the session stops instead of being silently unlinked by WhatsApp about five minutes later.
+
+**Fix:** acknowledge the modal once (open WhatsApp Web in the account holder's own browser and click
+through the "What's new" screen), **then restart the session** (`POST /sessions/:id/stop` →
+`POST /sessions/:id/start`). Acknowledging alone does not return the session to `ready` — the status
+is deliberately sticky — but the restart re-drives the engine from the stored credentials, so no new
+QR scan is needed. If the modal never actually appeared (a false trip is possible but rare), the
+same stop → start clears it.
+
### Issue: Frequent Disconnections
**Symptoms:**
diff --git a/openapi.json b/openapi.json
index ffb217cf7..5a2bf93ca 100644
--- a/openapi.json
+++ b/openapi.json
@@ -598,6 +598,9 @@
}
}
},
+ "400": {
+ "description": "Session is not started"
+ },
"404": {
"description": "Session not found"
}
diff --git a/src/common/security/ssrf-guard.spec.ts b/src/common/security/ssrf-guard.spec.ts
index fb37c43c9..22f576ebe 100644
--- a/src/common/security/ssrf-guard.spec.ts
+++ b/src/common/security/ssrf-guard.spec.ts
@@ -10,6 +10,7 @@ import {
withSafeFetch,
} from './ssrf-guard';
import * as dnsPromises from 'dns/promises';
+import { getEventListeners } from 'node:events';
import { fetch as undiciFetch, Agent, Headers } from 'undici';
import { createServer } from 'node:http';
import type { AddressInfo } from 'node:net';
@@ -639,6 +640,77 @@ describe('withSafeFetch (guarded + pinned fetch)', () => {
});
});
+describe('withSafeFetch DNS phase honors the caller abort signal', () => {
+ afterEach(() => {
+ (undiciFetch as jest.Mock).mockReset();
+ });
+
+ it('a pre-aborted signal skips DNS entirely and rejects with the abort reason', async () => {
+ const lookupSpy = dnsPromises.lookup as jest.Mock;
+ lookupSpy.mockClear();
+ const signal = AbortSignal.abort(new Error('already dead'));
+
+ await expect(
+ withSafeFetch('https://plugins.example.com/p.zip', { signal }, jest.fn(), { followRedirects: true }),
+ ).rejects.toThrow('already dead');
+ expect(lookupSpy).not.toHaveBeenCalled();
+ });
+
+ it('a wedged DNS lookup is cut by the caller timeout, not by the 10s DNS deadline', async () => {
+ (dnsPromises.lookup as jest.Mock).mockReturnValueOnce(new Promise<never>(() => undefined)); // never settles
+ const use = jest.fn();
+
+ const started = Date.now();
+ await expect(
+ withSafeFetch('https://plugins.example.com/p.zip', { signal: AbortSignal.timeout(30) }, use, {
+ followRedirects: true,
+ }),
+ ).rejects.toThrow(/aborted due to timeout/i);
+ expect(Date.now() - started).toBeLessThan(1000); // ~30ms — not the 10s DNS deadline
+ expect(use).not.toHaveBeenCalled();
+ });
+
+ it('a signal fired mid-chain ends the loop at the next hop resolve', async () => {
+ (dnsPromises.lookup as jest.Mock)
+ .mockResolvedValueOnce([{ address: '93.184.216.34', family: 4 }]) // hop 0 resolves
+ .mockReturnValueOnce(new Promise<never>(() => undefined)); // hop 1 DNS wedges
+ (undiciFetch as jest.Mock).mockResolvedValueOnce({
+ status: 302,
+ type: 'basic',
+ headers: new Map([['location', 'https://cdn.example.com/p.zip']]),
+ });
+ const use = jest.fn();
+
+ await expect(
+ withSafeFetch('https://github.com/x/p.zip', { signal: AbortSignal.timeout(30) }, use, {
+ followRedirects: true,
+ }),
+ ).rejects.toThrow(/aborted due to timeout/i);
+ expect(undiciFetch as jest.Mock).toHaveBeenCalledTimes(1); // hop 1 never fetched
+ });
+
+ it('removes its abort listener once each hop settles (no listener accumulation across a chain)', async () => {
+ const controller = new AbortController();
+ (dnsPromises.lookup as jest.Mock)
+ .mockResolvedValueOnce([{ address: '93.184.216.34', family: 4 }])
+ .mockResolvedValueOnce([{ address: '93.184.216.34', family: 4 }]);
+ (undiciFetch as jest.Mock)
+ .mockResolvedValueOnce({
+ status: 302,
+ type: 'basic',
+ headers: new Map([['location', 'https://cdn.example.com/p.zip']]),
+ })
+ .mockResolvedValueOnce({ status: 200, type: 'basic' });
+ const use = jest.fn(() => 'ok');
+
+ await withSafeFetch('https://github.com/x/p.zip', { signal: controller.signal }, use, {
+ followRedirects: true,
+ });
+
+ expect(getEventListeners(controller.signal, 'abort')).toHaveLength(0);
+ });
+});
+
describe('isSsrfProtectionEnabled', () => {
const orig = process.env.WEBHOOK_SSRF_PROTECT;
afterEach(() => {
diff --git a/src/common/security/ssrf-guard.ts b/src/common/security/ssrf-guard.ts
index d0eeb33ab..5ebc34dc7 100644
--- a/src/common/security/ssrf-guard.ts
+++ b/src/common/security/ssrf-guard.ts
@@ -245,21 +245,33 @@ const REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]);
* its late result swallowed (no unhandledRejection). Wrapping the rejection keeps every resolution
* failure typed, so callers map it to a 4xx instead of leaking a raw DNS error as a generic 500.
*/
-async function lookupWithDeadline(host: string): Promise<LookupAddress[]> {
+async function lookupWithDeadline(host: string, signal?: AbortSignal | null): Promise<LookupAddress[]> {
+ // An abort that already fired between hops burns no DNS query at all.
+ if (signal?.aborted) throw signal.reason;
const lookupPromise = lookup(host, { all: true });
lookupPromise.catch(() => undefined); // swallow a late rejection if the deadline already fired
let timer: NodeJS.Timeout | undefined;
+ let onAbort: (() => void) | undefined;
const deadline = new Promise<never>((_, reject) => {
timer = setTimeout(() => reject(new SsrfBlockedError(`Timed out resolving host: ${host}`)), resolveDnsTimeoutMs());
+ if (signal) {
+ // Reject with the signal's own reason — for AbortSignal.timeout that is the same TimeoutError
+ // a fetch-phase abort produces. Never an SsrfBlockedError: a caller timeout is not an SSRF
+ // block, and the redaction layer must not rewrite it into "destination not allowed".
+ onAbort = () => reject(signal.reason as Error);
+ signal.addEventListener('abort', onAbort, { once: true });
+ }
});
try {
return await Promise.race([lookupPromise, deadline]);
} catch (err) {
+ if (signal?.aborted) throw signal.reason; // the caller's abort wins over a simultaneous DNS error
if (err instanceof SsrfBlockedError) throw err; // deadline already produced a typed error
const code = (err as NodeJS.ErrnoException)?.code;
throw new SsrfBlockedError(`Could not resolve host: ${host}${code ? ` (${code})` : ''}`);
} finally {
if (timer) clearTimeout(timer);
+ if (signal && onAbort) signal.removeEventListener('abort', onAbort);
}
}
@@ -275,7 +287,10 @@ async function lookupWithDeadline(host: string): Promise<LookupAddress[]> {
* unpinned, since the operator opts in to whatever its DNS returns) or a literal IP (no DNS, so no
* rebind is possible — fetch connects straight to the validated literal).
*/
-export async function resolveSafeFetchTarget(rawUrl: string): Promise<LookupAddress[] | null> {
+export async function resolveSafeFetchTarget(
+ rawUrl: string,
+ signal?: AbortSignal | null,
+): Promise<LookupAddress[] | null> {
let url: URL;
try {
url = new URL(rawUrl);
@@ -300,7 +315,7 @@ export async function resolveSafeFetchTarget(rawUrl: string): Promise<LookupAddr
return null; // literal IP — fetch connects directly, nothing to rebind
}
- const resolved = await lookupWithDeadline(host);
+ const resolved = await lookupWithDeadline(host, signal);
if (resolved.length === 0) {
throw new SsrfBlockedError(`Could not resolve host: ${host}`);
}
@@ -316,8 +331,8 @@ export async function resolveSafeFetchTarget(rawUrl: string): Promise<LookupAddr
* Backwards-compatible assertion form: validate the URL (used at webhook registration time, where
* only the throw/no-throw outcome matters).
*/
-export async function assertSafeFetchUrl(rawUrl: string): Promise<void> {
- await resolveSafeFetchTarget(rawUrl);
+export async function assertSafeFetchUrl(rawUrl: string, signal?: AbortSignal | null): Promise<void> {
+ await resolveSafeFetchTarget(rawUrl, signal);
}
/**
@@ -444,7 +459,7 @@ export async function withSafeFetch<T>(
let hopInit = init;
let sawSecureHop = false;
for (let hop = 0; ; hop++) {
- const target = await resolveSafeFetchTarget(currentUrl);
+ const target = await resolveSafeFetchTarget(currentUrl, init.signal);
// Parsed already by resolveSafeFetchTarget above, so this cannot throw.
const current = new URL(currentUrl);
initialOrigin ??= current.origin;
@@ -479,7 +494,7 @@ export async function withSafeFetch<T>(
}
}
- const target = await resolveSafeFetchTarget(rawUrl);
+ const target = await resolveSafeFetchTarget(rawUrl, init.signal);
const dispatcher = target ? new Agent({ connect: { lookup: pinnedLookup(target) } }) : undefined;
try {
const response = await undiciFetch(rawUrl, { ...init, redirect: 'manual', dispatcher });
diff --git a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
index 96f2a014e..82c378e8d 100644
--- a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
+++ b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
@@ -1286,6 +1286,36 @@ describe('WhatsAppWebJsAdapter ready reconciliation (#251/#273)', () => {
expect(warnSpy).not.toHaveBeenCalled();
});
+ // A deliberate logout() also raises this event: client.logout() triggers the in-page Cmd 'logout'
+ // → framenavigated → DISCONNECTED 'LOGOUT' while the adapter is still awaiting it. The unlink is
+ // already acknowledged by the API response and the session service writes DISCONNECTED itself, so
+ // the handler must stay silent — mirroring the puppeteer-death gate. A WhatsApp-initiated unlink
+ // arrives with tearingDown=false and still flows through (the tests above).
+ it('does not report a disconnected event raised by a deliberate logout()', async () => {
+ let settleLogout: () => void = () => undefined;
+ const logout = jest.fn(
+ () =>
+ new Promise<void>(resolve => {
+ settleLogout = resolve;
+ }),
+ );
+ const adapter = newAdapter();
+ const { client } = attachFakeClient(adapter, {
+ logout,
+ destroy: jest.fn().mockResolvedValue(undefined),
+ });
+ const onDisconnected = jest.fn();
+ (adapter as unknown as { callbacks: { onDisconnected: jest.Mock } }).callbacks.onDisconnected = onDisconnected;
+
+ const logoutCall = adapter.logout();
+ client.emit('disconnected', 'LOGOUT'); // the in-page Socket.logout() raises this mid-flight
+ settleLogout();
+ await logoutCall;
+
+ expect(logout).toHaveBeenCalledTimes(1);
+ expect(onDisconnected).not.toHaveBeenCalled();
+ });
+
// The same #982 window for 'authenticated': the re-injected client can re-authenticate on the browser
// that is about to be replaced. Reviving to AUTHENTICATING would also re-arm the 90s ready-reconcile
// probe against it.
@@ -4430,7 +4460,19 @@ describe('WhatsAppWebJsAdapter honest outcomes (no phantom success)', () => {
expect(adapter.getStatus()).toBe(EngineStatus.READY);
expect(onActionRequired).not.toHaveBeenCalled();
- // Third click on a modal that is still there — the click is not landing, a human must act.
+ // Clicks three and four still fit a multi-step "What's new" flow being clicked through one
+ // screen per tick — not yet evidence the modal is stuck.
+ evaluate.mockResolvedValueOnce({ modalPresent: true, dismissed: true } satisfies ModalProbe);
+ await jest.advanceTimersByTimeAsync(5100);
+ expect(adapter.getStatus()).toBe(EngineStatus.READY);
+ expect(onActionRequired).not.toHaveBeenCalled();
+
+ evaluate.mockResolvedValueOnce({ modalPresent: true, dismissed: true } satisfies ModalProbe);
+ await jest.advanceTimersByTimeAsync(5100);
+ expect(adapter.getStatus()).toBe(EngineStatus.READY);
+ expect(onActionRequired).not.toHaveBeenCalled();
+
+ // Fifth click on a modal that is still there — the click is not landing, a human must act.
evaluate.mockResolvedValueOnce({ modalPresent: true, dismissed: true } satisfies ModalProbe);
await jest.advanceTimersByTimeAsync(5100);
@@ -4554,7 +4596,7 @@ describe('WhatsAppWebJsAdapter honest outcomes (no phantom success)', () => {
await jest.advanceTimersByTimeAsync(2100);
// Drive it to the fallback the only way that reaches it: clicks that keep failing to land.
- for (let i = 0; i < 3; i++) {
+ for (let i = 0; i < 5; i++) {
evaluate.mockResolvedValueOnce({ modalPresent: true, dismissed: true } satisfies ModalProbe);
await jest.advanceTimersByTimeAsync(5100);
}
diff --git a/src/engine/adapters/whatsapp-web-js.adapter.ts b/src/engine/adapters/whatsapp-web-js.adapter.ts
index b69e26723..f00a49a13 100644
--- a/src/engine/adapters/whatsapp-web-js.adapter.ts
+++ b/src/engine/adapters/whatsapp-web-js.adapter.ts
@@ -303,8 +303,10 @@ const ONBOARDING_MODAL_MAX_LIFETIME_MS = 5 * 60_000;
const ONBOARDING_MODAL_PROBE_TIMEOUT_MS = 5_000;
// Clicking Continue dismisses the modal, so one click is the normal case and the next tick finds
// nothing. Repeated clicks mean the click is not landing — the only evidence that actually justifies
-// asking a human to intervene.
-const ONBOARDING_MODAL_MAX_DISMISS_CLICKS = 3;
+// asking a human to intervene. Five, not three: a multi-step "What's new" flow is clicked through
+// one screen per tick, and three screens inside one watcher run must not read as a stuck modal.
+// Five failed clicks still trips in ~25s — far inside the lifetime cap and the ~5m unlink deadline.
+const ONBOARDING_MODAL_MAX_DISMISS_CLICKS = 5;
/**
* In-page probe for the onboarding modal: click its Continue button if it is on screen.
@@ -928,6 +930,13 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin
this.client.on('call', call => this.handleIncomingCall(call));
this.client.on('disconnected', reason => {
+ // A deliberate teardown (logout/disconnect/destroy/forceDestroy via beginClientTeardown) also
+ // raises this event: client.logout() triggers the in-page Cmd 'logout' → framenavigated →
+ // DISCONNECTED 'LOGOUT' while we are still awaiting it. The unlink is already acknowledged by
+ // the API response and the session service writes DISCONNECTED itself, so report nothing here
+ // (mirrors the puppeteer-death gate). A WhatsApp-initiated unlink arrives with
+ // tearingDown=false and still flows through.
+ if (this.tearingDown) return;
this.clearReadyReconcile();
// #982: LOGOUT is not a transient drop. whatsapp-web.js emits it when WhatsApp Web itself ran a
// logout (its in-page `Cmd` logout bus), and by then it has ALREADY deleted this session's
diff --git a/src/modules/session/session.controller.ts b/src/modules/session/session.controller.ts
index bc08a6da6..d9b45254f 100644
--- a/src/modules/session/session.controller.ts
+++ b/src/modules/session/session.controller.ts
@@ -194,6 +194,7 @@ export class SessionController {
description: 'Session force-killed',
type: SessionResponseDto,
})
+ @ApiResponse({ status: 400, description: 'Session is not started' })
@ApiResponse({ status: 404, description: 'Session not found' })
async forceKill(@Param('id', ParseUUIDPipe) id: string): Promise<SessionResponseDto> {
const session = await this.sessionService.forceKill(id);
diff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.ts
index d4cae47e5..bf56d3201 100644
--- a/src/modules/session/session.service.spec.ts
+++ b/src/modules/session/session.service.spec.ts
@@ -323,6 +323,10 @@ describe('SessionService', () => {
// Stop-mark stays set, like stop()/forceKill(): it blocks an in-flight reconnect
// from resurrecting a session we just unlinked; a later start() clears it.
expect(stoppingOf().has('sess-uuid-1')).toBe(true);
+ // A confirmed unlink wipes the stored credentials, so the session can never reach READY
+ // without a fresh QR — clearing phone takes it out of the boot auto-start query
+ // (phone IS NOT NULL) instead of resurrecting it into a QR it can never pass.
+ expect(repository.update).toHaveBeenCalledWith('sess-uuid-1', { phone: null });
expect(result).toBeDefined();
});
@@ -343,6 +347,9 @@ describe('SessionService', () => {
'sess-uuid-1',
expect.objectContaining({ status: SessionStatus.DISCONNECTED }),
);
+ // The unlink was NOT confirmed — the device may still be linked server-side, so the session
+ // must stay eligible for the boot auto-start (which is the "start and retry" automation).
+ expect(repository.update).not.toHaveBeenCalledWith('sess-uuid-1', { phone: null });
});
it('logout() rejects with 400 when no engine is loaded (session already stopped)', async () => {
@@ -484,6 +491,15 @@ describe('SessionService', () => {
(repository.findOne as jest.Mock).mockResolvedValue(null);
await expect(service.forceKill('nope')).rejects.toThrow(NotFoundException);
});
+
+ it('forceKill() rejects with BadRequestException when the session has no live engine', async () => {
+ // No engine registered: there is nothing to SIGKILL. Resolving would let the controller write
+ // a SESSION_FORCE_KILLED audit row for a kill that never happened — mirror logout()'s
+ // not-started refusal instead.
+ (repository.findOne as jest.Mock).mockResolvedValue(createMockSession());
+
+ await expect(service.forceKill('sess-uuid-1')).rejects.toBeInstanceOf(BadRequestException);
+ });
});
// ── stopOrphanEngines (infra import path) ─────────────────────────
diff --git a/src/modules/session/session.service.ts b/src/modules/session/session.service.ts
index 214f1da78..4bd301352 100644
--- a/src/modules/session/session.service.ts
+++ b/src/modules/session/session.service.ts
@@ -2279,6 +2279,12 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
);
}
+ // A confirmed unlink wipes the stored credentials on both engines, so this session can never
+ // reach READY again without a fresh QR/pairing. Clear `phone` to take it out of the boot
+ // auto-start query (phone IS NOT NULL) instead of resurrecting it into a QR it can never pass
+ // on every restart. onReady rewrites it on the next successful link.
+ await this.sessionRepository.update(id, { phone: null });
+
this.logger.log(`Session logged out: ${session.name}`, {
sessionId: id,
action: 'logout',
@@ -2294,16 +2300,22 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
*/
async forceKill(id: string): Promise<Session> {
const session = await this.findOne(id);
+ const engine = this.engines.get(id);
+
+ // No live engine means there is nothing to SIGKILL. Resolving would let the controller write a
+ // SESSION_FORCE_KILLED audit row for a kill that never happened — mirror logout()'s not-started
+ // refusal. A wedged engine torn down earlier is reaped by the next start()'s orphan sweep (and
+ // by process exit), not by force-kill.
+ if (!engine) {
+ throw new BadRequestException('Session is not started. Call POST /sessions/:id/start first.');
+ }
// Mark as tearing down BEFORE cleanup so an in-flight reconnect can't resurrect it.
this.stoppingSessions.add(id);
this.cancelReconnect(id);
- const engine = this.engines.get(id);
- if (engine) {
- await this.teardownEngineSafely(id, engine, e => e.forceDestroy(), 'force-destroy');
- if (this.isLiveEngine(id, engine)) this.engines.delete(id);
- }
+ await this.teardownEngineSafely(id, engine, e => e.forceDestroy(), 'force-destroy');
+ if (this.isLiveEngine(id, engine)) this.engines.delete(id);
this.logger.warn(`Session force-killed: ${session.name}`, {
sessionId: id,