Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix: a batch of small correctness gaps across pacing, restrictions, calls, labels and contacts

Yudhi Armyndharis1160a3375d50
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 95100d241..36322f11f 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -35,6 +35,7 @@ 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 }`.
+- **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.
- **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/openapi.json b/openapi.json
index 31964a878..2f0407cd6 100644
--- a/openapi.json
+++ b/openapi.json
@@ -5050,7 +5050,7 @@
"400": {
"description": "Session not started, or validation failed"
},
- "422": {
+ "403": {
"description": "The engine refused — channel creation may be disabled for this account"
}
},
@@ -5203,7 +5203,7 @@
"400": {
"description": "Session not started"
},
- "422": {
+ "403": {
"description": "The engine refused — not found, or this account does not own it"
}
},
@@ -5254,7 +5254,7 @@
"400": {
"description": "Session not started, or validation failed"
},
- "422": {
+ "403": {
"description": "The engine refused"
}
},
diff --git a/src/engine/adapters/baileys-events.ts b/src/engine/adapters/baileys-events.ts
index 8f6f85a94..aee4ad4bf 100644
--- a/src/engine/adapters/baileys-events.ts
+++ b/src/engine/adapters/baileys-events.ts
@@ -487,6 +487,14 @@ export class BaileysEvents {
* `rejectCall` arriving afterwards should report not-found instead of acting on a dead call.
*/
private reportCallOutcome(call: WACallEvent): void {
+ // `terminate` publishes no outcome (see above) but DOES end the call — drop the handle so a
+ // rejectCall arriving afterwards reports not-found instead of acting on a dead call. The other
+ // unmapped statuses (ringing/preaccept/transport/relaylatency) are chatter on a call that is
+ // still live and must stay rejectable.
+ if (call.status === 'terminate') {
+ this.liveCalls.delete(call.id);
+ return;
+ }
const outcome = CALL_OUTCOMES[call.status];
if (!outcome) return;
diff --git a/src/engine/adapters/baileys.adapter.spec.ts b/src/engine/adapters/baileys.adapter.spec.ts
index b51219dc7..8b103e1ac 100644
--- a/src/engine/adapters/baileys.adapter.spec.ts
+++ b/src/engine/adapters/baileys.adapter.spec.ts
@@ -4772,6 +4772,22 @@ describe('BaileysAdapter call outcomes', () => {
},
);
+ // `terminate` publishes no outcome, but it DOES end the call: the live handle must go with it,
+ // or a later outcome/reject acts on a call that is already over until the TTL happens to expire.
+ it('terminate drops the live call, so a later outcome for the same id is ignored', async () => {
+ const onCallOutcome = jest.fn();
+ await ringing({ onCall: jest.fn(), onCallOutcome });
+
+ fakeSock.fire('call', [
+ { id: CALL_ID, from: CALLER, chatId: CALLER, status: 'terminate', offline: false, date: new Date() },
+ ]);
+ fakeSock.fire('call', [
+ { id: CALL_ID, from: CALLER, chatId: CALLER, status: 'reject', offline: false, date: new Date() },
+ ]);
+
+ expect(onCallOutcome).not.toHaveBeenCalled();
+ });
+
// WhatsApp replays signalling for calls that ended while the session was disconnected. Announcing
// those would report last week's declined call as if it had just happened.
it('drops an offline-replayed outcome', async () => {
diff --git a/src/modules/channel/channel.controller.ts b/src/modules/channel/channel.controller.ts
index e15feb388..3a6269912 100644
--- a/src/modules/channel/channel.controller.ts
+++ b/src/modules/channel/channel.controller.ts
@@ -75,7 +75,7 @@ export class ChannelController {
@ApiBody({ type: CreateChannelDto })
@ApiResponse({ status: 201, description: 'The created channel' })
@ApiResponse({ status: 400, description: 'Session not started, or validation failed' })
- @ApiResponse({ status: 422, description: 'The engine refused — channel creation may be disabled for this account' })
+ @ApiResponse({ status: 403, description: 'The engine refused — channel creation may be disabled for this account' })
async create(@Param('sessionId') sessionId: string, @Body() dto: CreateChannelDto) {
return this.channelService.createChannel(sessionId, dto.name, dto.description);
}
@@ -94,7 +94,7 @@ export class ChannelController {
@ApiParam({ name: 'channelId', description: 'Channel ID' })
@ApiResponse({ status: 200, description: 'Channel deleted' })
@ApiResponse({ status: 400, description: 'Session not started' })
- @ApiResponse({ status: 422, description: 'The engine refused — not found, or this account does not own it' })
+ @ApiResponse({ status: 403, description: 'The engine refused — not found, or this account does not own it' })
async remove(
@Param('sessionId') sessionId: string,
@Param('channelId') channelId: string,
@@ -115,7 +115,7 @@ export class ChannelController {
@ApiBody({ type: MuteChannelDto })
@ApiResponse({ status: 200, description: 'Channel muted or unmuted' })
@ApiResponse({ status: 400, description: 'Session not started, or validation failed' })
- @ApiResponse({ status: 422, description: 'The engine refused' })
+ @ApiResponse({ status: 403, description: 'The engine refused' })
async mute(
@Param('sessionId') sessionId: string,
@Param('channelId') channelId: string,
diff --git a/src/modules/contact/contact.service.spec.ts b/src/modules/contact/contact.service.spec.ts
index fdb41c706..aecc6affd 100644
--- a/src/modules/contact/contact.service.spec.ts
+++ b/src/modules/contact/contact.service.spec.ts
@@ -119,5 +119,17 @@ describe('ContactService', () => {
await makeService({ upsertContact }).upsertContact('s1', '[email protected]', 'Ada', 'Lovelace');
expect(upsertContact).toHaveBeenCalledWith('[email protected]', 'Ada', 'Lovelace');
});
+
+ // Same hazard as the lid, different ids: a group/newsletter/broadcast id also carries digits
+ // that would be stored as a phone number for a contact that does not exist.
+ it.each(['[email protected]', '120363000000000000@newsletter', 'status@broadcast'])(
+ 'refuses the non-person id %s with a 400',
+ id => {
+ const upsertContact = jest.fn();
+ const svc = makeService({ upsertContact });
+ expect(() => svc.upsertContact('s1', id, 'Ada')).toThrow(BadRequestException);
+ expect(upsertContact).not.toHaveBeenCalled();
+ },
+ );
});
});
diff --git a/src/modules/contact/contact.service.ts b/src/modules/contact/contact.service.ts
index 0c6b71634..e1d92979e 100644
--- a/src/modules/contact/contact.service.ts
+++ b/src/modules/contact/contact.service.ts
@@ -113,11 +113,19 @@ export class ContactService {
* phone-based id.
*/
private assertAddressable(contactId: string): void {
- if (parseWaId(contactId).kind === 'lid') {
+ const kind = parseWaId(contactId).kind;
+ // 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 === '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`,
);
}
+ throw new BadRequestException(
+ `Contact ${contactId} does not name a person; the addressbook is keyed by phone number, so pass a phone-based contact id instead`,
+ );
}
upsertContact(sessionId: string, contactId: string, firstName: string, lastName?: string) {
diff --git a/src/modules/label/label.service.spec.ts b/src/modules/label/label.service.spec.ts
index 27643b86f..03abd6ecd 100644
--- a/src/modules/label/label.service.spec.ts
+++ b/src/modules/label/label.service.spec.ts
@@ -35,6 +35,12 @@ describe('LabelService label editing', () => {
return new LabelService(engines);
};
+ it('refuses an empty body — nothing to write, and an unused id would create a nameless label', async () => {
+ const upsertLabel = jest.fn();
+ expect(() => makeService({ upsertLabel }).upsertLabel('s1', 'l1', {})).toThrow(BadRequestException);
+ expect(upsertLabel).not.toHaveBeenCalled();
+ });
+
it('sends the path id as the label id', async () => {
const upsertLabel = jest.fn().mockResolvedValue(undefined);
await makeService({ upsertLabel }).upsertLabel('s1', 'l1', { name: 'VIP' });
diff --git a/src/modules/label/label.service.ts b/src/modules/label/label.service.ts
index 404c1f2c1..de56cd801 100644
--- a/src/modules/label/label.service.ts
+++ b/src/modules/label/label.service.ts
@@ -1,4 +1,4 @@
-import { Injectable, NotFoundException } from '@nestjs/common';
+import { BadRequestException, Injectable, NotFoundException } from '@nestjs/common';
import { EngineRegistry } from '../../engine/engine-registry.service';
import { IWhatsAppEngine } from '../../engine/interfaces/whatsapp-engine.interface';
@@ -37,6 +37,12 @@ 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) {
+ throw new BadRequestException('At least one of name or color must be provided');
+ }
return this.getEngine(sessionId).upsertLabel({ id: labelId, ...body });
}
diff --git a/src/modules/message/send-pacing-cold-query.spec.ts b/src/modules/message/send-pacing-cold-query.spec.ts
index 7b787f8d6..df3a38b79 100644
--- a/src/modules/message/send-pacing-cold-query.spec.ts
+++ b/src/modules/message/send-pacing-cold-query.spec.ts
@@ -137,6 +137,18 @@ describe('cold-reachout counting against a real database', () => {
await expect(service.assertSendAllowed('s1', '[email protected]')).rejects.toMatchObject({ status: 429 });
});
+ // Stored rows carry either user-id dialect (inbound neutralized to @c.us, outbound the caller's
+ // raw form) — byte-exact probing misread a known contact addressed the other way as cold.
+ it('matches history across user-id dialects, so a known contact is never misread as cold', async () => {
+ await addMessage('[email protected]', YESTERDAY);
+ await addMessage('[email protected]', TODAY);
+ await addMessage('[email protected]', TODAY);
+ await addMessage('[email protected]', TODAY);
+
+ // The budget of three is spent, but the @c.us spelling of a known contact stays warm.
+ await expect(service.assertSendAllowed('s1', '[email protected]')).resolves.toBeUndefined();
+ });
+
it("forgets yesterday's reachouts when the UTC day rolls over", async () => {
await addMessage('[email protected]', YESTERDAY);
await addMessage('[email protected]', YESTERDAY);
@@ -213,6 +225,15 @@ describe('group reachouts against a real database', () => {
).resolves.toBeUndefined();
});
+ it('does not charge for a contact known under the other user-id dialect', async () => {
+ await addMessage('[email protected]', YESTERDAY);
+
+ // Four participants, but the dialect twin is known — three strangers, exactly the allowance.
+ await expect(
+ service.assertReachoutAllowed('s1', ['[email protected]', '[email protected]', '[email protected]', '[email protected]']),
+ ).resolves.toBeUndefined();
+ });
+
it('counts a repeated id once', async () => {
await expect(
diff --git a/src/modules/message/send-pacing.service.spec.ts b/src/modules/message/send-pacing.service.spec.ts
index ae49adf18..b1e740d97 100644
--- a/src/modules/message/send-pacing.service.spec.ts
+++ b/src/modules/message/send-pacing.service.spec.ts
@@ -495,7 +495,13 @@ describe('SendPacingService cold-reachout cap', () => {
await expect(service.assertSendAllowed('s1', '[email protected]')).resolves.toBeUndefined();
- expect(exists).toHaveBeenCalledWith({ where: { sessionId: 's1', chatId: '[email protected]' } });
+ // Probed under both user-id dialects: stored rows may carry either spelling.
+ expect(exists).toHaveBeenCalledWith({
+ where: [
+ { sessionId: 's1', chatId: '[email protected]' },
+ { sessionId: 's1', chatId: '[email protected]' },
+ ],
+ });
});
it("allows a cold reachout while the day's allowance remains", async () => {
diff --git a/src/modules/message/send-pacing.service.ts b/src/modules/message/send-pacing.service.ts
index 450a7f7a0..e8ef1fb51 100644
--- a/src/modules/message/send-pacing.service.ts
+++ b/src/modules/message/send-pacing.service.ts
@@ -135,15 +135,19 @@ export class SendPacingService {
this.assertBreakerClosed(sessionId, config);
if (config.coldSchedule.length === 0 || contactIds.length === 0) return;
- // The same id twice in one request is one contact, and must cost one.
+ // The same id twice in one request is one contact, and must cost one. Each contact is probed
+ // under both user-id dialects (see dialectVariants) — a contact known under the other spelling
+ // is not a stranger.
const unique = [...new Set(contactIds)];
- const known = await this.messageRepository
+ const variantsByContact = new Map(unique.map(id => [id, dialectVariants(id)]));
+ const knownRows = await this.messageRepository
.createQueryBuilder('m')
.select('DISTINCT m.chatId', 'chatId')
.where('m.sessionId = :sessionId', { sessionId })
- .andWhere('m.chatId IN (:...ids)', { ids: unique })
+ .andWhere('m.chatId IN (:...ids)', { ids: [...new Set([...variantsByContact.values()].flat())] })
.getRawMany<{ chatId: string }>();
- const coldCount = unique.length - known.length;
+ const knownIds = new Set(knownRows.map(row => row.chatId));
+ const coldCount = unique.filter(id => !variantsByContact.get(id)!.some(v => knownIds.has(v))).length;
if (coldCount === 0) return;
const session = await this.sessionRepository.findOne({ where: { id: sessionId } });
@@ -336,9 +340,12 @@ export class SendPacingService {
if (!chatId || config.coldSchedule.length === 0) return;
// Any row at all, either direction, any time: one message from them, or one from us last month,
- // and this is an existing relationship rather than a reachout. The send being checked has not
- // persisted its own row yet — the gate runs before saveOutgoingMessage — so this cannot see it.
- const hasHistory = await this.messageRepository.exists({ where: { sessionId, chatId } });
+ // and this is an existing relationship rather than a reachout. Probed under both user-id
+ // dialects (see dialectVariants). The send being checked has not persisted its own row yet —
+ // the gate runs before saveOutgoingMessage — so this cannot see it.
+ const hasHistory = await this.messageRepository.exists({
+ where: dialectVariants(chatId).map(id => ({ sessionId, chatId: id })),
+ });
if (hasHistory) return;
const session = await this.sessionRepository.findOne({ where: { id: sessionId } });
@@ -425,6 +432,23 @@ export class SendPacingService {
const DAY_MS = 86_400_000;
+/**
+ * Both spellings of a user id. Stored rows carry either dialect — inbound rows are neutralized to
+ * `@c.us`, outbound rows keep the caller's raw form — so a byte-exact history probe misreads a
+ * 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.
+ */
+function dialectVariants(chatId: string): string[] {
+ const lower = chatId.toLowerCase();
+ if (lower.endsWith('@c.us')) {
+ return [chatId, chatId.slice(0, chatId.length - '@c.us'.length) + '@s.whatsapp.net'];
+ }
+ if (lower.endsWith('@s.whatsapp.net')) {
+ return [chatId, chatId.slice(0, chatId.length - '@s.whatsapp.net'.length) + '@c.us'];
+ }
+ return [chatId];
+}
+
/**
* The cap's day boundary is UTC, not the server's local midnight: a deployment that moves timezone,
* or replicas in different ones, must not disagree about when the allowance resets.
diff --git a/src/modules/session/session-restriction-store.service.spec.ts b/src/modules/session/session-restriction-store.service.spec.ts
index 2a165ad07..dadbc166b 100644
--- a/src/modules/session/session-restriction-store.service.spec.ts
+++ b/src/modules/session/session-restriction-store.service.spec.ts
@@ -54,10 +54,32 @@ describe('SessionRestrictionStore', () => {
// Announcing a re-report would be noise, but serving a stale expiry from the API would be wrong,
// so the stored entry refreshes even when the caller is told nothing changed.
it('refreshes the stored expiry without announcing it', () => {
- store.set('s1', timelock({ expiresAt: 1000 }));
+ // Future timestamps: an already-passed expiry reads as no restriction at all.
+ const first = Date.now() + 60_000;
+ const refreshed = Date.now() + 120_000;
+ store.set('s1', timelock({ expiresAt: first }));
- expect(store.set('s1', timelock({ expiresAt: 9999 }))).toBe(false);
- expect(store.get('s1')?.expiresAt).toBe(9999);
+ expect(store.set('s1', timelock({ expiresAt: refreshed }))).toBe(false);
+ expect(store.get('s1')?.expiresAt).toBe(refreshed);
+ });
+ });
+
+ describe('expiry', () => {
+ it('stops reporting a restriction whose stated end has passed, without a lift signal', () => {
+ store.set('s1', timelock({ expiresAt: Date.now() - 1000 }));
+
+ 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);
+ });
+
+ it('keeps reporting one that has not expired, or that states no end', () => {
+ store.set('s1', timelock({ expiresAt: Date.now() + 60_000 }));
+ store.set('s2', timelock());
+
+ expect(store.get('s1')?.kind).toBe('reachout_timelock');
+ expect(store.attachTo(sessionRow('s2')).restriction?.kind).toBe('reachout_timelock');
});
});
@@ -132,9 +154,10 @@ describe('SessionRestrictionStore', () => {
describe('the read projection', () => {
it('attaches the restriction in force', () => {
- store.set('s1', timelock({ expiresAt: 1234 }));
+ const expiresAt = Date.now() + 60_000;
+ store.set('s1', timelock({ expiresAt }));
- expect(store.attachTo(sessionRow('s1')).restriction).toEqual(timelock({ expiresAt: 1234 }));
+ expect(store.attachTo(sessionRow('s1')).restriction).toEqual(timelock({ expiresAt }));
});
it('attaches null when there is none, so the field is always present', () => {
diff --git a/src/modules/session/session-restriction-store.service.ts b/src/modules/session/session-restriction-store.service.ts
index 90412b877..287b21a58 100644
--- a/src/modules/session/session-restriction-store.service.ts
+++ b/src/modules/session/session-restriction-store.service.ts
@@ -40,7 +40,20 @@ export class SessionRestrictionStore {
/** The restriction in force, if any. `attachTo` is the projection; this is the raw read. */
get(sessionId: string): AccountRestriction | undefined {
- return this.restrictions.get(sessionId);
+ return this.inForce(sessionId);
+ }
+
+ /**
+ * The stored restriction, unless its stated end has passed — an expired timelock must not keep
+ * badging the session until the next reconnect happens to clear it. Read-side only: the entry
+ * stays stored (set/clear own the lift signal, and the engine re-report self-heals the map), it
+ * just stops being reported.
+ */
+ private inForce(sessionId: string): AccountRestriction | undefined {
+ const restriction = this.restrictions.get(sessionId);
+ if (!restriction) return undefined;
+ if (restriction.expiresAt != null && restriction.expiresAt <= Date.now()) return undefined;
+ return restriction;
}
/**
@@ -79,7 +92,7 @@ export class SessionRestrictionStore {
* is cleared by its own path rather than by whatever status the session happens to carry.
*/
attachTo(session: Session): Session {
- session.restriction = this.restrictions.get(session.id) ?? null;
+ session.restriction = this.inForce(session.id) ?? null;
return session;
}
}