Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

feat(groups): pace participant adds against the cold-reachout budget

Yudhi Armyndharisda194c84607d
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 52b9c01b6..b38eafc6c 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -24,6 +24,18 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added
+- **Group participant adds are paced too.** `POST .../groups/:groupId/participants` and
+ `POST .../groups` reached WhatsApp with no gate of any kind — no moderation hook, no pacing, no
+ persisted record — while being the most ban-associated action the product performs: they put the
+ account in front of people who did not ask for it, in bulk, in one call.
+
+ Each participant the account has no history with now costs one cold reachout from the same budget
+ a first message draws on, so a day spent on direct outreach leaves nothing for group invites and
+ vice versa. A repeated id costs one; participants already known cost nothing. The whole request is
+ refused rather than partially applied — these endpoints already report per-participant failures,
+ and a pacing refusal must not be mistaken for one. No message is sent, so neither call consumes the
+ overall daily send allowance.
+
- **Send pacing now bounds cold reachouts separately** (`SEND_PACING_COLD_DAILY_CAP`). A send counts
as a cold reachout when the account has no history with that chat **in either direction**; a reply
to someone who wrote first is never counted and never refused by this rule, and status posts, which
diff --git a/docs/06-api-specification.md b/docs/06-api-specification.md
index 48132143c..065c0d2cb 100644
--- a/docs/06-api-specification.md
+++ b/docs/06-api-specification.md
@@ -1199,6 +1199,14 @@ not. Do not retry a `SEND_PACING_LIMITED` response before `retryAfterSeconds`.
Inside a bulk batch a refusal fails just that item (honouring `stopOnError`), not the batch — the
allowance may free up, and a batch killed outright could not be resumed.
+**Group participant adds draw on the same cold budget.** `POST .../groups/:groupId/participants` and
+`POST .../groups` put the account in front of people who did not ask for it, in bulk, in a single
+call — the most ban-associated action available — so each participant the account has no history
+with costs one cold reachout. A repeated id costs one; participants already known cost nothing. The
+whole request is refused rather than partially applied, so a `429` can never be confused with the
+per-participant failures those endpoints report normally. No message is sent, so neither call
+consumes the overall daily send allowance.
+
Two consequences worth knowing: a paced-out send fires **no** `message:sending` plugin hook (see
`docs/19-plugin-architecture.md`), and refusals are counted in the `openwa_send_pacing_refusals_total`
Prometheus counter, labelled by rule.
diff --git a/src/modules/group/group.module.ts b/src/modules/group/group.module.ts
index f09827e8f..daae25976 100644
--- a/src/modules/group/group.module.ts
+++ b/src/modules/group/group.module.ts
@@ -1,8 +1,10 @@
import { Module } from '@nestjs/common';
+import { MessageModule } from '../message/message.module';
import { GroupController } from './group.controller';
import { GroupService } from './group.service';
@Module({
+ imports: [MessageModule],
controllers: [GroupController],
providers: [GroupService],
exports: [GroupService],
diff --git a/src/modules/group/group.service.spec.ts b/src/modules/group/group.service.spec.ts
index 0b9586f84..2a9a26cc1 100644
--- a/src/modules/group/group.service.spec.ts
+++ b/src/modules/group/group.service.spec.ts
@@ -4,12 +4,17 @@ import { EngineRegistry } from '../../engine/engine-registry.service';
import { IWhatsAppEngine } from '../../engine/interfaces/whatsapp-engine.interface';
import { EngineNotSupportedError } from '../../common/errors/engine-not-supported.error';
import { EngineRefusedError } from '../../common/errors/engine-refused.error';
+import { SendPacingService } from '../message/send-pacing.service';
describe('GroupService', () => {
- const makeService = (engine: Partial<IWhatsAppEngine> | undefined) => {
+ /** Pacing is off by default; its own spec covers the governor, so here it must simply not refuse. */
+ const inertPacing = (): SendPacingService =>
+ ({ assertReachoutAllowed: jest.fn().mockResolvedValue(undefined) }) as unknown as SendPacingService;
+
+ const makeService = (engine: Partial<IWhatsAppEngine> | undefined, pacing: SendPacingService = inertPacing()) => {
const engines = new EngineRegistry();
if (engine) engines.set('s1', engine as IWhatsAppEngine);
- return new GroupService(engines);
+ return new GroupService(engines, pacing);
};
it('throws 400 "Session is not started" when the engine is missing (guard preserved)', () => {
diff --git a/src/modules/group/group.service.ts b/src/modules/group/group.service.ts
index 8b94f3beb..7e520d4a6 100644
--- a/src/modules/group/group.service.ts
+++ b/src/modules/group/group.service.ts
@@ -4,6 +4,7 @@ import { GroupMemberAddMode, IWhatsAppEngine, MediaInput } from '../../engine/in
import { assertBase64WithinMediaCap, stripBase64DataUri } from '../message/media-cap.util';
import { SetGroupPictureDto } from './dto/group.dto';
import { paginate, ListOptions } from '../../common/utils/paginate';
+import { SendPacingService } from '../message/send-pacing.service';
/**
* Owns engine access for group operations. Controllers depend on this service instead of
@@ -12,7 +13,10 @@ import { paginate, ListOptions } from '../../common/utils/paginate';
*/
@Injectable()
export class GroupService {
- constructor(private readonly engines: EngineRegistry) {}
+ constructor(
+ private readonly engines: EngineRegistry,
+ private readonly pacing: SendPacingService,
+ ) {}
private getEngine(sessionId: string): IWhatsAppEngine {
// EngineRegistry.require()'s default is this exact 400 "Session is not started".
@@ -35,11 +39,22 @@ export class GroupService {
return group;
}
- createGroup(sessionId: string, name: string, participants: string[]) {
+ /**
+ * Creating a group invites every listed participant in the same call, so it carries the same
+ * reachout cost as adding them one by one — and is paced accordingly.
+ */
+ async createGroup(sessionId: string, name: string, participants: string[]) {
+ await this.pacing.assertReachoutAllowed(sessionId, participants);
return this.getEngine(sessionId).createGroup(name, participants);
}
- addParticipants(sessionId: string, groupId: string, participants: string[]) {
+ /**
+ * Paced: putting the account in front of people who did not ask for it, in bulk, is the most
+ * ban-associated action this product performs. Each participant the account has no history with
+ * draws on the same cold-reachout budget a first message does.
+ */
+ async addParticipants(sessionId: string, groupId: string, participants: string[]) {
+ await this.pacing.assertReachoutAllowed(sessionId, participants);
return this.getEngine(sessionId).addParticipants(groupId, participants);
}
diff --git a/src/modules/message/send-pacing-cold-query.spec.ts b/src/modules/message/send-pacing-cold-query.spec.ts
index 63038c268..0c6e2c00f 100644
--- a/src/modules/message/send-pacing-cold-query.spec.ts
+++ b/src/modules/message/send-pacing-cold-query.spec.ts
@@ -127,3 +127,94 @@ describe('cold-reachout counting against a real database', () => {
await expect(service.assertSendAllowed('s1', '[email protected]')).resolves.toBeUndefined();
});
});
+
+// Adding people to a group is the highest-risk reachout this product performs: it puts the account
+// in front of strangers in bulk, in one call. It draws on the same cold budget a first message does.
+describe('group reachouts against a real database', () => {
+ let ds: DataSource;
+ let service: SendPacingService;
+
+ const DAY_MS = 86_400_000;
+ const NOW = new Date('2026-08-03T12:00:00.000Z');
+ const TODAY = '2026-08-03T09:00:00.000Z';
+ const YESTERDAY = '2026-08-02T09:00:00.000Z';
+
+ const config = (): ConfigService =>
+ ({
+ get: (key: string) =>
+ key === 'sendPacing'
+ ? { ...computeSendPacingConfig({}), enabled: true, warmupSchedule: [10_000], coldSchedule: [3] }
+ : undefined,
+ }) as unknown as ConfigService;
+
+ const addMessage = (chatId: string, at: string): Promise<unknown> =>
+ ds.query(
+ `INSERT INTO "messages" ("id","sessionId","chatId","from","to","type","direction","createdAt")
+ VALUES (?,?,?,'a','b','text','outgoing',?)`,
+ [`${chatId}-${at}`, 's1', chatId, at],
+ );
+
+ beforeEach(async () => {
+ jest.useFakeTimers().setSystemTime(NOW);
+ ds = new DataSource({
+ type: 'better-sqlite3',
+ database: ':memory:',
+ entities: [Message, Session],
+ synchronize: true,
+ });
+ await ds.initialize();
+ await ds.getRepository(Session).save({ name: 'bot', id: 's1', createdAt: new Date(NOW.getTime() - 30 * DAY_MS) });
+ service = new SendPacingService(ds.getRepository(Message), ds.getRepository(Session), config());
+ });
+
+ afterEach(async () => {
+ jest.useRealTimers();
+ await ds.destroy();
+ });
+
+ it("allows a batch that fits inside the day's remaining allowance", async () => {
+ await expect(service.assertReachoutAllowed('s1', ['[email protected]', '[email protected]', '[email protected]'])).resolves.toBeUndefined();
+ });
+
+ // The cost is per stranger, not per call — otherwise one request adding two hundred numbers would
+ // cost exactly as much as adding one, which is the abuse the rule exists to bound.
+ it('charges the batch per new contact, not per call', async () => {
+ await expect(service.assertReachoutAllowed('s1', ['[email protected]', '[email protected]', '[email protected]', '[email protected]'])).rejects.toMatchObject({
+ status: 429,
+ });
+ });
+
+ it('does not charge for contacts the account already knows', async () => {
+ await addMessage('[email protected]', YESTERDAY);
+ await addMessage('[email protected]', YESTERDAY);
+
+ // Five participants, but only three are strangers — exactly the allowance.
+ await expect(
+ service.assertReachoutAllowed('s1', ['[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]']),
+ ).resolves.toBeUndefined();
+ });
+
+ it('counts a repeated id once', async () => {
+ await expect(
+ service.assertReachoutAllowed('s1', ['[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]']),
+ ).resolves.toBeUndefined();
+ });
+
+ // The two paths share one budget, so a day spent on direct messages leaves nothing for group adds.
+ it("shares the day's budget with cold sends already made", async () => {
+ await addMessage('[email protected]', TODAY);
+ await addMessage('[email protected]', TODAY);
+
+ await expect(service.assertReachoutAllowed('s1', ['[email protected]'])).resolves.toBeUndefined();
+ await addMessage('[email protected]', TODAY);
+ await expect(service.assertReachoutAllowed('s1', ['[email protected]'])).rejects.toMatchObject({ status: 429 });
+ });
+
+ it('is inert for an empty participant list', async () => {
+ await addMessage('[email protected]', TODAY);
+ await addMessage('[email protected]', TODAY);
+ await addMessage('[email protected]', TODAY);
+
+ await expect(service.assertReachoutAllowed('s1', [])).resolves.toBeUndefined();
+ });
+});
diff --git a/src/modules/message/send-pacing.service.spec.ts b/src/modules/message/send-pacing.service.spec.ts
index 87fefa807..ae49adf18 100644
--- a/src/modules/message/send-pacing.service.spec.ts
+++ b/src/modules/message/send-pacing.service.spec.ts
@@ -10,6 +10,7 @@ import { MessageService } from './message.service';
import { BulkMessageService } from './bulk-message.service';
import { StatusService } from '../status/status.service';
import { CatalogService } from '../catalog/catalog.service';
+import { GroupService } from '../group/group.service';
const DAY_MS = 86_400_000;
@@ -349,6 +350,24 @@ describe('send paths consult the governor', () => {
expect(engine.sendCatalog).not.toHaveBeenCalled();
});
+ // Group participant adds reach WhatsApp with no moderation gate of any kind, so the governor is
+ // the only thing standing between a caller and a bulk invite blast.
+ it('GroupService refuses participant adds and group creation before the engine is asked', async () => {
+ const engine = { addParticipants: jest.fn(), createGroup: jest.fn() };
+ const pacing = {
+ assertReachoutAllowed: jest.fn().mockRejectedValue(new HttpException({ code: SEND_PACING_LIMITED }, 429)),
+ };
+ const service = new GroupService({ require: () => engine } as never, pacing as never);
+
+ await expect(service.addParticipants('s1', '[email protected]', ['[email protected]', '[email protected]'])).rejects.toBeInstanceOf(HttpException);
+ await expect(service.createGroup('s1', 'New', ['[email protected]'])).rejects.toBeInstanceOf(HttpException);
+
+ expect(pacing.assertReachoutAllowed).toHaveBeenNthCalledWith(1, 's1', ['[email protected]', '[email protected]']);
+ expect(pacing.assertReachoutAllowed).toHaveBeenNthCalledWith(2, 's1', ['[email protected]']);
+ expect(engine.addParticipants).not.toHaveBeenCalled();
+ expect(engine.createGroup).not.toHaveBeenCalled();
+ });
+
// Bulk keeps its own inlined copy of the moderation gate, so it is the classic place for the two
// to drift apart. A refusal fails just the item, leaving the batch to carry on.
it('BulkMessageService consults the governor per item, before its own gate copy', async () => {
diff --git a/src/modules/message/send-pacing.service.ts b/src/modules/message/send-pacing.service.ts
index 8e0c157f0..4a692da54 100644
--- a/src/modules/message/send-pacing.service.ts
+++ b/src/modules/message/send-pacing.service.ts
@@ -92,6 +92,59 @@ export class SendPacingService {
await this.assertUnderColdCap(sessionId, chatId, config);
}
+ /**
+ * Throw unless this session may reach out to these contacts at once.
+ *
+ * Adding someone to a group is a reachout in every sense that matters: it puts the account in
+ * front of a stranger who did not ask for it, and doing it in bulk is the single most
+ * ban-associated action this product can perform. So it draws on the same cold budget a first
+ * message does — a batch of twenty strangers costs twenty, not one.
+ *
+ * It does NOT consume the overall daily message allowance: no message is sent, and spending a
+ * send budget on something that sends nothing would misreport both.
+ *
+ * The whole batch is refused rather than trimmed. Adding some of the requested participants and
+ * reporting success would leave the caller unable to tell who actually got added, and the engines
+ * report per-participant outcomes for real failures already — a pacing refusal must not be
+ * mistaken for one of those.
+ */
+ async assertReachoutAllowed(sessionId: string, contactIds: string[]): Promise<void> {
+ const config = resolveSendPacingConfig(this.configService);
+ if (!config.enabled) return;
+
+ 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.
+ const unique = [...new Set(contactIds)];
+ const known = await this.messageRepository
+ .createQueryBuilder('m')
+ .select('DISTINCT m.chatId', 'chatId')
+ .where('m.sessionId = :sessionId', { sessionId })
+ .andWhere('m.chatId IN (:...ids)', { ids: unique })
+ .getRawMany<{ chatId: string }>();
+ const coldCount = unique.length - known.length;
+ if (coldCount === 0) return;
+
+ const session = await this.sessionRepository.findOne({ where: { id: sessionId } });
+ if (!session) return;
+
+ const dayStart = startOfUtcDay(new Date());
+ const ageDays = Math.floor((dayStart.getTime() - startOfUtcDay(session.createdAt).getTime()) / DAY_MS);
+ const allowance = this.allowanceForAge(config.coldSchedule, ageDays);
+ const coldToday = await this.countColdReachoutsToday(sessionId, dayStart);
+ if (coldToday + coldCount <= allowance) return;
+
+ this.refuse('cold_daily_cap', sessionId, secondsUntilNextUtcDay(), {
+ reason:
+ `Reaching ${coldCount} new contact(s) would exceed the daily allowance of ${allowance} ` +
+ `new conversation(s) for a session ${ageDays} day(s) old (${coldToday} already used)`,
+ allowance,
+ coldToday,
+ coldCount,
+ });
+ }
+
/**
* Record a send that failed. A run of these trips the breaker.
*