Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
docs(api): align lifecycle and authorization contracts
Yudhi Armyndharis64db9d9b4353
diff --git a/.env.example b/.env.exampleindex 2c93e13dd..6a9ae391f 100644--- a/.env.example+++ b/.env.example@@ -21,12 +21,13 @@ 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). 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).+# see docs/13-horizontal-scaling.md). Auto-start selects sessions with a non-null `phone`. Both a+# completed logout (200, credentials wiped) and an incomplete logout (502, `code: 'SESSION_LOGOUT_INCOMPLETE'`)+# clear `phone`, so neither is auto-started on boot — an incomplete-logout session must be started+# explicitly and the logout retried. A session that must stay down can simply be left as-is.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.+# A FAILED session is evicted by design (no live engine), so it does not hold a concurrency slot.MAX_CONCURRENT_SESSIONS=0# Graceful-shutdown drain: on SIGTERM/SIGINT the app flips readiness to 503 (so a load balancer stopsdiff --git a/docs/06-api-specification.md b/docs/06-api-specification.mdindex bfc3e17bd..0d113b9f1 100644--- a/docs/06-api-specification.md+++ b/docs/06-api-specification.md@@ -100,7 +100,7 @@ Validation failures (`statusCode: 400`) return `message` as an **array** of fiel| `401` | Unauthorized | Missing/invalid/expired/revoked `X-API-Key` (or `METRICS_TOKEN` for metrics), a blocked source IP, or a key used outside its `allowedSessions` scope || `403` | Forbidden | A valid, in-scope key whose **role** is below the route's `@RequireRole` requirement || `404` | Not Found | The addressed resource (session, message, webhook, batch, …) does not exist |-| `409` | Conflict | A uniqueness constraint was violated (e.g. duplicate name) |+| `409` | Conflict | A uniqueness constraint was violated (e.g. duplicate name), or a credential teardown for the same session name is still in flight on `start`/`delete` (retryable; body carries `code: 'SESSION_NAME_TEARDOWN_PENDING'`) || `413` | Payload Too Large | Base64 media exceeds the media byte cap (see §6.3) || `500` | Internal Server Error | Send failed at the WhatsApp engine or an unexpected server error |@@ -467,7 +467,7 @@ No request body.Returned via `transformSession`. Status typically transitions to `initializing` / `qr_ready`.-**Errors:** `400` session already started / already starting · `401` · `403` · `404` not found+**Errors:** `400` session already started / already starting · `401` · `403` · `404` not found · `409` credential teardown for the same session name still in flight (retryable; body carries `code: 'SESSION_NAME_TEARDOWN_PENDING'`; no destructive side effect runs before the refusal — a retry after cleanup settles proceeds)#### POST /api/sessions/:id/stop@@ -506,40 +506,38 @@ Returned via `transformSession`; status typically becomes `disconnected`.#### POST /api/sessions/:id/logout-Log out of WhatsApp — unlinking this device from the account — and tear the session down.+Attempt an engine-native unlink of this companion device, then tear the session down locally.`stop` disconnects while keeping the stored credentials, and `delete` additionally purges theon-disk auth directories and the session row, but neither tells WhatsApp anything: the device stayslisted under the account holder's **Linked Devices** on the phone until they remove it by hand.-`logout` asks WhatsApp to remove the companion device itself. Both engines perform a real-protocol-level unlink and clear that session's stored credentials, so a later `start` requires a-fresh QR scan or pairing code.+`logout` attempts the engine-native unlink operation itself.++A `200` means the engine-native unlink operation **and** the required local credential cleanup both+completed — for Baileys, a valid companion identity, an acknowledged `remove-companion-device` IQ+response, and removal of the on-disk auth dir; for whatsapp-web.js, the native `Client.logout()`+promise (including `LocalAuth.logout()`) settled. `200` is **not** an independent observation that+the handset UI no longer shows the linked device — only the linked device itself can observe that,+and callers must not claim otherwise. Because a completed unlink wipes the stored credentials, a+later `start` always requires a fresh QR scan or pairing code.The session must be running — the unlink is a network round-trip that needs a live engine, so a-stopped session is rejected rather than reported as a success that never reached WhatsApp. The same-applies one level down: a session whose engine is loaded but whose underlying browser or socket has-gone (a stuck-auth recovery, a WhatsApp-side logout still inside its reconnect backoff) also answers-`502` rather than reporting an unlink it never sent.--If the engine's logout does not complete, the session is still torn down locally but the route-returns `502`: the unlink was not confirmed, the device may still be listed under Linked Devices, and-no `session_logged_out` audit row is written. Start the session again and retry.--Whether that retry needs a QR scan depends on how the attempt failed, and the route cannot tell you-which happened:--- **The engine rejected the logout** (no live client, socket already gone). Nothing was sent and- nothing was deleted, so the stored credentials survive and the retry reconnects without a QR.-- **The logout ran past the teardown deadline.** The 10s deadline bounds the *response*, not the- work: on whatsapp-web.js the still-running attempt ends in `LocalAuth.logout()`, which deletes the- profile directory. Once that lands the session comes back with a fresh QR, exactly as a successful- 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.+stopped session is rejected with `400` (the row is left untouched) rather than reported as a success+that never reached WhatsApp.++If the engine-backed logout attempt does not complete, the session is still torn down locally+(map reconciled, status `disconnected`) but the route returns `502` with a stable+`code: 'SESSION_LOGOUT_INCOMPLETE'`: no send / no acknowledgement / timeout or transport error / or+a local-cleanup failure. `phone` is cleared on this path and **no** `session_logged_out` audit row+is written (that audit is only written on the `200` path). Start the session again and retry the+logout. Do not assume the retry reconnects automatically or lands in a guaranteed QR state — whether+the old credentials remain usable depends on where the failure happened, and the route does not+report which.++With `AUTO_START_SESSIONS=true`, auto-start selects sessions whose `phone` is non-null. Both a `200`+and a `502` logout clear `phone`, so neither is auto-started on boot — an incomplete-logout (`502`)+session must be started explicitly and the logout retried by hand. A session that must stay down can+simply be left as-is.**Auth:** API key (OPERATOR) · **Scope:** session-scoped@@ -558,8 +556,8 @@ No request body."id": "8f3c2b1a-9d4e-4c7a-8b2f-1e6d5a4c3b2a","name": "my-bot","status": "disconnected",- "phone": "6281234567890",- "pushName": "My Bot",+ "phone": null,+ "pushName": null,"connectedAt": null,"lastActive": "2026-06-25T09:01:55.000Z","createdAt": "2026-06-20T11:30:00.000Z",@@ -568,10 +566,11 @@ No request body.}```-Returned via `transformSession`; status becomes `disconnected`. Recorded in the audit log as-`session_logged_out`, distinguishing an intentional unlink from a plain stop.+Returned via `transformSession`; status becomes `disconnected` and `phone` is cleared (so the boot+auto-start does not resurrect the session). Recorded in the audit log as `session_logged_out`,+distinguishing an intentional unlink from a plain stop.-**Errors:** `400` session is not started · `401` · `403` · `404` not found · `502` unlink not confirmed (session stopped locally; retryable)+**Errors:** `400` session is not started (no engine to send through; the row is left untouched) · `401` · `403` · `404` not found · `502` `SESSION_LOGOUT_INCOMPLETE` — session stopped locally but the logout operation did not complete (retryable; `phone` cleared, no success audit)#### POST /api/sessions/:id/force-kill@@ -783,7 +782,7 @@ Delete a session.**Response** `204` — empty body (`@HttpCode(204)`, returns void). A `findOne` lookup runs first, so a missing id yields `404`.-**Errors:** `401` missing/invalid key, or key not scoped to this session · `403` key role below OPERATOR · `404` session not found+**Errors:** `401` missing/invalid key, or key not scoped to this session · `403` key role below OPERATOR · `404` session not found · `409` credential teardown for the same session name still in flight (retryable; body carries `code: 'SESSION_NAME_TEARDOWN_PENDING'`; on a `409` the row is **not** deleted and no hook/auth-purge runs — retry after cleanup settles)### 6.4.2 Messages@@ -4713,9 +4712,9 @@ Set (or clear) a plugin config override for a specific session.#### PUT /api/plugins/:id/sessions-Set which sessions a session-scoped plugin is activated for.+Set which sessions a session-scoped plugin is activated for. This is a **full replacement** of the plugin's global activation set: the supplied `sessions` array overwrites `activeSessions` in its entirety (not a merge), so an omitted session is deactivated and `[]` deactivates the plugin for every session.-**Auth:** API key (ADMIN) · **Scope:** session-scoped (the key's `allowedSessions` is enforced)+**Auth:** API key (ADMIN) that is **not restricted to specific sessions** (`@RequireUnscopedKey`). Because the route replaces the whole activation set, a session-scoped key is rejected with `403` whatever it sends — even a request confined to its own `allowedSessions` would silently delete every other session's activation, so the fence refuses scoped keys before the handler runs. Use an unrestricted ADMIN key. (The per-session config override route `PUT /api/plugins/:id/config/:sessionId` is a different operation and stays scoped to the addressed session.)**Path parameters**@@ -4735,9 +4734,7 @@ Set which sessions a session-scoped plugin is activated for.**Response** `200` — the updated `PluginDto` (reflecting the new `activeSessions`).-A session-restricted key requesting `"*"` or out-of-scope sessions gets `403 API key not authorized for session(s): …`.--**Errors:** `400` plugin is global · `401` · `403` key not authorized for requested sessions · `404` unknown id+**Errors:** `400` plugin is global · `401` · `403` key is session-scoped (full activation replacement requires an unrestricted key) · `404` unknown id---diff --git a/docs/07-api-collection.md b/docs/07-api-collection.mdindex 8d93d8e6f..009917285 100644--- a/docs/07-api-collection.md+++ b/docs/07-api-collection.md@@ -138,8 +138,13 @@ curl -X POST "$BASE/api/sessions/8f3c2b1a-9d4e-4c7a-8b2f-1e6d5a4c3b2a/stop" \#### POST /api/sessions/:id/logout-Unlink this device from the WhatsApp account and stop the session (OPERATOR). Requires a running-session; a later start needs a fresh QR scan or pairing code.+Attempt an engine-native unlink of this device, then stop the session (OPERATOR). Requires a running+session. A `200` means the unlink operation AND the required local cleanup completed — it is not an+independent observation that the handset UI no longer shows the linked device, and a later start+needs a fresh QR scan or pairing code. A `502` carries `code: 'SESSION_LOGOUT_INCOMPLETE'`: the+session was stopped locally but the logout operation did not complete (no send / no acknowledgement+/ timeout or transport error / local-cleanup failure); `phone` is cleared and no success audit is+written, so start the session again and retry.```bashcurl -X POST "$BASE/api/sessions/8f3c2b1a-9d4e-4c7a-8b2f-1e6d5a4c3b2a/logout" \diff --git a/docs/14-migration-guide.md b/docs/14-migration-guide.mdindex ea5296bf7..e0f5ad72a 100644--- a/docs/14-migration-guide.md+++ b/docs/14-migration-guide.md@@ -705,6 +705,7 @@ docker compose run --rm openwa-api npm run migration:run:prod| Release | Change | Action || -------- | ----------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- |+| `0.12.0` | `PUT /api/plugins/:id/sessions` is a full replacement of the global activation set and now requires an **unrestricted ADMIN** key; a session-scoped key is rejected with `403` whatever it sends | Switch any automation that drives global plugin activation from a scoped key to an unrestricted ADMIN key. The per-session config override route `PUT /api/plugins/:id/config/:sessionId` is unaffected and stays scoped to the addressed session || `0.8.15` | PostgreSQL schemas bootstrapped with `DATABASE_SYNCHRONIZE=true` crash-loop on boot | Self-healing guard migration; see [14.9](#149-troubleshooting-migration-issues) for the large-table window || `0.9.0` | `GET /api/settings` no longer returns the always-zero `general.sessionTimeout` | Remove reads of that field — there is no replacement || `0.10.3` | Boolean/numeric request fields are parsed strictly (`1`, `yes`, `""` now `400`) | Send canonical JSON values; JSON clients and the SDKs are unaffected |diff --git a/docs/15-project-roadmap.md b/docs/15-project-roadmap.mdindex 259233efe..14e92b264 100644--- a/docs/15-project-roadmap.md+++ b/docs/15-project-roadmap.md@@ -657,8 +657,8 @@ version bump lands as a single commit on `main`, and pushing the tag hands everyExactly four files change. Nothing else belongs in this commit.```bash-npm version --no-git-tag-version 0.11.0 # package.json + package-lock.json-npm run openapi:export # openapi.json info.version follows package.json+npm version --no-git-tag-version <version> # package.json + package-lock.json+npm run openapi:export # openapi.json info.version follows package.json```Then in `CHANGELOG.md`, insert the new heading directly under the retained, now-empty@@ -667,7 +667,7 @@ Then in `CHANGELOG.md`, insert the new heading directly under the retained, now-```markdown## [Unreleased]-## [0.11.0] - 2026-07-27+## [<version>] - <YYYY-MM-DD>````## [<version>]` is not cosmetic: `npm run check:versions` fails without it, and the GitHub Release@@ -688,8 +688,8 @@ cd dashboard && npm run lint && npm run typecheck && npm run i18n:check && npm r```bashgit add package.json package-lock.json openapi.json CHANGELOG.md-git commit -m "chore(release): v0.11.0"-git tag -a v0.11.0 -m "v0.11.0"+git commit -m "chore(release): v<version>"+git tag -a v<version> -m "v<version>"git push origin main --follow-tags```@@ -724,17 +724,18 @@ are flagged prerelease on GitHub.Everything from `promote` onward is skipped, so no release tag reaches either registry and no GitHubRelease is created — the previous release stays intact. Confirm that is what happened, fix the cause-on `main`, then move the tag:+on `main`, then re-tag the version **only if nothing was published under it**:```bash-git push origin :refs/tags/v0.11.0 # delete the remote tag-git tag -d v0.11.0+git push origin :refs/tags/v<version> # delete the remote tag+git tag -d v<version># ... commit the fix ...-git tag -a v0.11.0 -m "v0.11.0" && git push origin v0.11.0+git tag -a v<version> -m "v<version>" && git push origin v<version>```-Re-using the version is safe precisely because nothing was published under it. A version that DID-publish before a defect was found must not be re-tagged — supersede it (v0.10.3 → v0.10.4).+Re-using a version is safe precisely because nothing was published under it. A version that DID+publish before a defect was found must not be re-tagged — never move or reuse an already-pushed tag;+supersede it with a new release instead (e.g. `v0.10.3` → `v0.10.4`).Two failure classes are worth anticipating because they depend on the outside world rather than onthe change being released:@@ -749,8 +750,8 @@ the change being released:```bashgh run list --workflow=release.yml --limit 1-gh release view v0.11.0-docker buildx imagetools inspect ghcr.io/rmyndharis/openwa:0.11.0+gh release view v<version>+docker buildx imagetools inspect ghcr.io/rmyndharis/openwa:<version>docker buildx imagetools inspect docker.io/rmyndharis/openwa:latest```diff --git a/docs/17-dashboard-design.md b/docs/17-dashboard-design.mdindex 23cbc8478..141dd1a54 100644--- a/docs/17-dashboard-design.md+++ b/docs/17-dashboard-design.md@@ -198,11 +198,13 @@ a non-admin hitting the path falls through to the `*` redirect.│ │ [Restart Session] [Unlink Device] [Delete] │ ││ └─────────────────────────────────────────────────────────────┘ ││ │-│ Unlink Device asks WhatsApp to remove this companion device from │-│ the account's Linked Devices (POST /sessions/:id/logout), then │-│ stops the session — reconnecting requires a fresh QR scan or │-│ pairing code. Delete only clears the local data; it does NOT │-│ unlink. │+│ Unlink Device attempts an engine-native unlink of this companion │+│ device (POST /sessions/:id/logout), then stops the session. A 200 │+│ means the unlink + local cleanup completed (not an independent │+│ Linked-Devices observation) — reconnecting then requires a fresh │+│ QR scan or pairing code. A 502 (SESSION_LOGOUT_INCOMPLETE) stops │+│ locally but leaves the operation incomplete; retry after starting. │+│ Delete only clears the local data; it does NOT unlink. ││ ││ ┌─────────────────────┬─────────────────────┐ ││ │ 📊 Statistics │ ⚙️ Configuration │ │diff --git a/docs/18-sdk-design.md b/docs/18-sdk-design.mdindex a6b02487f..417ede487 100644--- a/docs/18-sdk-design.md+++ b/docs/18-sdk-design.md@@ -131,7 +131,7 @@ The top-level client also exposes:| `delete` | `delete(id)` | Delete a session. **OPERATOR** || `start` | `start(id)` | Start a session and initialize the WhatsApp connection. **OPERATOR** || `stop` | `stop(id)` | Stop a session and disconnect gracefully. **OPERATOR** |-| `logout` | `logout(id)` | Unlink this device from the WhatsApp account, then stop the session; a later `start` needs a fresh QR. Requires a running session. **OPERATOR** |+| `logout` | `logout(id)` | Attempt an engine-native unlink of this device, then stop the session. A `200` means the unlink + local cleanup completed (not an independent Linked-Devices observation); a later `start` needs a fresh QR. A `502` (`SESSION_LOGOUT_INCOMPLETE`) stops locally but leaves the operation incomplete; start and retry. Requires a running session. **OPERATOR** || `forceKill` | `forceKill(id)` | Force-kill a stuck session (SIGKILL + teardown). **OPERATOR** || `getQrCode` | `getQrCode(id)` | Get the current QR code for authentication (live from the engine). **OPERATOR** || `requestPairingCode` | `requestPairingCode(id, body)` | Request an 8-character pairing code for phone-based login. **OPERATOR** |@@ -457,7 +457,7 @@ Resources are accessed as properties on the client (e.g. `client.messages`). All| `delete` | `delete(session_id) -> None` | Delete a session. **OPERATOR** || `start` | `start(session_id) -> SessionResponse` | Start (connect) a session. **OPERATOR** || `stop` | `stop(session_id) -> SessionResponse` | Stop a session. **OPERATOR** |-| `logout` | `logout(session_id) -> SessionResponse` | Unlink this device from the WhatsApp account, then stop the session. Requires a running session. **OPERATOR** |+| `logout` | `logout(session_id) -> SessionResponse` | Attempt an engine-native unlink of this device, then stop the session. A `200` means the unlink + local cleanup completed (not an independent Linked-Devices observation); a later `start` needs a fresh QR. A `502` (`SESSION_LOGOUT_INCOMPLETE`) stops locally but leaves the operation incomplete; start and retry. Requires a running session. **OPERATOR** || `force_kill` | `force_kill(session_id) -> SessionResponse` | Force-terminate a session. **OPERATOR** || `get_qr_code` | `get_qr_code(session_id) -> QrCodeResponse` | Fetch the login QR code. **OPERATOR** || `request_pairing_code` | `request_pairing_code(session_id, body) -> PairingCodeResponse` | Request a phone-number pairing code. **OPERATOR** |@@ -754,7 +754,7 @@ All payloads are associative arrays; all listed methods are synchronous and retu| `delete` | `delete(string $id): void` | Delete a session. **OPERATOR** || `start` | `start(string $id): array` | Start a session. **OPERATOR** || `stop` | `stop(string $id): array` | Stop a session. **OPERATOR** |-| `logout` | `logout(string $id): array` | Unlink this device from the WhatsApp account, then stop the session. Requires a running session. **OPERATOR** |+| `logout` | `logout(string $id): array` | Attempt an engine-native unlink of this device, then stop the session. A `200` means the unlink + local cleanup completed (not an independent Linked-Devices observation); a later `start` needs a fresh QR. A `502` (`SESSION_LOGOUT_INCOMPLETE`) stops locally but leaves the operation incomplete; start and retry. Requires a running session. **OPERATOR** || `forceKill` | `forceKill(string $id): array` | Force-kill a session. **OPERATOR** || `getQrCode` | `getQrCode(string $id): array` | Fetch the current QR code. **OPERATOR** || `requestPairingCode` | `requestPairingCode(string $id, array $body): array` | Request a phone-pairing code. **OPERATOR** |diff --git a/sdk/go/sessions.go b/sdk/go/sessions.goindex 9c7f073e0..45bbf0ef8 100644--- a/sdk/go/sessions.go+++ b/sdk/go/sessions.go@@ -58,9 +58,15 @@ func (s *SessionsService) Stop(ctx context.Context, sessionID string) (*SessionRreturn &out, nil}-// Logout unlinks this device from the WhatsApp account, then tears the session down. Unlike Stop-// and Delete, it removes the device from the account holder's Linked Devices list, so a later-// Start requires a fresh QR scan or pairing code. Requires a running session.+// Logout attempts an engine-native unlink of this device, then tears the session down. A 200+// means the unlink operation AND the required local credential cleanup completed — it is not an+// independent observation that the handset UI no longer shows the linked device. Because a+// completed unlink wipes the stored credentials, a later Start requires a fresh QR scan or+// pairing code. Requires a running session. Returns an HTTP 502 error with+// code 'SESSION_LOGOUT_INCOMPLETE' when the session was stopped locally but the logout operation+// did not complete (no send, no acknowledgement, timeout/transport error, or local cleanup+// failure); phone is cleared and no success audit is written. Start the session again and retry+// the logout; do not assume the retry reconnects automatically or lands in a guaranteed QR state.func (s *SessionsService) Logout(ctx context.Context, sessionID string) (*SessionResponse, error) {var out SessionResponseerr := s.client.do(ctx, "POST", "/api/sessions/"+pathEscape(sessionID)+"/logout", nil, nil, &out)diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/resources/SessionsResource.java b/sdk/java/src/main/java/com/rmyndharis/openwa/resources/SessionsResource.javaindex 68cc47ea3..498f885b4 100644--- a/sdk/java/src/main/java/com/rmyndharis/openwa/resources/SessionsResource.java+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/resources/SessionsResource.java@@ -51,9 +51,16 @@ public final class SessionsResource {}/**- * Unlink this device from the WhatsApp account, then stop the session. Unlike {@code stop} and- * {@code delete}, this removes the device from the account holder's Linked Devices list, so a- * later {@code start} requires a fresh QR scan or pairing code. Requires a running session.+ * Attempt an engine-native unlink of this device, then stop the session. A {@code 200} means the+ * unlink operation AND the required local credential cleanup completed — it is not an+ * independent observation that the handset UI no longer shows the linked device. Because a+ * completed unlink wipes the stored credentials, a later {@code start} requires a fresh QR scan+ * or pairing code. Requires a running session. Throws on HTTP {@code 502} with+ * {@code code: 'SESSION_LOGOUT_INCOMPLETE'} when the session was stopped locally but the logout+ * operation did not complete (no send, no acknowledgement, timeout/transport error, or local+ * cleanup failure); {@code phone} is cleared and no success audit is written. Start the session+ * again and retry the logout; do not assume the retry reconnects automatically or lands in a+ * guaranteed QR state.*/public SessionResponse logout(String id) {return client.request(HttpMethod.POST, "/api/sessions/" + encodeSegment(id) + "/logout", null, null, SessionResponse.class);diff --git a/sdk/javascript/src/resources/sessions.ts b/sdk/javascript/src/resources/sessions.tsindex 8e02c4cb8..c37df816c 100644--- a/sdk/javascript/src/resources/sessions.ts+++ b/sdk/javascript/src/resources/sessions.ts@@ -50,9 +50,16 @@ export class SessionsResource {}/**- * Unlink this device from the WhatsApp account, then stop the session. Unlike `stop` and- * `delete`, this removes the device from the account holder's Linked Devices list, so a later- * `start` requires a fresh QR scan or pairing code. Requires a running session.+ * Attempt an engine-native unlink of this device, then stop the session. A `200` means the+ * unlink operation AND the required local credential cleanup completed — it is not an+ * independent observation that the handset UI no longer shows the linked device. Because a+ * completed unlink wipes the stored credentials, a later `start` requires a fresh QR scan or+ * pairing code. Requires a running session. Rejects with HTTP `502` and+ * `code: 'SESSION_LOGOUT_INCOMPLETE'` when the session was stopped locally but the logout+ * operation did not complete (no send, no acknowledgement, timeout/transport error, or local+ * cleanup failure); `phone` is cleared and no success audit is written. Start the session again+ * and retry the logout; do not assume the retry reconnects automatically or lands in a+ * guaranteed QR state.*/logout(id: string): Promise<SessionResponse> {return this.client.request<SessionResponse>({ method: 'POST', path: `/api/sessions/${encodeSegment(id)}/logout` });diff --git a/sdk/php/src/Resources/SessionsResource.php b/sdk/php/src/Resources/SessionsResource.phpindex c2931bc00..144fa7087 100644--- a/sdk/php/src/Resources/SessionsResource.php+++ b/sdk/php/src/Resources/SessionsResource.php@@ -59,9 +59,16 @@ class SessionsResource}/**- * Unlink this device from the WhatsApp account, then stop the session. Unlike stop() and- * delete(), this removes the device from the account holder's Linked Devices list, so a later- * start() requires a fresh QR scan or pairing code. Requires a running session.+ * Attempt an engine-native unlink of this device, then stop the session. A 200 means the+ * unlink operation AND the required local credential cleanup completed — it is not an+ * independent observation that the handset UI no longer shows the linked device. Because a+ * completed unlink wipes the stored credentials, a later start() requires a fresh QR scan or+ * pairing code. Requires a running session. Throws on HTTP 502 with+ * `code: 'SESSION_LOGOUT_INCOMPLETE'` when the session was stopped locally but the logout+ * operation did not complete (no send, no acknowledgement, timeout/transport error, or local+ * cleanup failure); `phone` is cleared and no success audit is written. Start the session+ * again and retry the logout; do not assume the retry reconnects automatically or lands in a+ * guaranteed QR state.** @return array<string,mixed>*/diff --git a/sdk/python/openwa/resources/sessions.py b/sdk/python/openwa/resources/sessions.pyindex ebcf64ebf..d3c276d98 100644--- a/sdk/python/openwa/resources/sessions.py+++ b/sdk/python/openwa/resources/sessions.py@@ -50,14 +50,20 @@ class SessionsResource:return self._http.request("POST", f"/api/sessions/{quote_segment(session_id)}/stop")def logout(self, session_id: str) -> SessionResponse:- """Request WhatsApp to unlink this device, then tear the session down.-- Unlike stop() and delete(), this asks WhatsApp to remove the device- from the account holder's Linked Devices list, so a later start()- requires a fresh QR scan or pairing code. Requires a running session.- Raises on HTTP 502 when the session was stopped locally but WhatsApp- did not confirm the unlink (the device may still be listed) — start- the session and retry to confirm.+ """Attempt an engine-native unlink of this device, then tear the session down.++ A 200 means the engine-native unlink operation AND the required local+ credential cleanup completed -- it is not an independent observation+ that the handset UI no longer shows the linked device. Because a+ completed unlink wipes the stored credentials, a later start() requires+ a fresh QR scan or pairing code. Requires a running session.++ Raises on HTTP 502 with ``code: 'SESSION_LOGOUT_INCOMPLETE'`` when the+ session was stopped locally but the logout operation did not complete+ (no send, no acknowledgement, timeout/transport error, or local+ cleanup failure); ``phone`` is cleared and no success audit is written.+ Start the session again and retry the logout. Do not assume the retry+ reconnects automatically or lands in a guaranteed QR state."""return self._http.request("POST", f"/api/sessions/{quote_segment(session_id)}/logout")diff --git a/src/modules/session/session.controller.ts b/src/modules/session/session.controller.tsindex d9b45254f..3054f8114 100644--- a/src/modules/session/session.controller.ts+++ b/src/modules/session/session.controller.ts@@ -100,6 +100,13 @@ export class SessionController {@ApiParam({ name: 'id', description: 'Session ID' })@ApiResponse({ status: 204, description: 'Session deleted' })@ApiResponse({ status: 404, description: 'Session not found' })+ @ApiResponse({+ status: 409,+ description:+ 'A credential teardown for the same session name is still in flight. Retryable — the body ' ++ "carries `code: 'SESSION_NAME_TEARDOWN_PENDING'`; wait for it to settle and retry. No " ++ 'destructive side effect runs before this refusal.',+ })async delete(@Param('id', ParseUUIDPipe) id: string): Promise<void> {const session = await this.sessionService.findOne(id);await this.sessionService.delete(id);@@ -123,6 +130,14 @@ export class SessionController {})@ApiResponse({ status: 400, description: 'Session already started' })@ApiResponse({ status: 404, description: 'Session not found' })+ @ApiResponse({+ status: 409,+ description:+ 'A credential teardown for the same session name is still in flight (e.g. a prior logout ' ++ 'that owns destructive cleanup). Retryable — the body carries `code: ' ++ 'SESSION_NAME_TEARDOWN_PENDING`; wait for it to settle and retry. No destructive side ' ++ 'effect runs before this refusal.',+ })async start(@Param('id', ParseUUIDPipe) id: string): Promise<SessionResponseDto> {const session = await this.sessionService.start(id);await this.auditService.logInfo(AuditAction.SESSION_STARTED, {@@ -158,22 +173,51 @@ export class SessionController {@ApiOperation({summary: 'Log out of WhatsApp (unlinks this device) and stop the session',description:- "Asks WhatsApp to remove this companion device, so it disappears from the account holder's " +- 'Linked Devices list, then tears the session down. Unlike stop and delete — which only ' +- 'release the session locally and leave the device linked on the phone — reconnecting after ' +- 'a logout always requires a fresh QR scan or pairing code.',+ 'Attempts an engine-native unlink of this companion device, then tears the session down ' ++ 'locally. `200` means the engine-native unlink operation completed AND the required local ' ++ 'credential cleanup completed — for Baileys a valid companion identity, an acknowledged ' ++ '`remove-companion-device` IQ response, and removal of the on-disk auth dir; for ' ++ 'whatsapp-web.js the native `Client.logout()` promise settled. `200` is NOT an independent ' ++ 'observation that the handset UI no longer shows the linked device. Because a completed ' ++ 'unlink wipes the stored credentials, reconnecting after a `200` always requires a fresh QR ' ++ 'scan or pairing code.',})@ApiParam({ name: 'id', description: 'Session ID' })@ApiResponse({status: 200,- description: 'Session logged out',+ description:+ 'Unlink operation and required local cleanup completed; session is stopped and `phone` is ' ++ 'cleared. Recorded in the audit log as `session_logged_out`.',type: SessionResponseDto,+ content: {+ 'application/json': {+ example: {+ id: '8f3c2b1a-9d4e-4c7a-8b2f-1e6d5a4c3b2a',+ name: 'my-bot',+ status: 'disconnected',+ phone: null,+ pushName: null,+ connectedAt: null,+ lastActive: '2026-06-25T09:01:55.000Z',+ createdAt: '2026-06-20T11:30:00.000Z',+ updatedAt: '2026-06-25T09:11:00.000Z',+ lastError: null,+ },+ },+ },+ })+ @ApiResponse({+ status: 400,+ description: 'Session is not started (no engine to send through); the row is left untouched',})- @ApiResponse({ status: 400, description: 'Session is not started' })@ApiResponse({ status: 404, description: 'Session not found' })@ApiResponse({status: 502,- description: 'Session was stopped locally, but WhatsApp did not confirm the device unlink — retryable',+ description:+ 'Session was stopped locally, but the logout operation is incomplete (no send, no ' ++ 'acknowledgement, timeout/transport error, or local-cleanup failure). Retryable — the ' ++ "body carries `code: 'SESSION_LOGOUT_INCOMPLETE'`; `phone` is cleared and no success audit " ++ 'is written. Start the session again and retry the logout.',})async logout(@Param('id', ParseUUIDPipe) id: string): Promise<SessionResponseDto> {const session = await this.sessionService.logout(id);