Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix: close the pre-release review's ownership races, breaker over-counting and backup gap

Yudhi Armyndharisec172289b678
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 4a21e8b5c..2463b4890 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -35,6 +35,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- A media-storage root the app cannot write to is caught at boot with a clear error, instead of failing on the first write (#1066).
- The bundled `docker-compose.yml` now forwards the `SEND_PACING_*`, `MEDIA_CONVERSION_*`/`FFMPEG_PATH` and session-ownership (`NODE_ID`, `NODE_URL`, lease/sweep) variables — previously these features could not be enabled from `.env` in a compose deployment at all.
- The four label write tools (`LabelUpsert`, `LabelDelete`, `LabelAddToChat`, `LabelRemoveFromChat`) answered `Internal error` over MCP even though the write had succeeded on WhatsApp, prompting agents to retry a completed operation; they now return `{ success: true }`.
+- **Multi-node ownership races closed:** a `stop` landing while a `start` is mid-launch no longer hands back the claim under a live engine (which left the engine unclaimed and startable a second time elsewhere), a failed start no longer pins its session to that node forever, and a deliberate teardown of a session whose crashed owner's lease had lapsed now really leaves it down instead of being re-adopted by the takeover sweep. Successful forwarded requests also stop logging a spurious error.
+- **The send breaker only counts failures that reached WhatsApp.** Client-fault and engine-state errors raised inside the send call — a blocked media URL, a capability the engine lacks, a disconnected socket, a malformed status post — no longer accumulate toward it, so a client sending bad requests can no longer 429 every send on a healthy session for the cooldown. Applied to single sends, bulk batches and status posts alike.
+- **Backup/restore covers `automation_rules`.** The table was in neither the export nor the import while the restore's session wipe cascade-deletes it, so a documented backup→restore silently destroyed every autoreply rule.
+- 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.
- 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.
diff --git a/docker-compose.dev.yml b/docker-compose.dev.yml
index bcd98264f..6e7da8f68 100644
--- a/docker-compose.dev.yml
+++ b/docker-compose.dev.yml
@@ -100,6 +100,30 @@ services:
- BODY_SIZE_LIMIT=${BODY_SIZE_LIMIT:-}
- TRUSTED_PROXIES=${TRUSTED_PROXIES:-}
- QUEUE_ENABLED=${QUEUE_ENABLED:-false}
+ # Opt-in feature flags. Forwarded explicitly for the same reason as docker-compose.yml: this
+ # file has no env_file, so a variable absent from this list never reaches the container and
+ # the feature it gates stays off however the operator's .env is written.
+ - CHAT_MEDIA_ARCHIVE_ENABLED=${CHAT_MEDIA_ARCHIVE_ENABLED:-}
+ - CHAT_MEDIA_ARCHIVE_MAX_BYTES=${CHAT_MEDIA_ARCHIVE_MAX_BYTES:-}
+ - CHAT_MEDIA_ARCHIVE_TTL_DAYS=${CHAT_MEDIA_ARCHIVE_TTL_DAYS:-}
+ - CHAT_MEDIA_ORPHAN_SWEEP_INTERVAL_MS=${CHAT_MEDIA_ORPHAN_SWEEP_INTERVAL_MS:-}
+ - CHAT_MEDIA_ORPHAN_GRACE_MS=${CHAT_MEDIA_ORPHAN_GRACE_MS:-}
+ - SEND_PACING_ENABLED=${SEND_PACING_ENABLED:-}
+ - SEND_PACING_WARMUP_SCHEDULE=${SEND_PACING_WARMUP_SCHEDULE:-}
+ - SEND_PACING_COLD_DAILY_CAP=${SEND_PACING_COLD_DAILY_CAP:-}
+ - SEND_PACING_BREAKER_THRESHOLD=${SEND_PACING_BREAKER_THRESHOLD:-}
+ - SEND_PACING_BREAKER_COOLDOWN_MS=${SEND_PACING_BREAKER_COOLDOWN_MS:-}
+ - MEDIA_CONVERSION_ENABLED=${MEDIA_CONVERSION_ENABLED:-}
+ - FFMPEG_PATH=${FFMPEG_PATH:-}
+ - MEDIA_CONVERSION_TIMEOUT_MS=${MEDIA_CONVERSION_TIMEOUT_MS:-}
+ - MEDIA_CONVERSION_MAX_OUTPUT_BYTES=${MEDIA_CONVERSION_MAX_OUTPUT_BYTES:-}
+ - MEDIA_CONVERSION_CONCURRENCY=${MEDIA_CONVERSION_CONCURRENCY:-}
+ - NODE_ID=${NODE_ID:-}
+ - NODE_URL=${NODE_URL:-}
+ - SESSION_LEASE_TTL_MS=${SESSION_LEASE_TTL_MS:-}
+ - SESSION_LEASE_HEARTBEAT_MS=${SESSION_LEASE_HEARTBEAT_MS:-}
+ - SESSION_TAKEOVER_SWEEP_MS=${SESSION_TAKEOVER_SWEEP_MS:-}
+ - SESSION_PROXY_TIMEOUT_MS=${SESSION_PROXY_TIMEOUT_MS:-}
volumes:
- ./data:/app/data
restart: unless-stopped
diff --git a/src/common/errors/label-not-found.error.ts b/src/common/errors/label-not-found.error.ts
new file mode 100644
index 000000000..b0fbb0a52
--- /dev/null
+++ b/src/common/errors/label-not-found.error.ts
@@ -0,0 +1,15 @@
+import { NotFoundException } from '@nestjs/common';
+
+/**
+ * Thrown by the engine layer when a label id does not resolve — the label was never created, or the
+ * account is not a WhatsApp Business one and therefore holds no labels at all. Both are the same
+ * answer to the caller, and the same message shape LabelService.getLabelById already returns.
+ *
+ * Extends NestJS `NotFoundException` so it maps to **HTTP 404** through the built-in exception
+ * handler — no custom global filter required. Mirrors {@link GroupNotFoundError}.
+ */
+export class LabelNotFoundError extends NotFoundException {
+ constructor(labelId: string) {
+ super(`Label ${labelId} not found`);
+ }
+}
diff --git a/src/engine/adapters/baileys-groups.ts b/src/engine/adapters/baileys-groups.ts
index d8e8df6f8..29f8e5642 100644
--- a/src/engine/adapters/baileys-groups.ts
+++ b/src/engine/adapters/baileys-groups.ts
@@ -298,6 +298,8 @@ export class BaileysGroups {
async setGroupEphemeral(groupId: string, durationSec: number): Promise<void> {
this.host.ensureReady();
- await this.sock().groupToggleEphemeral(groupId, durationSec);
+ await mapServerRefusal('Setting the disappearing-message timer', () =>
+ this.sock().groupToggleEphemeral(groupId, durationSec),
+ );
}
}
diff --git a/src/engine/adapters/baileys-messaging.ts b/src/engine/adapters/baileys-messaging.ts
index e42f50acc..e5801e9f6 100644
--- a/src/engine/adapters/baileys-messaging.ts
+++ b/src/engine/adapters/baileys-messaging.ts
@@ -96,13 +96,18 @@ export class BaileysMessaging {
getUrlInfo: (text: string) => generateSafeLinkPreview(text),
};
// `linkPreview: null` is Baileys' explicit "no preview": with the key absent it instead calls the
- // configured generator (Utils/messages.js:279-281). Suppressing therefore also skips that call —
- // which today fails anyway, since the generator dynamically imports an optional package this
- // project does not install, and the failure is swallowed with a warn on every URL-bearing send.
+ // configured generator (Utils/messages.js:279-281), which for us means a blocking outbound fetch
+ // of every URL in the text (up to 3s each, no cache) before the message can go out.
+ //
+ // Previews are therefore OPT-IN on this engine: only `linkPreview: true` leaves the key absent.
+ // That keeps the documented engine default ("Baileys builds none") true, and keeps a bulk
+ // campaign whose template carries a slow or dead URL from stalling on every single message.
+ // getUrlInfo above is still passed unconditionally, so the library's vulnerable generator stays
+ // unreachable on the paths that do generate.
const content = {
text,
...this.withMentions(mentions),
- ...(sendOptions?.linkPreview === false ? { linkPreview: null } : {}),
+ ...(sendOptions?.linkPreview === true ? {} : { linkPreview: null }),
// A caller-supplied preview short-circuits generation entirely: with the key present Baileys
// never calls getUrlInfo, so nothing is fetched and the metadata is used verbatim.
...(sendOptions?.customPreview
diff --git a/src/engine/adapters/baileys.adapter.spec.ts b/src/engine/adapters/baileys.adapter.spec.ts
index 8b103e1ac..53afb211b 100644
--- a/src/engine/adapters/baileys.adapter.spec.ts
+++ b/src/engine/adapters/baileys.adapter.spec.ts
@@ -1178,7 +1178,11 @@ describe('BaileysAdapter messaging', () => {
fakeSock.sendMessage.mockResolvedValue({ key: { id: 'OUT1' }, messageTimestamp: 1700000001 });
const adapter = await readyAdapter();
const res = await adapter.sendTextMessage('[email protected]', 'hello');
- expect(fakeSock.sendMessage).toHaveBeenCalledWith('[email protected]', { text: 'hello' }, safeSendOptions());
+ expect(fakeSock.sendMessage).toHaveBeenCalledWith(
+ { text: 'hello', linkPreview: null },
+ safeSendOptions(),
+ );
expect(res).toEqual({ id: 'OUT1', timestamp: 1700000001 });
});
@@ -1217,7 +1221,11 @@ describe('BaileysAdapter messaging', () => {
const adapter = await readyAdapter();
await adapter.sendTextMessage('[email protected]', 'hello');
expect(fakeSock.signalRepository.lidMapping.getLIDForPN).toHaveBeenCalledWith('[email protected]');
- expect(fakeSock.sendMessage).toHaveBeenCalledWith('484848@lid', { text: 'hello' }, safeSendOptions());
+ expect(fakeSock.sendMessage).toHaveBeenCalledWith(
+ '484848@lid',
+ { text: 'hello', linkPreview: null },
+ safeSendOptions(),
+ );
});
it('sendTextMessage keeps the phone jid when no LID mapping is known', async () => {
@@ -1225,7 +1233,11 @@ describe('BaileysAdapter messaging', () => {
fakeSock.signalRepository = { lidMapping: { getLIDForPN: jest.fn().mockResolvedValue(null) } };
const adapter = await readyAdapter();
await adapter.sendTextMessage('[email protected]', 'hello');
- expect(fakeSock.sendMessage).toHaveBeenCalledWith('[email protected]', { text: 'hello' }, safeSendOptions());
+ expect(fakeSock.sendMessage).toHaveBeenCalledWith(
+ { text: 'hello', linkPreview: null },
+ safeSendOptions(),
+ );
});
it('sendTextMessage honors the chat disappearing timer when one is cached (#473)', async () => {
@@ -1235,7 +1247,7 @@ describe('BaileysAdapter messaging', () => {
await adapter.sendTextMessage('[email protected]', 'hello');
expect(fakeSock.sendMessage).toHaveBeenCalledWith(
- { text: 'hello' },
+ { text: 'hello', linkPreview: null },
// The disappearing timer still rides on the same options object the generator now shares.
expect.objectContaining({ ephemeralExpiration: 604800, getUrlInfo: expect.any(Function) as unknown }) as unknown,
);
@@ -1247,7 +1259,7 @@ describe('BaileysAdapter messaging', () => {
await adapter.sendTextMessage('[email protected]', 'hi @62811', ['[email protected]']);
expect(fakeSock.sendMessage).toHaveBeenCalledWith(
- { text: 'hi @62811', mentions: ['[email protected]'] },
+ { text: 'hi @62811', mentions: ['[email protected]'], linkPreview: null },
safeSendOptions(),
);
});
@@ -1256,7 +1268,11 @@ describe('BaileysAdapter messaging', () => {
fakeSock.sendMessage.mockResolvedValue({ key: { id: 'OUT1' }, messageTimestamp: 1700000001 });
const adapter = await readyAdapter();
await adapter.sendTextMessage('[email protected]', 'plain', []);
- expect(fakeSock.sendMessage).toHaveBeenCalledWith('[email protected]', { text: 'plain' }, safeSendOptions());
+ expect(fakeSock.sendMessage).toHaveBeenCalledWith(
+ { text: 'plain', linkPreview: null },
+ safeSendOptions(),
+ );
});
it('getNumberId resolves via onWhatsApp and returns a NEUTRAL jid (never @s.whatsapp.net)', async () => {
@@ -4871,12 +4887,17 @@ describe('BaileysAdapter link preview', () => {
expect(sentContent()).not.toHaveProperty('linkPreview');
});
- it('leaves the key out for a plain send', async () => {
+ // Previews are OPT-IN on this engine: generation means a blocking outbound fetch per URL before
+ // the message can go out (a bulk campaign carrying a slow URL would stall on every message), and
+ // the documented engine default is that Baileys builds none.
+ it('suppresses generation for a plain send, and for a send that says nothing about previews', async () => {
const adapter = await readyAdapter();
await adapter.sendTextMessage('[email protected]', 'hi');
+ expect(sentContent().linkPreview).toBeNull();
- expect(sentContent()).not.toHaveProperty('linkPreview');
+ await adapter.sendTextMessage('[email protected]', 'see https://example.com');
+ expect(sentContent().linkPreview).toBeNull();
});
});
diff --git a/src/engine/adapters/wwebjs-channels.ts b/src/engine/adapters/wwebjs-channels.ts
index f271911d2..efb81c1ad 100644
--- a/src/engine/adapters/wwebjs-channels.ts
+++ b/src/engine/adapters/wwebjs-channels.ts
@@ -87,6 +87,12 @@ export class WwebjsChannels {
*/
async muteChannel(channelId: string, mute: boolean): Promise<void> {
this.host.ensureReady();
+ // getChatById resolves — and will happily CREATE — an ordinary 1:1/group chat for a non-channel
+ // id, and Chat carries mute()/unmute() too: without this check a mistyped id muted a real
+ // conversation forever (an undefined expiry means "no end date" upstream) and reported success.
+ if (!channelId.endsWith('@newsletter')) {
+ throw new ChannelNotFoundError(channelId);
+ }
const chat = (await this.client().getChatById(channelId)) as unknown as {
mute?: () => Promise<boolean>;
unmute?: () => Promise<boolean>;
diff --git a/src/engine/adapters/wwebjs-groups.ts b/src/engine/adapters/wwebjs-groups.ts
index 1a42d56e6..d84b66c20 100644
--- a/src/engine/adapters/wwebjs-groups.ts
+++ b/src/engine/adapters/wwebjs-groups.ts
@@ -339,7 +339,7 @@ export class WwebjsGroups {
*/
async getGroupJoinInfo(inviteCode: string): Promise<GroupJoinInfo> {
this.host.ensureReady();
- const raw = (await this.client().getInviteInfo(inviteCode)) as {
+ type RawInviteInfo = {
id?: { _serialized?: string; $1?: string } | string;
subject?: string;
desc?: string;
@@ -348,6 +348,19 @@ export class WwebjsGroups {
size?: number;
participants?: unknown[];
} | null;
+ // A refused invite (invalid, expired, revoked) rejects PAGE-SIDE inside WA Web's query job, and
+ // Client.getInviteInfo bare-forwards that rejection — unmapped it escapes as an opaque 500 for
+ // the endpoint's most common error input, which the route documents (and Baileys answers) as
+ // 404. The sibling joinGroupViaInviteCode maps the same cause; this is the read half.
+ let raw: RawInviteInfo;
+ try {
+ raw = await this.client().getInviteInfo(inviteCode);
+ } catch (error) {
+ this.host.logger.debug('getInviteInfo rejected; treating the invite as not found', {
+ error: error instanceof Error ? error.message : String(error),
+ });
+ throw new GroupNotFoundError(inviteCode);
+ }
// Raw page-context Wids: read `$1` before concluding absence (#747, the WA Web minifier
// rename) — without the fallback a renamed build turns every VALID invite into a false 404.
diff --git a/src/engine/adapters/wwebjs-labels.ts b/src/engine/adapters/wwebjs-labels.ts
index 6873ab402..052de2c38 100644
--- a/src/engine/adapters/wwebjs-labels.ts
+++ b/src/engine/adapters/wwebjs-labels.ts
@@ -3,6 +3,7 @@ import { Label, ChatSummary } from '../interfaces/whatsapp-engine.interface';
import { GroupChat, BusinessClient } from '../types/whatsapp-web-js.types';
import { isChannelJid, chatKind } from '../identity/wa-id';
import { ChatLabelsUnsupportedError } from '../../common/errors/chat-labels-unsupported.error';
+import { LabelNotFoundError } from '../../common/errors/label-not-found.error';
import { type WwebjsEngineHost } from './wwebjs-host';
/**
@@ -39,7 +40,20 @@ export class WwebjsLabels {
*/
async getChatsByLabel(labelId: string): Promise<ChatSummary[]> {
this.host.ensureReady();
- const chats = await (this.client() as unknown as BusinessClient).getChatsByLabelId(labelId);
+ // The upstream page code dereferences the label without checking it exists, so an unknown id —
+ // and every id on a personal (non-Business) account, whose label collection is empty — throws a
+ // page-side TypeError that would surface as an opaque 500. A label that is not there is a 404,
+ // the same answer getLabelById gives.
+ let chats: Awaited<ReturnType<BusinessClient['getChatsByLabelId']>>;
+ try {
+ chats = await (this.client() as unknown as BusinessClient).getChatsByLabelId(labelId);
+ } catch (error) {
+ this.host.logger.debug('getChatsByLabelId rejected; treating the label as not found', {
+ labelId,
+ error: error instanceof Error ? error.message : String(error),
+ });
+ throw new LabelNotFoundError(labelId);
+ }
const summaries: ChatSummary[] = [];
for (const chat of chats ?? []) {
// The library builds this list via getChatById per label item and yields UNDEFINED entries
diff --git a/src/modules/contact/contact.service.ts b/src/modules/contact/contact.service.ts
index e1d92979e..cc4b72417 100644
--- a/src/modules/contact/contact.service.ts
+++ b/src/modules/contact/contact.service.ts
@@ -117,7 +117,7 @@ export class ContactService {
// Allow-list rather than deny-list: only a user id (or a bare number, which parses as
// `unknown`) names a phone. A group/newsletter/broadcast/status id also carries digits that
// whatsapp-web.js would happily store as a phone number for a contact that does not exist.
- if (kind === 'user' || kind === 'unknown') return;
+ if (kind === 'user' || this.isBareNumber(contactId)) return;
if (kind === 'lid') {
throw new BadRequestException(
`Contact ${contactId} is a privacy id (@lid) with no known phone number; the addressbook is keyed by phone number, so pass a phone-based contact id instead`,
@@ -128,14 +128,31 @@ export class ContactService {
);
}
+ /** A digits-only id, e.g. `628123456789` — accepted for convenience and qualified below. */
+ private isBareNumber(contactId: string): boolean {
+ return parseWaId(contactId).kind === 'unknown' && /^\d{5,}$/.test(contactId.trim());
+ }
+
+ /**
+ * Qualify a bare number to the neutral `@c.us` dialect before it reaches an engine.
+ *
+ * Baileys keys the addressbook app-state patch by the id it is handed and only folds a recognised
+ * user JID to the engine dialect, so an unqualified number would be written under a key WhatsApp
+ * never reads — reported as success. whatsapp-web.js takes the user-part either way, so the
+ * qualification is a no-op there.
+ */
+ private toAddressableId(contactId: string): string {
+ return this.isBareNumber(contactId) ? `${contactId.trim()}@c.us` : contactId;
+ }
+
upsertContact(sessionId: string, contactId: string, firstName: string, lastName?: string) {
this.assertAddressable(contactId);
- return this.getEngine(sessionId).upsertContact(contactId, firstName, lastName);
+ return this.getEngine(sessionId).upsertContact(this.toAddressableId(contactId), firstName, lastName);
}
deleteContact(sessionId: string, contactId: string) {
this.assertAddressable(contactId);
- return this.getEngine(sessionId).deleteContact(contactId);
+ return this.getEngine(sessionId).deleteContact(this.toAddressableId(contactId));
}
unblockContact(sessionId: string, contactId: string) {
diff --git a/src/modules/infra/infra-data.controller.spec.ts b/src/modules/infra/infra-data.controller.spec.ts
index 8321cd9ae..017929c68 100644
--- a/src/modules/infra/infra-data.controller.spec.ts
+++ b/src/modules/infra/infra-data.controller.spec.ts
@@ -36,6 +36,7 @@ import { IngressEvent } from '../integration/entities/ingress-event.entity';
import { WebhookDeliveryFailure } from '../webhook/entities/webhook-delivery-failure.entity';
import { IntegrationDeliveryFailure } from '../integration/entities/integration-delivery-failure.entity';
import { StatusUpdate } from '../status-store/entities/status-update.entity';
+import { AutomationRule } from '../automation/entities/automation-rule.entity';
import { AuditAction } from '../audit/entities/audit-log.entity';
describe('InfraDataController.importData round-trips export-data (no silent message/batch loss)', () => {
@@ -835,6 +836,7 @@ describe('InfraDataController.importData status_updates + runtime reconciliation
WebhookDeliveryFailure,
IntegrationDeliveryFailure,
StatusUpdate,
+ AutomationRule,
],
synchronize: true,
});
@@ -861,6 +863,40 @@ describe('InfraDataController.importData status_updates + runtime reconciliation
}),
);
+ // automation_rules FKs sessions ON DELETE CASCADE, so the import's `DELETE FROM sessions` takes
+ // every rule with it — on SQLite too, where better-sqlite3 enforces foreign keys. Without export +
+ // re-insert the documented backup/restore silently destroyed every autoreply rule.
+ it('exports and restores automation_rules, which the session wipe would otherwise cascade away', async () => {
+ await seedSession('s1');
+ const ruleRepo = ds.getRepository(AutomationRule);
+ await ruleRepo.save(
+ ruleRepo.create({
+ id: 'rule-1',
+ sessionId: 's1',
+ name: 'office hours',
+ enabled: true,
+ conditions: { bodyContains: ['hello'] } as never,
+ replyText: 'We are closed',
+ cooldownSeconds: 120,
+ }),
+ );
+
+ const controller = build();
+ const dump = await controller.exportData();
+ expect(dump.counts.automationRules).toBe(1);
+ expect(dump.skippedTables).toEqual([]);
+
+ const res = await controller.importData({ tables: dump.tables });
+
+ expect(res.imported).toBe(true);
+ expect(res.counts.automationRules).toBe(1);
+ const restored = await ruleRepo.findOneByOrFail({ id: 'rule-1' });
+ expect(restored.replyText).toBe('We are closed');
+ expect(restored.cooldownSeconds).toBe(120);
+ expect(restored.enabled).toBe(true);
+ expect(restored.conditions).toEqual({ bodyContains: ['hello'] });
+ });
+
it('exports and restores status_updates (the table the docs promise is covered)', async () => {
await seedSession('s1');
const statusRepo = ds.getRepository(StatusUpdate);
diff --git a/src/modules/infra/infra-data.controller.ts b/src/modules/infra/infra-data.controller.ts
index 9612920e3..9ecd8aae2 100644
--- a/src/modules/infra/infra-data.controller.ts
+++ b/src/modules/infra/infra-data.controller.ts
@@ -28,6 +28,7 @@ import type {
WebhookDeliveryFailureRow,
IntegrationDeliveryFailureRow,
StatusUpdateRow,
+ AutomationRuleRow,
} from './migration-tables.types';
import { TABLE_IMPORTERS } from './table-importers';
@@ -87,6 +88,7 @@ export class InfraDataController {
webhookDeliveryFailures: number;
integrationDeliveryFailures: number;
statusUpdates: number;
+ automationRules: number;
};
/** Optional tables that were skipped because they genuinely do not exist in this DB (older schema). */
skippedTables: string[];
@@ -135,6 +137,7 @@ export class InfraDataController {
'integration_delivery_failures',
);
const statusUpdates = await queryOptionalTable<StatusUpdateRow>('status_updates');
+ const automationRules = await queryOptionalTable<AutomationRuleRow>('automation_rules');
const counts = {
sessions: sessions.length,
@@ -150,6 +153,7 @@ export class InfraDataController {
webhookDeliveryFailures: webhookDeliveryFailures.length,
integrationDeliveryFailures: integrationDeliveryFailures.length,
statusUpdates: statusUpdates.length,
+ automationRules: automationRules.length,
};
// Audit the full-DB export: this payload carries webhook + plugin-instance secrets, so WHO pulled
@@ -174,6 +178,7 @@ export class InfraDataController {
webhookDeliveryFailures,
integrationDeliveryFailures,
statusUpdates,
+ automationRules,
},
counts,
skippedTables,
diff --git a/src/modules/infra/migration-tables.types.ts b/src/modules/infra/migration-tables.types.ts
index 3b42f7a7a..c3d3b9c37 100644
--- a/src/modules/infra/migration-tables.types.ts
+++ b/src/modules/infra/migration-tables.types.ts
@@ -207,6 +207,25 @@ export interface StatusUpdateRow {
expiresAt: number | string;
}
+/**
+ * automation_rules has an ON DELETE CASCADE FK to sessions, so the import's `DELETE FROM sessions`
+ * takes every rule with it — on SQLite too, where better-sqlite3 enforces foreign keys. Exporting
+ * and re-inserting it is therefore not optional: without it a backup/restore silently destroys
+ * every autoreply rule. `conditions` is stored as text (the webhook-filter JSON), `enabled` reads
+ * back as a boolean on Postgres and 0/1 on SQLite.
+ */
+export interface AutomationRuleRow {
+ id: string;
+ sessionId: string;
+ name: string;
+ enabled: boolean | number;
+ conditions: string | null;
+ replyText: string;
+ cooldownSeconds: number;
+ createdAt: string | Date;
+ updatedAt: string | Date;
+}
+
export interface MigrationTables {
sessions: SessionRow[];
webhooks: WebhookRow[];
@@ -221,6 +240,7 @@ export interface MigrationTables {
webhookDeliveryFailures: WebhookDeliveryFailureRow[];
integrationDeliveryFailures: IntegrationDeliveryFailureRow[];
statusUpdates: StatusUpdateRow[];
+ automationRules: AutomationRuleRow[];
}
export type TableCounts = { [K in keyof MigrationTables]: number };
diff --git a/src/modules/infra/table-importers.ts b/src/modules/infra/table-importers.ts
index aa8bab22a..12f14f439 100644
--- a/src/modules/infra/table-importers.ts
+++ b/src/modules/infra/table-importers.ts
@@ -14,6 +14,7 @@ import type {
WebhookDeliveryFailureRow,
IntegrationDeliveryFailureRow,
StatusUpdateRow,
+ AutomationRuleRow,
} from './migration-tables.types';
// A per-table restore step for importData: which backup key to read, the exact INSERT text (kept in
@@ -357,6 +358,27 @@ export const TABLE_IMPORTERS: AnyTableImporter[] = [
su.expiresAt,
],
}),
+ // Import automation rules (per-session autoreply rules; FK sessions ON DELETE CASCADE, so the
+ // import's `DELETE FROM sessions` wipes them and they must be re-inserted or a restore
+ // permanently loses every rule).
+ defineTableImporter({
+ key: 'automationRules',
+ label: 'automation rule',
+ sql: `INSERT INTO automation_rules (id, "sessionId", name, enabled, conditions, "replyText", "cooldownSeconds", "createdAt", "updatedAt")
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)`,
+ id: (rule: AutomationRuleRow) => rule.id,
+ map: (rule: AutomationRuleRow) => [
+ rule.id,
+ rule.sessionId,
+ rule.name,
+ rule.enabled ?? true,
+ rule.conditions ?? null,
+ rule.replyText,
+ rule.cooldownSeconds ?? 60,
+ rule.createdAt,
+ rule.updatedAt,
+ ],
+ }),
];
// The `as TableCounts` cast in importData means a dropped or mis-keyed descriptor is invisible to
@@ -376,6 +398,7 @@ const EXPECTED_TABLE_KEYS: ReadonlyArray<keyof MigrationTables> = [
'webhookDeliveryFailures',
'integrationDeliveryFailures',
'statusUpdates',
+ 'automationRules',
];
const importerKeys = TABLE_IMPORTERS.map(importer => importer.key);
for (const key of EXPECTED_TABLE_KEYS) {
diff --git a/src/modules/label/label.service.ts b/src/modules/label/label.service.ts
index de56cd801..4b05559c3 100644
--- a/src/modules/label/label.service.ts
+++ b/src/modules/label/label.service.ts
@@ -37,13 +37,21 @@ export class LabelService {
* already exists — which is also why the caller chooses the id rather than being handed one.
*/
upsertLabel(sessionId: string, labelId: string, body: { name?: string; color?: number }) {
- // Both fields are individually optional (either alone is a valid partial update), but an empty
- // body has nothing to write — on an unused id it would even create a nameless label — so it is
- // refused like the group-settings PUT refuses an empty patch.
- if (body.name === undefined && body.color === undefined) {
+ // Both fields are individually optional (either alone is a valid partial update), but a body
+ // that sets neither has nothing to write — on an unused id it would even create a nameless
+ // label — so it is refused like the group-settings PUT refuses an empty patch. `null` counts as
+ // "not set": class-validator's @IsOptional skips validation for it and class-transformer keeps
+ // it, so {"name": null} reached here as an explicit nothing.
+ const name = body.name ?? undefined;
+ const color = body.color ?? undefined;
+ if (name === undefined && color === undefined) {
throw new BadRequestException('At least one of name or color must be provided');
}
- return this.getEngine(sessionId).upsertLabel({ id: labelId, ...body });
+ return this.getEngine(sessionId).upsertLabel({
+ id: labelId,
+ ...(name === undefined ? {} : { name }),
+ ...(color === undefined ? {} : { color }),
+ });
}
deleteLabel(sessionId: string, labelId: string) {
diff --git a/src/modules/media/media-conversion.service.ts b/src/modules/media/media-conversion.service.ts
index adb972364..c2d42009e 100644
--- a/src/modules/media/media-conversion.service.ts
+++ b/src/modules/media/media-conversion.service.ts
@@ -1,7 +1,8 @@
-import { BadRequestException, Injectable, ServiceUnavailableException } from '@nestjs/common';
+import { BadRequestException, HttpException, Injectable, ServiceUnavailableException } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { createLogger } from '../../common/services/logger.service';
import { loadRemoteMediaBuffer } from '../../common/media/load-remote-media';
+import { SsrfBlockedError, SSRF_BLOCKED_CLIENT_MESSAGE } from '../../common/security/ssrf-guard';
import { ConcurrencyLimiter } from '../../common/utils/concurrency-limiter';
import { assertBase64WithinMediaCap, stripBase64DataUri } from '../message/media-cap.util';
import { FfmpegConversionError, probeFfmpeg, runFfmpeg, videoEncodeArgs, voiceEncodeArgs } from './ffmpeg';
@@ -105,8 +106,20 @@ export class MediaConversionService {
// Through the SSRF guard, exactly as a send does: it validates the host and pins the
// connection to the vetted address. ffmpeg itself never sees a URL — it is restricted to the
// file protocol and handed bytes this process already fetched and checked.
- const { data } = await loadRemoteMediaBuffer(dto.url);
- return data;
+ try {
+ const { data } = await loadRemoteMediaBuffer(dto.url);
+ return data;
+ } catch (error) {
+ // The fetch layer throws plain Errors (bad status, over the byte cap) and SsrfBlockedError,
+ // none of them HttpExceptions — unmapped they leave as a 500 for what is squarely a bad
+ // input, while the send path answers 400 for the very same URL. An SSRF block is reported
+ // generically: its raw message names the resolved internal address.
+ if (error instanceof SsrfBlockedError) {
+ throw new BadRequestException(SSRF_BLOCKED_CLIENT_MESSAGE);
+ }
+ if (error instanceof HttpException) throw error;
+ throw new BadRequestException(error instanceof Error ? error.message : String(error));
+ }
}
throw new BadRequestException('Either url or base64 must be provided');
}
diff --git a/src/modules/message/bulk-message.service.ts b/src/modules/message/bulk-message.service.ts
index ec0a00844..9b66b8fa3 100644
--- a/src/modules/message/bulk-message.service.ts
+++ b/src/modules/message/bulk-message.service.ts
@@ -20,7 +20,12 @@ import { SendBulkMessageDto } from './dto/bulk-message.dto';
import { MessageStatus } from './entities/message.entity';
import { EngineRegistry } from '../../engine/engine-registry.service';
import { MessageService } from './message.service';
-import { SendPacingService, isPacingLimitedError, SEND_PACING_LIMITED } from './send-pacing.service';
+import {
+ SendPacingService,
+ isPacingLimitedError,
+ countsTowardSendBreaker,
+ SEND_PACING_LIMITED,
+} from './send-pacing.service';
import { SessionOwnershipService } from '../session/session-ownership.service';
import { HookManager } from '../../core/hooks';
import { assertBase64WithinMediaCap, stripBase64DataUri } from './media-cap.util';
@@ -473,7 +478,11 @@ export class BulkMessageService implements OnApplicationBootstrap {
try {
messageResult = await this.sendMessage(engine, msg.chatId, msg.type, content);
} catch (engineError) {
- this.pacing.recordSendFailure(batch.sessionId);
+ // Same filter the single-send path applies: adapters also raise client-fault and
+ // engine-state errors from inside this call, and those say nothing about the account.
+ if (countsTowardSendBreaker(engineError)) {
+ this.pacing.recordSendFailure(batch.sessionId);
+ }
throw engineError;
}
this.pacing.recordSendSuccess(batch.sessionId);
diff --git a/src/modules/message/message.service.ts b/src/modules/message/message.service.ts
index 87b644af8..ae8a29356 100644
--- a/src/modules/message/message.service.ts
+++ b/src/modules/message/message.service.ts
@@ -12,7 +12,7 @@ import { assertBase64WithinMediaCap, stripBase64DataUri } from './media-cap.util
import { MediaInput, IWhatsAppEngine, MessageResult } from '../../engine/interfaces/whatsapp-engine.interface';
import { Message, MessageDirection, MessageStatus } from './entities/message.entity';
import { HookManager, applySendingGate } from '../../core/hooks';
-import { SendPacingService } from './send-pacing.service';
+import { SendPacingService, countsTowardSendBreaker } from './send-pacing.service';
import { TemplateService } from '../template/template.service';
import { renderTemplate } from '../../common/utils/template-render';
import { createLogger } from '../../common/services/logger.service';
@@ -178,10 +178,13 @@ export class MessageService {
input: unknown,
error: unknown,
): Promise<never> {
- // The engine was asked and refused, so this counts toward the breaker's streak. Validation
- // errors thrown before the engine is reached never come through here, which is what keeps a
- // client sending malformed requests from tripping the breaker on a healthy session.
- this.pacing.recordSendFailure(sessionId);
+ // Only failures that say something about the account's standing feed the breaker: adapters also
+ // raise client-fault and engine-state errors from inside this call (a blocked media URL, an
+ // unsupported capability, a disconnected socket), and counting those let a client sending bad
+ // requests trip the breaker on a healthy session.
+ if (countsTowardSendBreaker(error)) {
+ this.pacing.recordSendFailure(sessionId);
+ }
await this.saveFailedMessage(message);
// Sanitize the hook payload: an SSRF block's raw .message names the resolved internal address
// (a recon/DNS-rebind oracle) — the client-facing throw below already maps it to a generic
diff --git a/src/modules/message/send-pacing-cold-query.spec.ts b/src/modules/message/send-pacing-cold-query.spec.ts
index df3a38b79..b855ae2de 100644
--- a/src/modules/message/send-pacing-cold-query.spec.ts
+++ b/src/modules/message/send-pacing-cold-query.spec.ts
@@ -149,6 +149,24 @@ describe('cold-reachout counting against a real database', () => {
await expect(service.assertSendAllowed('s1', '[email protected]')).resolves.toBeUndefined();
});
+ // The per-send probe and the daily aggregate must agree about who is a stranger, or the aggregate
+ // over-counts and refuses legitimate sends a slot or more early.
+ it('counts a contact reached under either dialect once, and not at all when known before today', async () => {
+ // Known since yesterday under the engine spelling; today's outgoing uses the neutral one.
+ await addMessage('[email protected]', YESTERDAY);
+ await addMessage('[email protected]', TODAY);
+ // The same stranger written to under both spellings today is ONE cold reachout, not two.
+ await addMessage('[email protected]', TODAY);
+ await addMessage('[email protected]', TODAY);
+ await addMessage('[email protected]', TODAY);
+
+ // Two of three used (the warm contact counted zero, the double-spelled stranger counted once).
+ await expect(service.assertSendAllowed('s1', '[email protected]')).resolves.toBeUndefined();
+
+ await addMessage('[email protected]', TODAY);
+ await expect(service.assertSendAllowed('s1', '[email protected]')).rejects.toMatchObject({ status: 429 });
+ });
+
it("forgets yesterday's reachouts when the UTC day rolls over", async () => {
await addMessage('[email protected]', YESTERDAY);
await addMessage('[email protected]', YESTERDAY);
diff --git a/src/modules/message/send-pacing.service.spec.ts b/src/modules/message/send-pacing.service.spec.ts
index b1e740d97..428119829 100644
--- a/src/modules/message/send-pacing.service.spec.ts
+++ b/src/modules/message/send-pacing.service.spec.ts
@@ -1,5 +1,14 @@
-import { HttpException } from '@nestjs/common';
-import { SendPacingService, SEND_PACING_LIMITED } from './send-pacing.service';
+import {
+ BadRequestException,
+ HttpException,
+ InternalServerErrorException,
+ NotFoundException,
+ ServiceUnavailableException,
+} from '@nestjs/common';
+import { SendPacingService, SEND_PACING_LIMITED, countsTowardSendBreaker } from './send-pacing.service';
+import { EngineRefusedError } from '../../common/errors/engine-refused.error';
+import { EngineNotSupportedError } from '../../common/errors/engine-not-supported.error';
+import { SsrfBlockedError } from '../../common/security/ssrf-guard';
import { computeSendPacingConfig, type SendPacingConfig } from './send-pacing.config';
import { getSendPacingRefusals, resetSendPacingRefusals } from '../../common/metrics/send-pacing-metrics';
import { MessageDirection, type Message } from './entities/message.entity';
@@ -569,3 +578,27 @@ describe('SendPacingService cold-reachout cap', () => {
expect(auditCall(audit.logWarn)[1].metadata).toMatchObject({ rule: 'cold_daily_cap' });
});
});
+
+// The breaker exists to notice that WHATSAPP is refusing this account's sends. Adapters also raise
+// client-fault and engine-state errors from inside the same engine call, and counting those let a
+// client sending malformed requests open the breaker on a perfectly healthy session — 429ing every
+// send, including unrelated ones, for the whole cooldown.
+describe('countsTowardSendBreaker', () => {
+ it.each([
+ ['an SSRF-blocked media URL', new SsrfBlockedError('Host resolves to 169.254.169.254')],
+ ['a capability this engine lacks (501)', new EngineNotSupportedError('customLinkPreview')],
+ ['a disconnected engine (503)', new ServiceUnavailableException('engine not connected')],
+ ['a malformed request (400)', new BadRequestException('recipients is required')],
+ ['an unknown message id (404)', new NotFoundException('message not found')],
+ ])('does not count %s', (_label, error) => {
+ expect(countsTowardSendBreaker(error)).toBe(false);
+ });
+
+ it.each([
+ ['a WhatsApp refusal (403 EngineRefusedError)', new EngineRefusedError('not allowed to send here')],
+ ['a raw engine error', new Error('ack error 500')],
+ ['a server-side fault', new InternalServerErrorException('boom')],
+ ])('counts %s', (_label, error) => {
+ expect(countsTowardSendBreaker(error)).toBe(true);
+ });
+});
diff --git a/src/modules/message/send-pacing.service.ts b/src/modules/message/send-pacing.service.ts
index e8ef1fb51..67abdad93 100644
--- a/src/modules/message/send-pacing.service.ts
+++ b/src/modules/message/send-pacing.service.ts
@@ -7,6 +7,8 @@ import { Session } from '../session/entities/session.entity';
import { resolveSendPacingConfig, type SendPacingConfig } from './send-pacing.config';
import { incrementSendPacingRefusals, type SendPacingRefusalReason } from '../../common/metrics/send-pacing-metrics';
import { createLogger } from '../../common/services/logger.service';
+import { EngineRefusedError } from '../../common/errors/engine-refused.error';
+import { SsrfBlockedError } from '../../common/security/ssrf-guard';
import { AuditService } from '../audit/audit.service';
import { AuditAction } from '../audit/entities/audit-log.entity';
@@ -24,6 +26,32 @@ export function isPacingLimitedError(error: unknown): boolean {
return typeof body === 'object' && body !== null && (body as { code?: string }).code === SEND_PACING_LIMITED;
}
+/**
+ * Whether a failed send says anything about the ACCOUNT's standing with WhatsApp — the only thing
+ * the breaker is meant to measure.
+ *
+ * Adapters raise plenty of failures before (or instead of) asking WhatsApp: a blocked media URL, a
+ * capability the engine does not implement, a socket that is not connected, a message id that is
+ * not in the local store, a malformed request. Counting those lets a client sending bad requests
+ * open the breaker on a perfectly healthy session and 429 every send for the cooldown. The rule is
+ * therefore: a client-fault or engine-state HTTP status (4xx/501/503) does NOT count; a refusal
+ * WhatsApp itself returned — EngineRefusedError (403) — and anything unclassified (a raw engine
+ * error, a timeout, a 5xx) does.
+ */
+export function countsTowardSendBreaker(error: unknown): boolean {
+ if (error instanceof EngineRefusedError) return true;
+ if (error instanceof SsrfBlockedError) return false;
+ if (error instanceof HttpException) {
+ const status = error.getStatus();
+ // 4xx = the caller's request was wrong; 501 = this engine cannot do it; 503 = the engine is not
+ // connected (a transport fault the reconnect machinery owns, not an account signal).
+ const NOT_IMPLEMENTED: number = HttpStatus.NOT_IMPLEMENTED;
+ const SERVICE_UNAVAILABLE: number = HttpStatus.SERVICE_UNAVAILABLE;
+ return !((status >= 400 && status < 500) || status === NOT_IMPLEMENTED || status === SERVICE_UNAVAILABLE);
+ }
+ return true;
+}
+
/** Per-session breaker state. Deliberately in memory — see the class doc. */
interface BreakerState {
consecutiveFailures: number;
@@ -378,7 +406,12 @@ export class SendPacingService {
return (
this.messageRepository
.createQueryBuilder('m')
- .select('COUNT(DISTINCT m.chatId)', 'count')
+ // Counted per CONTACT, not per stored spelling: the same person reached under both user-id
+ // dialects today is one reachout, and the correlated lookups below match either spelling
+ // (see dialectVariants — a chat known as @s.whatsapp.net is not a stranger as @c.us).
+ // REPLACE is the portable normalisation both SQLite and Postgres carry; the paired IN keeps
+ // the inner side's `chatId` index usable.
+ .select(`COUNT(DISTINCT REPLACE(m."chatId", '@s.whatsapp.net', '@c.us'))`, 'count')
.where('m.sessionId = :sessionId', { sessionId })
.andWhere('m.direction = :direction', { direction: MessageDirection.OUTGOING })
.andWhere('m.createdAt >= :dayStart', { dayStart })
@@ -386,12 +419,12 @@ export class SendPacingService {
// — there is no snake_case naming strategy on this connection. Unquoted, Postgres would fold
// them to lowercase and the query would fail at runtime on the very first cold send.
.andWhere(
- 'NOT EXISTS (SELECT 1 FROM "messages" p WHERE p."sessionId" = :sessionId AND p."chatId" = m."chatId" AND p."createdAt" < :dayStart)',
+ `NOT EXISTS (SELECT 1 FROM "messages" p WHERE p."sessionId" = :sessionId AND p."chatId" IN (${DIALECT_PAIR('m')}) AND p."createdAt" < :dayStart)`,
)
// They wrote first: an incoming row strictly earlier than today's first outgoing one makes
// the chat an answered conversation, not a cold start. A tie stays cold (conservative).
.andWhere(
- 'NOT EXISTS (SELECT 1 FROM "messages" i WHERE i."sessionId" = :sessionId AND i."chatId" = m."chatId" AND i."direction" = :incoming AND i."createdAt" < (SELECT MIN(o."createdAt") FROM "messages" o WHERE o."sessionId" = :sessionId AND o."chatId" = m."chatId" AND o."direction" = :direction AND o."createdAt" >= :dayStart))',
+ `NOT EXISTS (SELECT 1 FROM "messages" i WHERE i."sessionId" = :sessionId AND i."chatId" IN (${DIALECT_PAIR('m')}) AND i."direction" = :incoming AND i."createdAt" < (SELECT MIN(o."createdAt") FROM "messages" o WHERE o."sessionId" = :sessionId AND o."chatId" IN (${DIALECT_PAIR('m')}) AND o."direction" = :direction AND o."createdAt" >= :dayStart))`,
{ incoming: MessageDirection.INCOMING },
)
.getRawOne<{ count: string | number }>()
@@ -438,6 +471,14 @@ const DAY_MS = 86_400_000;
* known contact addressed the other way as cold and over-draws the budget. Non-user ids (groups,
* lids, …) pass through unchanged; a lid has no derivable phone twin to probe.
*/
+/**
+ * SQL for both user-id spellings of `<alias>."chatId"`, for use as an `IN (…)` list. The same idea
+ * as {@link dialectVariants}, expressed portably: REPLACE exists on SQLite and Postgres alike, and
+ * for a non-user id (a group, a lid) both branches collapse to the raw value.
+ */
+const DIALECT_PAIR = (alias: string): string =>
+ `REPLACE(${alias}."chatId", '@s.whatsapp.net', '@c.us'), REPLACE(${alias}."chatId", '@c.us', '@s.whatsapp.net')`;
+
function dialectVariants(chatId: string): string[] {
const lower = chatId.toLowerCase();
if (lower.endsWith('@c.us')) {
diff --git a/src/modules/session/session-engine-controls.ts b/src/modules/session/session-engine-controls.ts
index 42d68d894..fea66c815 100644
--- a/src/modules/session/session-engine-controls.ts
+++ b/src/modules/session/session-engine-controls.ts
@@ -220,6 +220,10 @@ export class SessionEngineControls {
await this.fences.teardownEngineSafely(id, orphan, e => e.forceDestroy(), 'force-destroy');
await this.host.updateStatus(id, SessionStatus.FAILED).catch(() => undefined);
}
+ // Drop the reconnect state this start() armed up front: no engine was registered, so
+ // nothing will ever fire it, and leaving it behind is dead state a later liveness check
+ // would have to reason about. A retry builds its own.
+ this.host.cancelReconnect(id);
throw err;
}
diff --git a/src/modules/session/session-engine-lifecycle.service.ts b/src/modules/session/session-engine-lifecycle.service.ts
index d37c33d67..a76e1125b 100644
--- a/src/modules/session/session-engine-lifecycle.service.ts
+++ b/src/modules/session/session-engine-lifecycle.service.ts
@@ -409,7 +409,15 @@ export class SessionEngineLifecycle {
* "already starting/started" refusal never releases a session this node genuinely runs.
*/
isEngineActive(id: string): boolean {
- return this.engines.has(id) || this.initializingSessions.has(id) || this.reconnectStates.has(id);
+ if (this.engines.has(id) || this.initializingSessions.has(id)) return true;
+ // Reconnect state counts only while an attempt is actually pending: a timer armed by
+ // scheduleReconnect, or one that has fired and is running executeReconnect (which leaves the
+ // spent handle in place and has already counted its attempt). The entry start() creates up
+ // front — {attempts: 0, timer: null} — is dormant: a start that then failed leaves nothing
+ // that will ever re-register an engine, and treating it as liveness would pin the claim to
+ // this node forever.
+ const reconnect = this.reconnectStates.get(id);
+ return reconnect != null && (reconnect.timer !== null || reconnect.attempts > 0);
}
// --- Leaf-event delegates (SessionEngineLeafEvents) ------------------------------------------
diff --git a/src/modules/session/session-ownership.service.spec.ts b/src/modules/session/session-ownership.service.spec.ts
index e155d171d..b0311993d 100644
--- a/src/modules/session/session-ownership.service.spec.ts
+++ b/src/modules/session/session-ownership.service.spec.ts
@@ -140,6 +140,32 @@ describe('SessionOwnershipService', () => {
});
});
+ describe('releasing a lapsed foreign claim', () => {
+ // A deliberate teardown of a session whose crashed owner's lease expired must actually leave it
+ // down. A row still naming the dead node reads as an abandoned orphan, and the takeover sweep
+ // would adopt and restart the session the operator just stopped.
+ it('clears a claim whose holder is gone and its lease has lapsed', async () => {
+ const session = await seed({ nodeId: 'dead-node', leaseExpiresAt: new Date(Date.now() - 1000) });
+
+ await service('node-b').release(session.id);
+
+ const stored = await sessions.findOneByOrFail({ id: session.id });
+ expect(stored.nodeId).toBeNull();
+ expect(stored.leaseExpiresAt).toBeNull();
+ });
+
+ it('leaves a LIVE peer claim untouched — releasing it would strand a running engine', async () => {
+ const liveExpiry = new Date(Date.now() + 600_000);
+ const session = await seed({ nodeId: 'peer-node', leaseExpiresAt: liveExpiry });
+
+ await service('node-b').release(session.id);
+
+ const stored = await sessions.findOneByOrFail({ id: session.id });
+ expect(stored.nodeId).toBe('peer-node');
+ expect(stored.leaseExpiresAt!.getTime()).toBe(liveExpiry.getTime());
+ });
+ });
+
describe('renewing', () => {
it('pushes the expiry out, so a busy node does not lose what it is running', async () => {
const session = await seed();
diff --git a/src/modules/session/session-ownership.service.ts b/src/modules/session/session-ownership.service.ts
index 1843649dd..bd563bef6 100644
--- a/src/modules/session/session-ownership.service.ts
+++ b/src/modules/session/session-ownership.service.ts
@@ -130,14 +130,24 @@ export class SessionOwnershipService {
return claimed;
}
- /** Give a session up, so a peer can take it without waiting for the lease to lapse. */
+ /**
+ * Give a session up, so a peer can take it without waiting for the lease to lapse.
+ *
+ * Clears a LAPSED foreign claim too, on the same predicate `claim()` uses. A deliberate teardown
+ * (stop/logout/delete) of a session whose crashed owner's lease has expired must actually leave
+ * it down: a row still naming the dead node reads as an abandoned orphan to the takeover sweep,
+ * which would adopt and restart the session the operator just stopped. A LIVE foreign claim is
+ * left alone — releasing that would strand a peer's running engine.
+ */
async release(sessionId: string): Promise<void> {
+ const now = new Date();
this.owned.delete(sessionId);
await this.sessions
.createQueryBuilder()
.update(Session)
.set({ nodeId: null, claimedAt: null, leaseExpiresAt: null, nodeUrl: null })
- .where('id = :id AND "nodeId" = :me', { id: sessionId, me: this.nodeId })
+ .where('id = :id', { id: sessionId })
+ .andWhere('("nodeId" = :me OR "leaseExpiresAt" < :now)', { me: this.nodeId, now: leaseParam(now) })
.execute();
}
diff --git a/src/modules/session/session-proxy.interceptor.spec.ts b/src/modules/session/session-proxy.interceptor.spec.ts
index e6957462a..d9a340417 100644
--- a/src/modules/session/session-proxy.interceptor.spec.ts
+++ b/src/modules/session/session-proxy.interceptor.spec.ts
@@ -1,6 +1,6 @@
import http from 'http';
import { AddressInfo } from 'net';
-import { of, lastValueFrom, isEmpty } from 'rxjs';
+import { of, lastValueFrom } from 'rxjs';
import type { CallHandler, ExecutionContext } from '@nestjs/common';
import { SessionProxyInterceptor, FORWARDED_HEADER } from './session-proxy.interceptor';
import type { Session } from './entities/session.entity';
@@ -188,8 +188,10 @@ describe('SessionProxyInterceptor', () => {
const { interceptor, context, next, handle, res } = build({ req, row: row({ nodeUrl: serverUrl }) });
const result = await interceptor.intercept(context, next);
- // EMPTY: the response was written directly; nothing may flow to the route handler.
- expect(await lastValueFrom(result.pipe(isEmpty()))).toBe(true);
+ // The response was written directly, so nothing may flow to the route handler. The observable
+ // still EMITS (undefined) rather than completing empty: Nest resolves it with lastValueFrom,
+ // which rejects on an empty one and logged an ERROR for every successful forward.
+ expect(await lastValueFrom(result)).toBeUndefined();
expect(handle).not.toHaveBeenCalled();
expect(seen).toHaveLength(1);
diff --git a/src/modules/session/session-proxy.interceptor.ts b/src/modules/session/session-proxy.interceptor.ts
index efc8a835c..a899fbf8f 100644
--- a/src/modules/session/session-proxy.interceptor.ts
+++ b/src/modules/session/session-proxy.interceptor.ts
@@ -11,7 +11,7 @@ import { Reflector } from '@nestjs/core';
import { InjectRepository } from '@nestjs/typeorm';
import { isUUID } from 'class-validator';
import { Repository } from 'typeorm';
-import { EMPTY, Observable } from 'rxjs';
+import { Observable, of } from 'rxjs';
import type { Request, Response } from 'express';
import { Session } from './entities/session.entity';
import { SessionOwnershipService } from './session-ownership.service';
@@ -99,8 +99,12 @@ export class SessionProxyInterceptor implements NestInterceptor {
if (!owner.nodeUrl) return next.handle();
await this.forward(request, context.switchToHttp().getResponse<Response>(), owner.nodeId, owner.nodeUrl);
- // The response has been written; complete without emitting so nothing downstream re-answers it.
- return EMPTY;
+ // The response has been written and ended here. Emit undefined rather than completing empty:
+ // Nest resolves an interceptor's observable with `lastValueFrom`, which REJECTS on an empty one
+ // (EmptyError) — every successful forward then travelled the unknown-exception path and logged
+ // an ERROR stack, for a request that had in fact succeeded. Emitting leaves the already-sent
+ // response untouched (verified end-to-end in session-proxy.e2e-spec).
+ return of(undefined);
}
private sessionIdOf(context: ExecutionContext, request: Request): string | undefined {
diff --git a/src/modules/session/session-restriction-store.service.spec.ts b/src/modules/session/session-restriction-store.service.spec.ts
index dadbc166b..90fcfb666 100644
--- a/src/modules/session/session-restriction-store.service.spec.ts
+++ b/src/modules/session/session-restriction-store.service.spec.ts
@@ -70,8 +70,10 @@ describe('SessionRestrictionStore', () => {
expect(store.get('s1')).toBeUndefined();
expect(store.attachTo(sessionRow('s1')).restriction).toBeNull();
- // Still stored: set/clear own the lift signal, and the next engine report self-heals the map.
- expect(store.size()).toBe(1);
+ // Reported as not-restricted everywhere reads happen — including the count that feeds the
+ // gauge, which would otherwise claim a restriction the API no longer serves. The entry itself
+ // stays stored: set/clear own the lift signal, and the next engine report self-heals the map.
+ expect(store.size()).toBe(0);
});
it('keeps reporting one that has not expired, or that states no end', () => {
diff --git a/src/modules/session/session-restriction-store.service.ts b/src/modules/session/session-restriction-store.service.ts
index 287b21a58..8c0276f03 100644
--- a/src/modules/session/session-restriction-store.service.ts
+++ b/src/modules/session/session-restriction-store.service.ts
@@ -34,10 +34,23 @@ export class SessionRestrictionStore {
set(sessionId: string, restriction: AccountRestriction): boolean {
const previous = this.restrictions.get(sessionId);
this.restrictions.set(sessionId, restriction);
- setRestrictedSessionCount(this.restrictions.size);
+ this.publishCount();
return previous?.kind !== restriction.kind || previous?.code !== restriction.code;
}
+ /**
+ * Publish what the API would actually report: entries whose stated end has passed are no longer
+ * served, so counting them would leave the gauge claiming a session is restricted while every
+ * read says it is not.
+ */
+ private publishCount(): void {
+ let inForce = 0;
+ for (const sessionId of this.restrictions.keys()) {
+ if (this.inForce(sessionId)) inForce++;
+ }
+ setRestrictedSessionCount(inForce);
+ }
+
/** The restriction in force, if any. `attachTo` is the projection; this is the raw read. */
get(sessionId: string): AccountRestriction | undefined {
return this.inForce(sessionId);
@@ -63,7 +76,7 @@ export class SessionRestrictionStore {
clear(sessionId: string): AccountRestriction | undefined {
const previous = this.restrictions.get(sessionId);
this.restrictions.delete(sessionId);
- setRestrictedSessionCount(this.restrictions.size);
+ this.publishCount();
return previous;
}
@@ -81,9 +94,13 @@ export class SessionRestrictionStore {
return this.clear(sessionId);
}
- /** How many sessions are restricted right now. */
+ /** How many sessions are restricted right now — expired entries excluded, as reads are. */
size(): number {
- return this.restrictions.size;
+ let inForce = 0;
+ for (const sessionId of this.restrictions.keys()) {
+ if (this.inForce(sessionId)) inForce++;
+ }
+ return inForce;
}
/**
diff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.ts
index 4354fcc08..1a2a6f5e9 100644
--- a/src/modules/session/session.service.spec.ts
+++ b/src/modules/session/session.service.spec.ts
@@ -1110,10 +1110,27 @@ describe('SessionService', () => {
expect(ownership.release).toHaveBeenCalledWith('sess-uuid-1');
});
+
+ // A stop() that lands while a start() is mid-launch must NOT hand the claim back: the start
+ // holds it, and its engine is about to register. Releasing here left a live engine on an
+ // unclaimed row — no heartbeat renewed it, and any peer would start the account a second time.
+ it.each([
+ ['stop', (s: SessionService) => s.stop('sess-uuid-1')],
+ ['logout', (s: SessionService) => s.logout('sess-uuid-1')],
+ ['forceKill', (s: SessionService) => s.forceKill('sess-uuid-1')],
+ ])('%s() keeps the claim when a concurrent start still holds the session here', async (verb, call) => {
+ const ownership = withOwnership();
+ jest.spyOn(lifecycle, verb as 'stop' | 'logout' | 'forceKill').mockResolvedValue(createMockSession());
+ jest.spyOn(lifecycle, 'isEngineActive').mockReturnValue(true);
+
+ await call(service);
+
+ expect(ownership.release).not.toHaveBeenCalled();
+ });
});
describe('isEngineActive', () => {
- it('is live for a registered engine, an in-flight start, or reconnect state — dead otherwise', () => {
+ it('is live for a registered engine, an in-flight start, or a pending reconnect — dead otherwise', () => {
const intern = lifecycle as unknown as {
engines: { set: (id: string, e: unknown) => void; delete: (id: string) => void };
initializingSessions: Set<string>;
@@ -1129,11 +1146,34 @@ describe('SessionService', () => {
expect(lifecycle.isEngineActive('x')).toBe(true);
intern.initializingSessions.delete('x');
+ // An attempt counted but not yet armed (decideReconnect increments before setTimeout).
intern.reconnectStates.set('x', { attempts: 1, timer: null });
expect(lifecycle.isEngineActive('x')).toBe(true);
- intern.reconnectStates.delete('x');
+ // An armed timer, attempts reset by a successful READY.
+ intern.reconnectStates.set('x', { attempts: 0, timer: setTimeout(() => undefined, 60_000) });
+ expect(lifecycle.isEngineActive('x')).toBe(true);
+ clearTimeout((intern.reconnectStates.get('x') as { timer: NodeJS.Timeout }).timer);
+
+ // The dormant entry start() arms up front: a start that then FAILED leaves nothing that will
+ // ever register an engine, so counting it as liveness pinned the claim to this node forever.
+ intern.reconnectStates.set('x', { attempts: 0, timer: null });
expect(lifecycle.isEngineActive('x')).toBe(false);
+
+ intern.reconnectStates.delete('x');
+ expect(lifecycle.isEngineActive('x')).toBe(false);
+ });
+
+ it('a failed start leaves no reconnect state behind', async () => {
+ (repository.findOne as jest.Mock).mockResolvedValue(createMockSession());
+ (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });
+ mockEngine.initialize.mockRejectedValue(new Error('engine init failed'));
+
+ await expect(service.start('sess-uuid-1')).rejects.toThrow('engine init failed');
+
+ const intern = lifecycle as unknown as { reconnectStates: Map<string, unknown> };
+ expect(intern.reconnectStates.has('sess-uuid-1')).toBe(false);
+ expect(lifecycle.isEngineActive('sess-uuid-1')).toBe(false);
});
});
diff --git a/src/modules/session/session.service.ts b/src/modules/session/session.service.ts
index e93583ae7..7fa518c22 100644
--- a/src/modules/session/session.service.ts
+++ b/src/modules/session/session.service.ts
@@ -304,8 +304,12 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
async stop(id: string): Promise<Session> {
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
- // lease to lapse. Stop is the deliberate end of this process's ownership.
- await this.ownership?.release(id);
+ // lease to lapse. Stop is the deliberate end of this process's ownership — but a start() that
+ // began before this stop and is still mid-launch owns the claim now, so the same
+ // engine-liveness guard the failure paths use applies here: releasing under an in-flight start
+ // would leave a live engine on an unclaimed row that no heartbeat renews and any peer may
+ // start a second time.
+ await this.releaseUnlessEngineActive(id);
return session;
}
@@ -314,7 +318,7 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
try {
const session = await this.engineLifecycle.logout(id);
// Torn down locally on the 200 path — hand the claim back the way stop() does.
- await this.ownership?.release(id);
+ await this.releaseUnlessEngineActive(id);
return session;
} catch (error) {
// The 502-incomplete path tears the engine down too, and a "not started" refusal never had
@@ -327,7 +331,7 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
async forceKill(id: string): Promise<Session> {
try {
const session = await this.engineLifecycle.forceKill(id);
- await this.ownership?.release(id);
+ await this.releaseUnlessEngineActive(id);
return session;
} catch (error) {
await this.releaseUnlessEngineActive(id);
diff --git a/src/modules/status/status.service.ts b/src/modules/status/status.service.ts
index 360fada13..85b8c2f32 100644
--- a/src/modules/status/status.service.ts
+++ b/src/modules/status/status.service.ts
@@ -5,12 +5,13 @@ import { StorageService, isMissingObjectError } from '../../common/storage/stora
import type { Status, StatusResult, StatusPostOptions } from '../../engine/interfaces/whatsapp-engine.interface';
import { assertBase64WithinMediaCap, stripBase64DataUri } from '../message/media-cap.util';
import { HookManager, applySendingGate } from '../../core/hooks';
-import { SendPacingService } from '../message/send-pacing.service';
+import { SendPacingService, countsTowardSendBreaker } from '../message/send-pacing.service';
-/** Stored status media is only ever an image or video; a sender-declared mimetype outside that is
- * served as inert octet-stream so the media endpoint can't be turned into active content (HTML/JS)
- * on the API origin. */
-const SAFE_STATUS_MIMETYPE = /^(image|video)\//;
+/** Stored status media is only ever an image, a video or a voice note; a sender-declared mimetype
+ * outside that is served as inert octet-stream so the media endpoint can't be turned into active
+ * content (HTML/JS) on the API origin. Audio belongs here because a voice status is a first-class
+ * status type — without it the dashboard's audio player is handed an octet-stream it cannot play. */
+const SAFE_STATUS_MIMETYPE = /^(image|video|audio)\//;
@Injectable()
export class StatusService {
@@ -92,7 +93,9 @@ export class StatusService {
* Report the engine post's outcome to the pacing breaker, exactly as the chat send path does
* (message.service failSend/persistSentState): the engine was asked, so a refusal counts toward
* the failure streak and an accept resets it. The pre-engine pacing/plugin gate runs OUTSIDE this
- * wrapper, so a policy refusal never feeds the breaker — only a genuine engine refusal does.
+ * wrapper, so a policy refusal never feeds the breaker — and neither do the client-fault checks
+ * the adapters run inside the call (Baileys refuses a status with no recipients, a media URL can
+ * be SSRF-blocked): those say nothing about the account's standing. See countsTowardSendBreaker.
*/
private async recordedPost(sessionId: string, post: () => Promise<StatusResult>): Promise<StatusResult> {
try {
@@ -100,7 +103,9 @@ export class StatusService {
this.pacing.recordSendSuccess(sessionId);
return result;
} catch (error) {
- this.pacing.recordSendFailure(sessionId);
+ if (countsTowardSendBreaker(error)) {
+ this.pacing.recordSendFailure(sessionId);
+ }
throw error;
}
}