Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

feat(sessions): surface WhatsApp-imposed account restrictions

Yudhi Armyndharis054f23363b04
diff --git a/CHANGELOG.md b/CHANGELOG.md
index beea82bfa..d6cc1181b 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,35 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added
+- **WhatsApp-imposed account restrictions are now surfaced, instead of being lost inside a generic
+ disconnect:** a new `restriction` field on every session response, a `session.restriction` webhook,
+ and an `openwa_sessions_restricted` Prometheus gauge. Modelled in the JavaScript, Python, Go and
+ Java SDKs. Nothing is opt-in and nothing changes an existing payload's meaning; the field is
+ additive and `null` when there is no restriction.
+
+ The two engines can observe genuinely different things, so the signal says which:
+
+ - `reachout_timelock` (Baileys) — the account stays connected and existing chats keep working;
+ WhatsApp blocks only the start of **new** conversations. Read from the library's typed
+ `reachoutTimeLock` state, which reports both the onset and the lift, and carries an `expiresAt`
+ when WhatsApp states one.
+ - `tos_block` / `proxy_block` (whatsapp-web.js) — a connection-level refusal, derived from the
+ `WAState` the library reports when it drops the link.
+
+ Only three of whatsapp-web.js's twelve states are treated as restrictions. An unlink, a takeover
+ by another device, a stale client version and a timeout all say nothing about the account's
+ standing, and reporting them would make the signal useless to act on.
+
+ Because WhatsApp only *pushes* a timelock when it changes, a gateway that starts while an account
+ is already restricted would never be told, so the Baileys engine asks outright once per
+ connection. Repeats are deduped: an unchanged restriction is not re-announced, and a lift is only
+ sent when one was actually in force.
+
+ Detection is observational. It never changes a session's status or its reconnect behaviour, so a
+ misread cannot take a working session out of service — and a `reachout_timelock` in particular
+ applies to a session that is still fully `ready`. The state is held in memory rather than
+ persisted, because both engines re-establish it within one connection.
+
- **Polls can be voted on, on the whatsapp-web.js engine:**
`POST /api/sessions/:sessionId/messages/vote-poll` with `{ chatId, pollMessageId, options }`.
Exposed in all five SDKs as `messages.votePoll`. Baileys returns `501` — it has no vote-send
diff --git a/dashboard/src/pages/Webhooks.tsx b/dashboard/src/pages/Webhooks.tsx
index ce29badbb..17b6dd598 100644
--- a/dashboard/src/pages/Webhooks.tsx
+++ b/dashboard/src/pages/Webhooks.tsx
@@ -102,6 +102,7 @@ const availableEventNames = [
'session.authenticated',
'session.disconnected',
'session.reconnect_loop',
+ 'session.restriction',
'group.join',
'group.leave',
'group.update',
diff --git a/docs/05-database-design.md b/docs/05-database-design.md
index 127063e70..b82dc6399 100644
--- a/docs/05-database-design.md
+++ b/docs/05-database-design.md
@@ -383,6 +383,7 @@ CREATE TABLE webhooks (
"session.authenticated",
"session.disconnected",
"session.reconnect_loop",
+ "session.restriction",
"group.join",
"group.leave",
"group.update",
diff --git a/docs/06-api-specification.md b/docs/06-api-specification.md
index d14b0c67a..5e9079393 100644
--- a/docs/06-api-specification.md
+++ b/docs/06-api-specification.md
@@ -216,6 +216,7 @@ List all sessions, scoped to the API key's `allowedSessions`, ordered `createdAt
"createdAt": "2026-06-20T11:30:00.000Z",
"updatedAt": "2026-06-25T09:01:55.000Z",
"lastError": null,
+ "restriction": null,
"engineLoaded": true
}
]
@@ -223,6 +224,16 @@ List all sessions, scoped to the API key's `allowedSessions`, ordered `createdAt
`lastError` is non-null only when `status` is `failed` or `action_required`; any other status clears it. `config`/`proxyUrl`/`proxyType` are not present (stripped by `fromEntity`).
+`restriction` reports a limit **WhatsApp itself** has placed on the account, as opposed to `lastError`, which describes a fault on the gateway's side of the link. It is `null` when there is none, and otherwise `{ kind, code, expiresAt }`:
+
+| `kind` | Meaning | Engine |
+|---|---|---|
+| `reachout_timelock` | The account stays connected and existing chats keep working; WhatsApp blocks only the **start of new conversations**. `expiresAt` carries the end of enforcement when WhatsApp states it. | Baileys |
+| `tos_block` | WhatsApp Web refuses the link on Terms-of-Service grounds (`TOS_BLOCK`, or `SMB_TOS_BLOCK` for a business account). | whatsapp-web.js |
+| `proxy_block` | WhatsApp Web refuses the egress address the session connects from (`PROXYBLOCK`) — about the route, not the account. | whatsapp-web.js |
+
+`code` is the engine's own token for the cause, passed through verbatim (`TOS_BLOCK`, `BIZ_QUALITY`, `WEB_COMPANION_ONLY`, …), so a value newer than your gateway build still reaches you rather than being flattened. Because `tos_block`/`proxy_block` prevent the session from linking at all, neither can appear alongside a `ready` status; a `reachout_timelock` can, and usually does. Like `engineLoaded`, the field is derived from live engine state, never persisted, and re-established on the next connect. Changes are also delivered as the `session.restriction` webhook.
+
`engineLoaded` reports whether the gateway holds a live engine for the session at the moment of the response. It is the precondition the lifecycle routes enforce, and **`status` is not a substitute for it**: `disconnected` covers both a session whose engine is still registered while an automatic reconnect backs off — where `POST /start` answers `400` — and one stopped through `POST /stop`, which has no engine and does need a start. When `engineLoaded` is `true`, `stop`, `logout` and `force-kill` can act; when it is `false`, `start` is the applicable route. The field is derived per request from live process state, so it is never persisted and never appears in historical/exported data.
**Errors:** `401` missing/invalid `X-API-Key`
@@ -3500,7 +3511,7 @@ Webhooks are configured per session and managed under `/api/sessions/:sessionId/
Two fields — `secret` and `headers` — are **write-only**: they are accepted on create/update but are **never** returned in any response (the response DTO has no `@Expose` for them, so `fromEntity` drops them). The `secret` is used to compute the `X-OpenWA-Signature: sha256=<hex>` HMAC-SHA256 header on deliveries.
-The `events` array accepts these members plus the `*` wildcard: `message.received`, `message.sent`, `message.ack`, `message.failed`, `message.revoked`, `message.reaction`, `message.edited`, `session.status`, `session.qr`, `session.authenticated`, `session.disconnected`, `session.reconnect_loop`, `group.join`, `group.leave`, `group.update`, `call.received`, `status.received`. All of them are actively dispatched by the engines.
+The `events` array accepts these members plus the `*` wildcard: `message.received`, `message.sent`, `message.ack`, `message.failed`, `message.revoked`, `message.reaction`, `message.edited`, `session.status`, `session.qr`, `session.authenticated`, `session.disconnected`, `session.reconnect_loop`, `session.restriction`, `group.join`, `group.leave`, `group.update`, `call.received`, `status.received`. All of them are actively dispatched by the engines.
#### GET /api/sessions/:sessionId/webhooks
@@ -5376,7 +5387,7 @@ status.received
A subscribe request whose `events` array contains no recognized name (after filtering) is rejected with `INVALID_EVENTS`. Unknown names mixed with valid ones are silently dropped; the `subscribed` reply echoes only the accepted events.
-> `message.failed` and `session.reconnect_loop` are webhook-only — they are not subscribable on the socket.
+> `message.failed`, `session.reconnect_loop` and `session.restriction` are webhook-only — they are not subscribable on the socket.
### Wildcards and scoping
@@ -5445,6 +5456,7 @@ These are the events OpenWA actually emits. A webhook is registered with an `eve
| `session.authenticated` | The session pairs and becomes ready | `{ sessionId, phone, pushName }` |
| `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.restriction` | WhatsApp places a restriction on the account, or lifts one. Deduped: an unchanged restriction is not re-announced, and a lift is only sent when one was in force | `{ sessionId, active, kind, code, expiresAt }` — `active` is `false` for a lift and `kind`/`code` then describe the restriction that ended; `expiresAt` is an ISO timestamp or `null`. See `restriction` on the session response for the `kind` values |
| `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 |
| `group.leave` | Participant(s) leave or are removed from a group | `{ groupId, actorId?, participantIds, timestamp }` |
diff --git a/docs/12-troubleshooting-faq.md b/docs/12-troubleshooting-faq.md
index 5647575a1..3bf1f464e 100644
--- a/docs/12-troubleshooting-faq.md
+++ b/docs/12-troubleshooting-faq.md
@@ -1100,6 +1100,7 @@ available_events:
- session.authenticated # Session authenticated
- session.disconnected # Session disconnected
- session.reconnect_loop # Every 5th consecutive reconnect attempt (payload: sessionId, attempts, nextDelayMs)
+ - session.restriction # WhatsApp restricted the account, or lifted it (payload: sessionId, active, kind, code, expiresAt)
# Groups
- group.join # Participant(s) added/joined
diff --git a/docs/22-n8n-integration.md b/docs/22-n8n-integration.md
index 2d1552cf1..f5958a258 100644
--- a/docs/22-n8n-integration.md
+++ b/docs/22-n8n-integration.md
@@ -88,6 +88,7 @@ Start workflows when WhatsApp events occur.
| `session.authenticated` | Session logged in (phone available) | Startup notifications |
| `session.disconnected` | Session lost connection | Alert monitoring |
| `session.reconnect_loop` | Every 5th consecutive reconnect attempt | Stuck-session alerting |
+| `session.restriction` | WhatsApp restricted the account, or lifted it | Pausing outreach while an account is limited |
| `group.join` | Participant(s) joined a group | Welcome messages |
| `group.leave` | Participant(s) left a group | Churn tracking |
| `group.update` | Group subject/description/settings changed | Group administration |
diff --git a/openapi.json b/openapi.json
index f5baf7c5d..50e15e2be 100644
--- a/openapi.json
+++ b/openapi.json
@@ -6755,6 +6755,37 @@
"name"
]
},
+ "AccountRestrictionDto": {
+ "type": "object",
+ "properties": {
+ "kind": {
+ "type": "string",
+ "enum": [
+ "reachout_timelock",
+ "tos_block",
+ "proxy_block"
+ ],
+ "description": "What WhatsApp is restricting. `reachout_timelock` leaves the session connected and existing chats working, blocking only the start of new conversations. `tos_block` and `proxy_block` are connection-level refusals — the session cannot stay linked while one is in force, so seeing either alongside a `ready` status is not possible.",
+ "example": "reachout_timelock"
+ },
+ "code": {
+ "type": "string",
+ "description": "The engine's own token for the cause, passed through verbatim so it can be searched for and so a value newer than this gateway is still surfaced rather than flattened.",
+ "example": "BIZ_QUALITY"
+ },
+ "expiresAt": {
+ "type": "string",
+ "format": "date-time",
+ "description": "When enforcement ends, if the engine states it. Only reachout timelocks carry an expiry; absent means the engine gave no end time, not that the restriction is permanent.",
+ "example": "2026-08-04T09:00:00Z",
+ "nullable": true
+ }
+ },
+ "required": [
+ "kind",
+ "code"
+ ]
+ },
"SessionResponseDto": {
"type": "object",
"properties": {
@@ -6818,6 +6849,16 @@
"example": "Failed to launch the browser process: spawn /usr/bin/chromium ENOENT",
"nullable": true
},
+ "restriction": {
+ "description": "A restriction WhatsApp itself has placed on this session's account, or null when there is none. Distinct from `lastError`, which describes a fault on our side of the link. Derived from live engine state, so it is never persisted: it is re-established on the next connect.",
+ "nullable": true,
+ "type": "object",
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/AccountRestrictionDto"
+ }
+ ]
+ },
"engineLoaded": {
"type": "boolean",
"description": "Whether the gateway currently holds a live engine for this session. This is the precondition the lifecycle routes actually enforce, and `status` alone does not imply it: a `disconnected` session keeps its engine for the duration of an automatic reconnect backoff, while a session stopped through `POST /sessions/:id/stop` carries the same status with no engine. When `true`, `stop`, `logout` and `force-kill` can act and `start` answers 400; when `false`, the reverse. Derived per request from live process state, so it is never persisted and never historical.",
@@ -7045,6 +7086,7 @@
"session.authenticated",
"session.disconnected",
"session.reconnect_loop",
+ "session.restriction",
"group.join",
"group.leave",
"group.update",
@@ -7191,6 +7233,7 @@
"session.authenticated",
"session.disconnected",
"session.reconnect_loop",
+ "session.restriction",
"group.join",
"group.leave",
"group.update",
diff --git a/sdk/go/client_test.go b/sdk/go/client_test.go
index d52487bd9..6af0a5f8c 100644
--- a/sdk/go/client_test.go
+++ b/sdk/go/client_test.go
@@ -989,6 +989,7 @@ func TestWebhookEventWireValues(t *testing.T) {
EventSessionAuthenticated: "session.authenticated",
EventSessionDisconnected: "session.disconnected",
EventSessionReconnectLoop: "session.reconnect_loop",
+ EventSessionRestriction: "session.restriction",
EventGroupJoin: "group.join",
EventGroupLeave: "group.leave",
EventGroupUpdate: "group.update",
diff --git a/sdk/go/types_session.go b/sdk/go/types_session.go
index 85c2dd0db..bf8de07bc 100644
--- a/sdk/go/types_session.go
+++ b/sdk/go/types_session.go
@@ -15,6 +15,20 @@ func (q *ListSessionsQuery) values() url.Values {
return v
}
+// AccountRestriction is a restriction WhatsApp has in force on a session's account.
+//
+// "reachout_timelock" leaves the session connected and existing chats working -- only starting new
+// conversations is blocked -- whereas "tos_block" and "proxy_block" refuse the connection itself and
+// therefore cannot coexist with a "ready" status.
+type AccountRestriction struct {
+ // Kind is one of: reachout_timelock, tos_block, proxy_block.
+ Kind string `json:"kind"`
+ // Code is the engine's own token for the cause, verbatim (TOS_BLOCK, BIZ_QUALITY, ...).
+ Code string `json:"code"`
+ // ExpiresAt is an ISO timestamp for the end of enforcement, when WhatsApp states one.
+ ExpiresAt *string `json:"expiresAt,omitempty"`
+}
+
// SessionResponse describes a WhatsApp session. Status is one of: created,
// initializing, qr_ready, authenticating, ready, disconnected, action_required,
// failed.
@@ -29,6 +43,9 @@ type SessionResponse struct {
CreatedAt string `json:"createdAt,omitempty"`
UpdatedAt string `json:"updatedAt,omitempty"`
LastError *string `json:"lastError,omitempty"`
+ // Restriction reports a limit WhatsApp itself has placed on the account, or nil when there is
+ // none. Distinct from LastError, which describes a fault on the gateway's side.
+ Restriction *AccountRestriction `json:"restriction,omitempty"`
// EngineLoaded reports whether the gateway holds a live engine for this session -- the
// precondition stop/logout/force-kill require and start refuses. Not derivable from Status:
// "disconnected" covers both a session mid automatic-reconnect (engine present) and one stopped
diff --git a/sdk/go/types_webhook.go b/sdk/go/types_webhook.go
index 6118df670..7b7eda96b 100644
--- a/sdk/go/types_webhook.go
+++ b/sdk/go/types_webhook.go
@@ -21,6 +21,7 @@ const (
EventSessionAuthenticated WebhookEvent = "session.authenticated"
EventSessionDisconnected WebhookEvent = "session.disconnected"
EventSessionReconnectLoop WebhookEvent = "session.reconnect_loop"
+ EventSessionRestriction WebhookEvent = "session.restriction"
EventGroupJoin WebhookEvent = "group.join"
EventGroupLeave WebhookEvent = "group.leave"
EventGroupUpdate WebhookEvent = "group.update"
diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/model/AccountRestriction.java b/sdk/java/src/main/java/com/rmyndharis/openwa/model/AccountRestriction.java
new file mode 100644
index 000000000..685e0586b
--- /dev/null
+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/model/AccountRestriction.java
@@ -0,0 +1,14 @@
+package com.rmyndharis.openwa.model;
+
+/**
+ * A restriction WhatsApp has in force on a session's account.
+ *
+ * <p>{@code reachout_timelock} leaves the session connected and existing chats working — only
+ * starting new conversations is blocked — whereas {@code tos_block} and {@code proxy_block} refuse
+ * the connection itself and therefore cannot coexist with a {@code READY} status.
+ *
+ * @param kind one of {@code reachout_timelock}, {@code tos_block}, {@code proxy_block}
+ * @param code the engine's own token for the cause, verbatim ({@code TOS_BLOCK}, {@code BIZ_QUALITY}, …)
+ * @param expiresAt ISO timestamp for the end of enforcement, when WhatsApp states one
+ */
+public record AccountRestriction(String kind, String code, String expiresAt) {}
diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/model/SessionResponse.java b/sdk/java/src/main/java/com/rmyndharis/openwa/model/SessionResponse.java
index abf339868..f3475d93e 100644
--- a/sdk/java/src/main/java/com/rmyndharis/openwa/model/SessionResponse.java
+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/model/SessionResponse.java
@@ -13,6 +13,11 @@ public record SessionResponse(
String updatedAt,
/** Present when {@code status == FAILED} or {@code status == ACTION_REQUIRED}. */
String lastError,
+ /**
+ * A limit WhatsApp itself has placed on the account, or {@code null} when there is none.
+ * Distinct from {@code lastError}, which describes a fault on the gateway's side.
+ */
+ AccountRestriction restriction,
/**
* Whether the gateway holds a live engine for this session. The precondition the lifecycle
* routes enforce; not derivable from {@code status}, since {@code DISCONNECTED} covers both a
diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/model/WebhookEvent.java b/sdk/java/src/main/java/com/rmyndharis/openwa/model/WebhookEvent.java
index 93bf4752c..d9a876122 100644
--- a/sdk/java/src/main/java/com/rmyndharis/openwa/model/WebhookEvent.java
+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/model/WebhookEvent.java
@@ -32,6 +32,8 @@ public enum WebhookEvent {
SESSION_DISCONNECTED,
@SerializedName("session.reconnect_loop")
SESSION_RECONNECT_LOOP,
+ @SerializedName("session.restriction")
+ SESSION_RESTRICTION,
@SerializedName("group.join")
GROUP_JOIN,
@SerializedName("group.leave")
diff --git a/sdk/javascript/src/types.ts b/sdk/javascript/src/types.ts
index bf639f8da..68491a4f4 100644
--- a/sdk/javascript/src/types.ts
+++ b/sdk/javascript/src/types.ts
@@ -50,6 +50,12 @@ export interface SessionResponse {
updatedAt: string;
/** Only present when `status === 'failed'` (terminal failure) or `status === 'action_required'` (operator must intervene). */
lastError?: string | null;
+ /**
+ * A limit WhatsApp itself has placed on the account, or `null` when there is none. Distinct from
+ * `lastError`, which describes a fault on the gateway's side. Absent from a gateway that predates
+ * the field.
+ */
+ restriction?: AccountRestriction | null;
/**
* Whether the gateway holds a live engine for this session right now — the precondition `stop`,
* `logout` and `force-kill` require and `start` refuses. Not derivable from `status`:
@@ -59,6 +65,21 @@ export interface SessionResponse {
engineLoaded?: boolean;
}
+/**
+ * A restriction WhatsApp has in force on a session's account.
+ *
+ * `reachout_timelock` leaves the session connected and existing chats working — only starting new
+ * conversations is blocked — whereas `tos_block` and `proxy_block` refuse the connection itself and
+ * therefore cannot coexist with a `ready` status.
+ */
+export interface AccountRestriction {
+ kind: 'reachout_timelock' | 'tos_block' | 'proxy_block';
+ /** The engine's own token for the cause, verbatim (`TOS_BLOCK`, `BIZ_QUALITY`, …). */
+ code: string;
+ /** ISO timestamp when enforcement ends, when WhatsApp states one. */
+ expiresAt?: string | null;
+}
+
export interface CreateSessionRequest {
/** Alphanumeric + hyphens, 3–50 chars. */
name: string;
@@ -582,6 +603,7 @@ export type WebhookEvent =
| 'session.authenticated'
| 'session.disconnected'
| 'session.reconnect_loop'
+ | 'session.restriction'
| 'group.join'
| 'group.leave'
| 'group.update'
diff --git a/sdk/python/openwa/types.py b/sdk/python/openwa/types.py
index d2931a219..f5c29928b 100644
--- a/sdk/python/openwa/types.py
+++ b/sdk/python/openwa/types.py
@@ -30,7 +30,7 @@ BulkMessageType = Literal["text", "image", "video", "audio", "document"]
WebhookEvent = Literal[
"message.received", "message.sent", "message.ack", "message.failed", "message.revoked",
"message.reaction", "message.edited", "session.status", "session.qr", "session.authenticated",
- "session.disconnected", "session.reconnect_loop",
+ "session.disconnected", "session.reconnect_loop", "session.restriction",
"group.join", "group.leave", "group.update", "call.received", "status.received",
"*",
]
@@ -44,6 +44,21 @@ class SuccessResult(TypedDict, total=False):
# ── Session ───────────────────────────────────────────────────────
+class AccountRestriction(TypedDict, total=False):
+ """A restriction WhatsApp has in force on a session's account.
+
+ 'reachout_timelock' leaves the session connected and existing chats working -- only starting new
+ conversations is blocked -- whereas 'tos_block' and 'proxy_block' refuse the connection itself
+ and therefore cannot coexist with a 'ready' status.
+ """
+
+ kind: Literal["reachout_timelock", "tos_block", "proxy_block"]
+ # The engine's own token for the cause, verbatim (TOS_BLOCK, BIZ_QUALITY, ...).
+ code: str
+ # ISO timestamp when enforcement ends, when WhatsApp states one.
+ expiresAt: str | None
+
+
class SessionResponse(TypedDict, total=False):
id: str
name: str
@@ -55,6 +70,9 @@ class SessionResponse(TypedDict, total=False):
createdAt: str
updatedAt: str
lastError: str | None
+ # A limit WhatsApp itself has placed on the account, or None when there is none. Distinct from
+ # lastError, which describes a fault on the gateway's side.
+ restriction: AccountRestriction | None
# Whether the gateway holds a live engine for this session -- the precondition stop/logout/
# force-kill require and start refuses. Not derivable from status: 'disconnected' covers both a
# session mid automatic-reconnect (engine present) and one stopped with no engine. Absent from a
diff --git a/src/common/metrics/session-restriction-metrics.ts b/src/common/metrics/session-restriction-metrics.ts
new file mode 100644
index 000000000..856dbf3c2
--- /dev/null
+++ b/src/common/metrics/session-restriction-metrics.ts
@@ -0,0 +1,20 @@
+/**
+ * How many sessions WhatsApp is currently restricting, for the Prometheus gauge.
+ *
+ * A gauge and not a counter: what an operator alerts on is "an account is restricted right now", and
+ * a restriction that is applied, lifted and re-applied is the same one fact recurring, not a total to
+ * accumulate. It is mirrored here rather than read from the store at render time so the metrics
+ * module does not have to depend on the session module for one number — `SessionRestrictionStore` is
+ * the single writer and republishes its own size after every mutation.
+ */
+let restrictedSessions = 0;
+
+/** Publish the current number of restricted sessions (called by SessionRestrictionStore). */
+export function setRestrictedSessionCount(count: number): void {
+ restrictedSessions = count;
+}
+
+/** Sessions under a WhatsApp-imposed restriction at this moment. */
+export function getRestrictedSessionCount(): number {
+ return restrictedSessions;
+}
diff --git a/src/engine/adapters/baileys-lifecycle.ts b/src/engine/adapters/baileys-lifecycle.ts
index 484f24c92..b8f48af25 100644
--- a/src/engine/adapters/baileys-lifecycle.ts
+++ b/src/engine/adapters/baileys-lifecycle.ts
@@ -97,6 +97,8 @@ export interface BaileysLifecycleHost {
getOnStateChanged(): EngineEventCallbacks['onStateChanged'];
/** The currently-registered onCredentialTeardownStarted callback, if any (assigned at initialize()). */
getOnCredentialTeardownStarted(): EngineEventCallbacks['onCredentialTeardownStarted'];
+ /** The currently-registered onAccountRestriction callback, if any (assigned at initialize()). */
+ getOnAccountRestriction(): EngineEventCallbacks['onAccountRestriction'];
}
export class BaileysLifecycle {
@@ -325,8 +327,16 @@ export class BaileysLifecycle {
connection?: string;
qr?: string;
lastDisconnect?: { error?: unknown };
+ reachoutTimeLock?: { isActive?: boolean; timeEnforcementEnds?: Date; enforcementType?: string };
}): void {
- const { connection, qr, lastDisconnect } = update;
+ const { connection, qr, lastDisconnect, reachoutTimeLock } = update;
+
+ // Arrives on its own update (no `connection` key) both when WhatsApp pushes a change and when
+ // probeAccountRestriction() pulls the current state — Baileys routes its own query result back
+ // through this same event, so one handler covers both channels.
+ if (reachoutTimeLock) {
+ this.reportReachoutTimelock(reachoutTimeLock);
+ }
if (qr) {
// Baileys hands us the raw QR ref string; render it to a PNG data URL so the stored
@@ -350,6 +360,9 @@ export class BaileysLifecycle {
this.connectedAt = Math.floor(Date.now() / 1000) - 10;
this.setStatus(EngineStatus.READY);
this.host.getOnReady()?.(this.phoneNumber ?? '', this.pushName ?? '');
+ // WhatsApp only PUSHES a timelock when it changes, so a gateway that starts (or reconnects)
+ // while the account is already restricted would never hear about it. Ask once per connection.
+ void this.probeAccountRestriction();
// Backfill names the initial sync skipped (see BaileysHistory.hydrateNames).
void this.host.hydrateNames();
}
@@ -429,6 +442,59 @@ export class BaileysLifecycle {
}
}
+ /**
+ * Translate Baileys' reachout-timelock state into the neutral restriction signal. Baileys reports
+ * this first-class — it is not inferred from failures — and it reports the lift as well as the
+ * onset, so `isActive: false` is a positive "no restriction" and is forwarded as `null`.
+ *
+ * A timelock does NOT close the connection: the account stays linked and existing chats keep
+ * working, only starting new conversations is blocked. Nothing here touches status or reconnects.
+ */
+ private reportReachoutTimelock(state: {
+ isActive?: boolean;
+ timeEnforcementEnds?: Date;
+ enforcementType?: string;
+ }): void {
+ const report = this.host.getOnAccountRestriction();
+ if (!report) return;
+
+ if (!state.isActive) {
+ report(null);
+ return;
+ }
+
+ // `time_enforcement_ends` is a server-supplied string Baileys parses with parseInt, so a
+ // malformed value yields an Invalid Date whose getTime() is NaN — which would serialize to null
+ // and read as "no expiry known". Same outcome, but reached deliberately rather than by accident.
+ const endsAt = state.timeEnforcementEnds?.getTime();
+ report({
+ kind: 'reachout_timelock',
+ // DEFAULT is Baileys' own "no specific enforcement type" value, not a placeholder of ours.
+ code: state.enforcementType ?? 'DEFAULT',
+ expiresAt: typeof endsAt === 'number' && Number.isFinite(endsAt) ? endsAt : undefined,
+ });
+ }
+
+ /**
+ * Ask WhatsApp for the account's current restriction standing. The answer is not used here:
+ * Baileys emits its own `connection.update { reachoutTimeLock }` with the result, so it arrives
+ * through the same path as a pushed change.
+ *
+ * Best-effort by design — an account or server that does not answer this query must not turn a
+ * healthy connection into a logged failure, so it stays at debug level.
+ */
+ private async probeAccountRestriction(): Promise<void> {
+ try {
+ await this.sock?.fetchAccountReachoutTimelock();
+ } catch (error) {
+ this.host.logger.debug('Could not read the account restriction state', {
+ action: 'baileys_restriction_probe_failed',
+ sessionId: this.host.config.sessionId,
+ error: String(error),
+ });
+ }
+ }
+
/**
* Schedule the next reconnect attempt with capped exponential backoff (1 s doubling up to a 60 s
* cap, plus up to 1 s jitter). Deliberately NO attempt ceiling: transient drops retry forever —
diff --git a/src/engine/adapters/baileys.adapter.spec.ts b/src/engine/adapters/baileys.adapter.spec.ts
index ee05fae27..25c62b438 100644
--- a/src/engine/adapters/baileys.adapter.spec.ts
+++ b/src/engine/adapters/baileys.adapter.spec.ts
@@ -62,6 +62,9 @@ class FakeSock extends EventEmitter {
public newsletterFollow = jest.fn().mockResolvedValue(undefined);
public newsletterUnfollow = jest.fn().mockResolvedValue(undefined);
public rejectCall = jest.fn().mockResolvedValue(undefined);
+ // Baileys answers this by emitting its own connection.update carrying the result, so the default
+ // mirrors that: resolving alone proves nothing reached the adapter.
+ public fetchAccountReachoutTimelock = jest.fn().mockResolvedValue({ isActive: false });
public signalRepository: { lidMapping: { getLIDForPN: jest.Mock } } | undefined;
fire(event: string, arg: unknown): void {
this.emitter.emit(event, arg);
@@ -4124,3 +4127,121 @@ describe('BaileysAdapter catalog (#905)', () => {
expect(fakeSock.sendMessage).not.toHaveBeenCalled();
});
});
+
+// Baileys models the reachout timelock first-class — a typed state with both a push notification and
+// a query — so this is not inference from failed sends. The account stays connected throughout: a
+// timelock blocks only the start of NEW conversations, which is why nothing here touches status.
+describe('BaileysAdapter account-restriction reporting', () => {
+ beforeEach(() => {
+ fakeSock.user = undefined;
+ fakeSock.resetEmitter();
+ jest.clearAllMocks();
+ fakeSock.fetchAccountReachoutTimelock.mockResolvedValue({ isActive: false });
+ });
+
+ it('reports an active timelock with its enforcement type and expiry', async () => {
+ const onAccountRestriction = jest.fn();
+ const adapter = newAdapter();
+ await adapter.initialize(noopCallbacks({ onAccountRestriction }));
+ const ends = new Date('2026-08-04T09:00:00.000Z');
+
+ fakeSock.fire('connection.update', {
+ reachoutTimeLock: { isActive: true, timeEnforcementEnds: ends, enforcementType: 'BIZ_QUALITY' },
+ });
+
+ expect(onAccountRestriction).toHaveBeenCalledWith({
+ kind: 'reachout_timelock',
+ code: 'BIZ_QUALITY',
+ expiresAt: ends.getTime(),
+ });
+ });
+
+ // WhatsApp can omit the enforcement type; DEFAULT is Baileys' own name for "no specific type",
+ // so the field is never left undefined for consumers to special-case.
+ it('falls back to DEFAULT when no enforcement type is given', async () => {
+ const onAccountRestriction = jest.fn();
+ const adapter = newAdapter();
+ await adapter.initialize(noopCallbacks({ onAccountRestriction }));
+
+ fakeSock.fire('connection.update', { reachoutTimeLock: { isActive: true } });
+
+ expect(onAccountRestriction).toHaveBeenCalledWith({
+ kind: 'reachout_timelock',
+ code: 'DEFAULT',
+ expiresAt: undefined,
+ });
+ });
+
+ // `time_enforcement_ends` is a server string Baileys parses with parseInt, so a malformed value
+ // reaches us as an Invalid Date. NaN must not be forwarded as if it were a real expiry.
+ it('drops an unparseable expiry rather than forwarding NaN', async () => {
+ const onAccountRestriction = jest.fn();
+ const adapter = newAdapter();
+ await adapter.initialize(noopCallbacks({ onAccountRestriction }));
+
+ fakeSock.fire('connection.update', {
+ reachoutTimeLock: { isActive: true, timeEnforcementEnds: new Date('nonsense'), enforcementType: 'BIZ_QUALITY' },
+ });
+
+ expect(onAccountRestriction).toHaveBeenCalledWith({
+ kind: 'reachout_timelock',
+ code: 'BIZ_QUALITY',
+ expiresAt: undefined,
+ });
+ });
+
+ // Baileys reports the lift as well as the onset, so this is a positive "no restriction" and is
+ // forwarded as null — consumers may clear on it.
+ it('forwards a lifted timelock as null', async () => {
+ const onAccountRestriction = jest.fn();
+ const adapter = newAdapter();
+ await adapter.initialize(noopCallbacks({ onAccountRestriction }));
+
+ fakeSock.fire('connection.update', { reachoutTimeLock: { isActive: false } });
+
+ expect(onAccountRestriction).toHaveBeenCalledWith(null);
+ });
+
+ // The push only fires when the state CHANGES, so a gateway that starts while the account is
+ // already restricted would never be told. Asking on every connection is what closes that gap.
+ it('asks WhatsApp for the current restriction on every connection open', async () => {
+ const adapter = newAdapter();
+ await adapter.initialize(noopCallbacks({}));
+
+ fakeSock.fire('connection.update', { connection: 'open' });
+ await new Promise(r => setImmediate(r));
+
+ expect(fakeSock.fetchAccountReachoutTimelock).toHaveBeenCalledTimes(1);
+ });
+
+ // An account or server that will not answer the query must not turn a healthy connection into a
+ // failure — the connection is already open and READY by this point.
+ it('survives a probe that rejects, leaving the session READY', async () => {
+ fakeSock.fetchAccountReachoutTimelock.mockRejectedValue(new Error('not-authorized'));
+ const adapter = newAdapter();
+ await adapter.initialize(noopCallbacks({}));
+ fakeSock.user = { id: '628999:[email protected]', name: 'Me' };
+
+ fakeSock.fire('connection.update', { connection: 'open' });
+ await new Promise(r => setImmediate(r));
+
+ expect(adapter.getStatus()).toBe(EngineStatus.READY);
+ });
+
+ // Detection is observation only: a timelock leaves the account connected, so treating it as a
+ // disconnect would tear down a session that is still able to serve every existing chat.
+ it('does not disturb the session status or connection when a timelock arrives', async () => {
+ const onDisconnected = jest.fn();
+ const onError = jest.fn();
+ const adapter = newAdapter();
+ await adapter.initialize(noopCallbacks({ onDisconnected, onError }));
+ fakeSock.user = { id: '628999:[email protected]', name: 'Me' };
+ fakeSock.fire('connection.update', { connection: 'open' });
+
+ fakeSock.fire('connection.update', { reachoutTimeLock: { isActive: true, enforcementType: 'BIZ_QUALITY' } });
+
+ expect(adapter.getStatus()).toBe(EngineStatus.READY);
+ expect(onDisconnected).not.toHaveBeenCalled();
+ expect(onError).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/engine/adapters/baileys.adapter.ts b/src/engine/adapters/baileys.adapter.ts
index 589b4a3b2..8f7771b47 100644
--- a/src/engine/adapters/baileys.adapter.ts
+++ b/src/engine/adapters/baileys.adapter.ts
@@ -219,6 +219,7 @@ export class BaileysAdapter implements IWhatsAppEngine {
getOnError: () => this.callbacks.onError,
getOnStateChanged: () => this.callbacks.onStateChanged,
getOnCredentialTeardownStarted: () => this.callbacks.onCredentialTeardownStarted,
+ getOnAccountRestriction: () => this.callbacks.onAccountRestriction,
});
}
diff --git a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
index f7b810ee4..d9e75489f 100644
--- a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
+++ b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
@@ -5564,3 +5564,99 @@ describe('probeOnboardingModal (in-page onboarding modal detection)', () => {
expect(button.click).not.toHaveBeenCalled();
});
});
+
+// WhatsApp Web has no dedicated channel for account standing: a ToS block arrives as a WAState
+// string on the same generic `disconnected` event as an unlink, a takeover or a version mismatch.
+// These tests pin which of those twelve states the adapter is willing to call a restriction, because
+// a false positive here is worse than no signal at all — it is the input a consumer acts on.
+describe('WhatsAppWebJsAdapter account-restriction reporting', () => {
+ type FakeClient = EventEmitter & { getState: jest.Mock; pupPage: { evaluate: jest.Mock } };
+
+ // These tests emit disconnected:LOGOUT, whose handler reaches clearLocalAuth() → fs.rm(force:true)
+ // of `<sessionDataPath>/session-sess-1`. Stub it: unmocked, running this suite on a machine that
+ // happens to hold a session with that name would silently delete its WhatsApp credentials.
+ let rmSpy: jest.SpyInstance;
+ beforeEach(() => {
+ rmSpy = jest.spyOn(fs.promises, 'rm').mockResolvedValue(undefined);
+ });
+ afterEach(() => rmSpy.mockRestore());
+
+ const attachRestrictionAware = (): {
+ client: FakeClient;
+ onAccountRestriction: jest.Mock;
+ onDisconnected: jest.Mock;
+ } => {
+ const adapter = new WhatsAppWebJsAdapter({
+ sessionId: 'sess-1',
+ sessionDataPath: './data/sessions',
+ puppeteer: {},
+ });
+ const client = Object.assign(new EventEmitter(), {
+ getState: jest.fn().mockResolvedValue(WAState.CONNECTED),
+ pupPage: { evaluate: jest.fn().mockResolvedValue(true) },
+ }) as FakeClient;
+ const onAccountRestriction = jest.fn();
+ const onDisconnected = jest.fn();
+ (adapter as unknown as { client: unknown }).client = client;
+ (adapter as unknown as { callbacks: unknown }).callbacks = { onAccountRestriction, onDisconnected };
+ (adapter as unknown as { setupEventHandlers: () => void }).setupEventHandlers();
+ return { client, onAccountRestriction, onDisconnected };
+ };
+
+ it.each([
+ [WAState.TOS_BLOCK, 'tos_block'],
+ [WAState.SMB_TOS_BLOCK, 'tos_block'],
+ [WAState.PROXYBLOCK, 'proxy_block'],
+ ])('reports %s as a %s restriction, passing the state through as the cause', (state, kind) => {
+ const { client, onAccountRestriction } = attachRestrictionAware();
+
+ client.emit('disconnected', state);
+
+ expect(onAccountRestriction).toHaveBeenCalledWith({ kind, code: state });
+ });
+
+ // The states that are NOT WhatsApp judging the account. UNPAIRED/LOGOUT are unlinks, CONFLICT is
+ // another device taking over, DEPRECATED_VERSION is our client being stale and TIMEOUT is a fault.
+ // Reporting any of them would make the signal meaningless for the consumers that act on it.
+ it.each([
+ WAState.UNPAIRED,
+ WAState.UNPAIRED_IDLE,
+ WAState.CONFLICT,
+ WAState.DEPRECATED_VERSION,
+ WAState.TIMEOUT,
+ 'LOGOUT',
+ 'NAVIGATION',
+ ])('does not report %s as a restriction', state => {
+ const { client, onAccountRestriction } = attachRestrictionAware();
+
+ client.emit('disconnected', state);
+
+ expect(onAccountRestriction).not.toHaveBeenCalled();
+ // Guards the stub above rather than the feature: proves no LOGOUT path in these tests reached a
+ // real credential removal, so a future change here cannot start deleting a developer's profile.
+ expect(rmSpy).not.toHaveBeenCalled();
+ });
+
+ // The restriction explains the disconnect, so it has to be known before the disconnect is handled —
+ // a consumer that schedules a reconnect on the disconnect must already be able to see why.
+ it('reports the restriction before the disconnect it explains', () => {
+ const order: string[] = [];
+ const { client, onAccountRestriction, onDisconnected } = attachRestrictionAware();
+ onAccountRestriction.mockImplementation(() => order.push('restriction'));
+ onDisconnected.mockImplementation(() => order.push('disconnected'));
+
+ client.emit('disconnected', WAState.TOS_BLOCK);
+
+ expect(order).toEqual(['restriction', 'disconnected']);
+ });
+
+ // Detection is observation only. If it also decided the session were dead, a misread state would
+ // permanently down a session that the existing reconnect would have recovered.
+ it('leaves the disconnect handling untouched — the reason still flows through unchanged', () => {
+ const { client, onDisconnected } = attachRestrictionAware();
+
+ client.emit('disconnected', WAState.TOS_BLOCK);
+
+ expect(onDisconnected).toHaveBeenCalledWith(WAState.TOS_BLOCK);
+ });
+});
diff --git a/src/engine/adapters/whatsapp-web-js.adapter.ts b/src/engine/adapters/whatsapp-web-js.adapter.ts
index 1dbb0bddf..3be9036bc 100644
--- a/src/engine/adapters/whatsapp-web-js.adapter.ts
+++ b/src/engine/adapters/whatsapp-web-js.adapter.ts
@@ -41,6 +41,7 @@ import {
ChatState,
GroupEvent,
IncomingCallEvent,
+ AccountRestriction,
} from '../interfaces/whatsapp-engine.interface';
import { resolveWebVersionPin } from '../wa-web-version';
import { resolveAuthTimeoutMs } from '../engine-init-timeout';
@@ -114,6 +115,21 @@ export interface WhatsAppWebJsConfig {
const READY_RECONCILE_INTERVAL_MS = 2000;
const READY_RECONCILE_TIMEOUT_MS = 90_000;
+// WhatsApp Web states that mean WhatsApp has judged the account or its egress, mapped to the neutral
+// restriction kinds. This is the ONLY channel the library offers: there is no dedicated event, error
+// type or cause code for account standing (whatsapp-web.js 1.34.7), just a `WAState` string on the
+// `disconnected` event.
+//
+// Deliberately only three of the twelve states. UNPAIRED/UNPAIRED_IDLE and LOGOUT are unlinks,
+// CONFLICT is another device taking over, DEPRECATED_VERSION is our own client being too old, and
+// TIMEOUT is a fault — none is a statement about the account's standing, and reporting them as
+// restrictions would be exactly the false positive that makes the signal worthless to act on.
+const WA_STATE_RESTRICTIONS: Readonly<Record<string, AccountRestriction['kind']>> = {
+ TOS_BLOCK: 'tos_block',
+ SMB_TOS_BLOCK: 'tos_block',
+ PROXYBLOCK: 'proxy_block',
+};
+
// Onboarding-modal watcher (#982). A freshly-linked account shows a "What's new on WhatsApp Web"
// modal with a Continue button that must be acknowledged, or WhatsApp unlinks the companion ~5m
// later (surfacing as disconnected: LOGOUT). whatsapp-web.js exposes no API for this (#3550 open),
@@ -591,6 +607,13 @@ export class WhatsAppWebJsAdapter extends EventEmitter implements IWhatsAppEngin
);
}
this.setStatus(EngineStatus.DISCONNECTED);
+ // Report the account judgement BEFORE the disconnect so a consumer reacting to the disconnect
+ // already knows why it happened. Only the state token is passed through — the adapter draws no
+ // conclusion about recoverability from it and leaves the reconnect decision exactly as it was.
+ const restriction = WA_STATE_RESTRICTIONS[reason];
+ if (restriction) {
+ this.callbacks.onAccountRestriction?.({ kind: restriction, code: reason });
+ }
this.callbacks.onDisconnected?.(reason);
});
diff --git a/src/engine/interfaces/whatsapp-engine.interface.ts b/src/engine/interfaces/whatsapp-engine.interface.ts
index 84e5ccab1..f8017590b 100644
--- a/src/engine/interfaces/whatsapp-engine.interface.ts
+++ b/src/engine/interfaces/whatsapp-engine.interface.ts
@@ -504,6 +504,37 @@ export interface IncomingCallEvent {
timestamp: number;
}
+/**
+ * A restriction WhatsApp itself has placed on the account behind a session — as opposed to a
+ * connection fault, a stale credential, or an operator action.
+ *
+ * The two engines report genuinely different things, so `kind` is the discriminator consumers act
+ * on rather than a lowest common denominator:
+ *
+ * - `reachout_timelock` (Baileys) — the account stays connected and existing chats keep working;
+ * WhatsApp only blocks *starting new conversations*. Reported first-class by the library
+ * (`connection.update.reachoutTimeLock`), including when it is lifted.
+ * - `tos_block` / `proxy_block` (whatsapp-web.js) — a connection-level refusal: WhatsApp Web drops
+ * the socket and the engine cannot stay linked at all. Derived from the `WAState` the library
+ * reports on its `disconnected` event, which is the only channel that carries it.
+ *
+ * That difference is load-bearing for clearing: a `reachout_timelock` can only be resolved by an
+ * explicit lift signal, whereas a connection-scoped kind is disproved the moment the session reaches
+ * READY again — the block would have prevented that.
+ */
+export interface AccountRestriction {
+ kind: 'reachout_timelock' | 'tos_block' | 'proxy_block';
+ /**
+ * The engine's own token for the cause, kept verbatim so an operator can search for it and so a
+ * new upstream value is surfaced rather than flattened: the `WAState` string on whatsapp-web.js
+ * (`TOS_BLOCK`, `SMB_TOS_BLOCK`, `PROXYBLOCK`) or the enforcement type on Baileys (`BIZ_QUALITY`,
+ * `WEB_COMPANION_ONLY`, one of the BIZ_COMMERCE_VIOLATION_* values, …).
+ */
+ code: string;
+ /** Unix ms when enforcement ends, when the engine states it (Baileys timelocks only). */
+ expiresAt?: number;
+}
+
export interface EngineEventCallbacks {
onQRCode?: (qr: string) => void;
onReady?: (phone: string, pushName: string) => void;
@@ -551,6 +582,17 @@ export interface EngineEventCallbacks {
* to READY.
*/
onActionRequired?: (reason: string) => void;
+ /**
+ * Fired when the engine learns that WhatsApp has restricted (or un-restricted) the account behind
+ * this session. `null` means the engine positively reports no restriction in force — it is a
+ * *lift*, not "unknown", so consumers may clear state on it; an engine that simply never learns
+ * anything stays silent instead.
+ *
+ * Purely informational: the adapter does NOT change its own status or reconnect behavior because
+ * of a restriction, so this cannot turn a recoverable session into a dead one on a misread.
+ * Consumers decide what a restriction is worth.
+ */
+ onAccountRestriction?: (restriction: AccountRestriction | null) => void;
/**
* Fired on a terminal initialization/authentication failure (e.g. Chromium
* could not launch, or WhatsApp rejected the stored credentials). The engine
diff --git a/src/modules/metrics/metrics.service.spec.ts b/src/modules/metrics/metrics.service.spec.ts
index 097ecd6a7..3bddc5757 100644
--- a/src/modules/metrics/metrics.service.spec.ts
+++ b/src/modules/metrics/metrics.service.spec.ts
@@ -7,6 +7,7 @@ import {
getSessionReconnectAttemptsTotal,
getSessionReconnectLoopAlertsTotal,
} from '../../common/metrics/session-reconnect-metrics';
+import { setRestrictedSessionCount } from '../../common/metrics/session-restriction-metrics';
describe('MetricsService', () => {
const overview: OverviewStats = {
@@ -74,6 +75,23 @@ describe('MetricsService', () => {
expect(out.endsWith('\n')).toBe(true);
});
+ // A gauge, not a counter: what matters is how many accounts are restricted right now, and a
+ // restriction that is applied, lifted and re-applied is one recurring fact, not a running total.
+ it('emits the restricted-session gauge from the live count', async () => {
+ setRestrictedSessionCount(2);
+ const out = await makeService('s3cret').render();
+
+ expect(out).toContain('# TYPE openwa_sessions_restricted gauge');
+ expect(out).toContain('openwa_sessions_restricted 2');
+ });
+
+ it('reports zero restricted sessions rather than omitting the gauge', async () => {
+ setRestrictedSessionCount(0);
+ const out = await makeService('s3cret').render();
+
+ expect(out).toContain('openwa_sessions_restricted 0');
+ });
+
it('memoizes the rendered output within the TTL (one getOverview per window)', async () => {
jest.useFakeTimers();
try {
diff --git a/src/modules/metrics/metrics.service.ts b/src/modules/metrics/metrics.service.ts
index b15784290..00f1aca24 100644
--- a/src/modules/metrics/metrics.service.ts
+++ b/src/modules/metrics/metrics.service.ts
@@ -7,6 +7,7 @@ import {
getSessionReconnectAttemptsTotal,
getSessionReconnectLoopAlertsTotal,
} from '../../common/metrics/session-reconnect-metrics';
+import { getRestrictedSessionCount } from '../../common/metrics/session-restriction-metrics';
import { renderHttpRequestMetrics } from '../../common/metrics/request-metrics';
/**
@@ -117,6 +118,10 @@ export class MetricsService {
lines.push('# TYPE openwa_session_reconnect_loop_alerts_total counter');
lines.push(`openwa_session_reconnect_loop_alerts_total ${getSessionReconnectLoopAlertsTotal()}`);
+ lines.push('# HELP openwa_sessions_restricted Sessions whose account WhatsApp is currently restricting.');
+ lines.push('# TYPE openwa_sessions_restricted gauge');
+ lines.push(`openwa_sessions_restricted ${getRestrictedSessionCount()}`);
+
// HTTP RED metrics (request rate + duration per route), recorded by RequestMetricsInterceptor.
// Included in the same cached render — a few seconds of staleness is fine for Prometheus.
lines.push(...renderHttpRequestMetrics());
diff --git a/src/modules/session/dto/session-response.dto.ts b/src/modules/session/dto/session-response.dto.ts
index 0f7d9d0eb..48fd3e164 100644
--- a/src/modules/session/dto/session-response.dto.ts
+++ b/src/modules/session/dto/session-response.dto.ts
@@ -2,6 +2,38 @@ import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
import type { Session } from '../entities/session.entity';
import { SessionStatus } from '../entities/session.entity';
+export class AccountRestrictionDto {
+ @ApiProperty({
+ enum: ['reachout_timelock', 'tos_block', 'proxy_block'],
+ description:
+ 'What WhatsApp is restricting. `reachout_timelock` leaves the session connected and existing ' +
+ 'chats working, blocking only the start of new conversations. `tos_block` and `proxy_block` ' +
+ 'are connection-level refusals — the session cannot stay linked while one is in force, so ' +
+ 'seeing either alongside a `ready` status is not possible.',
+ example: 'reachout_timelock',
+ })
+ kind: 'reachout_timelock' | 'tos_block' | 'proxy_block';
+
+ @ApiProperty({
+ description:
+ "The engine's own token for the cause, passed through verbatim so it can be searched for and " +
+ 'so a value newer than this gateway is still surfaced rather than flattened.',
+ example: 'BIZ_QUALITY',
+ })
+ code: string;
+
+ @ApiPropertyOptional({
+ type: String,
+ format: 'date-time',
+ description:
+ 'When enforcement ends, if the engine states it. Only reachout timelocks carry an expiry; ' +
+ 'absent means the engine gave no end time, not that the restriction is permanent.',
+ example: '2026-08-04T09:00:00Z',
+ nullable: true,
+ })
+ expiresAt?: Date | null;
+}
+
export class SessionResponseDto {
@ApiProperty({ example: 'sess_123e4567-e89b-12d3-a456-426614174000' })
id: string;
@@ -40,6 +72,16 @@ export class SessionResponseDto {
})
lastError?: string | null;
+ @ApiPropertyOptional({
+ type: AccountRestrictionDto,
+ description:
+ "A restriction WhatsApp itself has placed on this session's account, or null when there is " +
+ 'none. Distinct from `lastError`, which describes a fault on our side of the link. Derived ' +
+ 'from live engine state, so it is never persisted: it is re-established on the next connect.',
+ nullable: true,
+ })
+ restriction?: AccountRestrictionDto | null;
+
@ApiProperty({
description:
'Whether the gateway currently holds a live engine for this session. This is the precondition ' +
@@ -74,6 +116,15 @@ export class SessionResponseDto {
createdAt: session.createdAt,
updatedAt: session.updatedAt,
lastError: session.lastError ?? null,
+ restriction: session.restriction
+ ? {
+ kind: session.restriction.kind,
+ code: session.restriction.code,
+ // Held as epoch ms internally (what the engine gives us); served as a date-time like
+ // every other timestamp in this response.
+ expiresAt: session.restriction.expiresAt ? new Date(session.restriction.expiresAt) : null,
+ }
+ : null,
engineLoaded,
};
}
diff --git a/src/modules/session/entities/session.entity.ts b/src/modules/session/entities/session.entity.ts
index 2a09eb58b..09cf863a7 100644
--- a/src/modules/session/entities/session.entity.ts
+++ b/src/modules/session/entities/session.entity.ts
@@ -1,6 +1,7 @@
import { Entity, Column, PrimaryGeneratedColumn, CreateDateColumn, UpdateDateColumn } from 'typeorm';
import { DateTransformer } from '../../../common/transformers/date.transformer';
import { jsonColumnType, dateColumnType } from '../../../common/utils/column-types';
+import type { AccountRestriction } from '../../../engine/interfaces/whatsapp-engine.interface';
export enum SessionStatus {
CREATED = 'created',
@@ -63,4 +64,11 @@ export class Session {
* is runtime state that resets when the engine re-initializes.
*/
lastError?: string;
+
+ /**
+ * Transient (non-persisted) restriction WhatsApp currently has in force on this session's account,
+ * or null when there is none. Populated at read time from SessionRestrictionStore, which explains
+ * why it is runtime state rather than a column.
+ */
+ restriction?: AccountRestriction | null;
}
diff --git a/src/modules/session/logout-teardown-race.spec.ts b/src/modules/session/logout-teardown-race.spec.ts
index 13b5d08ea..3f7f3e8be 100644
--- a/src/modules/session/logout-teardown-race.spec.ts
+++ b/src/modules/session/logout-teardown-race.spec.ts
@@ -6,6 +6,7 @@ import { ConfigService } from '@nestjs/config';
import { SessionService } from './session.service';
import { SessionEngineLifecycle } from './session-engine-lifecycle.service';
import { SessionErrorStore } from './session-error-store.service';
+import { SessionRestrictionStore } from './session-restriction-store.service';
import { Session, SessionStatus } from './entities/session.entity';
import { Message } from '../message/entities/message.entity';
import { EngineFactory } from '../../engine/engine.factory';
@@ -96,6 +97,7 @@ describe('SessionService logout() name-scoped teardown fence', () => {
SessionService,
SessionEngineLifecycle,
SessionErrorStore,
+ SessionRestrictionStore,
{ provide: getRepositoryToken(Session, 'data'), useValue: repository },
{ provide: getRepositoryToken(Message, 'data'), useValue: messageRepository },
{ provide: getDataSourceToken('data'), useValue: dataSource },
diff --git a/src/modules/session/session-engine-controls.ts b/src/modules/session/session-engine-controls.ts
index 8666c181b..faa02f25f 100644
--- a/src/modules/session/session-engine-controls.ts
+++ b/src/modules/session/session-engine-controls.ts
@@ -10,6 +10,7 @@ import { BaileysStoredMessage } from '../../engine/adapters/baileys-stored-messa
import { EngineFactory } from '../../engine/engine.factory';
import { EngineRegistry } from '../../engine/engine-registry.service';
import { SessionErrorStore } from './session-error-store.service';
+import { SessionRestrictionStore } from './session-restriction-store.service';
import { type createLogger } from '../../common/services/logger.service';
import { HookManager } from '../../core/hooks';
import { SessionLifecycleFences } from './session-lifecycle-fences';
@@ -43,6 +44,7 @@ export interface SessionEngineControlsHost {
engineFactory: EngineFactory;
engines: EngineRegistry;
sessionErrors: SessionErrorStore;
+ sessionRestrictions: SessionRestrictionStore;
hookManager: HookManager;
configService?: ConfigService;
logger: ReturnType<typeof createLogger>;
@@ -79,6 +81,7 @@ export class SessionEngineControls {
private readonly engineFactory: EngineFactory;
private readonly engines: EngineRegistry;
private readonly sessionErrors: SessionErrorStore;
+ private readonly sessionRestrictions: SessionRestrictionStore;
private readonly hookManager: HookManager;
private readonly configService?: ConfigService;
private readonly logger: ReturnType<typeof createLogger>;
@@ -94,6 +97,7 @@ export class SessionEngineControls {
this.engineFactory = host.engineFactory;
this.engines = host.engines;
this.sessionErrors = host.sessionErrors;
+ this.sessionRestrictions = host.sessionRestrictions;
this.hookManager = host.hookManager;
this.configService = host.configService;
this.logger = host.logger;
@@ -105,13 +109,13 @@ export class SessionEngineControls {
this.initializingSessions = host.initializingSessions;
}
- /** findOne-or-404 with the last-error projection, mirroring SessionService.findOne. */
+ /** findOne-or-404 with the runtime-state projection, mirroring SessionService.findOne. */
private async requireSession(id: string): Promise<Session> {
const session = await this.sessionRepository.findOne({ where: { id } });
if (!session) {
throw new NotFoundException(`Session with id '${id}' not found`);
}
- return this.sessionErrors.attachTo(session);
+ return this.sessionRestrictions.attachTo(this.sessionErrors.attachTo(session));
}
async start(id: string): Promise<Session> {
@@ -507,6 +511,9 @@ export class SessionEngineControls {
// Drop the FAILED-reason entry too: it's keyed by a now-deleted UUID that can never be read
// again, so leaving it would grow the map without bound across create/fail/delete churn.
this.sessionErrors.clear(id);
+ // Same unbounded-growth argument for the restriction entry, and the gauge it feeds must not
+ // keep counting an account whose session no longer exists.
+ this.sessionRestrictions.clear(id);
// The stuck-auth recovery budget is keyed by id; a committed delete frees it (and a recreated
// session under the same name gets a fresh UUID + fresh budget). Left only on a committed
// delete so a failed/409 delete — the session still exists — keeps the budget intact.
diff --git a/src/modules/session/session-engine-event-wiring.ts b/src/modules/session/session-engine-event-wiring.ts
index 3105dff27..2dcf7bdd6 100644
--- a/src/modules/session/session-engine-event-wiring.ts
+++ b/src/modules/session/session-engine-event-wiring.ts
@@ -1,6 +1,7 @@
import { SessionStatus } from './entities/session.entity';
import { MessageProjector } from './message-projector.service';
import { SessionErrorStore } from './session-error-store.service';
+import { SessionRestrictionStore } from './session-restriction-store.service';
import { EventsGateway } from '../events/events.gateway';
import { WebhookService } from '../webhook/webhook.service';
import { HookManager } from '../../core/hooks';
@@ -9,6 +10,7 @@ import {
EngineStatus,
IWhatsAppEngine,
IncomingCallEvent,
+ AccountRestriction,
} from '../../engine/interfaces/whatsapp-engine.interface';
import { type createLogger } from '../../common/services/logger.service';
import { SessionEngineLeafEvents } from './session-engine-leaf-events';
@@ -33,6 +35,8 @@ export interface SessionEngineWiringHost {
cancelReconnect(id: string): void;
evictAndForceDestroy(id: string, engine: IWhatsAppEngine): void;
trackPendingCredentialTeardown(sessionName: string, raw: Promise<void>): void;
+ /** Announce a restriction that has ended; shared with the lifecycle's own READY path. */
+ reportRestrictionLifted(id: string, lifted: AccountRestriction): void;
/**
* SYNCHRONOUS atomic one-shot claim over the lifecycle's shared stuckAuthRecoveryUsed Set (bound
* by reference through the closure): true exactly once per episode, and only while `engine` is
@@ -41,6 +45,7 @@ export interface SessionEngineWiringHost {
claimStuckAuthRecovery(id: string, engine: IWhatsAppEngine): boolean;
messages: MessageProjector;
sessionErrors: SessionErrorStore;
+ sessionRestrictions: SessionRestrictionStore;
webhookService: WebhookService;
eventsGateway: EventsGateway;
hookManager: HookManager;
@@ -208,6 +213,36 @@ export class SessionEngineEventWiring {
host.sessionErrors.set(id, reason);
void host.hookManager.execute('session:error', { reason }, { sessionId: id, source: 'Engine' });
},
+ onAccountRestriction: (restriction: AccountRestriction | null): void => {
+ if (!host.isLiveEngine(id, engine)) return;
+
+ // A lift is only news if we were holding a restriction; an engine that reports "no
+ // restriction" on every connect (the Baileys probe does exactly that) must stay quiet.
+ if (!restriction) {
+ const lifted = host.sessionRestrictions.clear(id);
+ if (lifted) host.reportRestrictionLifted(id, lifted);
+ return;
+ }
+
+ // Both engines repeat an unchanged restriction — whatsapp-web.js on every reconnect attempt,
+ // Baileys on every connect probe — so only a change reaches an operator.
+ if (!host.sessionRestrictions.set(id, restriction)) return;
+
+ this.logger.warn(`WhatsApp restricted this session's account: ${restriction.kind}`, {
+ sessionId: id,
+ kind: restriction.kind,
+ code: restriction.code,
+ expiresAt: restriction.expiresAt,
+ action: 'account_restricted',
+ });
+ void host.webhookService.dispatch(id, 'session.restriction', {
+ sessionId: id,
+ active: true,
+ kind: restriction.kind,
+ code: restriction.code,
+ expiresAt: restriction.expiresAt ? new Date(restriction.expiresAt).toISOString() : null,
+ });
+ },
onError: (reason: string): void => {
if (!host.isLiveEngine(id, engine)) return;
this.logger.error(`Session engine failed: ${reason}`, undefined, {
diff --git a/src/modules/session/session-engine-lifecycle.service.ts b/src/modules/session/session-engine-lifecycle.service.ts
index e3edd4196..cb5d6bf73 100644
--- a/src/modules/session/session-engine-lifecycle.service.ts
+++ b/src/modules/session/session-engine-lifecycle.service.ts
@@ -9,9 +9,10 @@ import { decideReconnect, type ReconnectAttemptState } from './reconnect-policy'
import { SessionLivenessWatchdog } from './session-liveness-watchdog.service';
import { MessageProjector } from './message-projector.service';
import { SessionErrorStore } from './session-error-store.service';
+import { SessionRestrictionStore } from './session-restriction-store.service';
import { resolveEngineInitTimeoutMs } from '../../engine/engine-init-timeout';
import { StatusStoreService } from '../status-store/status-store.service';
-import { IWhatsAppEngine } from '../../engine/interfaces/whatsapp-engine.interface';
+import { IWhatsAppEngine, AccountRestriction } from '../../engine/interfaces/whatsapp-engine.interface';
import { createLogger } from '../../common/services/logger.service';
import { ShutdownService } from '../../common/services/shutdown.service';
import {
@@ -209,6 +210,7 @@ export class SessionEngineLifecycle {
private readonly watchdog: SessionLivenessWatchdog,
private readonly messages: MessageProjector,
private readonly sessionErrors: SessionErrorStore,
+ private readonly sessionRestrictions: SessionRestrictionStore,
private readonly eventsGateway: EventsGateway,
private readonly webhookService: WebhookService,
private readonly hookManager: HookManager,
@@ -257,6 +259,7 @@ export class SessionEngineLifecycle {
cancelReconnect: id => this.cancelReconnect(id),
evictAndForceDestroy: (id, engine) => this.evictAndForceDestroy(id, engine),
trackPendingCredentialTeardown: (sessionName, raw) => this.trackPendingCredentialTeardown(sessionName, raw),
+ reportRestrictionLifted: (id, lifted) => this.reportRestrictionLifted(id, lifted),
claimStuckAuthRecovery: (id, engine) => {
// SYNCHRONOUS atomic claim for the one-shot automatic credential-reset budget. The adapter
// calls this right before it would wipe LocalAuth (recoverFromStuckAuth); a denial makes the
@@ -274,6 +277,7 @@ export class SessionEngineLifecycle {
},
messages: this.messages,
sessionErrors: this.sessionErrors,
+ sessionRestrictions: this.sessionRestrictions,
webhookService: this.webhookService,
eventsGateway: this.eventsGateway,
hookManager: this.hookManager,
@@ -289,6 +293,7 @@ export class SessionEngineLifecycle {
engineFactory: this.engineFactory,
engines: this.engineRegistry,
sessionErrors: this.sessionErrors,
+ sessionRestrictions: this.sessionRestrictions,
hookManager: this.hookManager,
configService: this.configService,
logger: this.logger,
@@ -423,7 +428,11 @@ export class SessionEngineLifecycle {
proxyType: session.proxyType || undefined,
});
this.engines.set(id, engine);
- // Clear any prior failure reason before a fresh start.
+ // Clear any prior failure reason before a fresh start. A recorded account restriction is
+ // deliberately NOT cleared here: it describes the account, not this attempt, so a restart does
+ // not resolve it — and clearing it per attempt would make it flicker off and on through a
+ // reconnect loop, re-announcing one unchanged block on every pass. It is dropped where it is
+ // actually disproved (handleEngineReady) or reported lifted.
this.sessionErrors.clear(id);
// Mark INITIALIZING before engine.initialize(): the engine drives status forward
@@ -575,6 +584,12 @@ export class SessionEngineLifecycle {
// A fresh READY stretch starts the watchdog's failure budget clean too.
this.watchdog.clear(id);
this.sessionErrors.clear(id);
+ // Being linked and ready is proof that a connection-level block is over — it is exactly what such
+ // a block prevents. A reachout timelock survives: it never stopped the session connecting.
+ const liftedByReady = this.sessionRestrictions.clearIfDisprovedByReady(id);
+ if (liftedByReady) {
+ this.reportRestrictionLifted(id, liftedByReady);
+ }
// READY proves any in-flight stuck-auth recovery succeeded (or none was needed), so the
// one-shot recovery budget is re-armed for a future episode.
this.stuckAuthRecoveryUsed.delete(id);
@@ -600,6 +615,31 @@ export class SessionEngineLifecycle {
void this.seedStatuses(id, engine);
}
+ /**
+ * Announce that a restriction has ended. Shared by the two paths that can end one — the engine
+ * reporting it lifted, and a session reaching READY despite a connection-level block — so the two
+ * cannot drift into announcing the same thing differently. The caller has already removed it from
+ * the store and passes what was removed, since the payload describes the restriction that ended.
+ */
+ reportRestrictionLifted(id: string, lifted: AccountRestriction): void {
+ // Phrased as "no longer in force" rather than "WhatsApp lifted it": only one of the two paths is
+ // WhatsApp saying so. The other infers it from the session having connected, and the log should
+ // not claim more than was actually observed.
+ this.logger.log(`The ${lifted.kind} restriction on this session is no longer in force`, {
+ sessionId: id,
+ kind: lifted.kind,
+ code: lifted.code,
+ action: 'account_restriction_lifted',
+ });
+ void this.webhookService.dispatch(id, 'session.restriction', {
+ sessionId: id,
+ active: false,
+ kind: lifted.kind,
+ code: lifted.code,
+ expiresAt: null,
+ });
+ }
+
/**
* Shared disconnect handling for BOTH the engine's onDisconnected callback and the liveness
* watchdog: notify consumers (webhook + WS + hook), persist DISCONNECTED, then schedule a
diff --git a/src/modules/session/session-restriction-store.service.spec.ts b/src/modules/session/session-restriction-store.service.spec.ts
new file mode 100644
index 000000000..2a165ad07
--- /dev/null
+++ b/src/modules/session/session-restriction-store.service.spec.ts
@@ -0,0 +1,156 @@
+import { SessionRestrictionStore } from './session-restriction-store.service';
+import { getRestrictedSessionCount } from '../../common/metrics/session-restriction-metrics';
+import { Session, SessionStatus } from './entities/session.entity';
+import type { AccountRestriction } from '../../engine/interfaces/whatsapp-engine.interface';
+
+const timelock = (over: Partial<AccountRestriction> = {}): AccountRestriction => ({
+ kind: 'reachout_timelock',
+ code: 'BIZ_QUALITY',
+ ...over,
+});
+
+const tosBlock = (): AccountRestriction => ({ kind: 'tos_block', code: 'TOS_BLOCK' });
+
+const sessionRow = (id: string, status = SessionStatus.READY): Session => ({ id, status }) as Session;
+
+describe('SessionRestrictionStore', () => {
+ let store: SessionRestrictionStore;
+
+ beforeEach(() => {
+ store = new SessionRestrictionStore();
+ });
+
+ describe('reporting a change', () => {
+ // The dedupe is the whole reason set() returns a boolean: whatsapp-web.js re-reports the same
+ // block on every reconnect attempt and the Baileys probe re-reads the same timelock on every
+ // connect, so an un-deduped caller would announce one unchanged fact on a loop.
+ it('is news the first time and not afterwards', () => {
+ expect(store.set('s1', timelock())).toBe(true);
+ expect(store.set('s1', timelock())).toBe(false);
+ expect(store.set('s1', timelock())).toBe(false);
+ });
+
+ it('is news again when the cause changes', () => {
+ store.set('s1', timelock({ code: 'BIZ_QUALITY' }));
+
+ expect(store.set('s1', timelock({ code: 'WEB_COMPANION_ONLY' }))).toBe(true);
+ });
+
+ it('is news when the kind changes even though the session already had a restriction', () => {
+ store.set('s1', timelock());
+
+ expect(store.set('s1', tosBlock())).toBe(true);
+ });
+
+ // Sessions must not dedupe against each other — the map is keyed per session, and an account
+ // restricted for the same reason as another is still separate news.
+ it('tracks sessions independently', () => {
+ expect(store.set('s1', timelock())).toBe(true);
+ expect(store.set('s2', timelock())).toBe(true);
+ expect(store.get('s1')).toEqual(timelock());
+ expect(store.get('s2')).toEqual(timelock());
+ });
+
+ // Announcing a re-report would be noise, but serving a stale expiry from the API would be wrong,
+ // so the stored entry refreshes even when the caller is told nothing changed.
+ it('refreshes the stored expiry without announcing it', () => {
+ store.set('s1', timelock({ expiresAt: 1000 }));
+
+ expect(store.set('s1', timelock({ expiresAt: 9999 }))).toBe(false);
+ expect(store.get('s1')?.expiresAt).toBe(9999);
+ });
+ });
+
+ describe('clearing', () => {
+ it('returns what it removed so the caller can report the cause that ended', () => {
+ store.set('s1', timelock());
+
+ expect(store.clear('s1')).toEqual(timelock());
+ expect(store.get('s1')).toBeUndefined();
+ });
+
+ it('returns nothing when there was no restriction, so no lift is announced', () => {
+ expect(store.clear('s1')).toBeUndefined();
+ });
+
+ // The load-bearing distinction between the two engines' restrictions. A connection-level block is
+ // exactly what prevents a session from reaching READY, so being READY disproves it.
+ it('READY disproves a connection-level block', () => {
+ store.set('s1', tosBlock());
+
+ expect(store.clearIfDisprovedByReady('s1')).toEqual(tosBlock());
+ expect(store.get('s1')).toBeUndefined();
+ });
+
+ // …but a timelock leaves the account fully connected, so READY says nothing about it. Clearing it
+ // here would silently drop a restriction that is still in force.
+ it('READY does not disprove a reachout timelock', () => {
+ store.set('s1', timelock());
+
+ expect(store.clearIfDisprovedByReady('s1')).toBeUndefined();
+ expect(store.get('s1')).toEqual(timelock());
+ });
+
+ it('READY on an unrestricted session is a no-op', () => {
+ expect(store.clearIfDisprovedByReady('s1')).toBeUndefined();
+ });
+ });
+
+ describe('the gauge', () => {
+ // The metric is mirrored out of the store rather than read from it, so every mutation path has
+ // to republish or the gauge drifts from reality.
+ it('counts restricted sessions as they are added and removed', () => {
+ store.set('s1', timelock());
+ store.set('s2', tosBlock());
+ expect(getRestrictedSessionCount()).toBe(2);
+
+ store.clear('s1');
+ expect(getRestrictedSessionCount()).toBe(1);
+
+ store.clearIfDisprovedByReady('s2');
+ expect(getRestrictedSessionCount()).toBe(0);
+ });
+
+ it('does not double-count a session whose restriction is re-reported', () => {
+ store.set('s1', timelock());
+ store.set('s1', timelock());
+ store.set('s1', timelock({ code: 'WEB_COMPANION_ONLY' }));
+
+ expect(getRestrictedSessionCount()).toBe(1);
+ });
+
+ // The count is per-deployment, not per-session: clearing one session republishes the whole map's
+ // size, so a delete of an unrestricted session must not disturb what other sessions contribute.
+ it('leaves the count alone when clearing a session that was not restricted', () => {
+ store.set('s1', timelock());
+
+ store.clear('s2');
+
+ expect(getRestrictedSessionCount()).toBe(1);
+ });
+ });
+
+ describe('the read projection', () => {
+ it('attaches the restriction in force', () => {
+ store.set('s1', timelock({ expiresAt: 1234 }));
+
+ expect(store.attachTo(sessionRow('s1')).restriction).toEqual(timelock({ expiresAt: 1234 }));
+ });
+
+ it('attaches null when there is none, so the field is always present', () => {
+ expect(store.attachTo(sessionRow('s1')).restriction).toBeNull();
+ });
+
+ // Unlike lastError, this is NOT conditioned on the session's status: a reachout timelock applies
+ // to a perfectly READY session, and hiding it behind a status would make it invisible exactly
+ // when it matters.
+ it.each([SessionStatus.READY, SessionStatus.DISCONNECTED, SessionStatus.FAILED, SessionStatus.CREATED])(
+ 'surfaces the restriction while the status is %s',
+ status => {
+ store.set('s1', timelock());
+
+ expect(store.attachTo(sessionRow('s1', status)).restriction).toEqual(timelock());
+ },
+ );
+ });
+});
diff --git a/src/modules/session/session-restriction-store.service.ts b/src/modules/session/session-restriction-store.service.ts
new file mode 100644
index 000000000..90412b877
--- /dev/null
+++ b/src/modules/session/session-restriction-store.service.ts
@@ -0,0 +1,85 @@
+import { Injectable } from '@nestjs/common';
+import type { AccountRestriction } from '../../engine/interfaces/whatsapp-engine.interface';
+import { setRestrictedSessionCount } from '../../common/metrics/session-restriction-metrics';
+import { Session } from './entities/session.entity';
+
+/**
+ * Restrictions WhatsApp currently has in force on the accounts behind live sessions.
+ *
+ * In memory and not a column, for the same reason as {@link SessionErrorStore}: it describes what
+ * the engine has observed in THIS process. The difference is that a restriction is a fact about the
+ * account rather than about our attempt, so losing it on restart would matter — except that both
+ * engines re-report it on the next connection (Baileys is asked directly on every connect, and
+ * whatsapp-web.js re-blocks the very next link attempt), so the state re-seeds itself within one
+ * session start. That self-healing is what makes the column unnecessary.
+ *
+ * Only ACTIVE restrictions are held: a lift removes the entry rather than storing a negative, so the
+ * map's size is the count of restricted sessions and `get` returning nothing means "not restricted".
+ */
+@Injectable()
+export class SessionRestrictionStore {
+ private readonly restrictions = new Map<string, AccountRestriction>();
+
+ /**
+ * Record a restriction the engine reported.
+ *
+ * Returns whether this is NEW news — a change of kind or cause — which is what callers gate their
+ * operator-facing signals on. Both engines repeat themselves: whatsapp-web.js re-reports the same
+ * block on every reconnect attempt, and the Baileys probe re-reads the same timelock on every
+ * connect, so an un-deduped webhook would fire on a loop for one unchanged fact.
+ *
+ * The stored entry is refreshed either way, so a re-report with a later `expiresAt` updates what
+ * the API serves without being announced as a new restriction.
+ */
+ set(sessionId: string, restriction: AccountRestriction): boolean {
+ const previous = this.restrictions.get(sessionId);
+ this.restrictions.set(sessionId, restriction);
+ setRestrictedSessionCount(this.restrictions.size);
+ return previous?.kind !== restriction.kind || previous?.code !== restriction.code;
+ }
+
+ /** The restriction in force, if any. `attachTo` is the projection; this is the raw read. */
+ get(sessionId: string): AccountRestriction | undefined {
+ return this.restrictions.get(sessionId);
+ }
+
+ /**
+ * Drop the restriction — it was lifted, or the session was restarted or deleted. Returns what was
+ * dropped so the caller can report the lift with the cause that ended.
+ */
+ clear(sessionId: string): AccountRestriction | undefined {
+ const previous = this.restrictions.get(sessionId);
+ this.restrictions.delete(sessionId);
+ setRestrictedSessionCount(this.restrictions.size);
+ return previous;
+ }
+
+ /**
+ * Drop the restriction only if reaching READY disproves it.
+ *
+ * `tos_block` and `proxy_block` are refusals of the connection itself, so a session that is now
+ * linked and ready cannot still be under one. A `reachout_timelock` is not connection-scoped — the
+ * account is fully connected while it applies — so READY says nothing about it and it survives
+ * here, waiting for the engine's explicit lift.
+ */
+ clearIfDisprovedByReady(sessionId: string): AccountRestriction | undefined {
+ const previous = this.restrictions.get(sessionId);
+ if (!previous || previous.kind === 'reachout_timelock') return undefined;
+ return this.clear(sessionId);
+ }
+
+ /** How many sessions are restricted right now. */
+ size(): number {
+ return this.restrictions.size;
+ }
+
+ /**
+ * Populate the transient `restriction` field. Unlike `lastError` this is not conditioned on the
+ * status: a reachout timelock applies to a perfectly READY session, and a connection-level block
+ * is cleared by its own path rather than by whatever status the session happens to carry.
+ */
+ attachTo(session: Session): Session {
+ session.restriction = this.restrictions.get(session.id) ?? null;
+ return session;
+ }
+}
diff --git a/src/modules/session/session.controller.spec.ts b/src/modules/session/session.controller.spec.ts
index 5a3300efe..5aa4fad37 100644
--- a/src/modules/session/session.controller.spec.ts
+++ b/src/modules/session/session.controller.spec.ts
@@ -65,6 +65,7 @@ describe('SessionController — create() response contract', () => {
createdAt: entity.createdAt,
updatedAt: entity.updatedAt,
lastError: null,
+ restriction: null,
engineLoaded: false,
});
});
diff --git a/src/modules/session/session.module.ts b/src/modules/session/session.module.ts
index 7a7dff395..1eed92026 100644
--- a/src/modules/session/session.module.ts
+++ b/src/modules/session/session.module.ts
@@ -8,6 +8,7 @@ import { SessionLidResolver } from './session-lid-resolver.service';
import { SessionLivenessWatchdog } from './session-liveness-watchdog.service';
import { MessageProjector } from './message-projector.service';
import { SessionErrorStore } from './session-error-store.service';
+import { SessionRestrictionStore } from './session-restriction-store.service';
import { SessionController } from './session.controller';
import { WebhookModule } from '../webhook/webhook.module';
import { StatusStoreModule } from '../status-store/status-store.module';
@@ -22,6 +23,7 @@ import { ChatMediaModule } from '../chat-media/chat-media.module';
SessionService,
SessionEngineLifecycle,
SessionErrorStore,
+ SessionRestrictionStore,
SessionLidResolver,
SessionLivenessWatchdog,
MessageProjector,
diff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.ts
index cfe9b555f..0b3146077 100644
--- a/src/modules/session/session.service.spec.ts
+++ b/src/modules/session/session.service.spec.ts
@@ -1,4 +1,5 @@
import { SessionErrorStore } from './session-error-store.service';
+import { SessionRestrictionStore } from './session-restriction-store.service';
import { Test, TestingModule } from '@nestjs/testing';
import { getRepositoryToken, getDataSourceToken } from '@nestjs/typeorm';
import { Repository, DataSource, In } from 'typeorm';
@@ -196,6 +197,7 @@ describe('SessionService', () => {
SessionService,
SessionEngineLifecycle,
SessionErrorStore,
+ SessionRestrictionStore,
{
provide: getRepositoryToken(Session, 'data'),
useValue: repository,
@@ -2023,6 +2025,146 @@ describe('SessionService', () => {
});
});
+ // A restriction is WhatsApp judging the account, not a fault on our side, so it has its own
+ // channel: a webhook, a field on the session, and a gauge — never a status change. Both engines
+ // repeat themselves (whatsapp-web.js on every reconnect attempt, the Baileys probe on every
+ // connect), so the dedupe is the load-bearing part of this wiring.
+ describe('engine account restriction', () => {
+ const timelock = { kind: 'reachout_timelock' as const, code: 'BIZ_QUALITY' };
+
+ const startAndCapture = async (): Promise<EngineEventCallbacks> => {
+ (repository.findOne as jest.Mock).mockResolvedValue(createMockSession());
+ (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });
+ await service.start('sess-uuid-1');
+ const calls = mockEngine.initialize.mock.calls as [EngineEventCallbacks][];
+ return calls[0][0];
+ };
+
+ it('announces a newly-detected restriction to webhook subscribers', async () => {
+ const callbacks = await startAndCapture();
+ (webhookService.dispatch as jest.Mock).mockClear();
+
+ callbacks.onAccountRestriction?.({ ...timelock, expiresAt: Date.UTC(2026, 7, 4, 9) });
+
+ expect(webhookService.dispatch).toHaveBeenCalledWith('sess-uuid-1', 'session.restriction', {
+ sessionId: 'sess-uuid-1',
+ active: true,
+ kind: 'reachout_timelock',
+ code: 'BIZ_QUALITY',
+ expiresAt: '2026-08-04T09:00:00.000Z',
+ });
+ });
+
+ it('stays silent when the same restriction is reported again', async () => {
+ const callbacks = await startAndCapture();
+ callbacks.onAccountRestriction?.(timelock);
+ (webhookService.dispatch as jest.Mock).mockClear();
+
+ callbacks.onAccountRestriction?.(timelock);
+ callbacks.onAccountRestriction?.(timelock);
+
+ expect(webhookService.dispatch).not.toHaveBeenCalled();
+ });
+
+ it('announces again when the cause changes', async () => {
+ const callbacks = await startAndCapture();
+ callbacks.onAccountRestriction?.(timelock);
+ (webhookService.dispatch as jest.Mock).mockClear();
+
+ callbacks.onAccountRestriction?.({ ...timelock, code: 'WEB_COMPANION_ONLY' });
+
+ expect(webhookService.dispatch).toHaveBeenCalledWith(
+ 'sess-uuid-1',
+ 'session.restriction',
+ expect.objectContaining({ active: true, code: 'WEB_COMPANION_ONLY' }),
+ );
+ });
+
+ it('announces a lift, carrying the cause that ended', async () => {
+ const callbacks = await startAndCapture();
+ callbacks.onAccountRestriction?.(timelock);
+ (webhookService.dispatch as jest.Mock).mockClear();
+
+ callbacks.onAccountRestriction?.(null);
+
+ expect(webhookService.dispatch).toHaveBeenCalledWith('sess-uuid-1', 'session.restriction', {
+ sessionId: 'sess-uuid-1',
+ active: false,
+ kind: 'reachout_timelock',
+ code: 'BIZ_QUALITY',
+ expiresAt: null,
+ });
+ });
+
+ // The Baileys probe reports "no restriction" on every single connect. Announcing a lift for a
+ // session that was never restricted would make the event meaningless.
+ it('stays silent when nothing was in force to lift', async () => {
+ const callbacks = await startAndCapture();
+ (webhookService.dispatch as jest.Mock).mockClear();
+
+ callbacks.onAccountRestriction?.(null);
+
+ expect(webhookService.dispatch).not.toHaveBeenCalled();
+ });
+
+ it('surfaces the restriction on the session read model', async () => {
+ const callbacks = await startAndCapture();
+ callbacks.onAccountRestriction?.({ ...timelock, expiresAt: 1234 });
+
+ (repository.findOne as jest.Mock).mockResolvedValue(createMockSession({ status: SessionStatus.READY }));
+ const result = await service.findOne('sess-uuid-1');
+
+ expect(result.restriction).toEqual({ ...timelock, expiresAt: 1234 });
+ });
+
+ // whatsapp-web.js never reports a block being lifted — it only stops refusing. Reaching READY is
+ // the proof, since a connection-level block is exactly what prevents it.
+ it('treats reaching READY as proof a connection-level block has ended', async () => {
+ const callbacks = await startAndCapture();
+ callbacks.onAccountRestriction?.({ kind: 'tos_block', code: 'TOS_BLOCK' });
+ (webhookService.dispatch as jest.Mock).mockClear();
+
+ callbacks.onReady?.('628123', 'Tester');
+
+ expect(webhookService.dispatch).toHaveBeenCalledWith('sess-uuid-1', 'session.restriction', {
+ sessionId: 'sess-uuid-1',
+ active: false,
+ kind: 'tos_block',
+ code: 'TOS_BLOCK',
+ expiresAt: null,
+ });
+ });
+
+ // …but a timelock leaves the account connected, so READY proves nothing about it. Clearing it
+ // here would drop a restriction that is still in force and still blocking new conversations.
+ it('keeps a reachout timelock across a READY, which does not disprove it', async () => {
+ const callbacks = await startAndCapture();
+ callbacks.onAccountRestriction?.(timelock);
+ (webhookService.dispatch as jest.Mock).mockClear();
+
+ callbacks.onReady?.('628123', 'Tester');
+
+ expect(webhookService.dispatch).not.toHaveBeenCalledWith(
+ 'sess-uuid-1',
+ 'session.restriction',
+ expect.objectContaining({ active: false }),
+ );
+ (repository.findOne as jest.Mock).mockResolvedValue(createMockSession({ status: SessionStatus.READY }));
+ expect((await service.findOne('sess-uuid-1')).restriction).toEqual(timelock);
+ });
+
+ // Detection must not move the session's status: a timelocked account is still connected and
+ // still serving every existing chat, and a status change would take the session out of service.
+ it('does not touch the session status', async () => {
+ const callbacks = await startAndCapture();
+ (repository.update as jest.Mock).mockClear();
+
+ callbacks.onAccountRestriction?.(timelock);
+
+ expect(repository.update).not.toHaveBeenCalled();
+ });
+ });
+
// ── engine-identity guard: stale-callback isolation ───────────────
// A callback can fire after its engine was torn down (post-stop) or after a newer engine
// replaced it for the same id (post-restart / reconnect). Such a stale callback must not
diff --git a/src/modules/session/session.service.ts b/src/modules/session/session.service.ts
index 251532261..449b23814 100644
--- a/src/modules/session/session.service.ts
+++ b/src/modules/session/session.service.ts
@@ -18,6 +18,7 @@ import { EngineRegistry } from '../../engine/engine-registry.service';
import { SessionLidResolver } from './session-lid-resolver.service';
import { SessionLivenessWatchdog } from './session-liveness-watchdog.service';
import { SessionErrorStore } from './session-error-store.service';
+import { SessionRestrictionStore } from './session-restriction-store.service';
import { SessionEngineLifecycle } from './session-engine-lifecycle.service';
import { paginate, ListOptions, resolveListWindow } from '../../common/utils/paginate';
import { isUniqueConstraintError } from '../../common/utils/unique-constraint.util';
@@ -70,6 +71,7 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
private readonly lidResolver: SessionLidResolver,
private readonly watchdog: SessionLivenessWatchdog,
private readonly sessionErrors: SessionErrorStore,
+ private readonly sessionRestrictions: SessionRestrictionStore,
private readonly hookManager: HookManager,
private readonly engineLifecycle: SessionEngineLifecycle,
@Optional()
@@ -208,7 +210,7 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
options.where = { id: In(allowedSessions) };
}
const sessions = await this.sessionRepository.find(options);
- return sessions.map(session => this.attachLastError(session));
+ return sessions.map(session => this.attachRuntimeState(session));
}
async findOne(id: string): Promise<Session> {
@@ -216,12 +218,16 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
if (!session) {
throw new NotFoundException(`Session with id '${id}' not found`);
}
- return this.attachLastError(session);
+ return this.attachRuntimeState(session);
}
- /** See SessionErrorStore — the reason map and this projection live together. */
- private attachLastError(session: Session): Session {
- return this.sessionErrors.attachTo(session);
+ /**
+ * Attach the transient fields no column carries: why the session last failed, and whether
+ * WhatsApp is restricting its account. See SessionErrorStore / SessionRestrictionStore — each map
+ * and its projection live together.
+ */
+ private attachRuntimeState(session: Session): Session {
+ return this.sessionRestrictions.attachTo(this.sessionErrors.attachTo(session));
}
async findByName(name: string): Promise<Session> {
diff --git a/src/modules/webhook/dto/webhook.dto.ts b/src/modules/webhook/dto/webhook.dto.ts
index 3e79c5e09..646a70ab9 100644
--- a/src/modules/webhook/dto/webhook.dto.ts
+++ b/src/modules/webhook/dto/webhook.dto.ts
@@ -48,6 +48,7 @@ export const WEBHOOK_EVENTS = [
'session.authenticated',
'session.disconnected',
'session.reconnect_loop',
+ 'session.restriction',
'group.join',
'group.leave',
'group.update',
diff --git a/src/modules/webhook/utils/idempotency.util.spec.ts b/src/modules/webhook/utils/idempotency.util.spec.ts
index 40e1e338f..91c686475 100644
--- a/src/modules/webhook/utils/idempotency.util.spec.ts
+++ b/src/modules/webhook/utils/idempotency.util.spec.ts
@@ -89,6 +89,41 @@ describe('Idempotency Utils', () => {
expect(a).not.toBe(b);
});
+ // An account restricted, freed and restricted again for the same cause produces byte-identical
+ // payloads. Without the salt the second restriction would be deduped away as a replay of the
+ // first — and that second one is exactly the event an operator needs.
+ it('salts session.restriction keys so a recurring restriction is not deduped away', () => {
+ const payload = { sessionId: 'A', active: true, kind: 'reachout_timelock', code: 'BIZ_QUALITY' };
+ const a = generateIdempotencyKey('session.restriction', payload, '2026-08-03T00:00:00.000Z');
+ const b = generateIdempotencyKey('session.restriction', payload, '2026-08-04T00:00:00.000Z');
+ expect(a).not.toBe(b);
+ });
+
+ // The onset and the lift are two different events about one restriction; they must never collide
+ // even when they land inside the same occurrence timestamp.
+ it('distinguishes a restriction from its lift', () => {
+ const at = '2026-08-03T00:00:00.000Z';
+ const applied = generateIdempotencyKey(
+ 'session.restriction',
+ { sessionId: 'A', active: true, kind: 'reachout_timelock', code: 'BIZ_QUALITY' },
+ at,
+ );
+ const lifted = generateIdempotencyKey(
+ 'session.restriction',
+ { sessionId: 'A', active: false, kind: 'reachout_timelock', code: 'BIZ_QUALITY' },
+ at,
+ );
+ expect(applied).not.toBe(lifted);
+ });
+
+ it('scopes session.restriction keys per session so two accounts do not dedupe each other', () => {
+ const at = '2026-08-03T00:00:00.000Z';
+ const payload = { active: true, kind: 'reachout_timelock', code: 'BIZ_QUALITY' };
+ const a = generateIdempotencyKey('session.restriction', { ...payload, sessionId: 'A' }, at);
+ const b = generateIdempotencyKey('session.restriction', { ...payload, sessionId: 'B' }, at);
+ expect(a).not.toBe(b);
+ });
+
it('is retry-stable: the same lifecycle occurrence regenerates the same key', () => {
const at = '2026-06-19T00:00:00.000Z';
const a = generateIdempotencyKey('session.disconnected', { sessionId: 'A', reason: 'logged out' }, at);
diff --git a/src/modules/webhook/utils/idempotency.util.ts b/src/modules/webhook/utils/idempotency.util.ts
index 591b1a39d..4cba9ae1c 100644
--- a/src/modules/webhook/utils/idempotency.util.ts
+++ b/src/modules/webhook/utils/idempotency.util.ts
@@ -88,6 +88,14 @@ export function generateIdempotencyKey(event: string, data: Record<string, unkno
// always sends 'logged out'), which would otherwise collapse every disconnect onto one key.
return `disc_${toStr(data.sessionId)}_${hashData({ reason: data.reason })}${occurrence}`;
+ case 'session.restriction':
+ // Keyed on what changed (`kind` is null when a restriction is lifted) and salted per
+ // occurrence: an account that is restricted, freed and restricted again for the same cause
+ // produces the same content twice, and the second one is genuine news that must not collapse
+ // onto the first. Without an explicit case the default branch hashes the whole payload, which
+ // would dedupe exactly that.
+ return `restr_${toStr(data.sessionId)}_${toStr(data.kind)}_${toStr(data.active)}${occurrence}`;
+
case 'group.join':
// A membership change carries no unique id and repeats with identical content (the same user
// leaves and rejoins the same group). Key on the affected participants and salt with