Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(automation): answer 404 for a rule created on an unknown session
Yudhi Armyndharis532b51da8fa7
diff --git a/docs/06-api-specification.md b/docs/06-api-specification.mdindex 85da961fc..06e0f43b2 100644--- a/docs/06-api-specification.md+++ b/docs/06-api-specification.md@@ -6539,7 +6539,7 @@ Create a rule. **Auth:** API key (OPERATOR)}```-`400` — invalid conditions (unknown field/operator, over-limit values) or over-limit text.+`400` — invalid conditions (unknown field/operator, over-limit values) or over-limit text. `404` when no session has this id.#### GET /api/sessions/:sessionId/automation-rulesdiff --git a/openapi.json b/openapi.jsonindex 6243f7a57..f0a498d3a 100644--- a/openapi.json+++ b/openapi.json@@ -2090,6 +2090,9 @@},"400": {"description": "Invalid rule (bad conditions, over-limit text)."+ },+ "404": {+ "description": "No session with this id."}},"summary": "Create an autoreply rule",diff --git a/src/modules/automation/automation-rule.controller.ts b/src/modules/automation/automation-rule.controller.tsindex 70503aed5..1b68b5930 100644--- a/src/modules/automation/automation-rule.controller.ts+++ b/src/modules/automation/automation-rule.controller.ts@@ -16,6 +16,7 @@ export class AutomationRuleController {@ApiParam({ name: 'sessionId', description: 'Session ID' })@ApiResponse({ status: 201, description: 'Rule created.', type: AutomationRuleResponseDto })@ApiResponse({ status: 400, description: 'Invalid rule (bad conditions, over-limit text).' })+ @ApiResponse({ status: 404, description: 'No session with this id.' })async create(@Param('sessionId') sessionId: string,@Body() dto: CreateAutomationRuleDto,diff --git a/src/modules/automation/automation-rules.service.spec.ts b/src/modules/automation/automation-rules.service.spec.tsindex 2d036252d..30fc3b888 100644--- a/src/modules/automation/automation-rules.service.spec.ts+++ b/src/modules/automation/automation-rules.service.spec.ts@@ -42,7 +42,12 @@ describe('AutomationRulesService', () => {sends.push({ sessionId, chatId: dto.chatId, text: dto.text });return Promise.resolve({});};- service = new AutomationRulesService(ds.getRepository(AutomationRule), moduleRefStub, undefined);+ service = new AutomationRulesService(+ ds.getRepository(AutomationRule),+ ds.getRepository(Session),+ moduleRefStub,+ undefined,+ );});afterEach(async () => {@@ -65,9 +70,15 @@ describe('AutomationRulesService', () => {// Every inbound message is evaluated against every rule of its session, so an unbounded count// turns each message into unbounded work — the same reason the webhook fan-out is capped.const cappedService = (max: number): AutomationRulesService =>- new AutomationRulesService(ds.getRepository(AutomationRule), moduleRefStub, undefined, {- get: (_key: string, def?: number) => max ?? def,- } as unknown as ConfigService);+ new AutomationRulesService(+ ds.getRepository(AutomationRule),+ ds.getRepository(Session),+ moduleRefStub,+ undefined,+ {+ get: (_key: string, def?: number) => max ?? def,+ } as unknown as ConfigService,+ );it('refuses a NEW rule at or over the cap; existing ones are grandfathered', async () => {const svc = cappedService(2);@@ -204,9 +215,18 @@ describe('AutomationRulesService', () => {expect(sends).toHaveLength(0);});+ it('refuses a rule for a session that does not exist with 404, not a driver error', async () => {+ // The sessionId FK would otherwise surface as a 500 from the save, with an unknown-exception+ // stack in the logs, for what is simply a wrong id in the path.+ await expect(service.create('no-such-session', { name: 'x', replyText: 'ack' })).rejects.toThrow(+ NotFoundException,+ );+ });+it('a failing rule lookup resolves without throwing (receive path stays safe)', async () => {const broken = new AutomationRulesService({ find: () => Promise.reject(new Error('db gone')) } as never,+ ds.getRepository(Session),moduleRefStub,undefined,);@@ -215,7 +235,12 @@ describe('AutomationRulesService', () => {});it('tolerates a missing ModuleRef (unit wiring) without throwing', async () => {- const bare = new AutomationRulesService(ds.getRepository(AutomationRule), undefined, undefined);+ const bare = new AutomationRulesService(+ ds.getRepository(AutomationRule),+ ds.getRepository(Session),+ undefined,+ undefined,+ );await service.create('sessA', { name: 'all', replyText: 'ack' });await expect(bare.evaluateInbound('sessA', inbound())).resolves.toBeUndefined();diff --git a/src/modules/automation/automation-rules.service.ts b/src/modules/automation/automation-rules.service.tsindex 95fd0ecaf..46a3cc3a1 100644--- a/src/modules/automation/automation-rules.service.ts+++ b/src/modules/automation/automation-rules.service.ts@@ -8,6 +8,7 @@ import { LidMappingStoreService } from '../../engine/identity/lid-mapping-store.import { evaluateFilters } from '../webhook/filters/filter-evaluator';import { PLUGIN_MESSAGE_PORT, type PluginMessagePort } from '../../core/plugins/plugin-host-ports';import { AutomationRule } from './entities/automation-rule.entity';+import { Session } from '../session/entities/session.entity';import { CreateAutomationRuleDto, UpdateAutomationRuleDto } from './dto/automation-rule.dto';/** Entries above this size trigger a sweep of expired cooldowns before inserting the next one. */@@ -44,6 +45,8 @@ export class AutomationRulesService {constructor(@InjectRepository(AutomationRule, 'data')private readonly ruleRepository: Repository<AutomationRule>,+ @InjectRepository(Session, 'data')+ private readonly sessionRepository: Repository<Session>,@Optional()private readonly moduleRef?: ModuleRef,@Optional()@@ -53,6 +56,11 @@ export class AutomationRulesService {) {}async create(sessionId: string, dto: CreateAutomationRuleDto): Promise<AutomationRule> {+ // The automation_rules.sessionId FK turns a missing session into a driver error (500) at save+ // time; check first so the caller gets a truthful 404, as the webhook create route does.+ if (!(await this.sessionRepository.exists({ where: { id: sessionId } }))) {+ throw new NotFoundException(`Session with id '${sessionId}' not found`);+ }// Per-session cap, the same shape (and softness) the webhook fan-out cap has: every inbound// message is evaluated against every rule of its session, so an unbounded count turns each// message into unbounded work. A concurrent create can race the count — the cap boundsdiff --git a/src/modules/automation/automation.module.ts b/src/modules/automation/automation.module.tsindex a99f4f851..0a227d0c8 100644--- a/src/modules/automation/automation.module.ts+++ b/src/modules/automation/automation.module.ts@@ -1,6 +1,7 @@import { Module } from '@nestjs/common';import { TypeOrmModule } from '@nestjs/typeorm';import { AutomationRule } from './entities/automation-rule.entity';+import { Session } from '../session/entities/session.entity';import { AutomationRulesService } from './automation-rules.service';import { AutomationRuleController } from './automation-rule.controller';@@ -8,9 +9,11 @@ import { AutomationRuleController } from './automation-rule.controller';* Deliberately imports no feature module: SessionModule imports this one (the projector fires rule* evaluation), so anything imported here must not lead back to SessionModule. The reply dependency* (MessageService) is resolved lazily via ModuleRef inside the service for exactly that reason.+ * The Session ENTITY is registered here for the same reason: a repository needs only the entity,+ * while importing SessionModule would close that cycle.*/@Module({- imports: [TypeOrmModule.forFeature([AutomationRule], 'data')],+ imports: [TypeOrmModule.forFeature([AutomationRule, Session], 'data')],controllers: [AutomationRuleController],providers: [AutomationRulesService],exports: [AutomationRulesService],