Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
feat(audit): record account restrictions and send-pacing enforcement
Yudhi Armyndharis9e2b674821b1
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 25b4df3d4..fa47ee931 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -9,6 +9,21 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Added+- **Enforcement and account standing are now in the audit log**, not only in the process log. Four new+ `AuditAction` members: `session_restricted` / `session_restriction_lifted` when WhatsApp restricts+ an account or releases it, and `send_pacing_blocked` / `send_breaker_tripped` when pacing refuses a+ send or the failure breaker opens.++ These are the durable record. Both features keep their live state in memory — correctly, since both+ re-establish themselves within one connection — which means without these rows there was no way to+ answer "when was this account restricted, and for how long" after a restart.++ `send_pacing_blocked` is sampled to at most one row per session per minute, carrying the count it+ stood in for, on the same reasoning as the websocket limiter's `rate_limit_exceeded`: a session that+ hits its daily cap goes on being refused for the rest of the day, and a row per refused request+ would make enforcing the limit a flood of its own. A breaker trip is rare and never sampled.+ Repeat reports of an unchanged restriction are not re-audited either.+- **Opt-in send pacing, to keep a young or struggling account from sending its way into a ban:**`SEND_PACING_ENABLED=false` by default, so nothing changes until you turn it on. When enabled, tworules can refuse an outbound send:diff --git a/docs/05-database-design.md b/docs/05-database-design.mdindex b82dc6399..6def3fd33 100644--- a/docs/05-database-design.md+++ b/docs/05-database-design.md@@ -510,8 +510,10 @@ CREATE INDEX "IDX_audit_logs_createdAt" ON audit_logs(created_at);`api_key_updated`, `api_key_used`, `api_key_revoked`, `api_key_deleted`, `api_key_auth_failed`), sessionlifecycle (`session_created`, `session_started`, `session_stopped`, `session_force_killed`,`session_logged_out`, `session_deleted`, `session_qr_generated`, `session_connected`,-`session_disconnected`), messages-(`message_sent`, `message_failed`), webhooks (`webhook_created`, `webhook_deleted`,+`session_disconnected`), WhatsApp-imposed account restrictions (`session_restricted`,+`session_restriction_lifted`), messages+(`message_sent`, `message_failed`), send-pacing enforcement (`send_pacing_blocked`, sampled to at+most one row per session per minute; `send_breaker_tripped`, never sampled), webhooks (`webhook_created`, `webhook_deleted`,`webhook_triggered`, `webhook_failed`), rate-limit enforcement (`rate_limit_exceeded`, sampled to atmost one row per subject+kind per minute), the queue dashboard (`queue_board_mutated`), integrationplugin instances (`integration_instance_created`, `integration_instance_updated`,diff --git a/openapi.json b/openapi.jsonindex 50e15e2be..d00068631 100644--- a/openapi.json+++ b/openapi.json@@ -28,8 +28,12 @@"session_qr_generated","session_connected","session_disconnected",+ "session_restricted",+ "session_restriction_lifted","message_sent","message_failed",+ "send_pacing_blocked",+ "send_breaker_tripped","webhook_created","webhook_deleted","webhook_triggered",diff --git a/src/modules/audit/entities/audit-log.entity.ts b/src/modules/audit/entities/audit-log.entity.tsindex f9c0c36e1..90e98b791 100644--- a/src/modules/audit/entities/audit-log.entity.ts+++ b/src/modules/audit/entities/audit-log.entity.ts@@ -26,10 +26,23 @@ export enum AuditAction {SESSION_QR_GENERATED = 'session_qr_generated',SESSION_CONNECTED = 'session_connected',SESSION_DISCONNECTED = 'session_disconnected',+ // WhatsApp's own judgement of the account, not our connection to it. Unlike the two above these+ // ARE audited: they are rare, they are not reconnect noise, and the in-memory store that serves+ // them to the API does not survive a restart — so the audit log is the only durable record of when+ // an account was restricted and for how long.+ SESSION_RESTRICTED = 'session_restricted',+ SESSION_RESTRICTION_LIFTED = 'session_restriction_lifted',// Message eventsMESSAGE_SENT = 'message_sent',MESSAGE_FAILED = 'message_failed',+ // Send-pacing enforcement. SEND_PACING_BLOCKED is sampled per session (at most one row per+ // session per minute, carrying the suppressed count) on the RATE_LIMIT_EXCEEDED precedent: a+ // session that hits its daily cap keeps being refused for the rest of the day, and one row per+ // refused send would make enforcing the limit an audit flood of its own. A breaker trip is rare+ // and alert-worthy, so it is never sampled.+ SEND_PACING_BLOCKED = 'send_pacing_blocked',+ SEND_BREAKER_TRIPPED = 'send_breaker_tripped',// Webhook eventsWEBHOOK_CREATED = 'webhook_created',diff --git a/src/modules/message/send-pacing.service.spec.ts b/src/modules/message/send-pacing.service.spec.tsindex f5c966d77..d6294f77a 100644--- a/src/modules/message/send-pacing.service.spec.ts+++ b/src/modules/message/send-pacing.service.spec.ts@@ -21,6 +21,7 @@ interface Harness {service: SendPacingService;count: jest.Mock;findOne: jest.Mock;+ audit: { logWarn: jest.Mock; logInfo: jest.Mock };}const build = (@@ -34,14 +35,20 @@ const build = (get: (key: string) =>key === 'sendPacing' ? { ...computeSendPacingConfig({}), enabled: true, ...config } : undefined,} as unknown as ConfigService;+ const audit = { logWarn: jest.fn().mockResolvedValue(null), logInfo: jest.fn().mockResolvedValue(null) };const service = new SendPacingService({ count } as unknown as Repository<Message>,{ findOne } as unknown as Repository<Session>,configService,+ audit as unknown as ConstructorParameters<typeof SendPacingService>[3],);- return { service, count, findOne };+ return { service, count, findOne, audit };};+/** The (action, context) pair of one audit call, typed so assertions do not fall back to `any`. */+const auditCall = (mock: jest.Mock, index = 0): [string, { sessionId?: string; metadata?: Record<string, unknown> }] =>+ mock.mock.calls[index] as [string, { sessionId?: string; metadata?: Record<string, unknown> }];+/** Assert the throw is the pacing 429 and hand back its body for further checks. */const expectPacingRefusal = async (promise: Promise<unknown>): Promise<Record<string, unknown>> => {await expect(promise).rejects.toBeInstanceOf(HttpException);@@ -365,3 +372,74 @@ describe('send paths consult the governor', () => {expect(engine.sendTextMessage).not.toHaveBeenCalled();});});++// The store that serves pacing state to the API is in memory, so the audit log is the durable+// record of enforcement. It has to stay accurate without becoming a flood of its own: a session that+// hits its daily cap goes on being refused for the rest of the day.+describe('SendPacingService audit trail', () => {+ beforeEach(() => resetSendPacingRefusals());++ it('records a breaker trip without sampling — it is rare and alert-worthy', () => {+ const { service, audit } = build({ breakerThreshold: 2 });++ service.recordSendFailure('s1');+ service.recordSendFailure('s1');++ const [action, context] = auditCall(audit.logWarn);+ expect(action).toBe('send_breaker_tripped');+ expect(context.sessionId).toBe('s1');+ expect(context.metadata).toMatchObject({ consecutiveFailures: 2 });+ });++ it('records a trip once per episode, not once per subsequent failure', () => {+ const { service, audit } = build({ breakerThreshold: 1 });++ service.recordSendFailure('s1');+ service.recordSendFailure('s1');+ service.recordSendFailure('s1');++ expect(audit.logWarn).toHaveBeenCalledTimes(1);+ });++ it('records a refusal with the rule that caused it', async () => {+ const { service, audit } = build({ warmupSchedule: [1] }, 5);++ await expectPacingRefusal(service.assertSendAllowed('s1'));++ const [action, context] = auditCall(audit.logWarn);+ expect(action).toBe('send_pacing_blocked');+ expect(context.sessionId).toBe('s1');+ expect(context.metadata).toMatchObject({ rule: 'daily_cap', suppressed: 0 });+ });++ // The sampling is the load-bearing part: without it, one capped session generates an audit row per+ // rejected request for the rest of the UTC day.+ it('samples repeat refusals to one row per window, carrying the suppressed count', async () => {+ const { service, audit } = build({ warmupSchedule: [1] }, 5);++ for (let i = 0; i < 5; i++) await expectPacingRefusal(service.assertSendAllowed('s1'));++ expect(audit.logWarn).toHaveBeenCalledTimes(1);++ // Past the window the next refusal is written, and it reports the four it stood in for.+ jest.useFakeTimers();+ try {+ jest.setSystemTime(Date.now() + 61_000);+ await expectPacingRefusal(service.assertSendAllowed('s1'));+ } finally {+ jest.useRealTimers();+ }++ expect(audit.logWarn).toHaveBeenCalledTimes(2);+ expect(auditCall(audit.logWarn, 1)[1].metadata).toMatchObject({ suppressed: 4 });+ });++ // Sampling is per session: one noisy account must not hide another's enforcement from the trail.+ it('samples per session', async () => {+ const a = build({ warmupSchedule: [1] }, 5);+ await expectPacingRefusal(a.service.assertSendAllowed('s1'));+ await expectPacingRefusal(a.service.assertSendAllowed('s2'));++ expect(a.audit.logWarn).toHaveBeenCalledTimes(2);+ });+});diff --git a/src/modules/message/send-pacing.service.ts b/src/modules/message/send-pacing.service.tsindex 500678197..b3adfb2dc 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 { AuditService } from '../audit/audit.service';+import { AuditAction } from '../audit/entities/audit-log.entity';/** Body code on a pacing refusal. The throttler's own 429 carries no `code`, which is what tells the two apart. */export const SEND_PACING_LIMITED = 'SEND_PACING_LIMITED';@@ -18,6 +20,22 @@ interface BreakerState {openedAt: number | null;}+/** Refusals suppressed since the last audited one, per session. */+interface RefusalSample {+ count: number;+ since: number;+}++/**+ * At most one `SEND_PACING_BLOCKED` row per session per window. A session that hits its daily cap+ * goes on being refused for the rest of the day, so one row per refused send would turn enforcing+ * the limit into an audit flood of its own — the same problem, and the same answer, as the+ * websocket rate limiter's `RATE_LIMIT_EXCEEDED` sampling.+ */+const REFUSAL_AUDIT_WINDOW_MS = 60_000;+/** Bound on the sampling map, so a churn of session ids cannot grow it without limit. */+const MAX_REFUSAL_KEYS = 1000;+/*** Refuses outbound sends that a young or misbehaving session should not be making.*@@ -44,6 +62,7 @@ interface BreakerState {export class SendPacingService {private readonly logger = createLogger('SendPacingService');private readonly breakers = new Map<string, BreakerState>();+ private readonly refusalSamples = new Map<string, RefusalSample>();constructor(@InjectRepository(Message, 'data')@@ -52,6 +71,10 @@ export class SendPacingService {private readonly sessionRepository: Repository<Session>,@Optional()private readonly configService?: ConfigService,+ // @Optional so the standalone constructions in specs keep working. AuditModule is @Global, so in+ // a running gateway it is always present; absent means the console log is the only record.+ @Optional()+ private readonly auditService?: AuditService,) {}/**@@ -89,6 +112,12 @@ export class SendPacingService {cooldownMs: config.breakerCooldownMs,action: 'send_breaker_tripped',});+ // Never sampled: a trip is rare and is the event an operator most wants to find afterwards.+ void this.auditService?.logWarn(AuditAction.SEND_BREAKER_TRIPPED, {+ sessionId,+ metadata: { consecutiveFailures: breaker.consecutiveFailures, cooldownMs: config.breakerCooldownMs },+ errorMessage: `Send breaker tripped after ${breaker.consecutiveFailures} consecutive send failures`,+ });}}@@ -158,6 +187,40 @@ export class SendPacingService {});}+ /**+ * Write one audit row per session per window, folding the refusals suppressed in between into the+ * next row's `suppressed` metadata — so the trail stays accurate without one write per refused+ * send. Modelled on the websocket limiter's own sampling, which exists for the same reason.+ */+ private auditRefusal(+ sessionId: string,+ rule: SendPacingRefusalReason,+ retryAfterSeconds: number,+ message: string,+ ): void {+ const now = Date.now();+ const prior = this.refusalSamples.get(sessionId);+ if (prior && now - prior.since < REFUSAL_AUDIT_WINDOW_MS) {+ prior.count += 1;+ return;+ }+ const suppressed = prior?.count ?? 0;+ // Re-insert rather than mutate, so the map stays in insertion order and the eviction below+ // really does drop the least recently audited session.+ this.refusalSamples.delete(sessionId);+ this.refusalSamples.set(sessionId, { count: 0, since: now });+ while (this.refusalSamples.size > MAX_REFUSAL_KEYS) {+ const oldest = this.refusalSamples.keys().next().value;+ if (oldest === undefined) break;+ this.refusalSamples.delete(oldest);+ }+ void this.auditService?.logWarn(AuditAction.SEND_PACING_BLOCKED, {+ sessionId,+ metadata: { rule, retryAfterSeconds, suppressed },+ errorMessage: message,+ });+ }+private refuse(reason: SendPacingRefusalReason,sessionId: string,@@ -172,6 +235,7 @@ export class SendPacingService {retryAfterSeconds,action: 'send_paced',});+ this.auditRefusal(sessionId, reason, retryAfterSeconds, detail.reason);// 429 with a body `code`, which is what distinguishes this from the global throttler's own 429 —// a client that retries blindly on 429 would otherwise treat a day-long cap like a one-second// rate limit. `retryAfterSeconds` says how long the refusal actually lasts.diff --git a/src/modules/session/session-engine-event-wiring.ts b/src/modules/session/session-engine-event-wiring.tsindex 2dcf7bdd6..a476d5bc8 100644--- a/src/modules/session/session-engine-event-wiring.ts+++ b/src/modules/session/session-engine-event-wiring.ts@@ -2,6 +2,8 @@ import { SessionStatus } from './entities/session.entity';import { MessageProjector } from './message-projector.service';import { SessionErrorStore } from './session-error-store.service';import { SessionRestrictionStore } from './session-restriction-store.service';+import { AuditService } from '../audit/audit.service';+import { AuditAction } from '../audit/entities/audit-log.entity';import { EventsGateway } from '../events/events.gateway';import { WebhookService } from '../webhook/webhook.service';import { HookManager } from '../../core/hooks';@@ -46,6 +48,8 @@ export interface SessionEngineWiringHost {messages: MessageProjector;sessionErrors: SessionErrorStore;sessionRestrictions: SessionRestrictionStore;+ /** @Global AuditService; absent only in the standalone constructions specs build. */+ auditService?: AuditService;webhookService: WebhookService;eventsGateway: EventsGateway;hookManager: HookManager;@@ -242,6 +246,18 @@ export class SessionEngineEventWiring {code: restriction.code,expiresAt: restriction.expiresAt ? new Date(restriction.expiresAt).toISOString() : null,});+ // Audited, unlike the engine-level connect/disconnect transitions next door: this is rare,+ // it is not reconnect noise, and the store that serves it to the API is in memory — so this+ // row is the only durable record of when the account was restricted.+ void host.auditService?.logWarn(AuditAction.SESSION_RESTRICTED, {+ sessionId: id,+ metadata: {+ kind: restriction.kind,+ code: restriction.code,+ expiresAt: restriction.expiresAt ? new Date(restriction.expiresAt).toISOString() : null,+ },+ errorMessage: `WhatsApp restricted this account: ${restriction.kind} (${restriction.code})`,+ });},onError: (reason: string): void => {if (!host.isLiveEngine(id, engine)) return;diff --git a/src/modules/session/session-engine-lifecycle.service.ts b/src/modules/session/session-engine-lifecycle.service.tsindex cb5d6bf73..aaf0ebd95 100644--- a/src/modules/session/session-engine-lifecycle.service.ts+++ b/src/modules/session/session-engine-lifecycle.service.ts@@ -10,6 +10,8 @@ import { SessionLivenessWatchdog } from './session-liveness-watchdog.service';import { MessageProjector } from './message-projector.service';import { SessionErrorStore } from './session-error-store.service';import { SessionRestrictionStore } from './session-restriction-store.service';+import { AuditService } from '../audit/audit.service';+import { AuditAction } from '../audit/entities/audit-log.entity';import { resolveEngineInitTimeoutMs } from '../../engine/engine-init-timeout';import { StatusStoreService } from '../status-store/status-store.service';import { IWhatsAppEngine, AccountRestriction } from '../../engine/interfaces/whatsapp-engine.interface';@@ -222,6 +224,10 @@ export class SessionEngineLifecycle {// service degrades to today's behaviour if it is ever constructed without the (global) LoggerModule.@Optional()private readonly shutdownService?: ShutdownService,+ // @Optional so the existing spec constructions keep working. AuditModule is @Global, so a+ // running gateway always has it.+ @Optional()+ private readonly auditService?: AuditService,) {// The fence Maps are handed over BY REFERENCE: they stay lifecycle fields (specs poke them// through the lifecycle), while the fence logic operates on the same instances.@@ -278,6 +284,7 @@ export class SessionEngineLifecycle {messages: this.messages,sessionErrors: this.sessionErrors,sessionRestrictions: this.sessionRestrictions,+ auditService: this.auditService,webhookService: this.webhookService,eventsGateway: this.eventsGateway,hookManager: this.hookManager,@@ -638,6 +645,10 @@ export class SessionEngineLifecycle {code: lifted.code,expiresAt: null,});+ void this.auditService?.logInfo(AuditAction.SESSION_RESTRICTION_LIFTED, {+ sessionId: id,+ metadata: { kind: lifted.kind, code: lifted.code },+ });}/**diff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.tsindex 0b3146077..4822f1b14 100644--- a/src/modules/session/session.service.spec.ts+++ b/src/modules/session/session.service.spec.ts@@ -49,6 +49,11 @@ import {getSessionReconnectAttemptsTotal,getSessionReconnectLoopAlertsTotal,} from '../../common/metrics/session-reconnect-metrics';+import { AuditService } from '../audit/audit.service';++/** The (action, context) pair of one audit call, typed so assertions do not fall back to `any`. */+const auditCall = (mock: jest.Mock, index = 0): [string, { sessionId?: string; metadata?: Record<string, unknown> }] =>+ mock.mock.calls[index] as [string, { sessionId?: string; metadata?: Record<string, unknown> }];function createMockSession(overrides: Partial<Session> = {}): Session {return {@@ -83,6 +88,7 @@ describe('SessionService', () => {let configService: jest.Mocked<Partial<ConfigService>>;let lidMappingStore: jest.Mocked<Partial<LidMappingStoreService>>;let statusStore: jest.Mocked<Partial<StatusStoreService>>;+ let auditService: { logWarn: jest.Mock; logInfo: jest.Mock };let mockEngine: Record<string, jest.Mock>;beforeEach(async () => {@@ -173,6 +179,8 @@ describe('SessionService', () => {dispatch: jest.fn().mockResolvedValue(undefined),};+ auditService = { logWarn: jest.fn().mockResolvedValue(null), logInfo: jest.fn().mockResolvedValue(null) };+hookManager = {execute: jest.fn().mockResolvedValue({ continue: true, data: {} }),};@@ -198,6 +206,7 @@ describe('SessionService', () => {SessionEngineLifecycle,SessionErrorStore,SessionRestrictionStore,+ { provide: AuditService, useValue: auditService },{provide: getRepositoryToken(Session, 'data'),useValue: repository,@@ -2040,6 +2049,37 @@ describe('SessionService', () => {return calls[0][0];};+ // The store that serves this to the API is in memory, so the audit row is the only durable+ // record of when the account was restricted — which is exactly the question asked afterwards.+ it('writes a durable audit record when a restriction is detected, and when it ends', async () => {+ const callbacks = await startAndCapture();++ callbacks.onAccountRestriction?.(timelock);+ const [restrictedAction, restrictedContext] = auditCall(auditService.logWarn);+ expect(restrictedAction).toBe('session_restricted');+ expect(restrictedContext.sessionId).toBe('sess-uuid-1');+ expect(restrictedContext.metadata).toMatchObject({ kind: 'reachout_timelock', code: 'BIZ_QUALITY' });++ callbacks.onAccountRestriction?.(null);+ const [liftedAction, liftedContext] = auditCall(auditService.logInfo);+ expect(liftedAction).toBe('session_restriction_lifted');+ expect(liftedContext.sessionId).toBe('sess-uuid-1');+ expect(liftedContext.metadata).toMatchObject({ kind: 'reachout_timelock' });+ });++ // Repeat reports are the normal case on both engines, and an audit row per reconnect attempt+ // would bury the one that matters.+ it('does not re-audit an unchanged restriction', async () => {+ const callbacks = await startAndCapture();+ callbacks.onAccountRestriction?.(timelock);+ auditService.logWarn.mockClear();++ callbacks.onAccountRestriction?.(timelock);+ callbacks.onAccountRestriction?.(timelock);++ expect(auditService.logWarn).not.toHaveBeenCalled();+ });+it('announces a newly-detected restriction to webhook subscribers', async () => {const callbacks = await startAndCapture();(webhookService.dispatch as jest.Mock).mockClear();