Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix: deliver the synchronous stop-mark and close the session-lifecycle follow-ups

Yudhi Armyndharis339659241acd
diff --git a/.env.example b/.env.example
index f5afd9a92..9788538b5 100644
--- a/.env.example
+++ b/.env.example
@@ -327,6 +327,8 @@ WEBHOOK_RETRY_DELAY=5000 # Delay between retries in ms
# WEBHOOK_TIMEOUT — that cross silently truncates deliveries.
# WEBHOOK_MAX_PER_SESSION=16 # max webhooks registered per session; new registrations at/over
# the cap get 400 (existing ones are grandfathered); 0 = unlimited
+# AUTOMATION_MAX_PER_SESSION=32 # max autoreply rules per session; new rules at/over the cap get
+ # 400 (existing ones are grandfathered); 0 = unlimited
# WEBHOOK_MEDIA_INLINE_MAX_BYTES=1048576 # decoded-byte cap for inline base64 media in webhook
# payloads; larger media is delivered as { omitted: true, sizeBytes }
# instead (0 = never inline media)
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 22f62bb1d..dbafd8c9f 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -46,6 +46,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Media conversion answers 400 (not 500) for a blocked, unreachable or oversized input URL; `PUT /channels/:id/mute` refuses a non-channel id instead of muting an ordinary chat forever; listing a label's chats and previewing an unknown group invite answer 404 instead of 500 on whatsapp-web.js; a refused disappearing-message change answers 403; voice-status media is served as audio rather than octet-stream; `PUT /labels/:id` treats explicit `null` fields as an empty body; and an addressbook write with a bare phone number is qualified before it reaches Baileys.
- Link previews are opt-in on the Baileys engine (`linkPreview: true`), restoring the documented engine default: every URL-bearing send was otherwise making a blocking outbound fetch first, which cost a bulk campaign minutes.
- **Small correctness batch:** the cold-reachout history probe matches both user-id spellings (a known contact addressed the other way no longer reads as cold), an expired account-restriction stops badging the session, ending a ringing call clears its live handle, `PUT /labels/:id` refuses an empty body, addressbook writes refuse group/newsletter/broadcast ids (not just `@lid`), and the channel endpoints' OpenAPI docs state the real 403 refusal status instead of 422.
+- **SDKs:** the Go SDK encodes a nil poll-vote `options` as `[]` (clearing a vote now works from the zero value), the Java `GroupSettings` and `SendVoiceStatusRequest` records keep back-compat constructors after gaining a field, and all five SDKs expose the voice-status `backgroundColor` the server accepts.
+- **Autoreply rules gain a per-session cap** (`AUTOMATION_MAX_PER_SESSION`, default 32), and boot now rejects a lease heartbeat that is not comfortably under the TTL and a `NODE_URL` that is scheme-less or carries embedded credentials — each previously failed silently or only at the first forward.
- The dashboard status viewer now plays a voice status with an audio player instead of rendering it as a broken image, the JS SDK's `StatusRecord.type` includes `'voice'`, and the SDK README's method tables and three misplaced doc comments were brought back in line with the actual surface.
- Fetching a status's media that S3 retention already removed answers 404 instead of 500 (the local-storage miss already did), and server-side media conversion is bounded to `MEDIA_CONVERSION_CONCURRENCY` (default 2) concurrent `ffmpeg` processes with a short queue — saturation answers 503 instead of stacking processes.
- **Baileys message-action targeting:** star/pin/unpin/react/delete now verify the stored message belongs to the requested chat (a mismatched pair answered success while writing under the wrong conversation), pin/unpin/react/delete resolve LID-migrated contacts like every other send, and tagging/untagging a chat's label folds the neutral id to the engine form so the write lands on the real chat instead of a phantom index.
diff --git a/docs/04-security-design.md b/docs/04-security-design.md
index b2ebe9452..d99039292 100644
--- a/docs/04-security-design.md
+++ b/docs/04-security-design.md
@@ -74,19 +74,19 @@ fixed `dev-admin-key`; with neither set, the seed key is generated in the format
API keys carry **no permission strings**. Authorization is a role hierarchy on the key itself, plus
two scoping dimensions enforced by `ApiKeyGuard`.
-| Role | Rank | Meaning |
-|------|------|---------|
-| `admin` | 3 | Satisfies every `@RequireRole` level, including API-key management |
-| `operator` | 2 | Satisfies `operator` and `viewer` routes — the default for a new key |
-| `viewer` | 1 | Satisfies `viewer` routes only |
+| Role | Rank | Meaning |
+| ---------- | ---- | -------------------------------------------------------------------- |
+| `admin` | 3 | Satisfies every `@RequireRole` level, including API-key management |
+| `operator` | 2 | Satisfies `operator` and `viewer` routes — the default for a new key |
+| `viewer` | 1 | Satisfies `viewer` routes only |
A route declares its minimum level with `@RequireRole(...)`; a key passes when its role ranks at or
above that level (`AuthService.hasPermission`). A key below it is rejected with `403 Forbidden`.
-| Scope | Field | Effect |
-|-------|-------|--------|
-| Source IP | `allowedIps` | Empty/absent = unrestricted; non-empty = fail-closed IP whitelist (see §4.3) |
-| Sessions | `allowedSessions` | Empty/absent = every session; non-empty = a request carrying any other session id is rejected with `401` |
+| Scope | Field | Effect |
+| --------- | ----------------- | -------------------------------------------------------------------------------------------------------- |
+| Source IP | `allowedIps` | Empty/absent = unrestricted; non-empty = fail-closed IP whitelist (see §4.3) |
+| Sessions | `allowedSessions` | Empty/absent = every session; non-empty = a request carrying any other session id is rejected with `401` |
The key-lifecycle routes (`/api/auth/api-keys`) are additionally fenced with `@RequireUnscopedKey()`:
a session-scoped key is refused there whatever its role, so it cannot mint or widen credentials
@@ -200,13 +200,13 @@ flowchart TB
### Validation Examples
-| Field | Rules |
-|-------|-------|
-| `chatId` | Non-empty string — **no format pattern**; the engine resolves the id, so `@c.us`, `@g.us`, `@lid`, `@newsletter` and `status@broadcast` all pass |
-| `phoneNumber` (pairing code) | Pattern: `^[0-9]{6,15}$` — digits only, international format |
-| `url` | Valid URL (`require_tld: false`, so single-label hosts like `http://localhost:3000` pass); HTTPS is a recommendation, not enforced |
-| `text` | Max 4096 chars (`send-text`) |
-| `sessionName` | Alphanumeric + hyphen, 3-50 chars |
+| Field | Rules |
+| ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ |
+| `chatId` | Non-empty string — **no format pattern**; the engine resolves the id, so `@c.us`, `@g.us`, `@lid`, `@newsletter` and `status@broadcast` all pass |
+| `phoneNumber` (pairing code) | Pattern: `^[0-9]{6,15}$` — digits only, international format |
+| `url` | Valid URL (`require_tld: false`, so single-label hosts like `http://localhost:3000` pass); HTTPS is a recommendation, not enforced |
+| `text` | Max 4096 chars (`send-text`) |
+| `sessionName` | Alphanumeric + hyphen, 3-50 chars |
### DTO Validation
@@ -370,6 +370,7 @@ from unauthenticated WhatsApp senders — so the copy amplification is bounded a
| Bound | Knob | Default | Behavior |
| ----------------------------- | ----------------------------------------- | ---------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| Webhooks per session | `WEBHOOK_MAX_PER_SESSION` | 16 (`0` = unlimited) | Creating a NEW webhook at/over the cap is rejected with `400`; existing webhooks are grandfathered |
+| Autoreply rules per session | `AUTOMATION_MAX_PER_SESSION` | 32 (`0` = unlimited) | Creating a NEW rule at/over the cap is rejected with `400`; existing rules are grandfathered. Every inbound message is evaluated against every rule of its session |
| Inline media in payloads | `WEBHOOK_MEDIA_INLINE_MAX_BYTES` | 1 MiB (`0` = never inline) | Larger media is replaced once, before per-webhook cloning, with `media: { mimetype, filename?, omitted: true, sizeBytes }` |
| Serialized body size | `WEBHOOK_MAX_PAYLOAD_BYTES` | 1 MiB | Over-budget bodies shed any remaining inline media (marker form) and are re-checked; still over budget → recorded as undelivered, never sent/queued |
| Failed-job retention in Redis | queue `removeOnComplete` / `removeOnFail` | 1h/1000 completed, 24h/5000 failed | Finished jobs auto-evict; payloads were already media-shed before enqueue, so retained jobs stay small. The durable record of a lost delivery is the `webhook_delivery_failures` row |
@@ -413,13 +414,13 @@ app.use(helmet({
### Security Headers Checklist
-| Header | Value | Purpose |
-|--------|-------|---------|
-| `Strict-Transport-Security` | `max-age=31536000; includeSubDomains; preload` | Force HTTPS |
-| `X-Content-Type-Options` | `nosniff` | Prevent MIME sniffing |
-| `X-Frame-Options` | `SAMEORIGIN` | Prevent clickjacking (helmet's default; not overridden) |
-| `X-XSS-Protection` | `0` | Helmet 8 deliberately disables the legacy auditor — the CSP is the protection |
-| `Referrer-Policy` | `strict-origin-when-cross-origin` | Control referrer |
+| Header | Value | Purpose |
+| --------------------------- | ---------------------------------------------- | ----------------------------------------------------------------------------- |
+| `Strict-Transport-Security` | `max-age=31536000; includeSubDomains; preload` | Force HTTPS |
+| `X-Content-Type-Options` | `nosniff` | Prevent MIME sniffing |
+| `X-Frame-Options` | `SAMEORIGIN` | Prevent clickjacking (helmet's default; not overridden) |
+| `X-XSS-Protection` | `0` | Helmet 8 deliberately disables the legacy auditor — the CSP is the protection |
+| `Referrer-Policy` | `strict-origin-when-cross-origin` | Control referrer |
## 4.10 Audit Logging
@@ -663,12 +664,12 @@ updates:
- dependencies
ignore:
# TypeScript 7 is the native port: typescript-eslint and ts-jest cannot load it (#727/#729).
- - dependency-name: "typescript"
- versions: [">=7.0.0"]
+ - dependency-name: 'typescript'
+ versions: ['>=7.0.0']
# better-sqlite3 v13: every released TypeORM caps its peer at ^12, and the linux-arm64
# prebuild needs glibc 2.38 (the node:22-slim base has 2.36).
- - dependency-name: "better-sqlite3"
- versions: [">=13.0.0"]
+ - dependency-name: 'better-sqlite3'
+ versions: ['>=13.0.0']
```
Majors are **not** ignored — they arrive as their own grouped PR, separate from the minor/patch
diff --git a/docs/06-api-specification.md b/docs/06-api-specification.md
index 487217519..a10760b57 100644
--- a/docs/06-api-specification.md
+++ b/docs/06-api-specification.md
@@ -1247,7 +1247,7 @@ When enabled, two rules can refuse a send:
| ----------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Warm-up daily cap | The session has used its allowance for the current **UTC** day. The allowance grows with the session's age (`SEND_PACING_WARMUP_SCHEDULE`), because a brand-new WhatsApp account that immediately sends at volume is the pattern that gets numbers banned. The count comes from the messages table, so it survives restarts. |
| Cold-reachout cap | The session has used its allowance of **new conversations** for the UTC day (`SEND_PACING_COLD_DAILY_CAP`). A send is a cold reachout when the account has no history with that chat in **either** direction — replying to someone who wrote to you first is never counted, and never refused by this rule. Status posts address no chat and are exempt. |
-| Failure breaker | Consecutive send failures reached `SEND_PACING_BREAKER_THRESHOLD`, which usually means WhatsApp has already started refusing this account. Sends resume after `SEND_PACING_BREAKER_COOLDOWN_MS`, or immediately after any send succeeds. |
+| Failure breaker | Consecutive send failures reached `SEND_PACING_BREAKER_THRESHOLD`, which usually means WhatsApp has already started refusing this account. The streak has no time decay — only a successful send resets it, so failures spread across a long quiet period still accumulate toward the threshold. Sends resume after `SEND_PACING_BREAKER_COOLDOWN_MS`, or immediately after any send succeeds. |
A refusal is `429` with a body carrying **`code: "SEND_PACING_LIMITED"`** and `retryAfterSeconds`:
@@ -1294,13 +1294,13 @@ Send a plain text message.
**Request body** — `SendTextMessageDto`
-| Field | Type | Required | Constraints | Description |
-| ----------------- | -------- | -------- | ------------------------------ | -------------------------------------------------------------------------- |
-| chatId | string | Yes | non-empty | `[email protected]` or `[email protected]` |
-| text | string | Yes | non-empty, max 4096 | Message text |
-| mentions | string[] | No | array of WIDs | WIDs to @mention (e.g. `["[email protected]"]`). See **Mentions** below |
+| Field | Type | Required | Constraints | Description |
+| ----------------- | -------- | -------- | ------------------------------ | -------------------------------------------------------------------------------------------- |
+| chatId | string | Yes | non-empty | `[email protected]` or `[email protected]` |
+| text | string | Yes | non-empty, max 4096 | Message text |
+| mentions | string[] | No | array of WIDs | WIDs to @mention (e.g. `["[email protected]"]`). See **Mentions** below |
| linkPreview | boolean | No | — | `false` suppresses it; on Baileys `true` is required to get one. See **Link previews** below |
-| customLinkPreview | object | No | `{ url, title, description? }` | Attach a preview you supply. **Baileys only.** See **Link previews** below |
+| customLinkPreview | object | No | `{ url, title, description? }` | Attach a preview you supply. **Baileys only.** See **Link previews** below |
```json
{ "chatId": "[email protected]", "text": "Hello from OpenWA!" }
@@ -3845,13 +3845,14 @@ Post an audio status (story) as a **voice note**, from a URL or base64 payload.
**Request body** — `SendVoiceStatusDto`
-| Field | Type | Required | Constraints | Description |
-| -------------- | --------------------------- | -------- | ----------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- |
-| audio | object (`StatusMediaInput`) | yes | validated nested object; one of `url`/`base64` must be present — an empty `{}` is rejected with `400` | Media source wrapper |
-| audio.url | string | no | must be a non-empty string whenever `base64` is absent **or** `url` is present at all | Media source URL |
-| audio.base64 | string | no | must be a non-empty string whenever `url` is absent **or** `base64` is present at all | Base64-encoded media data |
-| audio.mimetype | string | no | — | Media MIME type; if omitted the service defaults to `audio/ogg; codecs=opus` |
-| recipients | string[] | no | 0–256 items, each matching `^\d+@(c\.us\|lid)$` | JIDs permitted to view the status (`statusJidList`). Required in practice on Baileys; ignored by whatsapp-web.js |
+| Field | Type | Required | Constraints | Description |
+| --------------- | --------------------------- | -------- | ----------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- |
+| audio | object (`StatusMediaInput`) | yes | validated nested object; one of `url`/`base64` must be present — an empty `{}` is rejected with `400` | Media source wrapper |
+| audio.url | string | no | must be a non-empty string whenever `base64` is absent **or** `url` is present at all | Media source URL |
+| audio.base64 | string | no | must be a non-empty string whenever `url` is absent **or** `base64` is present at all | Base64-encoded media data |
+| audio.mimetype | string | no | — | Media MIME type; if omitted the service defaults to `audio/ogg; codecs=opus` |
+| recipients | string[] | no | 0–256 items, each matching `^\d+@(c\.us\|lid)$` | JIDs permitted to view the status (`statusJidList`). Required in practice on Baileys; ignored by whatsapp-web.js |
+| backgroundColor | string | no | `^#[0-9A-Fa-f]{6}$` | Background colour rendered behind the voice-note bubble. Baileys only; whatsapp-web.js ignores it |
There is **no `caption`**: WhatsApp has nowhere to render one on a status voice note.
diff --git a/docs/29-engine-capability-matrix.md b/docs/29-engine-capability-matrix.md
index 44eaf01c8..7a9df4442 100644
--- a/docs/29-engine-capability-matrix.md
+++ b/docs/29-engine-capability-matrix.md
@@ -174,8 +174,8 @@ These are hand-maintained and had drifted from the source before this pass; they
from `engine-capability-matrix.ts` rather than adjusted by hand. Re-derive them the same way when
adding a method, instead of incrementing the previous figure.
-- **99** interface methods, **198** adapter-cells (99 × 2 engines).
-- **176** supported cells; **22** not-available cells across **21** methods.
+- **100** interface methods, **200** adapter-cells (100 × 2 engines).
+- **178** supported cells; **22** not-available cells across **21** methods.
- Of the 22 not-available cells: **2 adapter-gaps** (fixable) + **20 library-limitations** + **0 uncertain**.
- **0 phantom-support rows** — every `not-available` row throws at the adapter boundary.
diff --git a/openapi.json b/openapi.json
index 92f7e6b93..9a7c425af 100644
--- a/openapi.json
+++ b/openapi.json
@@ -456,7 +456,7 @@
"description": "Session not found"
},
"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."
+ "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), OR another node currently holds this session's live engine and deleting it here would strip a session the owner is running. No destructive side effect runs before either refusal."
}
},
"summary": "Delete a session",
@@ -533,6 +533,9 @@
},
"404": {
"description": "Session not found"
+ },
+ "409": {
+ "description": "Another node currently holds this session's live engine (multi-node deployments): stopping it here would report the session down while the owner keeps running it, so the request is refused. Retry against the owning node, or once its lease has lapsed."
}
},
"summary": "Stop a session and disconnect WhatsApp",
diff --git a/sdk/go/types_status.go b/sdk/go/types_status.go
index d43224f83..79e81a3a9 100644
--- a/sdk/go/types_status.go
+++ b/sdk/go/types_status.go
@@ -30,7 +30,7 @@ type StatusListResponse struct {
Statuses []StatusRecord `json:"statuses"`
}
-// StatusResult is the acknowledgement returned by Send{Text,Image,Video}Status.
+// StatusResult is the acknowledgement returned by Send{Text,Image,Video,Voice}Status.
// It intentionally differs from StatusRecord: the POST response has statusId +
// timing, no contact/media.
type StatusResult struct {
@@ -88,4 +88,7 @@ type SendVideoStatusRequest struct {
type SendVoiceStatusRequest struct {
Audio StatusMediaInput `json:"audio"`
Recipients []string `json:"recipients,omitempty"`
+ // BackgroundColor as "#RRGGBB", rendered behind the voice-note bubble.
+ // Baileys only; whatsapp-web.js ignores it.
+ BackgroundColor string `json:"backgroundColor,omitempty"`
}
diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/model/SendVoiceStatusRequest.java b/sdk/java/src/main/java/com/rmyndharis/openwa/model/SendVoiceStatusRequest.java
index 7c8495ead..1bb03a1b3 100644
--- a/sdk/java/src/main/java/com/rmyndharis/openwa/model/SendVoiceStatusRequest.java
+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/model/SendVoiceStatusRequest.java
@@ -10,7 +10,15 @@ import java.util.List;
* mimetype defaults to {@code audio/ogg; codecs=opus}, the only format WhatsApp plays as one —
* neither engine transcodes, so produce those bytes with {@code MediaResource.convertVoice}.
*/
-public record SendVoiceStatusRequest(StatusMediaInput audio, List<String> recipients) {
+public record SendVoiceStatusRequest(StatusMediaInput audio, List<String> recipients, String backgroundColor) {
+ /**
+ * Back-compat constructor for callers written before {@code backgroundColor} existed; leaves it
+ * unset, which sends no colour.
+ */
+ public SendVoiceStatusRequest(StatusMediaInput audio, List<String> recipients) {
+ this(audio, recipients, null);
+ }
+
public static Builder builder() {
return new Builder();
}
@@ -18,6 +26,7 @@ public record SendVoiceStatusRequest(StatusMediaInput audio, List<String> recipi
public static final class Builder {
private StatusMediaInput audio;
private List<String> recipients;
+ private String backgroundColor;
/** Media payload: provide {@code url} OR {@code base64}. */
public Builder audio(StatusMediaInput v) {
@@ -31,8 +40,14 @@ public record SendVoiceStatusRequest(StatusMediaInput audio, List<String> recipi
return this;
}
+ /** Background colour as {@code #RRGGBB}, behind the voice-note bubble. Baileys only. */
+ public Builder backgroundColor(String v) {
+ this.backgroundColor = v;
+ return this;
+ }
+
public SendVoiceStatusRequest build() {
- return new SendVoiceStatusRequest(audio, recipients);
+ return new SendVoiceStatusRequest(audio, recipients, backgroundColor);
}
}
}
diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/model/StatusResult.java b/sdk/java/src/main/java/com/rmyndharis/openwa/model/StatusResult.java
index f33c6dbb2..91ab5d9a4 100644
--- a/sdk/java/src/main/java/com/rmyndharis/openwa/model/StatusResult.java
+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/model/StatusResult.java
@@ -1,7 +1,7 @@
package com.rmyndharis.openwa.model;
/**
- * Result of a status POST ({@code send-text}/{@code send-image}/{@code send-video}).
+ * Result of a status POST ({@code send-text}/{@code send-image}/{@code send-video}/{@code send-voice}).
* Mirrors the backend {@code StatusResult} exactly.
*/
public record StatusResult(
diff --git a/sdk/javascript/src/types.ts b/sdk/javascript/src/types.ts
index 83f621246..bc1fde3bd 100644
--- a/sdk/javascript/src/types.ts
+++ b/sdk/javascript/src/types.ts
@@ -189,9 +189,9 @@ export interface SendTextRequest {
/** WIDs to @mention (e.g. `["[email protected]"]`). The text must also contain the `@<number>` token. */
mentions?: string[];
/**
- * Set `false` to suppress the URL preview. Guaranteed only in that direction: unset means the
- * engine default, and the engines differ — whatsapp-web.js asks WhatsApp Web to build a preview,
- * preview by default; on Baileys a preview is OPT-IN and needs `true` (it costs an outbound fetch).
+ * Controls the URL preview. `false` suppresses it on both engines. Otherwise the engines differ:
+ * whatsapp-web.js builds one in-page by default, while on Baileys a preview is OPT-IN — it needs
+ * `true`, because generating one is a blocking outbound fetch per URL.
*/
linkPreview?: boolean;
/**
@@ -792,7 +792,7 @@ export interface StatusRecord {
}
/**
- * Result of a status POST (`send-text`/`send-image`/`send-video`).
+ * Result of a status POST (`send-text`/`send-image`/`send-video`/`send-voice`).
* Mirrors the backend `StatusResult` exactly.
*/
export interface StatusResult {
@@ -847,6 +847,8 @@ export interface SendVoiceStatusRequest {
audio: StatusMediaInput;
/** Recipient JIDs. Required on the Baileys engine (absent/empty → 400); omit on whatsapp-web.js, which broadcasts instead. */
recipients?: string[];
+ /** Background colour as `#RRGGBB`, rendered behind the voice-note bubble. Baileys only; whatsapp-web.js ignores it. */
+ backgroundColor?: string;
}
// ── Health ────────────────────────────────────────────────────────
diff --git a/sdk/php/src/Resources/StatusResource.php b/sdk/php/src/Resources/StatusResource.php
index ce9a6cd4c..b846fb36d 100644
--- a/sdk/php/src/Resources/StatusResource.php
+++ b/sdk/php/src/Resources/StatusResource.php
@@ -78,8 +78,8 @@ class StatusResource
/**
* Post an audio status as a voice note (OPERATOR). The body takes an `audio` wrapper and an
- * optional `recipients` list; it carries no caption, since WhatsApp has nowhere to render one
- * on a status voice note. WhatsApp plays one only as Ogg/Opus and neither engine transcodes —
+ * optional `recipients` list and an optional `backgroundColor` (#RRGGBB, Baileys only); it
+ * carries no caption, since WhatsApp has nowhere to render one on a status voice note. WhatsApp plays one only as Ogg/Opus and neither engine transcodes —
* convert first via MediaResource::convertVoice.
*
* @param array<string,mixed> $body
diff --git a/sdk/python/openwa/types.py b/sdk/python/openwa/types.py
index ae52a875c..aff044757 100644
--- a/sdk/python/openwa/types.py
+++ b/sdk/python/openwa/types.py
@@ -201,9 +201,9 @@ class SendTextRequest(TypedDict, total=False):
text: str
# WIDs to @mention (e.g. ["[email protected]"]). The text must also contain the @<number> token.
mentions: list[str]
- # Set False to suppress the URL preview. Guaranteed only in that direction: unset means the
- # engine default, and the engines differ -- whatsapp-web.js asks WhatsApp Web to build a preview,
- # preview by default; on Baileys a preview is OPT-IN and needs True (it costs an outbound fetch).
+ # Controls the URL preview. False suppresses it on both engines. Otherwise the engines differ:
+ # whatsapp-web.js builds one in-page by default, while on Baileys a preview is OPT-IN -- it needs
+ # True, because generating one is a blocking outbound fetch per URL.
linkPreview: bool
# Attach a preview you supply yourself instead of one fetched from the URL. Nothing is fetched,
# so this works even for a URL the gateway cannot reach. Baileys only -- whatsapp-web.js takes a
@@ -714,7 +714,7 @@ class StatusRecord(TypedDict, total=False):
expiresAt: str
-# Result of a status POST (``send-text``/``send-image``/``send-video``). Mirrors the backend
+# Result of a status POST (``send-text``/``send-image``/``send-video``/``send-voice``). Mirrors the backend
# ``StatusResult``, which is deliberately NOT ``Status``: the acknowledgement carries the id and
# timing only, with no contact or media. ``statusId`` is the handle ``delete()`` takes.
class StatusResult(TypedDict, total=False):
@@ -836,6 +836,8 @@ class SendVoiceStatusRequest(TypedDict, total=False):
audio: StatusMediaInput
#: Required on the Baileys engine (absent/empty -> 400); omit on whatsapp-web.js.
recipients: list[str]
+ #: Background colour as "#RRGGBB", behind the voice-note bubble. Baileys only; wwjs ignores it.
+ backgroundColor: str
# ── Health ────────────────────────────────────────────────────────
diff --git a/src/config/env.validation.spec.ts b/src/config/env.validation.spec.ts
index f89d9e753..7d0ae270f 100644
--- a/src/config/env.validation.spec.ts
+++ b/src/config/env.validation.spec.ts
@@ -301,12 +301,16 @@ describe('validateEnv', () => {
// ticks and peers adopt sessions from a healthy node, with nothing in the logs saying why.
it('rejects a lease heartbeat that does not comfortably fit inside the TTL', () => {
expect(() => validateEnv({ SESSION_LEASE_TTL_MS: '60000', SESSION_LEASE_HEARTBEAT_MS: '50000' })).toThrow(
- /at most half/,
+ /less than half/,
);
// The defaults stand in for whatever is unset, so a lone oversized heartbeat cannot slip past.
- expect(() => validateEnv({ SESSION_LEASE_HEARTBEAT_MS: '45000' })).toThrow(/at most half/);
- expect(() => validateEnv({ SESSION_LEASE_TTL_MS: '20000' })).toThrow(/at most half/);
+ expect(() => validateEnv({ SESSION_LEASE_HEARTBEAT_MS: '45000' })).toThrow(/less than half/);
+ expect(() => validateEnv({ SESSION_LEASE_TTL_MS: '20000' })).toThrow(/less than half/);
expect(() => validateEnv({ SESSION_LEASE_TTL_MS: '120000', SESSION_LEASE_HEARTBEAT_MS: '30000' })).not.toThrow();
+ // Exactly half is rejected too: a single missed renewal then lands on the expiry instant.
+ expect(() => validateEnv({ SESSION_LEASE_TTL_MS: '60000', SESSION_LEASE_HEARTBEAT_MS: '30000' })).toThrow(
+ /less than half/,
+ );
expect(() => validateEnv({})).not.toThrow();
});
@@ -316,6 +320,8 @@ describe('validateEnv', () => {
expect(() => validateEnv({ NODE_URL: 'localhost:2785' })).toThrow(/absolute http/);
expect(() => validateEnv({ NODE_URL: '10.0.0.5:2785' })).toThrow(/absolute http/);
expect(() => validateEnv({ NODE_URL: 'ftp://10.0.0.5' })).toThrow(/absolute http/);
+ // Embedded credentials parse as a valid URL but undici's fetch refuses them, so reject at boot.
+ expect(() => validateEnv({ NODE_URL: 'http://user:[email protected]:2785' })).toThrow(/must not embed credentials/);
expect(() => validateEnv({ NODE_URL: 'http://10.0.0.5:2785' })).not.toThrow();
expect(() => validateEnv({ NODE_URL: 'https://node-a.internal' })).not.toThrow();
});
diff --git a/src/config/env.validation.ts b/src/config/env.validation.ts
index ebd29f3b0..11e84aff9 100644
--- a/src/config/env.validation.ts
+++ b/src/config/env.validation.ts
@@ -170,6 +170,7 @@ export function validateEnv(config: EnvConfig): EnvConfig {
'WEBHOOK_DISPATCH_MAX_QUEUED',
'STATS_CACHE_TTL_MS', // 0 = memo disabled
'WEBHOOK_MAX_PER_SESSION', // 0 = unlimited
+ 'AUTOMATION_MAX_PER_SESSION', // 0 = unlimited
'WEBHOOK_MEDIA_INLINE_MAX_BYTES', // 0 = never inline media
]) {
checkNonNegativeInt(key);
@@ -226,16 +227,22 @@ export function validateEnv(config: EnvConfig): EnvConfig {
// operator happened to set would let a lone oversized heartbeat through.
const leaseTtlMs = Number(str('SESSION_LEASE_TTL_MS') ?? '60000');
const heartbeatMs = Number(str('SESSION_LEASE_HEARTBEAT_MS') ?? '20000');
- if (Number.isInteger(leaseTtlMs) && Number.isInteger(heartbeatMs) && heartbeatMs * 2 > leaseTtlMs) {
+ // Strictly LESS than half: at exactly half, two renewals span the whole TTL, so a single missed
+ // renewal lands on the expiry instant — a tie that any scheduling jitter turns into a lapse. A
+ // margin below half is what lets one late or failed renewal still land inside the lease.
+ if (Number.isInteger(leaseTtlMs) && Number.isInteger(heartbeatMs) && heartbeatMs * 2 >= leaseTtlMs) {
errors.push(
- `SESSION_LEASE_HEARTBEAT_MS (${heartbeatMs}) must be at most half of SESSION_LEASE_TTL_MS (${leaseTtlMs}) ` +
+ `SESSION_LEASE_HEARTBEAT_MS (${heartbeatMs}) must be less than half of SESSION_LEASE_TTL_MS (${leaseTtlMs}) ` +
'so a renewal that is late or fails once still lands inside the lease',
);
}
// The forwarder builds an absolute URL from this; a value without a scheme parses as something
// unusable (`localhost:2785` reads as the scheme `localhost:`) and only fails at the first
- // forward, as a 500 on a request that had nothing wrong with it.
+ // forward, as a 500 on a request that had nothing wrong with it. Embedded credentials
+ // (`http://user:pw@host`) parse fine here but undici's fetch rejects them outright — every
+ // forward would 503 permanently, with the credentials sitting in sessions.nodeUrl — so refuse
+ // those at boot too rather than let them reach the DB and the first forward.
const nodeUrl = str('NODE_URL');
if (nodeUrl) {
let parsed: URL | undefined;
@@ -246,6 +253,8 @@ export function validateEnv(config: EnvConfig): EnvConfig {
}
if (!parsed || (parsed.protocol !== 'http:' && parsed.protocol !== 'https:')) {
errors.push(`NODE_URL must be an absolute http(s) URL (got "${nodeUrl}")`);
+ } else if (parsed.username || parsed.password) {
+ errors.push('NODE_URL must not embed credentials — the forwarder cannot send a URL with a userinfo component');
}
}
diff --git a/src/engine/adapters/baileys.adapter.spec.ts b/src/engine/adapters/baileys.adapter.spec.ts
index a20e2506c..cb32c1ed5 100644
--- a/src/engine/adapters/baileys.adapter.spec.ts
+++ b/src/engine/adapters/baileys.adapter.spec.ts
@@ -1228,6 +1228,22 @@ describe('BaileysAdapter messaging', () => {
);
});
+ // Resolving a contact's LID at send time is the one place a cold contact's mapping is learned
+ // before any message arrives; without writing it back, a later message-target ownership check
+ // comparing the stored key's lid against a phone-dialect chatId rejects a message that IS in chat.
+ it('sendTextMessage records the resolved LID back into the session store (device-stripped)', async () => {
+ fakeSock.sendMessage.mockResolvedValue({ key: { id: 'OUT1' }, messageTimestamp: 1700000001 });
+ fakeSock.signalRepository = { lidMapping: { getLIDForPN: jest.fn().mockResolvedValue('484848:3@lid') } };
+ const adapter = await readyAdapter();
+ const store = (adapter as unknown as { sessionStore: { addLidMappings: (m: unknown[]) => void } }).sessionStore;
+ const spy = jest.spyOn(store, 'addLidMappings');
+
+ await adapter.sendTextMessage('[email protected]', 'hello');
+
+ // The device suffix (:3) is stripped — that is the key the lid->phone lookup reads.
+ expect(spy).toHaveBeenCalledWith([{ lid: '484848@lid', pn: '[email protected]' }]);
+ });
+
it('sendTextMessage keeps the phone jid when no LID mapping is known', async () => {
fakeSock.sendMessage.mockResolvedValue({ key: { id: 'OUT1' }, messageTimestamp: 1700000001 });
fakeSock.signalRepository = { lidMapping: { getLIDForPN: jest.fn().mockResolvedValue(null) } };
diff --git a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
index f78094170..f75ac1913 100644
--- a/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
+++ b/src/engine/adapters/whatsapp-web-js.adapter.spec.ts
@@ -6110,6 +6110,19 @@ describe('WhatsAppWebJsAdapter raw-id extraction hardening', () => {
expect(result[0].id).toBe('[email protected]');
});
+ // getNumberId returns a raw page-context Wid; on a WA Web build that renamed _serialized to $1,
+ // reading only _serialized made every number resolve to null — and checkNumberExists then reports
+ // every contact as unregistered.
+ it('getNumberId reads $1 on a renamed build, and checkNumberExists follows', async () => {
+ const renamed = readyAdapter({ getNumberId: jest.fn().mockResolvedValue({ $1: '[email protected]' }) });
+ await expect(renamed.getNumberId('628111')).resolves.toBe('[email protected]');
+ await expect(renamed.checkNumberExists('628111')).resolves.toBe(true);
+
+ const missing = readyAdapter({ getNumberId: jest.fn().mockResolvedValue(null) });
+ await expect(missing.getNumberId('628111')).resolves.toBeNull();
+ await expect(missing.checkNumberExists('628111')).resolves.toBe(false);
+ });
+
it('getSubscribedChannels reads $1 on a renamed build, never the literal "undefined"', async () => {
const getChannels = jest.fn().mockResolvedValue([{ id: { $1: '120363@newsletter' }, name: 'Renamed' }]);
diff --git a/src/engine/interfaces/whatsapp-engine.interface.ts b/src/engine/interfaces/whatsapp-engine.interface.ts
index 68b6e7571..546ba8220 100644
--- a/src/engine/interfaces/whatsapp-engine.interface.ts
+++ b/src/engine/interfaces/whatsapp-engine.interface.ts
@@ -362,9 +362,9 @@ export interface StatusPostOptions {
* whatsapp-web.js, which broadcasts to the account's status-privacy audience.
*/
recipients?: string[];
- /** Hex background colour (#RRGGBB). Text status only. */
+ /** Hex background colour (#RRGGBB). Honoured on text and voice statuses (Baileys engine). */
backgroundColor?: string;
- /** Font index. Text status only. */
+ /** Font index. Honoured on text and voice statuses (Baileys engine). */
font?: number;
/** Caption. Image/video status only. */
caption?: string;
@@ -795,11 +795,9 @@ export interface IWhatsAppEngine {
/**
* Send text.
*
- * `linkPreview: false` suppresses the URL preview on BOTH engines. Leaving it unset means "whatever
- * the engine does by default", and the two differ: whatsapp-web.js asks WhatsApp Web to build a
- * preview in-page, while Baileys builds none unless its optional preview generator is installed.
- * The parameter is therefore only guaranteed in its suppressing direction, and is documented as
- * such rather than pretending at symmetry.
+ * `linkPreview: false` suppresses the URL preview on BOTH engines. Otherwise the two differ:
+ * whatsapp-web.js builds one in-page by default, while on Baileys a preview is OPT-IN — only
+ * `linkPreview: true` produces one, because generating it is a blocking outbound fetch per URL.
*/
sendTextMessage(
chatId: string,
diff --git a/src/modules/automation/automation-rules.service.spec.ts b/src/modules/automation/automation-rules.service.spec.ts
index e6b7cb504..2d036252d 100644
--- a/src/modules/automation/automation-rules.service.spec.ts
+++ b/src/modules/automation/automation-rules.service.spec.ts
@@ -4,12 +4,13 @@
// cooldown window, and no failure may escape into the receive path. These run against a real
// in-memory DB so scoping and ordering are exercised end-to-end, not asserted on a mock's WHERE.
import { DataSource } from 'typeorm';
-import { NotFoundException } from '@nestjs/common';
+import { BadRequestException, NotFoundException } from '@nestjs/common';
import { AutomationRulesService } from './automation-rules.service';
import { AutomationRule } from './entities/automation-rule.entity';
import { Session, SessionStatus } from '../session/entities/session.entity';
import type { MessageService } from '../message/message.service';
import type { ModuleRef } from '@nestjs/core';
+import type { ConfigService } from '@nestjs/config';
describe('AutomationRulesService', () => {
let ds: DataSource;
@@ -60,6 +61,30 @@ describe('AutomationRulesService', () => {
...over,
});
+ describe('per-session cap', () => {
+ // Every inbound message is evaluated against every rule of its session, so an unbounded count
+ // turns each message into unbounded work — the same reason the webhook fan-out is capped.
+ const cappedService = (max: number): AutomationRulesService =>
+ new AutomationRulesService(ds.getRepository(AutomationRule), moduleRefStub, undefined, {
+ get: (_key: string, def?: number) => max ?? def,
+ } as unknown as ConfigService);
+
+ it('refuses a NEW rule at or over the cap; existing ones are grandfathered', async () => {
+ const svc = cappedService(2);
+ await svc.create('sessA', { name: 'r1', replyText: 'a' });
+ await svc.create('sessA', { name: 'r2', replyText: 'b' });
+ await expect(svc.create('sessA', { name: 'r3', replyText: 'c' })).rejects.toBeInstanceOf(BadRequestException);
+ // The cap is per-session — another session is unaffected.
+ await expect(svc.create('sessB', { name: 'r1', replyText: 'a' })).resolves.toBeDefined();
+ });
+
+ it('0 disables the cap', async () => {
+ const svc = cappedService(0);
+ for (let i = 0; i < 5; i++) await svc.create('sessA', { name: `r${i}`, replyText: 'x' });
+ await expect(svc.create('sessA', { name: 'more', replyText: 'x' })).resolves.toBeDefined();
+ });
+ });
+
describe('CRUD scoping', () => {
it('create applies the defaults: enabled, 60s cooldown, no conditions', async () => {
const rule = await service.create('sessA', { name: 'r', replyText: 'hi' });
diff --git a/src/modules/events/redis-io.adapter.spec.ts b/src/modules/events/redis-io.adapter.spec.ts
index f13ca8701..72f1c022c 100644
--- a/src/modules/events/redis-io.adapter.spec.ts
+++ b/src/modules/events/redis-io.adapter.spec.ts
@@ -163,6 +163,42 @@ describe('RedisIoAdapter', () => {
}
});
+ // The server must close BEFORE the clients are released: the namespace adapters unsubscribe as
+ // the server closes, and issuing those on already-quit clients surfaced as a handful of
+ // unhandled-rejection ERRORs on every graceful shutdown.
+ it('closes the server before releasing the pub/sub clients', async () => {
+ process.env.REDIS_ENABLED = 'true';
+ const { server } = fakeServer();
+ const createSpy = withBaseServer(server);
+ const order: string[] = [];
+ const closeSpy = jest.spyOn(IoAdapter.prototype, 'close').mockImplementation(() => {
+ order.push('super.close');
+ return Promise.resolve();
+ });
+ try {
+ const adapter = new RedisIoAdapter({} as never);
+ adapter.createIOServer(2785);
+ const [pub, sub] = redisInstances;
+ pub.quit.mockImplementation(() => {
+ order.push('pub.quit');
+ return Promise.resolve();
+ });
+ sub.quit.mockImplementation(() => {
+ order.push('sub.quit');
+ return Promise.resolve();
+ });
+
+ await adapter.close(server);
+
+ expect(order[0]).toBe('super.close');
+ expect(order).toContain('pub.quit');
+ expect(order).toContain('sub.quit');
+ } finally {
+ createSpy.mockRestore();
+ closeSpy.mockRestore();
+ }
+ });
+
it('does not hang when quit() never resolves (Redis down at shutdown), then force-disconnects', async () => {
jest.useFakeTimers();
process.env.REDIS_ENABLED = 'true';
diff --git a/src/modules/session/session-engine-lifecycle.service.ts b/src/modules/session/session-engine-lifecycle.service.ts
index a76e1125b..641e2c94e 100644
--- a/src/modules/session/session-engine-lifecycle.service.ts
+++ b/src/modules/session/session-engine-lifecycle.service.ts
@@ -401,6 +401,21 @@ export class SessionEngineLifecycle {
this.fences.evictAndForceDestroy(id, engine);
}
+ /**
+ * Set the tearing-down mark synchronously, before any awaited work a retiring control performs.
+ *
+ * The pre-initialize retirement race turns on this mark being visible to initializeEngine's
+ * post-INITIALIZING check (line ~507) by the time that awaited DB write settles. stop()/delete()
+ * both add the mark internally, but only AFTER their own first await (requireSession /
+ * awaitPendingTeardown), and the ownership fence added another await ahead of them — so the mark
+ * could land after the window it guards. Exposing it lets SessionService set it at true entry,
+ * with nothing awaited in between; a mark left behind by a request that then refuses (a 409) is
+ * harmless and is cleared by the next start(), which is what the mark is designed for.
+ */
+ markStopping(id: string): void {
+ this.stoppingSessions.add(id);
+ }
+
/**
* True while this process still has anything alive for the session: a registered engine, an
* in-flight start(), or reconnect state whose armed/executing attempt will re-register one.
diff --git a/src/modules/session/session.controller.ts b/src/modules/session/session.controller.ts
index 53dbcf3ce..2e08ef35f 100644
--- a/src/modules/session/session.controller.ts
+++ b/src/modules/session/session.controller.ts
@@ -108,9 +108,10 @@ export class SessionController {
@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.',
+ '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), OR " +
+ "another node currently holds this session's live engine and deleting it here would strip a " +
+ 'session the owner is running. No destructive side effect runs before either refusal.',
})
async delete(@Param('id', ParseUUIDPipe) id: string): Promise<void> {
const session = await this.sessionService.findOne(id);
@@ -165,6 +166,13 @@ export class SessionController {
type: SessionResponseDto,
})
@ApiResponse({ status: 404, description: 'Session not found' })
+ @ApiResponse({
+ status: 409,
+ description:
+ "Another node currently holds this session's live engine (multi-node deployments): stopping " +
+ 'it here would report the session down while the owner keeps running it, so the request is ' +
+ 'refused. Retry against the owning node, or once its lease has lapsed.',
+ })
async stop(@Param('id', ParseUUIDPipe) id: string): Promise<SessionResponseDto> {
const session = await this.sessionService.stop(id);
await this.auditService.logInfo(AuditAction.SESSION_STOPPED, {
diff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.ts
index c3e756939..84bf025fb 100644
--- a/src/modules/session/session.service.spec.ts
+++ b/src/modules/session/session.service.spec.ts
@@ -1164,6 +1164,26 @@ describe('SessionService', () => {
expect(ownership.release).not.toHaveBeenCalled();
});
+
+ // The pre-initialize retirement race needs the stop-mark set SYNCHRONOUSLY at entry — before
+ // the ownership fence's awaited query, and before the lifecycle's own first await — or an
+ // in-flight start() can reach engine.initialize() on the engine being retired. Prove the mark
+ // lands synchronously even when the fence is a promise that never settles.
+ it.each([
+ ['stop', (s: SessionService) => s.stop('sess-uuid-1')],
+ ['delete', (s: SessionService) => s.delete('sess-uuid-1')],
+ ])('%s() sets the stop mark synchronously, before the awaited ownership fence', (_verb, call) => {
+ const ownership = withOwnership();
+ // A fence that never resolves: if the mark depended on it, it would never be set.
+ ownership.isHeldByOtherNode.mockReturnValue(new Promise<boolean>(() => undefined));
+ const stopping = (lifecycle as unknown as { stoppingSessions: Set<string> }).stoppingSessions;
+ expect(stopping.has('sess-uuid-1')).toBe(false);
+
+ void call(service); // do NOT await — the fence never settles
+
+ // Synchronously, on the same tick, the mark must already be set.
+ expect(stopping.has('sess-uuid-1')).toBe(true);
+ });
});
describe('isEngineActive', () => {
diff --git a/src/modules/session/session.service.ts b/src/modules/session/session.service.ts
index e8d31a4cc..41c96c5e5 100644
--- a/src/modules/session/session.service.ts
+++ b/src/modules/session/session.service.ts
@@ -276,10 +276,12 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
/** Record removal + engine retirement + credential purge: owned by the lifecycle service. */
async delete(id: string): Promise<void> {
- // Guarded at the call site rather than inside an always-awaited helper: without ownership there
- // is nothing to check, and awaiting anything at all here would push the lifecycle call a
- // microtask later — enough for an in-flight start to reach engine.initialize() before the
- // retirement lands, which the pre-initialize retirement race deliberately prevents.
+ // Set the tearing-down mark SYNCHRONOUSLY, before the ownership fence's awaited query. The
+ // pre-initialize retirement race needs this mark visible to an in-flight start()'s
+ // post-INITIALIZING check by the time that write settles; awaiting anything first — the fence's
+ // COUNT, or delete()'s own requireSession — would let the mark land after that window. A mark
+ // left behind when the fence refuses (409) is harmless and is cleared by the next start().
+ this.engineLifecycle.markStopping(id);
if (this.ownership) await this.assertNotHeldElsewhere(id);
await this.engineLifecycle.delete(id);
await this.ownership?.release(id);
@@ -323,7 +325,8 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
}
async stop(id: string): Promise<Session> {
- // Call-site guarded — see delete().
+ // Synchronous stop-mark before the awaited fence — see delete() for why.
+ this.engineLifecycle.markStopping(id);
if (this.ownership) await this.assertNotHeldElsewhere(id);
const session = await this.engineLifecycle.stop(id);
// Handed back on the way out so a peer can pick it up immediately rather than waiting for the