Merge branch 'release/2.3.3'

This commit is contained in:
Davidson Gomes 2025-09-18 14:17:50 -03:00
commit a1281927a8
68 changed files with 14301 additions and 1681 deletions

107
.cursor/rules/README.md Normal file
View File

@ -0,0 +1,107 @@
# Evolution API Cursor Rules
Este diretório contém as regras e configurações do Cursor IDE para o projeto Evolution API.
## Estrutura dos Arquivos
### Arquivos Principais (alwaysApply: true)
- **`core-development.mdc`** - Princípios fundamentais de desenvolvimento
- **`project-context.mdc`** - Contexto específico do projeto Evolution API
- **`cursor.json`** - Configurações do Cursor IDE
### Regras Especializadas (alwaysApply: false)
Estas regras são ativadas automaticamente quando você trabalha nos arquivos correspondentes:
#### Camadas da Aplicação
- **`specialized-rules/service-rules.mdc`** - Padrões para services (`src/api/services/`)
- **`specialized-rules/controller-rules.mdc`** - Padrões para controllers (`src/api/controllers/`)
- **`specialized-rules/dto-rules.mdc`** - Padrões para DTOs (`src/api/dto/`)
- **`specialized-rules/guard-rules.mdc`** - Padrões para guards (`src/api/guards/`)
- **`specialized-rules/route-rules.mdc`** - Padrões para routers (`src/api/routes/`)
#### Tipos e Validação
- **`specialized-rules/type-rules.mdc`** - Definições TypeScript (`src/api/types/`)
- **`specialized-rules/validate-rules.mdc`** - Schemas de validação (`src/validate/`)
#### Utilitários
- **`specialized-rules/util-rules.mdc`** - Funções utilitárias (`src/utils/`)
#### Integrações
- **`specialized-rules/integration-channel-rules.mdc`** - Integrações de canal (`src/api/integrations/channel/`)
- **`specialized-rules/integration-chatbot-rules.mdc`** - Integrações de chatbot (`src/api/integrations/chatbot/`)
- **`specialized-rules/integration-storage-rules.mdc`** - Integrações de storage (`src/api/integrations/storage/`)
- **`specialized-rules/integration-event-rules.mdc`** - Integrações de eventos (`src/api/integrations/event/`)
## Como Usar
### Referências Cruzadas
Os arquivos principais fazem referência aos especializados usando a sintaxe `@specialized-rules/nome-do-arquivo.mdc`. Quando você trabalha em um arquivo específico, o Cursor automaticamente carrega as regras relevantes.
### Exemplo de Uso
Quando você edita um arquivo em `src/api/services/`, o Cursor automaticamente:
1. Carrega `core-development.mdc` (sempre ativo)
2. Carrega `project-context.mdc` (sempre ativo)
3. Carrega `specialized-rules/service-rules.mdc` (ativado pelo glob pattern)
### Padrões de Código
Cada arquivo de regras contém:
- **Estruturas padrão** - Como organizar o código
- **Padrões de nomenclatura** - Convenções de nomes
- **Exemplos práticos** - Código de exemplo
- **Anti-padrões** - O que evitar
- **Testes** - Como testar o código
- **Padrões de Commit** - Conventional Commits com commitlint
## Configuração do Cursor
O arquivo `cursor.json` contém:
- Configurações de formatação
- Padrões de código específicos do Evolution API
- Diretórios principais do projeto
- Integrações e tecnologias utilizadas
## Manutenção
Para manter as regras atualizadas:
1. Analise novos padrões no código
2. Atualize as regras especializadas correspondentes
3. Mantenha os exemplos sincronizados com o código real
4. Documente mudanças significativas
## Tecnologias Cobertas
- **Backend**: Node.js 20+ + TypeScript 5+ + Express.js
- **Database**: Prisma ORM (PostgreSQL/MySQL)
- **Cache**: Redis + Node-cache
- **Queue**: RabbitMQ + Amazon SQS
- **Real-time**: Socket.io
- **Storage**: AWS S3 + Minio
- **Validation**: JSONSchema7
- **Logging**: Pino
- **WhatsApp**: Baileys + Meta Business API
- **Integrations**: Chatwoot, Typebot, OpenAI, Dify
## Estrutura do Projeto
```
src/
├── api/
│ ├── controllers/ # Controllers (HTTP handlers)
│ ├── services/ # Business logic
│ ├── dto/ # Data Transfer Objects
│ ├── guards/ # Authentication/Authorization
│ ├── routes/ # Express routers
│ ├── types/ # TypeScript definitions
│ └── integrations/ # External integrations
│ ├── channel/ # WhatsApp channels (Baileys, Business API)
│ ├── chatbot/ # Chatbot integrations
│ ├── event/ # Event integrations
│ └── storage/ # Storage integrations
├── cache/ # Cache implementations
├── config/ # Configuration files
├── utils/ # Utility functions
├── validate/ # Validation schemas
└── exceptions/ # Custom exceptions
```
Este sistema de regras garante consistência no código e facilita o desenvolvimento seguindo os padrões estabelecidos do Evolution API.

View File

@ -0,0 +1,167 @@
---
description: Core development principles and standards for Evolution API development
globs:
alwaysApply: true
---
# Evolution API Development Standards
## Cross-References
- **Project Context**: @project-context.mdc for Evolution API-specific patterns
- **Specialized Rules**:
- @specialized-rules/service-rules.mdc for service layer patterns
- @specialized-rules/controller-rules.mdc for controller patterns
- @specialized-rules/dto-rules.mdc for DTO validation patterns
- @specialized-rules/guard-rules.mdc for authentication/authorization
- @specialized-rules/route-rules.mdc for router patterns
- @specialized-rules/type-rules.mdc for TypeScript definitions
- @specialized-rules/util-rules.mdc for utility functions
- @specialized-rules/validate-rules.mdc for validation schemas
- @specialized-rules/integration-channel-rules.mdc for channel integrations
- @specialized-rules/integration-chatbot-rules.mdc for chatbot integrations
- @specialized-rules/integration-storage-rules.mdc for storage integrations
- @specialized-rules/integration-event-rules.mdc for event integrations
- **TypeScript/Node.js**: Node.js 20+ + TypeScript 5+ best practices
- **Express/Prisma**: Express.js + Prisma ORM patterns
- **WhatsApp Integrations**: Baileys + Meta Business API patterns
## Senior Engineer Context - Evolution API Platform
- You are a senior software engineer working on a WhatsApp API platform
- Focus on Node.js + TypeScript + Express.js full-stack development
- Specialized in real-time messaging, WhatsApp integrations, and event-driven architecture
- Apply scalable patterns for multi-tenant API platform
- Consider WhatsApp integration workflow implications and performance at scale
## Fundamental Principles
### Code Quality Standards
- **Simplicity First**: Always prefer simple solutions over complex ones
- **DRY Principle**: Avoid code duplication - check for existing similar functionality before implementing
- **Single Responsibility**: Each function/class should have one clear purpose
- **Readable Code**: Write code that tells a story - clear naming and structure
### Problem Resolution Approach
- **Follow Existing Patterns**: Use established Service patterns, DTOs, and Integration patterns
- **Event-Driven First**: Leverage EventEmitter2 for event publishing when adding new features
- **Integration Pattern**: Follow existing WhatsApp integration patterns for new channels
- **Conservative Changes**: Prefer extending existing services over creating new architecture
- **Clean Migration**: Remove deprecated patterns when introducing new ones
- **Incremental Changes**: Break large changes into smaller, testable increments with proper migrations
### File and Function Organization - Node.js/TypeScript Structure
- **Services**: Keep services focused and under 200 lines
- **Controllers**: Keep controllers thin - only routing and validation
- **DTOs**: Use JSONSchema7 for all input validation
- **Integrations**: Follow `src/api/integrations/` structure for new integrations
- **Utils**: Extract common functionality into well-named utilities
- **Types**: Define clear TypeScript interfaces and types
### Code Analysis and Reflection
- After writing code, deeply reflect on scalability and maintainability
- Provide 1-2 paragraph analysis of code changes
- Suggest improvements or next steps based on reflection
- Consider performance, security, and maintenance implications
## Development Standards
### TypeScript Standards
- **Strict Mode**: Always use TypeScript strict mode
- **No Any**: Avoid `any` type - use proper typing
- **Interfaces**: Define clear contracts with interfaces
- **Enums**: Use enums for constants and status values
- **Generics**: Use generics for reusable components
### Error Handling Standards
- **HTTP Exceptions**: Use appropriate HTTP status codes
- **Logging**: Structured logging with context
- **Retry Logic**: Implement retry for external services
- **Graceful Degradation**: Handle service failures gracefully
### Security Standards
- **Input Validation**: Validate all inputs with JSONSchema7
- **Authentication**: Use API keys and JWT tokens
- **Rate Limiting**: Implement rate limiting for APIs
- **Data Sanitization**: Sanitize sensitive data in logs
### Performance Standards
- **Caching**: Use Redis for frequently accessed data
- **Database**: Optimize Prisma queries with proper indexing
- **Memory**: Monitor memory usage and implement cleanup
- **Async**: Use async/await properly with error handling
## Communication Standards
### Language Requirements
- **User Communication**: Always respond in Portuguese (PT-BR)
- **Code Comments**: English for technical documentation
- **API Documentation**: English for consistency
- **Error Messages**: Portuguese for user-facing errors
### Documentation Standards
- **Code Comments**: Document complex business logic
- **API Documentation**: Document all public endpoints
- **README**: Keep project documentation updated
- **Changelog**: Document breaking changes
## Quality Assurance
### Testing Standards
- **Unit Tests**: Test business logic in services
- **Integration Tests**: Test API endpoints
- **Mocks**: Mock external dependencies
- **Coverage**: Aim for 70%+ test coverage
### Code Review Standards
- **Peer Review**: All code must be reviewed
- **Automated Checks**: ESLint, Prettier, TypeScript
- **Security Review**: Check for security vulnerabilities
- **Performance Review**: Check for performance issues
### Commit Standards (Conventional Commits)
- **Format**: `type(scope): subject` (max 100 characters)
- **Types**:
- `feat` - New feature
- `fix` - Bug fix
- `docs` - Documentation changes
- `style` - Code style changes (formatting, etc)
- `refactor` - Code refactoring
- `perf` - Performance improvements
- `test` - Adding or updating tests
- `chore` - Maintenance tasks
- `ci` - CI/CD changes
- `build` - Build system changes
- `revert` - Reverting changes
- `security` - Security fixes
- **Examples**:
- `feat(api): add WhatsApp message status endpoint`
- `fix(baileys): resolve connection timeout issue`
- `docs(readme): update installation instructions`
- `refactor(service): extract common message validation logic`
- **Tools**: Use `npm run commit` (Commitizen) for guided commits
- **Validation**: Enforced by commitlint on commit-msg hook
## Evolution API Specific Patterns
### WhatsApp Integration Patterns
- **Connection Management**: One connection per instance
- **Event Handling**: Proper event listeners for Baileys
- **Message Processing**: Queue-based message processing
- **Error Recovery**: Automatic reconnection logic
### Multi-Database Support
- **Schema Compatibility**: Support PostgreSQL and MySQL
- **Migration Sync**: Keep migrations synchronized
- **Type Safety**: Use Prisma generated types
- **Connection Pooling**: Proper database connection management
### Cache Strategy
- **Redis Primary**: Use Redis for distributed caching
- **Local Fallback**: Node-cache for local fallback
- **TTL Strategy**: Appropriate TTL for different data types
- **Cache Invalidation**: Proper cache invalidation patterns
### Event System
- **EventEmitter2**: Use for internal events
- **WebSocket**: Socket.io for real-time updates
- **Queue Systems**: RabbitMQ/SQS for async processing
- **Webhook Processing**: Proper webhook validation and processing

179
.cursor/rules/cursor.json Normal file
View File

@ -0,0 +1,179 @@
{
"version": "1.0",
"description": "Cursor IDE configuration for Evolution API project",
"rules": {
"general": {
"max_line_length": 120,
"indent_size": 2,
"end_of_line": "lf",
"charset": "utf-8",
"trim_trailing_whitespace": true,
"insert_final_newline": true
},
"typescript": {
"quotes": "single",
"semi": true,
"trailing_comma": "es5",
"bracket_spacing": true,
"arrow_parens": "avoid",
"print_width": 120,
"tab_width": 2,
"use_tabs": false,
"single_quote": true,
"end_of_line": "lf",
"strict": true,
"no_implicit_any": true,
"strict_null_checks": true
},
"javascript": {
"quotes": "single",
"semi": true,
"trailing_comma": "es5",
"bracket_spacing": true,
"arrow_parens": "avoid",
"print_width": 120,
"tab_width": 2,
"use_tabs": false,
"single_quote": true,
"end_of_line": "lf",
"style_guide": "eslint-airbnb"
},
"json": {
"tab_width": 2,
"use_tabs": false,
"parser": "json"
},
"ignore": {
"files": [
"node_modules/**",
"dist/**",
"build/**",
".git/**",
"*.min.js",
"*.min.css",
".env",
".env.*",
".env.example",
"coverage/**",
"*.log",
"*.lock",
"pnpm-lock.yaml",
"package-lock.json",
"yarn.lock",
"log/**",
"tmp/**",
"instances/**",
"public/uploads/**",
"*.dump",
"*.rdb",
"*.mmdb",
".DS_Store",
"*.swp",
"*.swo",
"*.un~",
".jest-cache",
".idea/**",
".vscode/**",
".yalc/**",
"yalc.lock",
"*.local",
"prisma/migrations/**",
"prisma/mysql-migrations/**",
"prisma/postgresql-migrations/**"
]
},
"search": {
"exclude_patterns": [
"**/node_modules/**",
"**/dist/**",
"**/build/**",
"**/.git/**",
"**/coverage/**",
"**/log/**",
"**/tmp/**",
"**/instances/**",
"**/public/uploads/**",
"**/*.min.js",
"**/*.min.css",
"**/*.log",
"**/*.lock",
"**/pnpm-lock.yaml",
"**/package-lock.json",
"**/yarn.lock",
"**/*.dump",
"**/*.rdb",
"**/*.mmdb",
"**/.DS_Store",
"**/*.swp",
"**/*.swo",
"**/*.un~",
"**/.jest-cache",
"**/.idea/**",
"**/.vscode/**",
"**/.yalc/**",
"**/yalc.lock",
"**/*.local",
"**/prisma/migrations/**",
"**/prisma/mysql-migrations/**",
"**/prisma/postgresql-migrations/**"
]
},
"evolution_api": {
"project_type": "nodejs_typescript_api",
"backend_framework": "express_prisma",
"database": ["postgresql", "mysql"],
"cache": ["redis", "node_cache"],
"queue": ["rabbitmq", "sqs"],
"real_time": "socket_io",
"file_storage": ["aws_s3", "minio"],
"validation": "class_validator",
"logging": "pino",
"main_directories": {
"source": "src/",
"api": "src/api/",
"controllers": "src/api/controllers/",
"services": "src/api/services/",
"integrations": "src/api/integrations/",
"dto": "src/api/dto/",
"types": "src/api/types/",
"guards": "src/api/guards/",
"routes": "src/api/routes/",
"cache": "src/cache/",
"config": "src/config/",
"utils": "src/utils/",
"exceptions": "src/exceptions/",
"validate": "src/validate/",
"prisma": "prisma/",
"tests": "test/",
"docs": "docs/"
},
"key_patterns": [
"whatsapp_integration",
"multi_database_support",
"instance_management",
"event_driven_architecture",
"service_layer_pattern",
"dto_validation",
"webhook_processing",
"message_queuing",
"real_time_communication",
"file_storage_integration"
],
"whatsapp_integrations": [
"baileys",
"meta_business_api",
"whatsapp_cloud_api"
],
"external_integrations": [
"chatwoot",
"typebot",
"openai",
"dify",
"rabbitmq",
"sqs",
"s3",
"minio"
]
}
}
}

View File

@ -0,0 +1,174 @@
---
description: Evolution API project-specific context and constraints
globs:
alwaysApply: true
---
# Evolution API Project Context
## Cross-References
- **Core Development**: @core-development.mdc for fundamental development principles
- **Specialized Rules**: Reference specific specialized rules when working on:
- Services: @specialized-rules/service-rules.mdc
- Controllers: @specialized-rules/controller-rules.mdc
- DTOs: @specialized-rules/dto-rules.mdc
- Guards: @specialized-rules/guard-rules.mdc
- Routes: @specialized-rules/route-rules.mdc
- Types: @specialized-rules/type-rules.mdc
- Utils: @specialized-rules/util-rules.mdc
- Validation: @specialized-rules/validate-rules.mdc
- Channel Integrations: @specialized-rules/integration-channel-rules.mdc
- Chatbot Integrations: @specialized-rules/integration-chatbot-rules.mdc
- Storage Integrations: @specialized-rules/integration-storage-rules.mdc
- Event Integrations: @specialized-rules/integration-event-rules.mdc
- **TypeScript/Node.js**: Node.js 20+ + TypeScript 5+ backend standards
- **Express/Prisma**: Express.js + Prisma ORM patterns
- **WhatsApp Integrations**: Baileys, Meta Business API, and other messaging platforms
## Technology Stack
- **Backend**: Node.js 20+ + TypeScript 5+ + Express.js
- **Database**: Prisma ORM (PostgreSQL/MySQL support)
- **Cache**: Redis + Node-cache for local fallback
- **Queue**: RabbitMQ + Amazon SQS for message processing
- **Real-time**: Socket.io for WebSocket connections
- **Storage**: AWS S3 + Minio for file storage
- **Validation**: JSONSchema7 for input validation
- **Logging**: Pino for structured logging
- **Architecture**: Multi-tenant API with WhatsApp integrations
## Project-Specific Patterns
### WhatsApp Integration Architecture
- **MANDATORY**: All WhatsApp integrations must follow established patterns
- **BAILEYS**: Use `whatsapp.baileys.service.ts` patterns for WhatsApp Web
- **META BUSINESS**: Use `whatsapp.business.service.ts` for official API
- **CONNECTION MANAGEMENT**: One connection per instance with proper lifecycle
- **EVENT HANDLING**: Proper event listeners and error handling
### Multi-Database Architecture
- **CRITICAL**: Support both PostgreSQL and MySQL
- **SCHEMAS**: Use appropriate schema files (postgresql-schema.prisma / mysql-schema.prisma)
- **MIGRATIONS**: Keep migrations synchronized between databases
- **TYPES**: Use database-specific types (@db.JsonB vs @db.Json)
- **COMPATIBILITY**: Ensure feature parity between databases
### API Integration Workflow
- **CORE FEATURE**: REST API for WhatsApp communication
- **COMPLEXITY**: High - involves webhook processing, message routing, and instance management
- **COMPONENTS**: Instance management, message handling, media processing
- **INTEGRATIONS**: Baileys, Meta Business API, Chatwoot, Typebot, OpenAI, Dify
### Multi-Tenant Instance Architecture
- **CRITICAL**: All operations must be scoped by instance
- **ISOLATION**: Complete data isolation between instances
- **SECURITY**: Validate instance ownership before operations
- **SCALING**: Support thousands of concurrent instances
- **AUTHENTICATION**: API key-based authentication per instance
## Documentation Requirements
### Implementation Documentation
- **MANDATORY**: Document complex integration patterns
- **LOCATION**: Use inline comments for business logic
- **API DOCS**: Document all public endpoints
- **WEBHOOK DOCS**: Document webhook payloads and signatures
### Change Documentation
- **CHANGELOG**: Document breaking changes
- **MIGRATION GUIDES**: Document database migrations
- **INTEGRATION GUIDES**: Document new integration patterns
## Environment and Security
### Environment Variables
- **CRITICAL**: Never hardcode sensitive values
- **VALIDATION**: Validate required environment variables on startup
- **SECURITY**: Use secure defaults and proper encryption
- **DOCUMENTATION**: Document all environment variables
### File Organization - Node.js/TypeScript Structure
- **CONTROLLERS**: Organized by feature (`api/controllers/`)
- **SERVICES**: Business logic in service classes (`api/services/`)
- **INTEGRATIONS**: External integrations (`api/integrations/`)
- **DTOS**: Data transfer objects (`api/dto/`)
- **TYPES**: TypeScript types (`api/types/`)
- **UTILS**: Utility functions (`utils/`)
## Integration Points
### WhatsApp Providers
- **BAILEYS**: WhatsApp Web integration with QR code
- **META BUSINESS**: Official WhatsApp Business API
- **CLOUD API**: WhatsApp Cloud API integration
- **WEBHOOK PROCESSING**: Proper webhook validation and processing
### External Integrations
- **CHATWOOT**: Customer support platform integration
- **TYPEBOT**: Chatbot flow integration
- **OPENAI**: AI-powered chat integration
- **DIFY**: AI workflow integration
- **STORAGE**: S3/Minio for media file storage
### Event-Driven Communication
- **EVENTEMITTER2**: Internal event system
- **SOCKET.IO**: Real-time WebSocket communication
- **RABBITMQ**: Message queue for async processing
- **SQS**: Amazon SQS for cloud-based queuing
- **WEBHOOKS**: Outbound webhook system
## Development Constraints
### Language Requirements
- **USER COMMUNICATION**: Always respond in Portuguese (PT-BR)
- **CODE/COMMENTS**: English for code and technical documentation
- **API RESPONSES**: English for consistency
- **ERROR MESSAGES**: Portuguese for user-facing errors
### Performance Constraints
- **MEMORY**: Efficient memory usage for multiple instances
- **DATABASE**: Optimized queries with proper indexing
- **CACHE**: Strategic caching for frequently accessed data
- **CONNECTIONS**: Proper connection pooling and management
### Security Constraints
- **AUTHENTICATION**: API key validation for all endpoints
- **AUTHORIZATION**: Instance-based access control
- **INPUT VALIDATION**: Validate all inputs with JSONSchema7
- **RATE LIMITING**: Prevent abuse with rate limiting
- **WEBHOOK SECURITY**: Validate webhook signatures
## Quality Standards
- **TYPE SAFETY**: Full TypeScript coverage with strict mode
- **ERROR HANDLING**: Comprehensive error scenarios with proper logging
- **TESTING**: Unit and integration tests for critical paths
- **MONITORING**: Proper logging and error tracking
- **DOCUMENTATION**: Clear API documentation and code comments
- **PERFORMANCE**: Optimized for high-throughput message processing
- **SECURITY**: Secure by default with proper validation
- **SCALABILITY**: Design for horizontal scaling
## Evolution API Specific Development Patterns
### Instance Management
- **LIFECYCLE**: Proper instance creation, connection, and cleanup
- **STATE MANAGEMENT**: Track connection status and health
- **RECOVERY**: Automatic reconnection and error recovery
- **MONITORING**: Health checks and status reporting
### Message Processing
- **QUEUE-BASED**: Use queues for message processing
- **RETRY LOGIC**: Implement exponential backoff for failures
- **MEDIA HANDLING**: Proper media upload and processing
- **WEBHOOK DELIVERY**: Reliable webhook delivery with retries
### Integration Patterns
- **SERVICE LAYER**: Business logic in service classes
- **DTO VALIDATION**: Input validation with JSONSchema7
- **ERROR HANDLING**: Consistent error responses
- **LOGGING**: Structured logging with correlation IDs
### Database Patterns
- **PRISMA**: Use Prisma ORM for all database operations
- **TRANSACTIONS**: Use transactions for multi-step operations
- **MIGRATIONS**: Proper migration management
- **INDEXING**: Optimize queries with appropriate indexes

View File

@ -0,0 +1,342 @@
---
description: Controller patterns for Evolution API
globs:
- "src/api/controllers/**/*.ts"
- "src/api/integrations/**/controllers/*.ts"
alwaysApply: false
---
# Evolution API Controller Rules
## Controller Structure Pattern
### Standard Controller Class
```typescript
export class ExampleController {
constructor(private readonly exampleService: ExampleService) {}
public async createExample(instance: InstanceDto, data: ExampleDto) {
return this.exampleService.create(instance, data);
}
public async findExample(instance: InstanceDto) {
return this.exampleService.find(instance);
}
}
```
## Dependency Injection Pattern
### Service Injection
```typescript
// CORRECT - Evolution API pattern
export class ChatController {
constructor(private readonly waMonitor: WAMonitoringService) {}
public async whatsappNumber({ instanceName }: InstanceDto, data: WhatsAppNumberDto) {
return await this.waMonitor.waInstances[instanceName].getWhatsAppNumbers(data);
}
}
// INCORRECT - Don't inject multiple services when waMonitor is sufficient
export class ChatController {
constructor(
private readonly waMonitor: WAMonitoringService,
private readonly prismaRepository: PrismaRepository, // ❌ Unnecessary if waMonitor has access
private readonly configService: ConfigService, // ❌ Unnecessary if waMonitor has access
) {}
}
```
## Method Signature Pattern
### Instance Parameter Pattern
```typescript
// CORRECT - Evolution API pattern (destructuring instanceName)
public async fetchCatalog({ instanceName }: InstanceDto, data: getCatalogDto) {
return await this.waMonitor.waInstances[instanceName].fetchCatalog(instanceName, data);
}
// CORRECT - Alternative pattern for full instance (when using services)
public async createTemplate(instance: InstanceDto, data: TemplateDto) {
return this.templateService.create(instance, data);
}
// INCORRECT - Don't use generic method names
public async methodName(instance: InstanceDto, data: DataDto) { // ❌ Use specific names
return this.service.performAction(instance, data);
}
```
## WAMonitor Access Pattern
### Direct WAMonitor Usage
```typescript
// CORRECT - Standard pattern in controllers
export class CallController {
constructor(private readonly waMonitor: WAMonitoringService) {}
public async offerCall({ instanceName }: InstanceDto, data: OfferCallDto) {
return await this.waMonitor.waInstances[instanceName].offerCall(data);
}
}
```
## Controller Registration Pattern
### Server Module Registration
```typescript
// In server.module.ts
export const templateController = new TemplateController(templateService);
export const businessController = new BusinessController(waMonitor);
export const chatController = new ChatController(waMonitor);
export const callController = new CallController(waMonitor);
```
## Error Handling in Controllers
### Let Services Handle Errors
```typescript
// CORRECT - Let service handle errors
public async fetchCatalog(instance: InstanceDto, data: getCatalogDto) {
return await this.waMonitor.waInstances[instance.instanceName].fetchCatalog(instance.instanceName, data);
}
// INCORRECT - Don't add try-catch in controllers unless specific handling needed
public async fetchCatalog(instance: InstanceDto, data: getCatalogDto) {
try {
return await this.waMonitor.waInstances[instance.instanceName].fetchCatalog(instance.instanceName, data);
} catch (error) {
throw error; // ❌ Unnecessary try-catch
}
}
```
## Complex Controller Pattern
### Instance Controller Pattern
```typescript
export class InstanceController {
constructor(
private readonly waMonitor: WAMonitoringService,
private readonly configService: ConfigService,
private readonly prismaRepository: PrismaRepository,
private readonly eventEmitter: EventEmitter2,
private readonly chatwootService: ChatwootService,
private readonly settingsService: SettingsService,
private readonly proxyService: ProxyController,
private readonly cache: CacheService,
private readonly chatwootCache: CacheService,
private readonly baileysCache: CacheService,
private readonly providerFiles: ProviderFiles,
) {}
private readonly logger = new Logger('InstanceController');
// Multiple methods handling different aspects
public async createInstance(data: InstanceDto) {
// Complex instance creation logic
}
public async deleteInstance({ instanceName }: InstanceDto) {
// Complex instance deletion logic
}
}
```
## Channel Controller Pattern
### Base Channel Controller
```typescript
export class ChannelController {
public prismaRepository: PrismaRepository;
public waMonitor: WAMonitoringService;
constructor(prismaRepository: PrismaRepository, waMonitor: WAMonitoringService) {
this.prisma = prismaRepository;
this.monitor = waMonitor;
}
// Getters and setters for dependency access
public set prisma(prisma: PrismaRepository) {
this.prismaRepository = prisma;
}
public get prisma() {
return this.prismaRepository;
}
public set monitor(waMonitor: WAMonitoringService) {
this.waMonitor = waMonitor;
}
public get monitor() {
return this.waMonitor;
}
}
```
### Extended Channel Controller
```typescript
export class EvolutionController extends ChannelController implements ChannelControllerInterface {
private readonly logger = new Logger('EvolutionController');
constructor(prismaRepository: PrismaRepository, waMonitor: WAMonitoringService) {
super(prismaRepository, waMonitor);
}
integrationEnabled: boolean;
public async receiveWebhook(data: any) {
const numberId = data.numberId;
if (!numberId) {
this.logger.error('WebhookService -> receiveWebhookEvolution -> numberId not found');
return;
}
const instance = await this.prismaRepository.instance.findFirst({
where: { number: numberId },
});
if (!instance) {
this.logger.error('WebhookService -> receiveWebhook -> instance not found');
return;
}
await this.waMonitor.waInstances[instance.name].connectToWhatsapp(data);
return {
status: 'success',
};
}
}
```
## Chatbot Controller Pattern
### Base Chatbot Controller
```typescript
export abstract class BaseChatbotController<BotType = any, BotData extends BaseChatbotDto = BaseChatbotDto>
extends ChatbotController
implements ChatbotControllerInterface
{
public readonly logger: Logger;
integrationEnabled: boolean;
// Abstract methods to be implemented
protected abstract readonly integrationName: string;
protected abstract processBot(/* parameters */): Promise<void>;
protected abstract getFallbackBotId(settings: any): string | undefined;
constructor(prismaRepository: PrismaRepository, waMonitor: WAMonitoringService) {
super(prismaRepository, waMonitor);
}
// Base implementation methods
public async createBot(instance: InstanceDto, data: BotData) {
// Common bot creation logic
}
}
```
## Method Naming Conventions
### Standard Method Names
- `create*()` - Create operations
- `find*()` - Find operations
- `fetch*()` - Fetch from external APIs
- `send*()` - Send operations
- `receive*()` - Receive webhook/data
- `handle*()` - Handle specific actions
- `offer*()` - Offer services (like calls)
## Return Patterns
### Direct Return Pattern
```typescript
// CORRECT - Direct return from service
public async createTemplate(instance: InstanceDto, data: TemplateDto) {
return this.templateService.create(instance, data);
}
// CORRECT - Direct return from waMonitor
public async offerCall({ instanceName }: InstanceDto, data: OfferCallDto) {
return await this.waMonitor.waInstances[instanceName].offerCall(data);
}
```
## Controller Testing Pattern
### Unit Test Structure
```typescript
describe('ExampleController', () => {
let controller: ExampleController;
let service: jest.Mocked<ExampleService>;
beforeEach(() => {
const mockService = {
create: jest.fn(),
find: jest.fn(),
};
controller = new ExampleController(mockService as any);
service = mockService as any;
});
describe('createExample', () => {
it('should call service create method', async () => {
const instance = { instanceName: 'test' };
const data = { test: 'data' };
const expectedResult = { success: true };
service.create.mockResolvedValue(expectedResult);
const result = await controller.createExample(instance, data);
expect(service.create).toHaveBeenCalledWith(instance, data);
expect(result).toEqual(expectedResult);
});
});
});
```
## Interface Implementation
### Controller Interface Pattern
```typescript
export interface ChannelControllerInterface {
integrationEnabled: boolean;
}
export interface ChatbotControllerInterface {
integrationEnabled: boolean;
createBot(instance: InstanceDto, data: any): Promise<any>;
findBot(instance: InstanceDto): Promise<any>;
// ... other methods
}
```
## Controller Organization
### File Naming Convention
- `*.controller.ts` - Main controllers
- `*/*.controller.ts` - Integration-specific controllers
### Method Organization
1. Constructor
2. Public methods (alphabetical order)
3. Private methods (if any)
### Import Organization
```typescript
// DTOs first
import { InstanceDto } from '@api/dto/instance.dto';
import { ExampleDto } from '@api/dto/example.dto';
// Services
import { ExampleService } from '@api/services/example.service';
// Types
import { WAMonitoringService } from '@api/services/monitor.service';
```

View File

@ -0,0 +1,433 @@
---
description: DTO patterns and validation for Evolution API
globs:
- "src/api/dto/**/*.ts"
- "src/api/integrations/**/dto/*.ts"
alwaysApply: false
---
# Evolution API DTO Rules
## DTO Structure Pattern
### Basic DTO Class
```typescript
export class ExampleDto {
name: string;
category: string;
allowCategoryChange: boolean;
language: string;
components: any;
webhookUrl?: string;
}
```
## Inheritance Pattern
### DTO Inheritance
```typescript
// CORRECT - Evolution API pattern
export class InstanceDto extends IntegrationDto {
instanceName: string;
instanceId?: string;
qrcode?: boolean;
businessId?: string;
number?: string;
integration?: string;
token?: string;
status?: string;
ownerJid?: string;
profileName?: string;
profilePicUrl?: string;
// Settings
rejectCall?: boolean;
msgCall?: string;
groupsIgnore?: boolean;
alwaysOnline?: boolean;
readMessages?: boolean;
readStatus?: boolean;
syncFullHistory?: boolean;
wavoipToken?: string;
// Proxy settings
proxyHost?: string;
proxyPort?: string;
proxyProtocol?: string;
proxyUsername?: string;
proxyPassword?: string;
// Webhook configuration
webhook?: {
enabled?: boolean;
events?: string[];
headers?: JsonValue;
url?: string;
byEvents?: boolean;
base64?: boolean;
};
// Chatwoot integration
chatwootAccountId?: string;
chatwootConversationPending?: boolean;
chatwootAutoCreate?: boolean;
chatwootDaysLimitImportMessages?: number;
chatwootImportContacts?: boolean;
chatwootImportMessages?: boolean;
chatwootLogo?: string;
chatwootMergeBrazilContacts?: boolean;
chatwootNameInbox?: string;
chatwootOrganization?: string;
chatwootReopenConversation?: boolean;
chatwootSignMsg?: boolean;
chatwootToken?: string;
chatwootUrl?: string;
}
```
## Base DTO Pattern
### Base Chatbot DTO
```typescript
/**
* Base DTO for all chatbot integrations
* Contains common properties shared by all chatbot types
*/
export class BaseChatbotDto {
enabled?: boolean;
description: string;
expire?: number;
keywordFinish?: string;
delayMessage?: number;
unknownMessage?: string;
listeningFromMe?: boolean;
stopBotFromMe?: boolean;
keepOpen?: boolean;
debounceTime?: number;
triggerType: TriggerType;
triggerOperator?: TriggerOperator;
triggerValue?: string;
ignoreJids?: string[];
splitMessages?: boolean;
timePerChar?: number;
}
/**
* Base settings DTO for all chatbot integrations
*/
export class BaseChatbotSettingDto {
expire?: number;
keywordFinish?: string;
delayMessage?: number;
unknownMessage?: string;
listeningFromMe?: boolean;
stopBotFromMe?: boolean;
keepOpen?: boolean;
debounceTime?: number;
ignoreJids?: string[];
splitMessages?: boolean;
timePerChar?: number;
}
```
## Message DTO Patterns
### Send Message DTOs
```typescript
export class Metadata {
number: string;
delay?: number;
}
export class SendTextDto extends Metadata {
text: string;
linkPreview?: boolean;
mentionsEveryOne?: boolean;
mentioned?: string[];
}
export class SendListDto extends Metadata {
title: string;
description: string;
buttonText: string;
footerText?: string;
sections: Section[];
}
export class ContactMessage {
fullName: string;
wuid: string;
phoneNumber: string;
organization?: string;
email?: string;
url?: string;
}
export class SendTemplateDto extends Metadata {
name: string;
language: string;
components: any;
}
```
## Simple DTO Patterns
### Basic DTOs
```typescript
export class NumberDto {
number: string;
}
export class LabelDto {
id?: string;
name: string;
color: string;
predefinedId?: string;
}
export class HandleLabelDto {
number: string;
labelId: string;
}
export class ProfileNameDto {
name: string;
}
export class WhatsAppNumberDto {
numbers: string[];
}
```
## Complex DTO Patterns
### Business DTOs
```typescript
export class getCatalogDto {
number?: string;
limit?: number;
cursor?: string;
}
export class getCollectionsDto {
number?: string;
limit?: number;
cursor?: string;
}
export class NumberBusiness {
number: string;
name?: string;
description?: string;
email?: string;
websites?: string[];
latitude?: number;
longitude?: number;
address?: string;
profilehandle?: string;
}
```
## Settings DTO Pattern
### Settings Configuration
```typescript
export class SettingsDto {
rejectCall?: boolean;
msgCall?: string;
groupsIgnore?: boolean;
alwaysOnline?: boolean;
readMessages?: boolean;
readStatus?: boolean;
syncFullHistory?: boolean;
wavoipToken?: string;
}
export class ProxyDto {
host?: string;
port?: string;
protocol?: string;
username?: string;
password?: string;
}
```
## Presence DTO Pattern
### WhatsApp Presence
```typescript
export class SetPresenceDto {
presence: WAPresence;
}
export class SendPresenceDto {
number: string;
presence: WAPresence;
}
```
## DTO Structure (No Decorators)
### Simple DTO Classes (Evolution API Pattern)
```typescript
// CORRECT - Evolution API pattern (no decorators)
export class ExampleDto {
name: string;
description?: string;
enabled: boolean;
items?: string[];
timeout?: number;
}
// INCORRECT - Don't use class-validator decorators
export class ValidatedDto {
@IsString() // ❌ Evolution API doesn't use decorators
name: string;
}
```
## Type Safety Patterns
### Prisma Type Integration
```typescript
import { JsonValue } from '@prisma/client/runtime/library';
import { WAPresence } from 'baileys';
import { TriggerOperator, TriggerType } from '@prisma/client';
export class TypeSafeDto {
presence: WAPresence;
triggerType: TriggerType;
triggerOperator?: TriggerOperator;
metadata?: JsonValue;
}
```
## DTO Documentation
### JSDoc Comments
```typescript
/**
* DTO for creating WhatsApp templates
* Used by Meta Business API integration
*/
export class TemplateDto {
/** Template name - must be unique */
name: string;
/** Template category (MARKETING, UTILITY, AUTHENTICATION) */
category: string;
/** Whether category can be changed after creation */
allowCategoryChange: boolean;
/** Language code (e.g., 'pt_BR', 'en_US') */
language: string;
/** Template components (header, body, footer, buttons) */
components: any;
/** Optional webhook URL for template status updates */
webhookUrl?: string;
}
```
## DTO Naming Conventions
### Standard Naming Patterns
- `*Dto` - Data transfer objects
- `Create*Dto` - Creation DTOs
- `Update*Dto` - Update DTOs
- `Send*Dto` - Message sending DTOs
- `Get*Dto` - Query DTOs
- `Handle*Dto` - Action DTOs
## File Organization
### DTO File Structure
```
src/api/dto/
├── instance.dto.ts # Main instance DTO
├── template.dto.ts # Template management
├── sendMessage.dto.ts # Message sending DTOs
├── chat.dto.ts # Chat operations
├── business.dto.ts # Business API DTOs
├── group.dto.ts # Group management
├── label.dto.ts # Label management
├── proxy.dto.ts # Proxy configuration
├── settings.dto.ts # Instance settings
└── call.dto.ts # Call operations
```
## Integration DTO Patterns
### Chatbot Integration DTOs
```typescript
// Base for all chatbot DTOs
export class BaseChatbotDto {
enabled?: boolean;
description: string;
// ... common properties
}
// Specific chatbot DTOs extend base
export class TypebotDto extends BaseChatbotDto {
url: string;
typebot: string;
// ... typebot-specific properties
}
export class OpenaiDto extends BaseChatbotDto {
apiKey: string;
model: string;
// ... openai-specific properties
}
```
## DTO Testing Pattern
### DTO Validation Tests
```typescript
describe('ExampleDto', () => {
it('should validate required fields', () => {
const dto = new ExampleDto();
dto.name = 'test';
dto.category = 'MARKETING';
dto.allowCategoryChange = true;
dto.language = 'pt_BR';
dto.components = {};
expect(dto.name).toBe('test');
expect(dto.category).toBe('MARKETING');
});
it('should handle optional fields', () => {
const dto = new ExampleDto();
dto.name = 'test';
dto.category = 'MARKETING';
dto.allowCategoryChange = true;
dto.language = 'pt_BR';
dto.components = {};
dto.webhookUrl = 'https://example.com/webhook';
expect(dto.webhookUrl).toBe('https://example.com/webhook');
});
});
```
## DTO Transformation
### Request to DTO Mapping (Evolution API Pattern)
```typescript
// CORRECT - Evolution API uses RouterBroker dataValidate
const response = await this.dataValidate<ExampleDto>({
request: req,
schema: exampleSchema, // JSONSchema7
ClassRef: ExampleDto,
execute: (instance, data) => controller.method(instance, data),
});
// INCORRECT - Don't use class-validator
const dto = plainToClass(ExampleDto, req.body); // ❌ Not used in Evolution API
const errors = await validate(dto); // ❌ Not used in Evolution API
```

View File

@ -0,0 +1,416 @@
---
description: Guard patterns for authentication and authorization in Evolution API
globs:
- "src/api/guards/**/*.ts"
alwaysApply: false
---
# Evolution API Guard Rules
## Guard Structure Pattern
### Standard Guard Function
```typescript
import { NextFunction, Request, Response } from 'express';
import { Logger } from '@config/logger.config';
import { UnauthorizedException, ForbiddenException } from '@exceptions';
const logger = new Logger('GUARD');
async function guardFunction(req: Request, _: Response, next: NextFunction) {
// Guard logic here
if (validationFails) {
throw new UnauthorizedException();
}
return next();
}
export const guardName = { guardFunction };
```
## Authentication Guard Pattern
### API Key Authentication
```typescript
async function apikey(req: Request, _: Response, next: NextFunction) {
const env = configService.get<Auth>('AUTHENTICATION').API_KEY;
const key = req.get('apikey');
const db = configService.get<Database>('DATABASE');
if (!key) {
throw new UnauthorizedException();
}
// Global API key check
if (env.KEY === key) {
return next();
}
// Special routes handling
if ((req.originalUrl.includes('/instance/create') || req.originalUrl.includes('/instance/fetchInstances')) && !key) {
throw new ForbiddenException('Missing global api key', 'The global api key must be set');
}
const param = req.params as unknown as InstanceDto;
try {
if (param?.instanceName) {
const instance = await prismaRepository.instance.findUnique({
where: { name: param.instanceName },
});
if (instance.token === key) {
return next();
}
} else {
if (req.originalUrl.includes('/instance/fetchInstances') && db.SAVE_DATA.INSTANCE) {
const instanceByKey = await prismaRepository.instance.findFirst({
where: { token: key },
});
if (instanceByKey) {
return next();
}
}
}
} catch (error) {
logger.error(error);
}
throw new UnauthorizedException();
}
export const authGuard = { apikey };
```
## Instance Validation Guards
### Instance Exists Guard
```typescript
async function getInstance(instanceName: string) {
try {
const cacheConf = configService.get<CacheConf>('CACHE');
const exists = !!waMonitor.waInstances[instanceName];
if (cacheConf.REDIS.ENABLED && cacheConf.REDIS.SAVE_INSTANCES) {
const keyExists = await cache.has(instanceName);
return exists || keyExists;
}
return exists || (await prismaRepository.instance.findMany({ where: { name: instanceName } })).length > 0;
} catch (error) {
throw new InternalServerErrorException(error?.toString());
}
}
export async function instanceExistsGuard(req: Request, _: Response, next: NextFunction) {
if (req.originalUrl.includes('/instance/create')) {
return next();
}
const param = req.params as unknown as InstanceDto;
if (!param?.instanceName) {
throw new BadRequestException('"instanceName" not provided.');
}
if (!(await getInstance(param.instanceName))) {
throw new NotFoundException(`The "${param.instanceName}" instance does not exist`);
}
next();
}
```
### Instance Logged Guard
```typescript
export async function instanceLoggedGuard(req: Request, _: Response, next: NextFunction) {
if (req.originalUrl.includes('/instance/create')) {
const instance = req.body as InstanceDto;
if (await getInstance(instance.instanceName)) {
throw new ForbiddenException(`This name "${instance.instanceName}" is already in use.`);
}
if (waMonitor.waInstances[instance.instanceName]) {
delete waMonitor.waInstances[instance.instanceName];
}
}
next();
}
```
## Telemetry Guard Pattern
### Telemetry Collection
```typescript
class Telemetry {
public collectTelemetry(req: Request, res: Response, next: NextFunction): void {
// Collect telemetry data
const telemetryData = {
route: req.originalUrl,
method: req.method,
timestamp: new Date(),
userAgent: req.get('User-Agent'),
};
// Send telemetry asynchronously (don't block request)
setImmediate(() => {
this.sendTelemetry(telemetryData);
});
next();
}
private async sendTelemetry(data: any): Promise<void> {
try {
// Send telemetry data
} catch (error) {
// Silently fail - don't affect main request
}
}
}
export default Telemetry;
```
## Guard Composition Pattern
### Multiple Guards Usage
```typescript
// In router setup
const guards = [instanceExistsGuard, instanceLoggedGuard, authGuard['apikey']];
router
.use('/instance', new InstanceRouter(configService, ...guards).router)
.use('/message', new MessageRouter(...guards).router)
.use('/chat', new ChatRouter(...guards).router);
```
## Error Handling in Guards
### Proper Exception Throwing
```typescript
// CORRECT - Use proper HTTP exceptions
if (!apiKey) {
throw new UnauthorizedException('API key required');
}
if (instanceExists) {
throw new ForbiddenException('Instance already exists');
}
if (!instanceFound) {
throw new NotFoundException('Instance not found');
}
if (validationFails) {
throw new BadRequestException('Invalid request parameters');
}
// INCORRECT - Don't use generic Error
if (!apiKey) {
throw new Error('API key required'); // ❌ Use specific exceptions
}
```
## Configuration Access in Guards
### Config Service Usage
```typescript
async function configAwareGuard(req: Request, _: Response, next: NextFunction) {
const authConfig = configService.get<Auth>('AUTHENTICATION');
const cacheConfig = configService.get<CacheConf>('CACHE');
const dbConfig = configService.get<Database>('DATABASE');
// Use configuration for guard logic
if (authConfig.API_KEY.KEY === providedKey) {
return next();
}
throw new UnauthorizedException();
}
```
## Database Access in Guards
### Prisma Repository Usage
```typescript
async function databaseGuard(req: Request, _: Response, next: NextFunction) {
try {
const param = req.params as unknown as InstanceDto;
const instance = await prismaRepository.instance.findUnique({
where: { name: param.instanceName },
});
if (!instance) {
throw new NotFoundException('Instance not found');
}
// Additional validation logic
if (instance.status !== 'active') {
throw new ForbiddenException('Instance not active');
}
return next();
} catch (error) {
logger.error('Database guard error:', error);
throw new InternalServerErrorException('Database access failed');
}
}
```
## Cache Integration in Guards
### Cache Service Usage
```typescript
async function cacheAwareGuard(req: Request, _: Response, next: NextFunction) {
const cacheConf = configService.get<CacheConf>('CACHE');
if (cacheConf.REDIS.ENABLED) {
const cached = await cache.get(`guard:${req.params.instanceName}`);
if (cached) {
// Use cached validation result
return next();
}
}
// Perform validation and cache result
const isValid = await performValidation(req.params.instanceName);
if (cacheConf.REDIS.ENABLED) {
await cache.set(`guard:${req.params.instanceName}`, isValid, 300); // 5 min TTL
}
if (isValid) {
return next();
}
throw new UnauthorizedException();
}
```
## Logging in Guards
### Structured Logging
```typescript
const logger = new Logger('GUARD');
async function loggedGuard(req: Request, _: Response, next: NextFunction) {
logger.log(`Guard validation started for ${req.originalUrl}`);
try {
// Guard logic
const isValid = await validateRequest(req);
if (isValid) {
logger.log(`Guard validation successful for ${req.params.instanceName}`);
return next();
}
logger.warn(`Guard validation failed for ${req.params.instanceName}`);
throw new UnauthorizedException();
} catch (error) {
logger.error(`Guard validation error: ${error.message}`, error.stack);
throw error;
}
}
```
## Guard Testing Pattern
### Unit Test Structure
```typescript
describe('authGuard', () => {
let req: Partial<Request>;
let res: Partial<Response>;
let next: NextFunction;
beforeEach(() => {
req = {
get: jest.fn(),
params: {},
originalUrl: '/test',
};
res = {};
next = jest.fn();
});
describe('apikey', () => {
it('should pass with valid global API key', async () => {
(req.get as jest.Mock).mockReturnValue('valid-global-key');
await authGuard.apikey(req as Request, res as Response, next);
expect(next).toHaveBeenCalled();
});
it('should throw UnauthorizedException with no API key', async () => {
(req.get as jest.Mock).mockReturnValue(undefined);
await expect(
authGuard.apikey(req as Request, res as Response, next)
).rejects.toThrow(UnauthorizedException);
});
it('should pass with valid instance token', async () => {
(req.get as jest.Mock).mockReturnValue('instance-token');
req.params = { instanceName: 'test-instance' };
// Mock prisma repository
jest.spyOn(prismaRepository.instance, 'findUnique').mockResolvedValue({
token: 'instance-token',
} as any);
await authGuard.apikey(req as Request, res as Response, next);
expect(next).toHaveBeenCalled();
});
});
});
```
## Guard Performance Considerations
### Efficient Validation
```typescript
// CORRECT - Efficient guard with early returns
async function efficientGuard(req: Request, _: Response, next: NextFunction) {
// Quick checks first
if (req.originalUrl.includes('/public')) {
return next(); // Skip validation for public routes
}
const apiKey = req.get('apikey');
if (!apiKey) {
throw new UnauthorizedException(); // Fail fast
}
// More expensive checks only if needed
if (apiKey === globalKey) {
return next(); // Skip database check
}
// Database check only as last resort
const isValid = await validateInDatabase(apiKey);
if (isValid) {
return next();
}
throw new UnauthorizedException();
}
// INCORRECT - Inefficient guard
async function inefficientGuard(req: Request, _: Response, next: NextFunction) {
// Always do expensive database check first
const dbResult = await expensiveDatabaseQuery(); // ❌ Expensive operation first
const apiKey = req.get('apikey');
if (!apiKey && dbResult) { // ❌ Complex logic
throw new UnauthorizedException();
}
next();
}
```

View File

@ -0,0 +1,552 @@
---
description: Channel integration patterns for Evolution API
globs:
- "src/api/integrations/channel/**/*.ts"
alwaysApply: false
---
# Evolution API Channel Integration Rules
## Channel Controller Pattern
### Base Channel Controller
```typescript
export interface ChannelControllerInterface {
integrationEnabled: boolean;
}
export class ChannelController {
public prismaRepository: PrismaRepository;
public waMonitor: WAMonitoringService;
constructor(prismaRepository: PrismaRepository, waMonitor: WAMonitoringService) {
this.prisma = prismaRepository;
this.monitor = waMonitor;
}
public set prisma(prisma: PrismaRepository) {
this.prismaRepository = prisma;
}
public get prisma() {
return this.prismaRepository;
}
public set monitor(waMonitor: WAMonitoringService) {
this.waMonitor = waMonitor;
}
public get monitor() {
return this.waMonitor;
}
public init(instanceData: InstanceDto, data: ChannelDataType) {
if (!instanceData.token && instanceData.integration === Integration.WHATSAPP_BUSINESS) {
throw new BadRequestException('token is required');
}
if (instanceData.integration === Integration.WHATSAPP_BUSINESS) {
return new BusinessStartupService(/* dependencies */);
}
if (instanceData.integration === Integration.EVOLUTION) {
return new EvolutionStartupService(/* dependencies */);
}
if (instanceData.integration === Integration.WHATSAPP_BAILEYS) {
return new BaileysStartupService(/* dependencies */);
}
return null;
}
}
```
### Extended Channel Controller
```typescript
export class EvolutionController extends ChannelController implements ChannelControllerInterface {
private readonly logger = new Logger('EvolutionController');
constructor(prismaRepository: PrismaRepository, waMonitor: WAMonitoringService) {
super(prismaRepository, waMonitor);
}
integrationEnabled: boolean;
public async receiveWebhook(data: any) {
const numberId = data.numberId;
if (!numberId) {
this.logger.error('WebhookService -> receiveWebhookEvolution -> numberId not found');
return;
}
const instance = await this.prismaRepository.instance.findFirst({
where: { number: numberId },
});
if (!instance) {
this.logger.error('WebhookService -> receiveWebhook -> instance not found');
return;
}
await this.waMonitor.waInstances[instance.name].connectToWhatsapp(data);
return {
status: 'success',
};
}
}
```
## Channel Service Pattern
### Base Channel Service
```typescript
export class ChannelStartupService {
constructor(
private readonly configService: ConfigService,
private readonly eventEmitter: EventEmitter2,
private readonly prismaRepository: PrismaRepository,
public readonly cache: CacheService,
public readonly chatwootCache: CacheService,
) {}
public readonly logger = new Logger('ChannelStartupService');
public client: WASocket;
public readonly instance: wa.Instance = {};
public readonly localChatwoot: wa.LocalChatwoot = {};
public readonly localProxy: wa.LocalProxy = {};
public readonly localSettings: wa.LocalSettings = {};
public readonly localWebhook: wa.LocalWebHook = {};
public setInstance(instance: InstanceDto) {
this.logger.setInstance(instance.instanceName);
this.instance.name = instance.instanceName;
this.instance.id = instance.instanceId;
this.instance.integration = instance.integration;
this.instance.number = instance.number;
this.instance.token = instance.token;
this.instance.businessId = instance.businessId;
if (this.configService.get<Chatwoot>('CHATWOOT').ENABLED && this.localChatwoot?.enabled) {
this.chatwootService.eventWhatsapp(
Events.STATUS_INSTANCE,
{ instanceName: this.instance.name },
{
instance: this.instance.name,
status: 'created',
},
);
}
}
public set instanceName(name: string) {
this.logger.setInstance(name);
this.instance.name = name;
}
public get instanceName() {
return this.instance.name;
}
}
```
### Extended Channel Service
```typescript
export class EvolutionStartupService extends ChannelStartupService {
constructor(
configService: ConfigService,
eventEmitter: EventEmitter2,
prismaRepository: PrismaRepository,
cache: CacheService,
chatwootCache: CacheService,
) {
super(configService, eventEmitter, prismaRepository, cache, chatwootCache);
}
public async sendMessage(data: SendTextDto): Promise<any> {
// Evolution-specific message sending logic
const response = await this.evolutionApiCall('/send-message', data);
return response;
}
public async connectToWhatsapp(data: any): Promise<void> {
// Evolution-specific connection logic
this.logger.log('Connecting to Evolution API');
// Set up webhook listeners
this.setupWebhookHandlers();
// Initialize connection
await this.initializeConnection(data);
}
private async evolutionApiCall(endpoint: string, data: any): Promise<any> {
const config = this.configService.get<Evolution>('EVOLUTION');
try {
const response = await axios.post(`${config.API_URL}${endpoint}`, data, {
headers: {
'Authorization': `Bearer ${this.instance.token}`,
'Content-Type': 'application/json',
},
});
return response.data;
} catch (error) {
this.logger.error(`Evolution API call failed: ${error.message}`);
throw new InternalServerErrorException('Evolution API call failed');
}
}
private setupWebhookHandlers(): void {
// Set up webhook event handlers
}
private async initializeConnection(data: any): Promise<void> {
// Initialize connection with Evolution API
}
}
```
## Business API Service Pattern
### Meta Business Service
```typescript
export class BusinessStartupService extends ChannelStartupService {
constructor(
configService: ConfigService,
eventEmitter: EventEmitter2,
prismaRepository: PrismaRepository,
cache: CacheService,
chatwootCache: CacheService,
baileysCache: CacheService,
providerFiles: ProviderFiles,
) {
super(configService, eventEmitter, prismaRepository, cache, chatwootCache);
}
public async sendMessage(data: SendTextDto): Promise<any> {
const businessConfig = this.configService.get<WaBusiness>('WA_BUSINESS');
const payload = {
messaging_product: 'whatsapp',
to: data.number,
type: 'text',
text: {
body: data.text,
},
};
try {
const response = await axios.post(
`${businessConfig.URL}/${businessConfig.VERSION}/${this.instance.businessId}/messages`,
payload,
{
headers: {
'Authorization': `Bearer ${this.instance.token}`,
'Content-Type': 'application/json',
},
}
);
return response.data;
} catch (error) {
this.logger.error(`Business API call failed: ${error.message}`);
throw new BadRequestException('Failed to send message via Business API');
}
}
public async receiveWebhook(data: any): Promise<void> {
// Process incoming webhook from Meta Business API
const { entry } = data;
for (const entryItem of entry) {
const { changes } = entryItem;
for (const change of changes) {
if (change.field === 'messages') {
await this.processMessage(change.value);
}
}
}
}
private async processMessage(messageData: any): Promise<void> {
// Process incoming message from Business API
const { messages, contacts } = messageData;
if (messages) {
for (const message of messages) {
await this.handleIncomingMessage(message, contacts);
}
}
}
private async handleIncomingMessage(message: any, contacts: any[]): Promise<void> {
// Handle individual message
const contact = contacts?.find(c => c.wa_id === message.from);
// Emit event for message processing
this.eventEmitter.emit(Events.MESSAGES_UPSERT, {
instanceName: this.instance.name,
message,
contact,
});
}
}
```
## Baileys Service Pattern
### Baileys Integration Service
```typescript
export class BaileysStartupService extends ChannelStartupService {
constructor(
configService: ConfigService,
eventEmitter: EventEmitter2,
prismaRepository: PrismaRepository,
cache: CacheService,
chatwootCache: CacheService,
baileysCache: CacheService,
providerFiles: ProviderFiles,
) {
super(configService, eventEmitter, prismaRepository, cache, chatwootCache);
}
public async connectToWhatsapp(): Promise<void> {
const authPath = path.join(INSTANCE_DIR, this.instance.name);
const { state, saveCreds } = await useMultiFileAuthState(authPath);
this.client = makeWASocket({
auth: state,
logger: P({ level: 'error' }),
printQRInTerminal: false,
browser: ['Evolution API', 'Chrome', '4.0.0'],
defaultQueryTimeoutMs: 60000,
});
this.setupEventHandlers();
this.client.ev.on('creds.update', saveCreds);
}
private setupEventHandlers(): void {
this.client.ev.on('connection.update', (update) => {
this.handleConnectionUpdate(update);
});
this.client.ev.on('messages.upsert', ({ messages, type }) => {
this.handleIncomingMessages(messages, type);
});
this.client.ev.on('messages.update', (updates) => {
this.handleMessageUpdates(updates);
});
this.client.ev.on('contacts.upsert', (contacts) => {
this.handleContactsUpdate(contacts);
});
this.client.ev.on('chats.upsert', (chats) => {
this.handleChatsUpdate(chats);
});
}
private async handleConnectionUpdate(update: ConnectionUpdate): Promise<void> {
const { connection, lastDisconnect, qr } = update;
if (qr) {
this.instance.qrcode = {
count: this.instance.qrcode?.count ? this.instance.qrcode.count + 1 : 1,
base64: qr,
};
this.eventEmitter.emit(Events.QRCODE_UPDATED, {
instanceName: this.instance.name,
qrcode: this.instance.qrcode,
});
}
if (connection === 'close') {
const shouldReconnect = (lastDisconnect?.error as Boom)?.output?.statusCode !== DisconnectReason.loggedOut;
if (shouldReconnect) {
this.logger.log('Connection closed, reconnecting...');
await this.connectToWhatsapp();
} else {
this.logger.log('Connection closed, logged out');
this.eventEmitter.emit(Events.LOGOUT_INSTANCE, {
instanceName: this.instance.name,
});
}
}
if (connection === 'open') {
this.logger.log('Connection opened successfully');
this.instance.wuid = this.client.user?.id;
this.eventEmitter.emit(Events.CONNECTION_UPDATE, {
instanceName: this.instance.name,
state: 'open',
});
}
}
public async sendMessage(data: SendTextDto): Promise<any> {
const jid = createJid(data.number);
const message = {
text: data.text,
};
if (data.linkPreview !== undefined) {
message.linkPreview = data.linkPreview;
}
if (data.mentionsEveryOne) {
// Handle mentions
}
try {
const response = await this.client.sendMessage(jid, message);
return response;
} catch (error) {
this.logger.error(`Failed to send message: ${error.message}`);
throw new BadRequestException('Failed to send message');
}
}
}
```
## Channel Router Pattern
### Channel Router Structure
```typescript
export class ChannelRouter {
public readonly router: Router;
constructor(configService: any, ...guards: any[]) {
this.router = Router();
this.router.use('/', new EvolutionRouter(configService).router);
this.router.use('/', new MetaRouter(configService).router);
this.router.use('/baileys', new BaileysRouter(...guards).router);
}
}
```
### Specific Channel Router
```typescript
export class EvolutionRouter extends RouterBroker {
constructor(private readonly configService: ConfigService) {
super();
this.router
.post(this.routerPath('webhook'), async (req, res) => {
const response = await evolutionController.receiveWebhook(req.body);
return res.status(HttpStatus.OK).json(response);
});
}
public readonly router: Router = Router();
}
```
## Integration Types
### Channel Data Types
```typescript
type ChannelDataType = {
configService: ConfigService;
eventEmitter: EventEmitter2;
prismaRepository: PrismaRepository;
cache: CacheService;
chatwootCache: CacheService;
baileysCache: CacheService;
providerFiles: ProviderFiles;
};
export enum Integration {
WHATSAPP_BUSINESS = 'WHATSAPP-BUSINESS',
WHATSAPP_BAILEYS = 'WHATSAPP-BAILEYS',
EVOLUTION = 'EVOLUTION',
}
```
## Error Handling in Channels
### Channel-Specific Error Handling
```typescript
// CORRECT - Channel-specific error handling
public async sendMessage(data: SendTextDto): Promise<any> {
try {
const response = await this.channelSpecificSend(data);
return response;
} catch (error) {
this.logger.error(`${this.constructor.name} send failed: ${error.message}`);
if (error.response?.status === 401) {
throw new UnauthorizedException('Invalid token for channel');
}
if (error.response?.status === 429) {
throw new BadRequestException('Rate limit exceeded');
}
throw new InternalServerErrorException('Channel communication failed');
}
}
```
## Channel Testing Pattern
### Channel Service Testing
```typescript
describe('EvolutionStartupService', () => {
let service: EvolutionStartupService;
let configService: jest.Mocked<ConfigService>;
let eventEmitter: jest.Mocked<EventEmitter2>;
beforeEach(() => {
const mockConfig = {
get: jest.fn().mockReturnValue({
API_URL: 'https://api.evolution.com',
}),
};
service = new EvolutionStartupService(
mockConfig as any,
eventEmitter,
prismaRepository,
cache,
chatwootCache,
);
});
describe('sendMessage', () => {
it('should send message successfully', async () => {
const data = { number: '5511999999999', text: 'Test message' };
// Mock axios response
jest.spyOn(axios, 'post').mockResolvedValue({
data: { success: true, messageId: '123' },
});
const result = await service.sendMessage(data);
expect(result.success).toBe(true);
expect(axios.post).toHaveBeenCalledWith(
expect.stringContaining('/send-message'),
data,
expect.objectContaining({
headers: expect.objectContaining({
'Authorization': expect.stringContaining('Bearer'),
}),
})
);
});
});
});
```

View File

@ -0,0 +1,597 @@
---
description: Chatbot integration patterns for Evolution API
globs:
- "src/api/integrations/chatbot/**/*.ts"
alwaysApply: false
---
# Evolution API Chatbot Integration Rules
## Base Chatbot Pattern
### Base Chatbot DTO
```typescript
/**
* Base DTO for all chatbot integrations
* Contains common properties shared by all chatbot types
*/
export class BaseChatbotDto {
enabled?: boolean;
description: string;
expire?: number;
keywordFinish?: string;
delayMessage?: number;
unknownMessage?: string;
listeningFromMe?: boolean;
stopBotFromMe?: boolean;
keepOpen?: boolean;
debounceTime?: number;
triggerType: TriggerType;
triggerOperator?: TriggerOperator;
triggerValue?: string;
ignoreJids?: string[];
splitMessages?: boolean;
timePerChar?: number;
}
```
### Base Chatbot Controller
```typescript
export abstract class BaseChatbotController<BotType = any, BotData extends BaseChatbotDto = BaseChatbotDto>
extends ChatbotController
implements ChatbotControllerInterface
{
public readonly logger: Logger;
integrationEnabled: boolean;
botRepository: any;
settingsRepository: any;
sessionRepository: any;
userMessageDebounce: { [key: string]: { message: string; timeoutId: NodeJS.Timeout } } = {};
// Abstract methods to be implemented by specific chatbots
protected abstract readonly integrationName: string;
protected abstract processBot(
waInstance: any,
remoteJid: string,
bot: BotType,
session: any,
settings: ChatbotSettings,
content: string,
pushName?: string,
msg?: any,
): Promise<void>;
protected abstract getFallbackBotId(settings: any): string | undefined;
constructor(prismaRepository: PrismaRepository, waMonitor: WAMonitoringService) {
super(prismaRepository, waMonitor);
this.sessionRepository = this.prismaRepository.integrationSession;
}
// Base implementation methods
public async createBot(instance: InstanceDto, data: BotData) {
if (!data.enabled) {
throw new BadRequestException(`${this.integrationName} is disabled`);
}
// Common bot creation logic
const bot = await this.botRepository.create({
data: {
...data,
instanceId: instance.instanceId,
},
});
return bot;
}
}
```
### Base Chatbot Service
```typescript
/**
* Base class for all chatbot service implementations
* Contains common methods shared across different chatbot integrations
*/
export abstract class BaseChatbotService<BotType = any, SettingsType = any> {
protected readonly logger: Logger;
protected readonly waMonitor: WAMonitoringService;
protected readonly prismaRepository: PrismaRepository;
protected readonly configService?: ConfigService;
constructor(
waMonitor: WAMonitoringService,
prismaRepository: PrismaRepository,
loggerName: string,
configService?: ConfigService,
) {
this.waMonitor = waMonitor;
this.prismaRepository = prismaRepository;
this.logger = new Logger(loggerName);
this.configService = configService;
}
/**
* Check if a message contains an image
*/
protected isImageMessage(content: string): boolean {
return content.includes('imageMessage');
}
/**
* Extract text content from message
*/
protected getMessageContent(msg: any): string {
return getConversationMessage(msg);
}
/**
* Send typing indicator
*/
protected async sendTyping(instanceName: string, remoteJid: string): Promise<void> {
await this.waMonitor.waInstances[instanceName].sendPresence(remoteJid, 'composing');
}
}
```
## Typebot Integration Pattern
### Typebot Service
```typescript
export class TypebotService extends BaseChatbotService<TypebotModel, any> {
constructor(
waMonitor: WAMonitoringService,
configService: ConfigService,
prismaRepository: PrismaRepository,
private readonly openaiService: OpenaiService,
) {
super(waMonitor, prismaRepository, 'TypebotService', configService);
}
public async sendTypebotMessage(
instanceName: string,
remoteJid: string,
typebot: TypebotModel,
content: string,
): Promise<void> {
try {
const response = await axios.post(
`${typebot.url}/api/v1/typebots/${typebot.typebot}/startChat`,
{
message: content,
sessionId: `${instanceName}-${remoteJid}`,
},
{
headers: {
'Content-Type': 'application/json',
},
}
);
const { messages } = response.data;
for (const message of messages) {
await this.processTypebotMessage(instanceName, remoteJid, message);
}
} catch (error) {
this.logger.error(`Typebot API error: ${error.message}`);
throw new InternalServerErrorException('Typebot communication failed');
}
}
private async processTypebotMessage(
instanceName: string,
remoteJid: string,
message: any,
): Promise<void> {
const waInstance = this.waMonitor.waInstances[instanceName];
if (message.type === 'text') {
await waInstance.sendMessage({
number: remoteJid.split('@')[0],
text: message.content.richText[0].children[0].text,
});
}
if (message.type === 'image') {
await waInstance.sendMessage({
number: remoteJid.split('@')[0],
mediaMessage: {
mediatype: 'image',
media: message.content.url,
},
});
}
}
}
```
## OpenAI Integration Pattern
### OpenAI Service
```typescript
export class OpenaiService extends BaseChatbotService<OpenaiModel, any> {
constructor(
waMonitor: WAMonitoringService,
prismaRepository: PrismaRepository,
configService: ConfigService,
) {
super(waMonitor, prismaRepository, 'OpenaiService', configService);
}
public async sendOpenaiMessage(
instanceName: string,
remoteJid: string,
openai: OpenaiModel,
content: string,
pushName?: string,
): Promise<void> {
try {
const openaiConfig = this.configService.get<Openai>('OPENAI');
const response = await axios.post(
'https://api.openai.com/v1/chat/completions',
{
model: openai.model || 'gpt-3.5-turbo',
messages: [
{
role: 'system',
content: openai.systemMessage || 'You are a helpful assistant.',
},
{
role: 'user',
content: content,
},
],
max_tokens: openai.maxTokens || 1000,
temperature: openai.temperature || 0.7,
},
{
headers: {
'Authorization': `Bearer ${openai.apiKey || openaiConfig.API_KEY}`,
'Content-Type': 'application/json',
},
}
);
const aiResponse = response.data.choices[0].message.content;
await this.waMonitor.waInstances[instanceName].sendMessage({
number: remoteJid.split('@')[0],
text: aiResponse,
});
} catch (error) {
this.logger.error(`OpenAI API error: ${error.message}`);
// Send fallback message
await this.waMonitor.waInstances[instanceName].sendMessage({
number: remoteJid.split('@')[0],
text: openai.unknownMessage || 'Desculpe, não consegui processar sua mensagem.',
});
}
}
}
```
## Chatwoot Integration Pattern
### Chatwoot Service
```typescript
export class ChatwootService extends BaseChatbotService<any, any> {
constructor(
waMonitor: WAMonitoringService,
configService: ConfigService,
prismaRepository: PrismaRepository,
private readonly chatwootCache: CacheService,
) {
super(waMonitor, prismaRepository, 'ChatwootService', configService);
}
public async eventWhatsapp(
event: Events,
instanceName: { instanceName: string },
data: any,
): Promise<void> {
const chatwootConfig = this.configService.get<Chatwoot>('CHATWOOT');
if (!chatwootConfig.ENABLED) {
return;
}
try {
const instance = await this.prismaRepository.instance.findUnique({
where: { name: instanceName.instanceName },
});
if (!instance?.chatwootAccountId) {
return;
}
const webhook = {
event,
instance: instanceName.instanceName,
data,
timestamp: new Date().toISOString(),
};
await axios.post(
`${instance.chatwootUrl}/api/v1/accounts/${instance.chatwootAccountId}/webhooks`,
webhook,
{
headers: {
'Authorization': `Bearer ${instance.chatwootToken}`,
'Content-Type': 'application/json',
},
}
);
} catch (error) {
this.logger.error(`Chatwoot webhook error: ${error.message}`);
}
}
public async createConversation(
instanceName: string,
contact: any,
message: any,
): Promise<void> {
// Create conversation in Chatwoot
const instance = await this.prismaRepository.instance.findUnique({
where: { name: instanceName },
});
if (!instance?.chatwootAccountId) {
return;
}
try {
const conversation = await axios.post(
`${instance.chatwootUrl}/api/v1/accounts/${instance.chatwootAccountId}/conversations`,
{
source_id: contact.id,
inbox_id: instance.chatwootInboxId,
contact_id: contact.chatwootContactId,
},
{
headers: {
'Authorization': `Bearer ${instance.chatwootToken}`,
'Content-Type': 'application/json',
},
}
);
// Cache conversation
await this.chatwootCache.set(
`conversation:${instanceName}:${contact.id}`,
conversation.data,
3600
);
} catch (error) {
this.logger.error(`Chatwoot conversation creation error: ${error.message}`);
}
}
}
```
## Dify Integration Pattern
### Dify Service
```typescript
export class DifyService extends BaseChatbotService<DifyModel, any> {
constructor(
waMonitor: WAMonitoringService,
prismaRepository: PrismaRepository,
configService: ConfigService,
private readonly openaiService: OpenaiService,
) {
super(waMonitor, prismaRepository, 'DifyService', configService);
}
public async sendDifyMessage(
instanceName: string,
remoteJid: string,
dify: DifyModel,
content: string,
): Promise<void> {
try {
const response = await axios.post(
`${dify.apiUrl}/v1/chat-messages`,
{
inputs: {},
query: content,
user: remoteJid,
conversation_id: `${instanceName}-${remoteJid}`,
response_mode: 'blocking',
},
{
headers: {
'Authorization': `Bearer ${dify.apiKey}`,
'Content-Type': 'application/json',
},
}
);
const aiResponse = response.data.answer;
await this.waMonitor.waInstances[instanceName].sendMessage({
number: remoteJid.split('@')[0],
text: aiResponse,
});
} catch (error) {
this.logger.error(`Dify API error: ${error.message}`);
// Fallback to OpenAI if configured
if (dify.fallbackOpenai && this.openaiService) {
await this.openaiService.sendOpenaiMessage(instanceName, remoteJid, dify.openaiBot, content);
}
}
}
}
```
## Chatbot Router Pattern
### Chatbot Router Structure (Evolution API Real Pattern)
```typescript
export class ChatbotRouter {
public readonly router: Router;
constructor(...guards: any[]) {
this.router = Router();
// Real Evolution API chatbot integrations
this.router.use('/evolutionBot', new EvolutionBotRouter(...guards).router);
this.router.use('/chatwoot', new ChatwootRouter(...guards).router);
this.router.use('/typebot', new TypebotRouter(...guards).router);
this.router.use('/openai', new OpenaiRouter(...guards).router);
this.router.use('/dify', new DifyRouter(...guards).router);
this.router.use('/flowise', new FlowiseRouter(...guards).router);
this.router.use('/n8n', new N8nRouter(...guards).router);
this.router.use('/evoai', new EvoaiRouter(...guards).router);
}
}
```
## Chatbot Validation Patterns
### Chatbot Schema Validation (Evolution API Pattern)
```typescript
import { JSONSchema7 } from 'json-schema';
import { v4 } from 'uuid';
const isNotEmpty = (...fields: string[]) => {
const properties = {};
fields.forEach((field) => {
properties[field] = {
if: { properties: { [field]: { type: 'string' } } },
then: { properties: { [field]: { minLength: 1 } } },
};
});
return {
allOf: Object.values(properties),
};
};
export const evolutionBotSchema: JSONSchema7 = {
$id: v4(),
type: 'object',
properties: {
enabled: { type: 'boolean' },
description: { type: 'string' },
apiUrl: { type: 'string' },
apiKey: { type: 'string' },
triggerType: { type: 'string', enum: ['all', 'keyword', 'none', 'advanced'] },
triggerOperator: { type: 'string', enum: ['equals', 'contains', 'startsWith', 'endsWith', 'regex'] },
triggerValue: { type: 'string' },
expire: { type: 'integer' },
keywordFinish: { type: 'string' },
delayMessage: { type: 'integer' },
unknownMessage: { type: 'string' },
listeningFromMe: { type: 'boolean' },
stopBotFromMe: { type: 'boolean' },
keepOpen: { type: 'boolean' },
debounceTime: { type: 'integer' },
ignoreJids: { type: 'array', items: { type: 'string' } },
splitMessages: { type: 'boolean' },
timePerChar: { type: 'integer' },
},
required: ['enabled', 'apiUrl', 'triggerType'],
...isNotEmpty('enabled', 'apiUrl', 'triggerType'),
};
function validateKeywordTrigger(
content: string,
operator: TriggerOperator,
value: string,
): boolean {
const normalizedContent = content.toLowerCase().trim();
const normalizedValue = value.toLowerCase().trim();
switch (operator) {
case TriggerOperator.EQUALS:
return normalizedContent === normalizedValue;
case TriggerOperator.CONTAINS:
return normalizedContent.includes(normalizedValue);
case TriggerOperator.STARTS_WITH:
return normalizedContent.startsWith(normalizedValue);
case TriggerOperator.ENDS_WITH:
return normalizedContent.endsWith(normalizedValue);
default:
return false;
}
}
```
## Session Management Pattern
### Chatbot Session Handling
```typescript
export class ChatbotSessionManager {
constructor(
private readonly prismaRepository: PrismaRepository,
private readonly cache: CacheService,
) {}
public async getSession(
instanceName: string,
remoteJid: string,
botId: string,
): Promise<IntegrationSession | null> {
const cacheKey = `session:${instanceName}:${remoteJid}:${botId}`;
// Try cache first
let session = await this.cache.get(cacheKey);
if (session) {
return session;
}
// Query database
session = await this.prismaRepository.integrationSession.findFirst({
where: {
instanceId: instanceName,
remoteJid,
botId,
status: 'opened',
},
});
// Cache result
if (session) {
await this.cache.set(cacheKey, session, 300); // 5 min TTL
}
return session;
}
public async createSession(
instanceName: string,
remoteJid: string,
botId: string,
): Promise<IntegrationSession> {
const session = await this.prismaRepository.integrationSession.create({
data: {
instanceId: instanceName,
remoteJid,
botId,
status: 'opened',
createdAt: new Date(),
},
});
// Cache new session
const cacheKey = `session:${instanceName}:${remoteJid}:${botId}`;
await this.cache.set(cacheKey, session, 300);
return session;
}
public async closeSession(sessionId: string): Promise<void> {
await this.prismaRepository.integrationSession.update({
where: { id: sessionId },
data: { status: 'closed', updatedAt: new Date() },
});
// Invalidate cache
// Note: In a real implementation, you'd need to track cache keys by session ID
}
}
```

View File

@ -0,0 +1,851 @@
---
description: Event integration patterns for Evolution API
globs:
- "src/api/integrations/event/**/*.ts"
alwaysApply: false
---
# Evolution API Event Integration Rules
## Event Manager Pattern
### Event Manager Structure
```typescript
import { PrismaRepository } from '@api/repository/repository.service';
import { ConfigService } from '@config/env.config';
import { Logger } from '@config/logger.config';
import { Server } from 'http';
export class EventManager {
private prismaRepository: PrismaRepository;
private configService: ConfigService;
private logger = new Logger('EventManager');
// Event integrations
private webhook: WebhookController;
private websocket: WebsocketController;
private rabbitmq: RabbitmqController;
private nats: NatsController;
private sqs: SqsController;
private pusher: PusherController;
constructor(
prismaRepository: PrismaRepository,
configService: ConfigService,
server?: Server,
) {
this.prismaRepository = prismaRepository;
this.configService = configService;
// Initialize event controllers
this.webhook = new WebhookController(prismaRepository, configService);
this.websocket = new WebsocketController(prismaRepository, configService, server);
this.rabbitmq = new RabbitmqController(prismaRepository, configService);
this.nats = new NatsController(prismaRepository, configService);
this.sqs = new SqsController(prismaRepository, configService);
this.pusher = new PusherController(prismaRepository, configService);
}
public async emit(eventData: {
instanceName: string;
origin: string;
event: string;
data: Object;
serverUrl: string;
dateTime: string;
sender: string;
apiKey?: string;
local?: boolean;
integration?: string[];
}): Promise<void> {
this.logger.log(`Emitting event ${eventData.event} for instance ${eventData.instanceName}`);
// Emit to all configured integrations
await Promise.allSettled([
this.webhook.emit(eventData),
this.websocket.emit(eventData),
this.rabbitmq.emit(eventData),
this.nats.emit(eventData),
this.sqs.emit(eventData),
this.pusher.emit(eventData),
]);
}
public async setInstance(instanceName: string, data: any): Promise<any> {
const promises = [];
if (data.websocket) {
promises.push(
this.websocket.set(instanceName, {
websocket: {
enabled: true,
events: data.websocket?.events,
},
})
);
}
if (data.rabbitmq) {
promises.push(
this.rabbitmq.set(instanceName, {
rabbitmq: {
enabled: true,
events: data.rabbitmq?.events,
},
})
);
}
if (data.webhook) {
promises.push(
this.webhook.set(instanceName, {
webhook: {
enabled: true,
events: data.webhook?.events,
url: data.webhook?.url,
headers: data.webhook?.headers,
base64: data.webhook?.base64,
byEvents: data.webhook?.byEvents,
},
})
);
}
// Set other integrations...
await Promise.allSettled(promises);
}
}
```
## Base Event Controller Pattern
### Abstract Event Controller
```typescript
import { PrismaRepository } from '@api/repository/repository.service';
import { ConfigService } from '@config/env.config';
import { Logger } from '@config/logger.config';
export type EmitData = {
instanceName: string;
origin: string;
event: string;
data: Object;
serverUrl: string;
dateTime: string;
sender: string;
apiKey?: string;
local?: boolean;
integration?: string[];
};
export interface EventControllerInterface {
integrationEnabled: boolean;
emit(data: EmitData): Promise<void>;
set(instanceName: string, data: any): Promise<any>;
}
export abstract class EventController implements EventControllerInterface {
protected readonly logger: Logger;
protected readonly prismaRepository: PrismaRepository;
protected readonly configService: ConfigService;
public integrationEnabled: boolean = false;
// Available events for all integrations
public static readonly events = [
'APPLICATION_STARTUP',
'INSTANCE_CREATE',
'INSTANCE_DELETE',
'QRCODE_UPDATED',
'CONNECTION_UPDATE',
'STATUS_INSTANCE',
'MESSAGES_SET',
'MESSAGES_UPSERT',
'MESSAGES_EDITED',
'MESSAGES_UPDATE',
'MESSAGES_DELETE',
'SEND_MESSAGE',
'CONTACTS_SET',
'CONTACTS_UPSERT',
'CONTACTS_UPDATE',
'PRESENCE_UPDATE',
'CHATS_SET',
'CHATS_UPDATE',
'CHATS_UPSERT',
'CHATS_DELETE',
'GROUPS_UPSERT',
'GROUPS_UPDATE',
'GROUP_PARTICIPANTS_UPDATE',
'CALL',
'TYPEBOT_START',
'TYPEBOT_CHANGE_STATUS',
'LABELS_EDIT',
'LABELS_ASSOCIATION',
'CREDS_UPDATE',
'MESSAGING_HISTORY_SET',
'REMOVE_INSTANCE',
'LOGOUT_INSTANCE',
];
constructor(
prismaRepository: PrismaRepository,
configService: ConfigService,
loggerName: string,
) {
this.prismaRepository = prismaRepository;
this.configService = configService;
this.logger = new Logger(loggerName);
}
// Abstract methods to be implemented by specific integrations
public abstract emit(data: EmitData): Promise<void>;
public abstract set(instanceName: string, data: any): Promise<any>;
// Helper method to check if event should be processed
protected shouldProcessEvent(eventName: string, configuredEvents?: string[]): boolean {
if (!configuredEvents || configuredEvents.length === 0) {
return true; // Process all events if none specified
}
return configuredEvents.includes(eventName);
}
// Helper method to get instance configuration
protected async getInstanceConfig(instanceName: string): Promise<any> {
try {
const instance = await this.prismaRepository.instance.findUnique({
where: { name: instanceName },
});
return instance;
} catch (error) {
this.logger.error(`Failed to get instance config for ${instanceName}:`, error);
return null;
}
}
}
```
## Webhook Integration Pattern
### Webhook Controller Implementation
```typescript
export class WebhookController extends EventController {
constructor(
prismaRepository: PrismaRepository,
configService: ConfigService,
) {
super(prismaRepository, configService, 'WebhookController');
}
public async emit(data: EmitData): Promise<void> {
try {
const instance = await this.getInstanceConfig(data.instanceName);
if (!instance?.webhook?.enabled) {
return;
}
const webhookConfig = instance.webhook;
if (!this.shouldProcessEvent(data.event, webhookConfig.events)) {
return;
}
const payload = {
event: data.event,
instance: data.instanceName,
data: data.data,
timestamp: data.dateTime,
sender: data.sender,
server: {
version: process.env.npm_package_version,
url: data.serverUrl,
},
};
// Encode data as base64 if configured
if (webhookConfig.base64) {
payload.data = Buffer.from(JSON.stringify(payload.data)).toString('base64');
}
const headers = {
'Content-Type': 'application/json',
'User-Agent': 'Evolution-API-Webhook',
...webhookConfig.headers,
};
if (webhookConfig.byEvents) {
// Send to event-specific endpoint
const eventUrl = `${webhookConfig.url}/${data.event.toLowerCase()}`;
await this.sendWebhook(eventUrl, payload, headers);
} else {
// Send to main webhook URL
await this.sendWebhook(webhookConfig.url, payload, headers);
}
this.logger.log(`Webhook sent for event ${data.event} to instance ${data.instanceName}`);
} catch (error) {
this.logger.error(`Webhook emission failed for ${data.instanceName}:`, error);
}
}
public async set(instanceName: string, data: any): Promise<any> {
try {
const webhookData = data.webhook;
await this.prismaRepository.instance.update({
where: { name: instanceName },
data: {
webhook: webhookData,
},
});
this.logger.log(`Webhook configuration set for instance ${instanceName}`);
return { webhook: webhookData };
} catch (error) {
this.logger.error(`Failed to set webhook config for ${instanceName}:`, error);
throw error;
}
}
private async sendWebhook(url: string, payload: any, headers: any): Promise<void> {
try {
const response = await axios.post(url, payload, {
headers,
timeout: 30000,
maxRedirects: 3,
});
if (response.status >= 200 && response.status < 300) {
this.logger.log(`Webhook delivered successfully to ${url}`);
} else {
this.logger.warn(`Webhook returned status ${response.status} for ${url}`);
}
} catch (error) {
this.logger.error(`Webhook delivery failed to ${url}:`, error.message);
// Implement retry logic here if needed
if (error.response?.status >= 500) {
// Server error - might be worth retrying
this.logger.log(`Server error detected, webhook might be retried later`);
}
}
}
}
```
## WebSocket Integration Pattern
### WebSocket Controller Implementation
```typescript
import { Server as SocketIOServer } from 'socket.io';
import { Server } from 'http';
export class WebsocketController extends EventController {
private io: SocketIOServer;
constructor(
prismaRepository: PrismaRepository,
configService: ConfigService,
server?: Server,
) {
super(prismaRepository, configService, 'WebsocketController');
if (server) {
this.io = new SocketIOServer(server, {
cors: {
origin: "*",
methods: ["GET", "POST"],
},
});
this.setupSocketHandlers();
}
}
private setupSocketHandlers(): void {
this.io.on('connection', (socket) => {
this.logger.log(`WebSocket client connected: ${socket.id}`);
socket.on('join-instance', (instanceName: string) => {
socket.join(`instance:${instanceName}`);
this.logger.log(`Client ${socket.id} joined instance ${instanceName}`);
});
socket.on('leave-instance', (instanceName: string) => {
socket.leave(`instance:${instanceName}`);
this.logger.log(`Client ${socket.id} left instance ${instanceName}`);
});
socket.on('disconnect', () => {
this.logger.log(`WebSocket client disconnected: ${socket.id}`);
});
});
}
public async emit(data: EmitData): Promise<void> {
if (!this.io) {
return;
}
try {
const instance = await this.getInstanceConfig(data.instanceName);
if (!instance?.websocket?.enabled) {
return;
}
const websocketConfig = instance.websocket;
if (!this.shouldProcessEvent(data.event, websocketConfig.events)) {
return;
}
const payload = {
event: data.event,
instance: data.instanceName,
data: data.data,
timestamp: data.dateTime,
sender: data.sender,
};
// Emit to specific instance room
this.io.to(`instance:${data.instanceName}`).emit('evolution-event', payload);
// Also emit to global room for monitoring
this.io.emit('global-event', payload);
this.logger.log(`WebSocket event ${data.event} emitted for instance ${data.instanceName}`);
} catch (error) {
this.logger.error(`WebSocket emission failed for ${data.instanceName}:`, error);
}
}
public async set(instanceName: string, data: any): Promise<any> {
try {
const websocketData = data.websocket;
await this.prismaRepository.instance.update({
where: { name: instanceName },
data: {
websocket: websocketData,
},
});
this.logger.log(`WebSocket configuration set for instance ${instanceName}`);
return { websocket: websocketData };
} catch (error) {
this.logger.error(`Failed to set WebSocket config for ${instanceName}:`, error);
throw error;
}
}
}
```
## Queue Integration Patterns
### RabbitMQ Controller Implementation
```typescript
import amqp from 'amqplib';
export class RabbitmqController extends EventController {
private connection: amqp.Connection | null = null;
private channel: amqp.Channel | null = null;
constructor(
prismaRepository: PrismaRepository,
configService: ConfigService,
) {
super(prismaRepository, configService, 'RabbitmqController');
this.initializeConnection();
}
private async initializeConnection(): Promise<void> {
try {
const rabbitmqConfig = this.configService.get('RABBITMQ');
if (!rabbitmqConfig?.ENABLED) {
return;
}
this.connection = await amqp.connect(rabbitmqConfig.URI);
this.channel = await this.connection.createChannel();
// Declare exchange for Evolution API events
await this.channel.assertExchange('evolution-events', 'topic', { durable: true });
this.logger.log('RabbitMQ connection established');
} catch (error) {
this.logger.error('Failed to initialize RabbitMQ connection:', error);
}
}
public async emit(data: EmitData): Promise<void> {
if (!this.channel) {
return;
}
try {
const instance = await this.getInstanceConfig(data.instanceName);
if (!instance?.rabbitmq?.enabled) {
return;
}
const rabbitmqConfig = instance.rabbitmq;
if (!this.shouldProcessEvent(data.event, rabbitmqConfig.events)) {
return;
}
const payload = {
event: data.event,
instance: data.instanceName,
data: data.data,
timestamp: data.dateTime,
sender: data.sender,
};
const routingKey = `evolution.${data.instanceName}.${data.event.toLowerCase()}`;
await this.channel.publish(
'evolution-events',
routingKey,
Buffer.from(JSON.stringify(payload)),
{
persistent: true,
timestamp: Date.now(),
messageId: `${data.instanceName}-${Date.now()}`,
}
);
this.logger.log(`RabbitMQ message published for event ${data.event} to instance ${data.instanceName}`);
} catch (error) {
this.logger.error(`RabbitMQ emission failed for ${data.instanceName}:`, error);
}
}
public async set(instanceName: string, data: any): Promise<any> {
try {
const rabbitmqData = data.rabbitmq;
await this.prismaRepository.instance.update({
where: { name: instanceName },
data: {
rabbitmq: rabbitmqData,
},
});
this.logger.log(`RabbitMQ configuration set for instance ${instanceName}`);
return { rabbitmq: rabbitmqData };
} catch (error) {
this.logger.error(`Failed to set RabbitMQ config for ${instanceName}:`, error);
throw error;
}
}
}
```
### SQS Controller Implementation
```typescript
import { SQSClient, SendMessageCommand } from '@aws-sdk/client-sqs';
export class SqsController extends EventController {
private sqsClient: SQSClient | null = null;
constructor(
prismaRepository: PrismaRepository,
configService: ConfigService,
) {
super(prismaRepository, configService, 'SqsController');
this.initializeSQSClient();
}
private initializeSQSClient(): void {
try {
const sqsConfig = this.configService.get('SQS');
if (!sqsConfig?.ENABLED) {
return;
}
this.sqsClient = new SQSClient({
region: sqsConfig.REGION,
credentials: {
accessKeyId: sqsConfig.ACCESS_KEY_ID,
secretAccessKey: sqsConfig.SECRET_ACCESS_KEY,
},
});
this.logger.log('SQS client initialized');
} catch (error) {
this.logger.error('Failed to initialize SQS client:', error);
}
}
public async emit(data: EmitData): Promise<void> {
if (!this.sqsClient) {
return;
}
try {
const instance = await this.getInstanceConfig(data.instanceName);
if (!instance?.sqs?.enabled) {
return;
}
const sqsConfig = instance.sqs;
if (!this.shouldProcessEvent(data.event, sqsConfig.events)) {
return;
}
const payload = {
event: data.event,
instance: data.instanceName,
data: data.data,
timestamp: data.dateTime,
sender: data.sender,
};
const command = new SendMessageCommand({
QueueUrl: sqsConfig.queueUrl,
MessageBody: JSON.stringify(payload),
MessageAttributes: {
event: {
DataType: 'String',
StringValue: data.event,
},
instance: {
DataType: 'String',
StringValue: data.instanceName,
},
},
MessageGroupId: data.instanceName, // For FIFO queues
MessageDeduplicationId: `${data.instanceName}-${Date.now()}`, // For FIFO queues
});
await this.sqsClient.send(command);
this.logger.log(`SQS message sent for event ${data.event} to instance ${data.instanceName}`);
} catch (error) {
this.logger.error(`SQS emission failed for ${data.instanceName}:`, error);
}
}
public async set(instanceName: string, data: any): Promise<any> {
try {
const sqsData = data.sqs;
await this.prismaRepository.instance.update({
where: { name: instanceName },
data: {
sqs: sqsData,
},
});
this.logger.log(`SQS configuration set for instance ${instanceName}`);
return { sqs: sqsData };
} catch (error) {
this.logger.error(`Failed to set SQS config for ${instanceName}:`, error);
throw error;
}
}
}
```
## Event DTO Pattern
### Event Configuration DTO
```typescript
import { JsonValue } from '@prisma/client/runtime/library';
export class EventDto {
webhook?: {
enabled?: boolean;
events?: string[];
url?: string;
headers?: JsonValue;
byEvents?: boolean;
base64?: boolean;
};
websocket?: {
enabled?: boolean;
events?: string[];
};
sqs?: {
enabled?: boolean;
events?: string[];
queueUrl?: string;
};
rabbitmq?: {
enabled?: boolean;
events?: string[];
exchange?: string;
};
nats?: {
enabled?: boolean;
events?: string[];
subject?: string;
};
pusher?: {
enabled?: boolean;
appId?: string;
key?: string;
secret?: string;
cluster?: string;
useTLS?: boolean;
events?: string[];
};
}
```
## Event Router Pattern
### Event Router Structure
```typescript
import { NatsRouter } from '@api/integrations/event/nats/nats.router';
import { PusherRouter } from '@api/integrations/event/pusher/pusher.router';
import { RabbitmqRouter } from '@api/integrations/event/rabbitmq/rabbitmq.router';
import { SqsRouter } from '@api/integrations/event/sqs/sqs.router';
import { WebhookRouter } from '@api/integrations/event/webhook/webhook.router';
import { WebsocketRouter } from '@api/integrations/event/websocket/websocket.router';
import { Router } from 'express';
export class EventRouter {
public readonly router: Router;
constructor(configService: any, ...guards: any[]) {
this.router = Router();
this.router.use('/webhook', new WebhookRouter(configService, ...guards).router);
this.router.use('/websocket', new WebsocketRouter(...guards).router);
this.router.use('/rabbitmq', new RabbitmqRouter(...guards).router);
this.router.use('/nats', new NatsRouter(...guards).router);
this.router.use('/pusher', new PusherRouter(...guards).router);
this.router.use('/sqs', new SqsRouter(...guards).router);
}
}
```
## Event Validation Schema
### Event Configuration Validation
```typescript
import Joi from 'joi';
import { EventController } from '@api/integrations/event/event.controller';
const eventListSchema = Joi.array().items(
Joi.string().valid(...EventController.events)
).optional();
export const webhookSchema = Joi.object({
enabled: Joi.boolean().required(),
url: Joi.string().when('enabled', {
is: true,
then: Joi.required().uri({ scheme: ['http', 'https'] }),
otherwise: Joi.optional(),
}),
events: eventListSchema,
headers: Joi.object().pattern(Joi.string(), Joi.string()).optional(),
byEvents: Joi.boolean().optional().default(false),
base64: Joi.boolean().optional().default(false),
}).required();
export const websocketSchema = Joi.object({
enabled: Joi.boolean().required(),
events: eventListSchema,
}).required();
export const rabbitmqSchema = Joi.object({
enabled: Joi.boolean().required(),
events: eventListSchema,
exchange: Joi.string().optional().default('evolution-events'),
}).required();
export const sqsSchema = Joi.object({
enabled: Joi.boolean().required(),
events: eventListSchema,
queueUrl: Joi.string().when('enabled', {
is: true,
then: Joi.required().uri(),
otherwise: Joi.optional(),
}),
}).required();
export const eventSchema = Joi.object({
webhook: webhookSchema.optional(),
websocket: websocketSchema.optional(),
rabbitmq: rabbitmqSchema.optional(),
sqs: sqsSchema.optional(),
nats: Joi.object({
enabled: Joi.boolean().required(),
events: eventListSchema,
subject: Joi.string().optional().default('evolution.events'),
}).optional(),
pusher: Joi.object({
enabled: Joi.boolean().required(),
appId: Joi.string().when('enabled', { is: true, then: Joi.required() }),
key: Joi.string().when('enabled', { is: true, then: Joi.required() }),
secret: Joi.string().when('enabled', { is: true, then: Joi.required() }),
cluster: Joi.string().when('enabled', { is: true, then: Joi.required() }),
useTLS: Joi.boolean().optional().default(true),
events: eventListSchema,
}).optional(),
}).min(1).required();
```
## Event Testing Pattern
### Event Controller Testing
```typescript
describe('WebhookController', () => {
let controller: WebhookController;
let prismaRepository: jest.Mocked<PrismaRepository>;
let configService: jest.Mocked<ConfigService>;
beforeEach(() => {
controller = new WebhookController(prismaRepository, configService);
});
describe('emit', () => {
it('should send webhook when enabled', async () => {
const mockInstance = {
webhook: {
enabled: true,
url: 'https://example.com/webhook',
events: ['MESSAGES_UPSERT'],
},
};
prismaRepository.instance.findUnique.mockResolvedValue(mockInstance);
jest.spyOn(axios, 'post').mockResolvedValue({ status: 200 });
const eventData = {
instanceName: 'test-instance',
event: 'MESSAGES_UPSERT',
data: { message: 'test' },
origin: 'test',
serverUrl: 'http://localhost',
dateTime: new Date().toISOString(),
sender: 'test',
};
await controller.emit(eventData);
expect(axios.post).toHaveBeenCalledWith(
'https://example.com/webhook',
expect.objectContaining({
event: 'MESSAGES_UPSERT',
instance: 'test-instance',
}),
expect.objectContaining({
headers: expect.objectContaining({
'Content-Type': 'application/json',
}),
})
);
});
});
});
```

View File

@ -0,0 +1,608 @@
---
description: Storage integration patterns for Evolution API
globs:
- "src/api/integrations/storage/**/*.ts"
alwaysApply: false
---
# Evolution API Storage Integration Rules
## Storage Service Pattern
### Base Storage Service Structure
```typescript
import { InstanceDto } from '@api/dto/instance.dto';
import { PrismaRepository } from '@api/repository/repository.service';
import { Logger } from '@config/logger.config';
import { BadRequestException } from '@exceptions';
export class StorageService {
constructor(private readonly prismaRepository: PrismaRepository) {}
private readonly logger = new Logger('StorageService');
public async getMedia(instance: InstanceDto, query?: MediaDto) {
try {
const where: any = {
instanceId: instance.instanceId,
...query,
};
const media = await this.prismaRepository.media.findMany({
where,
select: {
id: true,
fileName: true,
type: true,
mimetype: true,
createdAt: true,
Message: true,
},
});
if (!media || media.length === 0) {
throw 'Media not found';
}
return media;
} catch (error) {
throw new BadRequestException(error);
}
}
public async getMediaUrl(instance: InstanceDto, data: MediaDto) {
const media = (await this.getMedia(instance, { id: data.id }))[0];
const mediaUrl = await this.generateUrl(media.fileName, data.expiry);
return {
mediaUrl,
...media,
};
}
protected abstract generateUrl(fileName: string, expiry?: number): Promise<string>;
}
```
## S3/MinIO Integration Pattern
### MinIO Client Setup
```typescript
import { ConfigService, S3 } from '@config/env.config';
import { Logger } from '@config/logger.config';
import { BadRequestException } from '@exceptions';
import * as MinIo from 'minio';
import { join } from 'path';
import { Readable, Transform } from 'stream';
const logger = new Logger('S3 Service');
const BUCKET = new ConfigService().get<S3>('S3');
interface Metadata extends MinIo.ItemBucketMetadata {
instanceId: string;
messageId?: string;
}
const minioClient = (() => {
if (BUCKET?.ENABLE) {
return new MinIo.Client({
endPoint: BUCKET.ENDPOINT,
port: BUCKET.PORT,
useSSL: BUCKET.USE_SSL,
accessKey: BUCKET.ACCESS_KEY,
secretKey: BUCKET.SECRET_KEY,
region: BUCKET.REGION,
});
}
})();
const bucketName = process.env.S3_BUCKET;
```
### Bucket Management Functions
```typescript
const bucketExists = async (): Promise<boolean> => {
if (minioClient) {
try {
const list = await minioClient.listBuckets();
return !!list.find((bucket) => bucket.name === bucketName);
} catch (error) {
logger.error('Error checking bucket existence:', error);
return false;
}
}
return false;
};
const setBucketPolicy = async (): Promise<void> => {
if (minioClient && bucketName) {
try {
const policy = {
Version: '2012-10-17',
Statement: [
{
Effect: 'Allow',
Principal: { AWS: ['*'] },
Action: ['s3:GetObject'],
Resource: [`arn:aws:s3:::${bucketName}/*`],
},
],
};
await minioClient.setBucketPolicy(bucketName, JSON.stringify(policy));
logger.log('Bucket policy set successfully');
} catch (error) {
logger.error('Error setting bucket policy:', error);
}
}
};
const createBucket = async (): Promise<void> => {
if (minioClient && bucketName) {
try {
const exists = await bucketExists();
if (!exists) {
await minioClient.makeBucket(bucketName, BUCKET.REGION || 'us-east-1');
await setBucketPolicy();
logger.log(`Bucket ${bucketName} created successfully`);
}
} catch (error) {
logger.error('Error creating bucket:', error);
}
}
};
```
### File Upload Functions
```typescript
export const uploadFile = async (
fileName: string,
buffer: Buffer,
mimetype: string,
metadata?: Metadata,
): Promise<string> => {
if (!minioClient || !bucketName) {
throw new BadRequestException('S3 storage not configured');
}
try {
await createBucket();
const uploadMetadata = {
'Content-Type': mimetype,
...metadata,
};
await minioClient.putObject(bucketName, fileName, buffer, buffer.length, uploadMetadata);
logger.log(`File ${fileName} uploaded successfully`);
return fileName;
} catch (error) {
logger.error(`Error uploading file ${fileName}:`, error);
throw new BadRequestException(`Failed to upload file: ${error.message}`);
}
};
export const uploadStream = async (
fileName: string,
stream: Readable,
size: number,
mimetype: string,
metadata?: Metadata,
): Promise<string> => {
if (!minioClient || !bucketName) {
throw new BadRequestException('S3 storage not configured');
}
try {
await createBucket();
const uploadMetadata = {
'Content-Type': mimetype,
...metadata,
};
await minioClient.putObject(bucketName, fileName, stream, size, uploadMetadata);
logger.log(`Stream ${fileName} uploaded successfully`);
return fileName;
} catch (error) {
logger.error(`Error uploading stream ${fileName}:`, error);
throw new BadRequestException(`Failed to upload stream: ${error.message}`);
}
};
```
### File Download Functions
```typescript
export const getObject = async (fileName: string): Promise<Buffer> => {
if (!minioClient || !bucketName) {
throw new BadRequestException('S3 storage not configured');
}
try {
const stream = await minioClient.getObject(bucketName, fileName);
const chunks: Buffer[] = [];
return new Promise((resolve, reject) => {
stream.on('data', (chunk) => chunks.push(chunk));
stream.on('end', () => resolve(Buffer.concat(chunks)));
stream.on('error', reject);
});
} catch (error) {
logger.error(`Error getting object ${fileName}:`, error);
throw new BadRequestException(`Failed to get object: ${error.message}`);
}
};
export const getObjectUrl = async (fileName: string, expiry: number = 3600): Promise<string> => {
if (!minioClient || !bucketName) {
throw new BadRequestException('S3 storage not configured');
}
try {
const url = await minioClient.presignedGetObject(bucketName, fileName, expiry);
logger.log(`Generated URL for ${fileName} with expiry ${expiry}s`);
return url;
} catch (error) {
logger.error(`Error generating URL for ${fileName}:`, error);
throw new BadRequestException(`Failed to generate URL: ${error.message}`);
}
};
export const getObjectStream = async (fileName: string): Promise<Readable> => {
if (!minioClient || !bucketName) {
throw new BadRequestException('S3 storage not configured');
}
try {
const stream = await minioClient.getObject(bucketName, fileName);
return stream;
} catch (error) {
logger.error(`Error getting object stream ${fileName}:`, error);
throw new BadRequestException(`Failed to get object stream: ${error.message}`);
}
};
```
### File Management Functions
```typescript
export const deleteObject = async (fileName: string): Promise<void> => {
if (!minioClient || !bucketName) {
throw new BadRequestException('S3 storage not configured');
}
try {
await minioClient.removeObject(bucketName, fileName);
logger.log(`File ${fileName} deleted successfully`);
} catch (error) {
logger.error(`Error deleting file ${fileName}:`, error);
throw new BadRequestException(`Failed to delete file: ${error.message}`);
}
};
export const listObjects = async (prefix?: string): Promise<MinIo.BucketItem[]> => {
if (!minioClient || !bucketName) {
throw new BadRequestException('S3 storage not configured');
}
try {
const objects: MinIo.BucketItem[] = [];
const stream = minioClient.listObjects(bucketName, prefix, true);
return new Promise((resolve, reject) => {
stream.on('data', (obj) => objects.push(obj));
stream.on('end', () => resolve(objects));
stream.on('error', reject);
});
} catch (error) {
logger.error('Error listing objects:', error);
throw new BadRequestException(`Failed to list objects: ${error.message}`);
}
};
export const objectExists = async (fileName: string): Promise<boolean> => {
if (!minioClient || !bucketName) {
return false;
}
try {
await minioClient.statObject(bucketName, fileName);
return true;
} catch (error) {
return false;
}
};
```
## Storage Controller Pattern
### S3 Controller Implementation
```typescript
import { InstanceDto } from '@api/dto/instance.dto';
import { MediaDto } from '@api/integrations/storage/s3/dto/media.dto';
import { S3Service } from '@api/integrations/storage/s3/services/s3.service';
export class S3Controller {
constructor(private readonly s3Service: S3Service) {}
public async getMedia(instance: InstanceDto, data: MediaDto) {
return this.s3Service.getMedia(instance, data);
}
public async getMediaUrl(instance: InstanceDto, data: MediaDto) {
return this.s3Service.getMediaUrl(instance, data);
}
public async uploadMedia(instance: InstanceDto, data: UploadMediaDto) {
return this.s3Service.uploadMedia(instance, data);
}
public async deleteMedia(instance: InstanceDto, data: MediaDto) {
return this.s3Service.deleteMedia(instance, data);
}
}
```
## Storage Router Pattern
### Storage Router Structure
```typescript
import { S3Router } from '@api/integrations/storage/s3/routes/s3.router';
import { Router } from 'express';
export class StorageRouter {
public readonly router: Router;
constructor(...guards: any[]) {
this.router = Router();
this.router.use('/s3', new S3Router(...guards).router);
// Add other storage providers here
// this.router.use('/gcs', new GCSRouter(...guards).router);
// this.router.use('/azure', new AzureRouter(...guards).router);
}
}
```
### S3 Specific Router
```typescript
import { RouterBroker } from '@api/abstract/abstract.router';
import { MediaDto } from '@api/integrations/storage/s3/dto/media.dto';
import { s3Schema, s3UrlSchema } from '@api/integrations/storage/s3/validate/s3.schema';
import { HttpStatus } from '@api/routes/index.router';
import { s3Controller } from '@api/server.module';
import { RequestHandler, Router } from 'express';
export class S3Router extends RouterBroker {
constructor(...guards: RequestHandler[]) {
super();
this.router
.post(this.routerPath('getMedia'), ...guards, async (req, res) => {
const response = await this.dataValidate<MediaDto>({
request: req,
schema: s3Schema,
ClassRef: MediaDto,
execute: (instance, data) => s3Controller.getMedia(instance, data),
});
res.status(HttpStatus.OK).json(response);
})
.post(this.routerPath('getMediaUrl'), ...guards, async (req, res) => {
const response = await this.dataValidate<MediaDto>({
request: req,
schema: s3UrlSchema,
ClassRef: MediaDto,
execute: (instance, data) => s3Controller.getMediaUrl(instance, data),
});
res.status(HttpStatus.OK).json(response);
})
.post(this.routerPath('uploadMedia'), ...guards, async (req, res) => {
const response = await this.dataValidate<UploadMediaDto>({
request: req,
schema: uploadSchema,
ClassRef: UploadMediaDto,
execute: (instance, data) => s3Controller.uploadMedia(instance, data),
});
res.status(HttpStatus.CREATED).json(response);
})
.delete(this.routerPath('deleteMedia'), ...guards, async (req, res) => {
const response = await this.dataValidate<MediaDto>({
request: req,
schema: s3Schema,
ClassRef: MediaDto,
execute: (instance, data) => s3Controller.deleteMedia(instance, data),
});
res.status(HttpStatus.OK).json(response);
});
}
public readonly router: Router = Router();
}
```
## Storage DTO Pattern
### Media DTO
```typescript
export class MediaDto {
id?: string;
fileName?: string;
type?: string;
mimetype?: string;
expiry?: number;
}
export class UploadMediaDto {
fileName: string;
mimetype: string;
buffer?: Buffer;
base64?: string;
url?: string;
metadata?: {
instanceId: string;
messageId?: string;
contactId?: string;
[key: string]: any;
};
}
```
## Storage Validation Schema
### S3 Validation Schemas
```typescript
import Joi from 'joi';
export const s3Schema = Joi.object({
id: Joi.string().optional(),
fileName: Joi.string().optional(),
type: Joi.string().optional().valid('image', 'video', 'audio', 'document'),
mimetype: Joi.string().optional(),
expiry: Joi.number().optional().min(60).max(604800).default(3600), // 1 min to 7 days
}).min(1).required();
export const s3UrlSchema = Joi.object({
id: Joi.string().required(),
expiry: Joi.number().optional().min(60).max(604800).default(3600),
}).required();
export const uploadSchema = Joi.object({
fileName: Joi.string().required().max(255),
mimetype: Joi.string().required(),
buffer: Joi.binary().optional(),
base64: Joi.string().base64().optional(),
url: Joi.string().uri().optional(),
metadata: Joi.object({
instanceId: Joi.string().required(),
messageId: Joi.string().optional(),
contactId: Joi.string().optional(),
}).optional(),
}).xor('buffer', 'base64', 'url').required(); // Exactly one of these must be present
```
## Error Handling in Storage
### Storage-Specific Error Handling
```typescript
// CORRECT - Storage-specific error handling
public async uploadFile(fileName: string, buffer: Buffer): Promise<string> {
try {
const result = await this.storageClient.upload(fileName, buffer);
return result;
} catch (error) {
this.logger.error(`Storage upload failed: ${error.message}`);
if (error.code === 'NoSuchBucket') {
throw new BadRequestException('Storage bucket not found');
}
if (error.code === 'AccessDenied') {
throw new UnauthorizedException('Storage access denied');
}
if (error.code === 'EntityTooLarge') {
throw new BadRequestException('File too large');
}
throw new InternalServerErrorException('Storage operation failed');
}
}
```
## Storage Configuration Pattern
### Environment Configuration
```typescript
export interface S3Config {
ENABLE: boolean;
ENDPOINT: string;
PORT: number;
USE_SSL: boolean;
ACCESS_KEY: string;
SECRET_KEY: string;
REGION: string;
BUCKET: string;
}
// Usage in service
const s3Config = this.configService.get<S3Config>('S3');
if (!s3Config.ENABLE) {
throw new BadRequestException('S3 storage is disabled');
}
```
## Storage Testing Pattern
### Storage Service Testing
```typescript
describe('S3Service', () => {
let service: S3Service;
let prismaRepository: jest.Mocked<PrismaRepository>;
beforeEach(() => {
service = new S3Service(prismaRepository);
});
describe('getMedia', () => {
it('should return media list', async () => {
const instance = { instanceId: 'test-instance' };
const mockMedia = [
{ id: '1', fileName: 'test.jpg', type: 'image', mimetype: 'image/jpeg' },
];
prismaRepository.media.findMany.mockResolvedValue(mockMedia);
const result = await service.getMedia(instance);
expect(result).toEqual(mockMedia);
expect(prismaRepository.media.findMany).toHaveBeenCalledWith({
where: { instanceId: 'test-instance' },
select: expect.objectContaining({
id: true,
fileName: true,
type: true,
mimetype: true,
}),
});
});
it('should throw error when no media found', async () => {
const instance = { instanceId: 'test-instance' };
prismaRepository.media.findMany.mockResolvedValue([]);
await expect(service.getMedia(instance)).rejects.toThrow(BadRequestException);
});
});
});
```
## Storage Performance Considerations
### Efficient File Handling
```typescript
// CORRECT - Stream-based upload for large files
public async uploadLargeFile(fileName: string, stream: Readable, size: number): Promise<string> {
const uploadStream = new Transform({
transform(chunk, encoding, callback) {
// Optional: Add compression, encryption, etc.
callback(null, chunk);
},
});
return new Promise((resolve, reject) => {
stream
.pipe(uploadStream)
.on('error', reject)
.on('finish', () => resolve(fileName));
});
}
// INCORRECT - Loading entire file into memory
public async uploadLargeFile(fileName: string, filePath: string): Promise<string> {
const buffer = fs.readFileSync(filePath); // ❌ Memory intensive for large files
return await this.uploadFile(fileName, buffer);
}
```

View File

@ -0,0 +1,416 @@
---
description: Router patterns for Evolution API
globs:
- "src/api/routes/**/*.ts"
alwaysApply: false
---
# Evolution API Route Rules
## Router Base Pattern
### RouterBroker Extension
```typescript
import { RouterBroker } from '@api/abstract/abstract.router';
import { RequestHandler, Router } from 'express';
import { HttpStatus } from './index.router';
export class ExampleRouter extends RouterBroker {
constructor(...guards: RequestHandler[]) {
super();
this.router
.get(this.routerPath('findExample'), ...guards, async (req, res) => {
const response = await this.dataValidate<ExampleDto>({
request: req,
schema: null,
ClassRef: ExampleDto,
execute: (instance) => exampleController.find(instance),
});
return res.status(HttpStatus.OK).json(response);
})
.post(this.routerPath('createExample'), ...guards, async (req, res) => {
const response = await this.dataValidate<ExampleDto>({
request: req,
schema: exampleSchema,
ClassRef: ExampleDto,
execute: (instance, data) => exampleController.create(instance, data),
});
return res.status(HttpStatus.CREATED).json(response);
});
}
public readonly router: Router = Router();
}
```
## Main Router Pattern
### Index Router Structure
```typescript
import { Router } from 'express';
import { authGuard } from '@api/guards/auth.guard';
import { instanceExistsGuard, instanceLoggedGuard } from '@api/guards/instance.guard';
import Telemetry from '@api/guards/telemetry.guard';
enum HttpStatus {
OK = 200,
CREATED = 201,
NOT_FOUND = 404,
FORBIDDEN = 403,
BAD_REQUEST = 400,
UNAUTHORIZED = 401,
INTERNAL_SERVER_ERROR = 500,
}
const router: Router = Router();
const guards = [instanceExistsGuard, instanceLoggedGuard, authGuard['apikey']];
const telemetry = new Telemetry();
router
.use((req, res, next) => telemetry.collectTelemetry(req, res, next))
.get('/', async (req, res) => {
res.status(HttpStatus.OK).json({
status: HttpStatus.OK,
message: 'Welcome to the Evolution API, it is working!',
version: packageJson.version,
clientName: process.env.DATABASE_CONNECTION_CLIENT_NAME,
manager: !serverConfig.DISABLE_MANAGER ? `${req.protocol}://${req.get('host')}/manager` : undefined,
documentation: `https://doc.evolution-api.com`,
whatsappWebVersion: (await fetchLatestWaWebVersion({})).version.join('.'),
});
})
.use('/instance', new InstanceRouter(configService, ...guards).router)
.use('/message', new MessageRouter(...guards).router)
.use('/chat', new ChatRouter(...guards).router)
.use('/business', new BusinessRouter(...guards).router);
export { HttpStatus, router };
```
## Data Validation Pattern
### RouterBroker dataValidate Usage
```typescript
// CORRECT - Standard validation pattern
.post(this.routerPath('createTemplate'), ...guards, async (req, res) => {
const response = await this.dataValidate<TemplateDto>({
request: req,
schema: templateSchema,
ClassRef: TemplateDto,
execute: (instance, data) => templateController.create(instance, data),
});
return res.status(HttpStatus.CREATED).json(response);
})
// CORRECT - No schema validation (for simple DTOs)
.get(this.routerPath('findTemplate'), ...guards, async (req, res) => {
const response = await this.dataValidate<InstanceDto>({
request: req,
schema: null,
ClassRef: InstanceDto,
execute: (instance) => templateController.find(instance),
});
return res.status(HttpStatus.OK).json(response);
})
```
## Error Handling in Routes
### Try-Catch Pattern
```typescript
// CORRECT - Error handling with utility function
.post(this.routerPath('getCatalog'), ...guards, async (req, res) => {
try {
const response = await this.dataValidate<NumberDto>({
request: req,
schema: catalogSchema,
ClassRef: NumberDto,
execute: (instance, data) => businessController.fetchCatalog(instance, data),
});
return res.status(HttpStatus.OK).json(response);
} catch (error) {
// Log error for debugging
console.error('Business catalog error:', error);
// Use utility function to create standardized error response
const errorResponse = createMetaErrorResponse(error, 'business_catalog');
return res.status(errorResponse.status).json(errorResponse);
}
})
// INCORRECT - Let RouterBroker handle errors (when possible)
.post(this.routerPath('simpleOperation'), ...guards, async (req, res) => {
try {
const response = await this.dataValidate<SimpleDto>({
request: req,
schema: simpleSchema,
ClassRef: SimpleDto,
execute: (instance, data) => controller.simpleOperation(instance, data),
});
return res.status(HttpStatus.OK).json(response);
} catch (error) {
throw error; // ❌ Unnecessary - RouterBroker handles this
}
})
```
## Route Path Pattern
### routerPath Usage
```typescript
// CORRECT - Use routerPath for consistent naming
.get(this.routerPath('findLabels'), ...guards, async (req, res) => {
// Implementation
})
.post(this.routerPath('handleLabel'), ...guards, async (req, res) => {
// Implementation
})
// INCORRECT - Hardcoded paths
.get('/labels', ...guards, async (req, res) => { // ❌ Use routerPath
// Implementation
})
```
## Guard Application Pattern
### Guards Usage
```typescript
// CORRECT - Apply guards to protected routes
export class ProtectedRouter extends RouterBroker {
constructor(...guards: RequestHandler[]) {
super();
this.router
.get(this.routerPath('protectedAction'), ...guards, async (req, res) => {
// Protected action
})
.post(this.routerPath('anotherAction'), ...guards, async (req, res) => {
// Another protected action
});
}
}
// CORRECT - No guards for public routes
export class PublicRouter extends RouterBroker {
constructor() {
super();
this.router
.get('/health', async (req, res) => {
res.status(HttpStatus.OK).json({ status: 'healthy' });
})
.get('/version', async (req, res) => {
res.status(HttpStatus.OK).json({ version: packageJson.version });
});
}
}
```
## Static File Serving Pattern
### Static Assets Route
```typescript
// CORRECT - Secure static file serving
router.get('/assets/*', (req, res) => {
const fileName = req.params[0];
// Security: Reject paths containing traversal patterns
if (!fileName || fileName.includes('..') || fileName.includes('\\') || path.isAbsolute(fileName)) {
return res.status(403).send('Forbidden');
}
const basePath = path.join(process.cwd(), 'manager', 'dist');
const assetsPath = path.join(basePath, 'assets');
const filePath = path.join(assetsPath, fileName);
// Security: Ensure the resolved path is within the assets directory
const resolvedPath = path.resolve(filePath);
const resolvedAssetsPath = path.resolve(assetsPath);
if (!resolvedPath.startsWith(resolvedAssetsPath + path.sep) && resolvedPath !== resolvedAssetsPath) {
return res.status(403).send('Forbidden');
}
if (fs.existsSync(resolvedPath)) {
res.set('Content-Type', mimeTypes.lookup(resolvedPath) || 'text/css');
res.send(fs.readFileSync(resolvedPath));
} else {
res.status(404).send('File not found');
}
});
```
## Special Route Patterns
### Manager Route Pattern
```typescript
export class ViewsRouter extends RouterBroker {
public readonly router: Router;
constructor() {
super();
this.router = Router();
const basePath = path.join(process.cwd(), 'manager', 'dist');
const indexPath = path.join(basePath, 'index.html');
this.router.use(express.static(basePath));
this.router.get('*', (req, res) => {
res.sendFile(indexPath);
});
}
}
```
### Webhook Route Pattern
```typescript
// CORRECT - Webhook without guards
.post('/webhook/evolution', async (req, res) => {
const response = await evolutionController.receiveWebhook(req.body);
return res.status(HttpStatus.OK).json(response);
})
// CORRECT - Webhook with signature validation
.post('/webhook/meta', validateWebhookSignature, async (req, res) => {
const response = await metaController.receiveWebhook(req.body);
return res.status(HttpStatus.OK).json(response);
})
```
## Response Pattern
### Standard Response Format
```typescript
// CORRECT - Standard success response
return res.status(HttpStatus.OK).json(response);
// CORRECT - Created response
return res.status(HttpStatus.CREATED).json(response);
// CORRECT - Custom response with additional data
return res.status(HttpStatus.OK).json({
...response,
timestamp: new Date().toISOString(),
instanceName: req.params.instanceName,
});
```
## Route Organization
### File Structure
```
src/api/routes/
├── index.router.ts # Main router with all route registrations
├── instance.router.ts # Instance management routes
├── sendMessage.router.ts # Message sending routes
├── chat.router.ts # Chat operations routes
├── business.router.ts # Business API routes
├── group.router.ts # Group management routes
├── label.router.ts # Label management routes
├── proxy.router.ts # Proxy configuration routes
├── settings.router.ts # Instance settings routes
├── template.router.ts # Template management routes
├── call.router.ts # Call operations routes
└── view.router.ts # Frontend views routes
```
## Route Testing Pattern
### Router Testing
```typescript
describe('ExampleRouter', () => {
let app: express.Application;
let router: ExampleRouter;
beforeEach(() => {
app = express();
router = new ExampleRouter();
app.use('/api', router.router);
app.use(express.json());
});
describe('GET /findExample', () => {
it('should return example data', async () => {
const response = await request(app)
.get('/api/findExample/test-instance')
.set('apikey', 'test-key')
.expect(200);
expect(response.body).toBeDefined();
expect(response.body.instanceName).toBe('test-instance');
});
it('should return 401 without API key', async () => {
await request(app)
.get('/api/findExample/test-instance')
.expect(401);
});
});
describe('POST /createExample', () => {
it('should create example successfully', async () => {
const data = {
name: 'Test Example',
description: 'Test Description',
};
const response = await request(app)
.post('/api/createExample/test-instance')
.set('apikey', 'test-key')
.send(data)
.expect(201);
expect(response.body.name).toBe(data.name);
});
it('should validate required fields', async () => {
const data = {
description: 'Test Description',
// Missing required 'name' field
};
await request(app)
.post('/api/createExample/test-instance')
.set('apikey', 'test-key')
.send(data)
.expect(400);
});
});
});
```
## Route Documentation
### JSDoc for Routes
```typescript
/**
* @route GET /api/template/findTemplate/:instanceName
* @description Find template for instance
* @param {string} instanceName - Instance name
* @returns {TemplateDto} Template data
* @throws {404} Template not found
* @throws {401} Unauthorized
*/
.get(this.routerPath('findTemplate'), ...guards, async (req, res) => {
// Implementation
})
/**
* @route POST /api/template/createTemplate/:instanceName
* @description Create new template
* @param {string} instanceName - Instance name
* @body {TemplateDto} Template data
* @returns {TemplateDto} Created template
* @throws {400} Validation error
* @throws {401} Unauthorized
*/
.post(this.routerPath('createTemplate'), ...guards, async (req, res) => {
// Implementation
})
```

View File

@ -0,0 +1,294 @@
---
description: Service layer patterns for Evolution API
globs:
- "src/api/services/**/*.ts"
- "src/api/integrations/**/services/*.ts"
alwaysApply: false
---
# Evolution API Service Rules
## Service Structure Pattern
### Standard Service Class
```typescript
export class ExampleService {
constructor(private readonly waMonitor: WAMonitoringService) {}
private readonly logger = new Logger('ExampleService');
public async create(instance: InstanceDto, data: ExampleDto) {
await this.waMonitor.waInstances[instance.instanceName].setData(data);
return { example: { ...instance, data } };
}
public async find(instance: InstanceDto): Promise<ExampleDto> {
try {
const result = await this.waMonitor.waInstances[instance.instanceName].findData();
if (Object.keys(result).length === 0) {
throw new Error('Data not found');
}
return result;
} catch (error) {
return null; // Evolution pattern - return null on error
}
}
}
```
## Dependency Injection Pattern
### Constructor Pattern
```typescript
// CORRECT - Evolution API pattern
constructor(
private readonly waMonitor: WAMonitoringService,
private readonly prismaRepository: PrismaRepository,
private readonly configService: ConfigService,
) {}
// INCORRECT - Don't use
constructor(waMonitor, prismaRepository, configService) {} // ❌ No types
```
## Logger Pattern
### Standard Logger Usage
```typescript
// CORRECT - Evolution API pattern
private readonly logger = new Logger('ServiceName');
// Usage
this.logger.log('Operation started');
this.logger.error('Operation failed', error);
// INCORRECT
console.log('Operation started'); // ❌ Use Logger
```
## WAMonitor Integration Pattern
### Instance Access Pattern
```typescript
// CORRECT - Standard pattern
public async operation(instance: InstanceDto, data: DataDto) {
await this.waMonitor.waInstances[instance.instanceName].performAction(data);
return { result: { ...instance, data } };
}
// Instance validation
const waInstance = this.waMonitor.waInstances[instance.instanceName];
if (!waInstance) {
throw new NotFoundException('Instance not found');
}
```
## Error Handling Pattern
### Try-Catch Pattern
```typescript
// CORRECT - Evolution API pattern
public async find(instance: InstanceDto): Promise<DataDto> {
try {
const result = await this.waMonitor.waInstances[instance.instanceName].findData();
if (Object.keys(result).length === 0) {
throw new Error('Data not found');
}
return result;
} catch (error) {
this.logger.error('Find operation failed', error);
return null; // Return null on error (Evolution pattern)
}
}
```
## Cache Integration Pattern
### Cache Service Usage
```typescript
export class CacheAwareService {
constructor(
private readonly cache: CacheService,
private readonly chatwootCache: CacheService,
private readonly baileysCache: CacheService,
) {}
public async getCachedData(key: string): Promise<any> {
const cached = await this.cache.get(key);
if (cached) return cached;
const data = await this.fetchFromSource(key);
await this.cache.set(key, data, 300); // 5 min TTL
return data;
}
}
```
## Integration Service Patterns
### Chatbot Service Base Pattern
```typescript
export class ChatbotService extends BaseChatbotService<BotType, SettingsType> {
constructor(
waMonitor: WAMonitoringService,
prismaRepository: PrismaRepository,
configService: ConfigService,
) {
super(waMonitor, prismaRepository, 'ChatbotService', configService);
}
protected async processBot(
waInstance: any,
remoteJid: string,
bot: BotType,
session: any,
settings: any,
content: string,
): Promise<void> {
// Implementation
}
}
```
### Channel Service Pattern
```typescript
export class ChannelService extends ChannelStartupService {
constructor(
configService: ConfigService,
eventEmitter: EventEmitter2,
prismaRepository: PrismaRepository,
cache: CacheService,
chatwootCache: CacheService,
baileysCache: CacheService,
) {
super(configService, eventEmitter, prismaRepository, cache, chatwootCache, baileysCache);
}
public readonly logger = new Logger('ChannelService');
public client: WASocket;
public readonly instance: wa.Instance = {};
}
```
## Service Initialization Pattern
### Service Registration
```typescript
// In server.module.ts pattern
export const templateService = new TemplateService(
waMonitor,
prismaRepository,
configService,
);
export const settingsService = new SettingsService(waMonitor);
```
## Async Operation Patterns
### Promise Handling
```typescript
// CORRECT - Evolution API pattern
public async sendMessage(instance: InstanceDto, data: MessageDto) {
const waInstance = this.waMonitor.waInstances[instance.instanceName];
return await waInstance.sendMessage(data);
}
// INCORRECT - Don't use .then()
public sendMessage(instance: InstanceDto, data: MessageDto) {
return this.waMonitor.waInstances[instance.instanceName]
.sendMessage(data)
.then(result => result); // ❌ Use async/await
}
```
## Configuration Access Pattern
### Config Service Usage
```typescript
// CORRECT - Evolution API pattern
const serverConfig = this.configService.get<HttpServer>('SERVER');
const authConfig = this.configService.get<Auth>('AUTHENTICATION');
const dbConfig = this.configService.get<Database>('DATABASE');
// Type-safe configuration access
if (this.configService.get<Chatwoot>('CHATWOOT').ENABLED) {
// Chatwoot logic
}
```
## Event Emission Pattern
### EventEmitter2 Usage
```typescript
// CORRECT - Evolution API pattern
this.eventEmitter.emit(Events.INSTANCE_CREATE, {
instanceName: instance.name,
status: 'created',
});
// Chatwoot event pattern
if (this.configService.get<Chatwoot>('CHATWOOT').ENABLED && this.localChatwoot?.enabled) {
this.chatwootService.eventWhatsapp(
Events.STATUS_INSTANCE,
{ instanceName: this.instance.name },
{
instance: this.instance.name,
status: 'created',
},
);
}
```
## Service Method Naming
### Standard Method Names
- `create()` - Create new resource
- `find()` - Find single resource
- `findAll()` - Find multiple resources
- `update()` - Update resource
- `delete()` - Delete resource
- `fetch*()` - Fetch from external API
- `send*()` - Send data/messages
- `process*()` - Process data
## Service Testing Pattern
### Unit Test Structure
```typescript
describe('ExampleService', () => {
let service: ExampleService;
let waMonitor: jest.Mocked<WAMonitoringService>;
let prismaRepository: jest.Mocked<PrismaRepository>;
beforeEach(() => {
const mockWaMonitor = {
waInstances: {
'test-instance': {
performAction: jest.fn(),
},
},
};
service = new ExampleService(
mockWaMonitor as any,
prismaRepository,
configService,
);
});
it('should perform action successfully', async () => {
const instance = { instanceName: 'test-instance' };
const data = { test: 'data' };
const result = await service.create(instance, data);
expect(result).toBeDefined();
expect(waMonitor.waInstances['test-instance'].performAction).toHaveBeenCalledWith(data);
});
});
```

View File

@ -0,0 +1,490 @@
---
description: Type definitions and interfaces for Evolution API
globs:
- "src/api/types/**/*.ts"
- "src/@types/**/*.ts"
alwaysApply: false
---
# Evolution API Type Rules
## Namespace Pattern
### WhatsApp Types Namespace
```typescript
/* eslint-disable @typescript-eslint/no-namespace */
import { JsonValue } from '@prisma/client/runtime/library';
import { AuthenticationState, WAConnectionState } from 'baileys';
export declare namespace wa {
export type QrCode = {
count?: number;
pairingCode?: string;
base64?: string;
code?: string;
};
export type Instance = {
id?: string;
qrcode?: QrCode;
pairingCode?: string;
authState?: { state: AuthenticationState; saveCreds: () => void };
name?: string;
wuid?: string;
profileName?: string;
profilePictureUrl?: string;
token?: string;
number?: string;
integration?: string;
businessId?: string;
};
export type LocalChatwoot = {
enabled?: boolean;
accountId?: string;
token?: string;
url?: string;
nameInbox?: string;
mergeBrazilContacts?: boolean;
importContacts?: boolean;
importMessages?: boolean;
daysLimitImportMessages?: number;
organization?: string;
logo?: string;
};
export type LocalProxy = {
enabled?: boolean;
host?: string;
port?: string;
protocol?: string;
username?: string;
password?: string;
};
export type LocalSettings = {
rejectCall?: boolean;
msgCall?: string;
groupsIgnore?: boolean;
alwaysOnline?: boolean;
readMessages?: boolean;
readStatus?: boolean;
syncFullHistory?: boolean;
};
export type LocalWebHook = {
enabled?: boolean;
url?: string;
events?: string[];
headers?: JsonValue;
byEvents?: boolean;
base64?: boolean;
};
export type StatusMessage = 'ERROR' | 'PENDING' | 'SERVER_ACK' | 'DELIVERY_ACK' | 'READ' | 'DELETED' | 'PLAYED';
}
```
## Enum Definitions
### Events Enum
```typescript
export enum Events {
APPLICATION_STARTUP = 'application.startup',
INSTANCE_CREATE = 'instance.create',
INSTANCE_DELETE = 'instance.delete',
QRCODE_UPDATED = 'qrcode.updated',
CONNECTION_UPDATE = 'connection.update',
STATUS_INSTANCE = 'status.instance',
MESSAGES_SET = 'messages.set',
MESSAGES_UPSERT = 'messages.upsert',
MESSAGES_EDITED = 'messages.edited',
MESSAGES_UPDATE = 'messages.update',
MESSAGES_DELETE = 'messages.delete',
SEND_MESSAGE = 'send.message',
SEND_MESSAGE_UPDATE = 'send.message.update',
CONTACTS_SET = 'contacts.set',
CONTACTS_UPSERT = 'contacts.upsert',
CONTACTS_UPDATE = 'contacts.update',
PRESENCE_UPDATE = 'presence.update',
CHATS_SET = 'chats.set',
CHATS_UPDATE = 'chats.update',
CHATS_UPSERT = 'chats.upsert',
CHATS_DELETE = 'chats.delete',
GROUPS_UPSERT = 'groups.upsert',
GROUPS_UPDATE = 'groups.update',
GROUP_PARTICIPANTS_UPDATE = 'group-participants.update',
CALL = 'call',
TYPEBOT_START = 'typebot.start',
TYPEBOT_CHANGE_STATUS = 'typebot.change-status',
LABELS_EDIT = 'labels.edit',
LABELS_ASSOCIATION = 'labels.association',
CREDS_UPDATE = 'creds.update',
MESSAGING_HISTORY_SET = 'messaging-history.set',
REMOVE_INSTANCE = 'remove.instance',
LOGOUT_INSTANCE = 'logout.instance',
}
```
### Integration Types
```typescript
export const Integration = {
WHATSAPP_BUSINESS: 'WHATSAPP-BUSINESS',
WHATSAPP_BAILEYS: 'WHATSAPP-BAILEYS',
EVOLUTION: 'EVOLUTION',
} as const;
export type IntegrationType = typeof Integration[keyof typeof Integration];
```
## Constant Arrays
### Message Type Constants
```typescript
export const TypeMediaMessage = [
'imageMessage',
'documentMessage',
'audioMessage',
'videoMessage',
'stickerMessage',
'ptvMessage', // Evolution API includes this
];
export const MessageSubtype = [
'ephemeralMessage',
'documentWithCaptionMessage',
'viewOnceMessage',
'viewOnceMessageV2',
];
export type MediaMessageType = typeof TypeMediaMessage[number];
export type MessageSubtypeType = typeof MessageSubtype[number];
```
## Interface Definitions
### Service Interfaces
```typescript
export interface ServiceInterface {
create(instance: InstanceDto, data: any): Promise<any>;
find(instance: InstanceDto): Promise<any>;
update?(instance: InstanceDto, data: any): Promise<any>;
delete?(instance: InstanceDto): Promise<any>;
}
export interface ChannelServiceInterface extends ServiceInterface {
sendMessage(data: SendMessageDto): Promise<any>;
connectToWhatsapp(data?: any): Promise<void>;
receiveWebhook?(data: any): Promise<void>;
}
export interface ChatbotServiceInterface extends ServiceInterface {
processMessage(
instanceName: string,
remoteJid: string,
message: any,
pushName?: string,
): Promise<void>;
}
```
## Configuration Types
### Environment Configuration Types
```typescript
export interface DatabaseConfig {
CONNECTION: {
URI: string;
DB_PREFIX_NAME: string;
CLIENT_NAME?: string;
};
ENABLED: boolean;
SAVE_DATA: {
INSTANCE: boolean;
NEW_MESSAGE: boolean;
MESSAGE_UPDATE: boolean;
CONTACTS: boolean;
CHATS: boolean;
};
}
export interface AuthConfig {
TYPE: 'apikey' | 'jwt';
API_KEY: {
KEY: string;
};
JWT?: {
EXPIRIN_IN: number;
SECRET: string;
};
}
export interface CacheConfig {
REDIS: {
ENABLED: boolean;
URI: string;
PREFIX_KEY: string;
SAVE_INSTANCES: boolean;
};
LOCAL: {
ENABLED: boolean;
TTL: number;
};
}
```
## Message Types
### Message Structure Types
```typescript
export interface MessageContent {
text?: string;
caption?: string;
media?: Buffer | string;
mediatype?: 'image' | 'video' | 'audio' | 'document' | 'sticker';
fileName?: string;
mimetype?: string;
}
export interface MessageOptions {
delay?: number;
presence?: 'unavailable' | 'available' | 'composing' | 'recording' | 'paused';
linkPreview?: boolean;
mentionsEveryOne?: boolean;
mentioned?: string[];
quoted?: {
key: {
remoteJid: string;
fromMe: boolean;
id: string;
};
message: any;
};
}
export interface SendMessageRequest {
number: string;
content: MessageContent;
options?: MessageOptions;
}
```
## Webhook Types
### Webhook Payload Types
```typescript
export interface WebhookPayload {
event: Events;
instance: string;
data: any;
timestamp: string;
server?: {
version: string;
host: string;
};
}
export interface WebhookConfig {
enabled: boolean;
url: string;
events: Events[];
headers?: Record<string, string>;
byEvents?: boolean;
base64?: boolean;
}
```
## Error Types
### Custom Error Types
```typescript
export interface ApiError {
status: number;
message: string;
error?: string;
details?: any;
timestamp: string;
path: string;
}
export interface ValidationError extends ApiError {
status: 400;
validationErrors: Array<{
field: string;
message: string;
value?: any;
}>;
}
export interface AuthenticationError extends ApiError {
status: 401;
message: 'Unauthorized' | 'Invalid API Key' | 'Token Expired';
}
```
## Utility Types
### Generic Utility Types
```typescript
export type Optional<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;
export type RequiredFields<T, K extends keyof T> = T & Required<Pick<T, K>>;
export type DeepPartial<T> = {
[P in keyof T]?: T[P] extends object ? DeepPartial<T[P]> : T[P];
};
export type NonEmptyArray<T> = [T, ...T[]];
export type StringKeys<T> = {
[K in keyof T]: T[K] extends string ? K : never;
}[keyof T];
```
## Response Types
### API Response Types
```typescript
export interface ApiResponse<T = any> {
success: boolean;
data?: T;
message?: string;
error?: string;
timestamp: string;
}
export interface PaginatedResponse<T> extends ApiResponse<T[]> {
pagination: {
page: number;
limit: number;
total: number;
totalPages: number;
hasNext: boolean;
hasPrev: boolean;
};
}
export interface InstanceResponse extends ApiResponse {
instance: {
instanceName: string;
status: 'connecting' | 'open' | 'close' | 'qr';
qrcode?: string;
profileName?: string;
profilePicUrl?: string;
};
}
```
## Integration-Specific Types
### Baileys Types Extension
```typescript
import { WASocket, ConnectionState, DisconnectReason } from 'baileys';
export interface BaileysInstance {
client: WASocket;
state: ConnectionState;
qrRetry: number;
authPath: string;
}
export interface BaileysConfig {
qrTimeout: number;
maxQrRetries: number;
authTimeout: number;
reconnectInterval: number;
}
```
### Business API Types
```typescript
export interface BusinessApiConfig {
version: string;
baseUrl: string;
timeout: number;
retries: number;
}
export interface BusinessApiMessage {
messaging_product: 'whatsapp';
to: string;
type: 'text' | 'image' | 'document' | 'audio' | 'video' | 'template';
text?: {
body: string;
preview_url?: boolean;
};
image?: {
link?: string;
id?: string;
caption?: string;
};
template?: {
name: string;
language: {
code: string;
};
components?: any[];
};
}
```
## Type Guards
### Type Guard Functions
```typescript
export function isMediaMessage(message: any): message is MediaMessage {
return message && TypeMediaMessage.some(type => message[type]);
}
export function isTextMessage(message: any): message is TextMessage {
return message && message.conversation;
}
export function isValidIntegration(integration: string): integration is IntegrationType {
return Object.values(Integration).includes(integration as IntegrationType);
}
export function isValidEvent(event: string): event is Events {
return Object.values(Events).includes(event as Events);
}
```
## Module Augmentation
### Express Request Extension
```typescript
declare global {
namespace Express {
interface Request {
instanceName?: string;
instanceData?: InstanceDto;
user?: {
id: string;
apiKey: string;
};
}
}
}
```
## Type Documentation
### JSDoc Type Documentation
```typescript
/**
* WhatsApp instance configuration
* @interface InstanceConfig
* @property {string} name - Unique instance name
* @property {IntegrationType} integration - Integration type
* @property {string} [token] - API token for business integrations
* @property {WebhookConfig} [webhook] - Webhook configuration
* @property {ProxyConfig} [proxy] - Proxy configuration
*/
export interface InstanceConfig {
name: string;
integration: IntegrationType;
token?: string;
webhook?: WebhookConfig;
proxy?: ProxyConfig;
}
```

View File

@ -0,0 +1,653 @@
---
description: Utility functions and helpers for Evolution API
globs:
- "src/utils/**/*.ts"
alwaysApply: false
---
# Evolution API Utility Rules
## Utility Function Structure
### Standard Utility Pattern
```typescript
import { Logger } from '@config/logger.config';
const logger = new Logger('UtilityName');
export function utilityFunction(param: ParamType): ReturnType {
try {
// Utility logic
return result;
} catch (error) {
logger.error(`Utility function failed: ${error.message}`);
throw error;
}
}
export default utilityFunction;
```
## Authentication Utilities
### Multi-File Auth State Pattern
```typescript
import { AuthenticationState } from 'baileys';
import { CacheService } from '@api/services/cache.service';
import fs from 'fs/promises';
import path from 'path';
export default async function useMultiFileAuthStatePrisma(
sessionId: string,
cache: CacheService,
): Promise<{
state: AuthenticationState;
saveCreds: () => Promise<void>;
}> {
const localFolder = path.join(INSTANCE_DIR, sessionId);
const localFile = (key: string) => path.join(localFolder, fixFileName(key) + '.json');
await fs.mkdir(localFolder, { recursive: true });
async function writeData(data: any, key: string): Promise<any> {
const dataString = JSON.stringify(data, BufferJSON.replacer);
if (key !== 'creds') {
if (process.env.CACHE_REDIS_ENABLED === 'true') {
return await cache.hSet(sessionId, key, data);
} else {
await fs.writeFile(localFile(key), dataString);
return;
}
}
await saveKey(sessionId, dataString);
return;
}
async function readData(key: string): Promise<any> {
try {
let rawData;
if (key !== 'creds') {
if (process.env.CACHE_REDIS_ENABLED === 'true') {
return await cache.hGet(sessionId, key);
} else {
if (!(await fileExists(localFile(key)))) return null;
rawData = await fs.readFile(localFile(key), { encoding: 'utf-8' });
return JSON.parse(rawData, BufferJSON.reviver);
}
} else {
rawData = await getAuthKey(sessionId);
}
const parsedData = JSON.parse(rawData, BufferJSON.reviver);
return parsedData;
} catch (error) {
return null;
}
}
async function removeData(key: string): Promise<any> {
try {
if (key !== 'creds') {
if (process.env.CACHE_REDIS_ENABLED === 'true') {
return await cache.hDelete(sessionId, key);
} else {
await fs.unlink(localFile(key));
}
} else {
await deleteAuthKey(sessionId);
}
} catch (error) {
return;
}
}
let creds = await readData('creds');
if (!creds) {
creds = initAuthCreds();
await writeData(creds, 'creds');
}
return {
state: {
creds,
keys: {
get: async (type, ids) => {
const data = {};
await Promise.all(
ids.map(async (id) => {
let value = await readData(`${type}-${id}`);
if (type === 'app-state-sync-key' && value) {
value = proto.Message.AppStateSyncKeyData.fromObject(value);
}
data[id] = value;
})
);
return data;
},
set: async (data) => {
const tasks = [];
for (const category in data) {
for (const id in data[category]) {
const value = data[category][id];
const key = `${category}-${id}`;
tasks.push(value ? writeData(value, key) : removeData(key));
}
}
await Promise.all(tasks);
},
},
},
saveCreds: () => writeData(creds, 'creds'),
};
}
```
## Message Processing Utilities
### Message Content Extraction
```typescript
export const getConversationMessage = (msg: any): string => {
const types = getTypeMessage(msg);
const messageContent = getMessageContent(types);
return messageContent;
};
const getTypeMessage = (msg: any): any => {
return Object.keys(msg?.message || msg || {})[0];
};
const getMessageContent = (type: string, msg?: any): string => {
const typeKey = type?.replace('Message', '');
const types = {
conversation: msg?.message?.conversation,
extendedTextMessage: msg?.message?.extendedTextMessage?.text,
imageMessage: msg?.message?.imageMessage?.caption || 'Image',
videoMessage: msg?.message?.videoMessage?.caption || 'Video',
audioMessage: 'Audio',
documentMessage: msg?.message?.documentMessage?.caption || 'Document',
stickerMessage: 'Sticker',
contactMessage: 'Contact',
locationMessage: 'Location',
liveLocationMessage: 'Live Location',
viewOnceMessage: 'View Once',
reactionMessage: 'Reaction',
pollCreationMessage: 'Poll',
pollUpdateMessage: 'Poll Update',
};
let result = types[typeKey] || types[type] || 'Unknown';
if (!result || result === 'Unknown') {
result = JSON.stringify(msg);
}
return result;
};
```
### JID Creation Utility
```typescript
export const createJid = (number: string): string => {
if (number.includes('@')) {
return number;
}
// Remove any non-numeric characters except +
let cleanNumber = number.replace(/[^\d+]/g, '');
// Remove + if present
if (cleanNumber.startsWith('+')) {
cleanNumber = cleanNumber.substring(1);
}
// Add country code if missing (assuming Brazil as default)
if (cleanNumber.length === 11 && cleanNumber.startsWith('11')) {
cleanNumber = '55' + cleanNumber;
} else if (cleanNumber.length === 10) {
cleanNumber = '5511' + cleanNumber;
}
// Determine if it's a group or individual
const isGroup = cleanNumber.includes('-');
const domain = isGroup ? 'g.us' : 's.whatsapp.net';
return `${cleanNumber}@${domain}`;
};
```
## Cache Utilities
### WhatsApp Number Cache
```typescript
interface ISaveOnWhatsappCacheParams {
remoteJid: string;
lid?: string;
}
function getAvailableNumbers(remoteJid: string): string[] {
const numbersAvailable: string[] = [];
if (remoteJid.startsWith('+')) {
remoteJid = remoteJid.slice(1);
}
const [number, domain] = remoteJid.split('@');
// Brazilian numbers
if (remoteJid.startsWith('55')) {
const numberWithDigit =
number.slice(4, 5) === '9' && number.length === 13 ? number : `${number.slice(0, 4)}9${number.slice(4)}`;
const numberWithoutDigit = number.length === 12 ? number : number.slice(0, 4) + number.slice(5);
numbersAvailable.push(numberWithDigit);
numbersAvailable.push(numberWithoutDigit);
}
// Mexican/Argentina numbers
else if (number.startsWith('52') || number.startsWith('54')) {
let prefix = '';
if (number.startsWith('52')) {
prefix = '1';
}
if (number.startsWith('54')) {
prefix = '9';
}
const numberWithDigit =
number.slice(2, 3) === prefix && number.length === 13
? number
: `${number.slice(0, 2)}${prefix}${number.slice(2)}`;
const numberWithoutDigit = number.length === 12 ? number : number.slice(0, 2) + number.slice(3);
numbersAvailable.push(numberWithDigit);
numbersAvailable.push(numberWithoutDigit);
}
// Other countries
else {
numbersAvailable.push(remoteJid);
}
return numbersAvailable.map((number) => `${number}@${domain}`);
}
export async function saveOnWhatsappCache(params: ISaveOnWhatsappCacheParams): Promise<void> {
const { remoteJid, lid } = params;
const db = configService.get<Database>('DATABASE');
if (!db.SAVE_DATA.CONTACTS) {
return;
}
try {
const numbersAvailable = getAvailableNumbers(remoteJid);
const existingContact = await prismaRepository.contact.findFirst({
where: {
OR: numbersAvailable.map(number => ({ id: number })),
},
});
if (!existingContact) {
await prismaRepository.contact.create({
data: {
id: remoteJid,
pushName: '',
profilePicUrl: '',
isOnWhatsapp: true,
lid: lid || null,
createdAt: new Date(),
updatedAt: new Date(),
},
});
} else {
await prismaRepository.contact.update({
where: { id: existingContact.id },
data: {
isOnWhatsapp: true,
lid: lid || existingContact.lid,
updatedAt: new Date(),
},
});
}
} catch (error) {
console.error('Error saving WhatsApp cache:', error);
}
}
```
## Search Utilities
### Advanced Search Operators
```typescript
function normalizeString(str: string): string {
return str
.toLowerCase()
.normalize('NFD')
.replace(/[\u0300-\u036f]/g, '');
}
export function advancedOperatorsSearch(data: string, query: string): boolean {
const normalizedData = normalizeString(data);
const normalizedQuery = normalizeString(query);
// Exact phrase search with quotes
if (normalizedQuery.startsWith('"') && normalizedQuery.endsWith('"')) {
const phrase = normalizedQuery.slice(1, -1);
return normalizedData.includes(phrase);
}
// OR operator
if (normalizedQuery.includes(' OR ')) {
const terms = normalizedQuery.split(' OR ');
return terms.some(term => normalizedData.includes(term.trim()));
}
// AND operator (default behavior)
if (normalizedQuery.includes(' AND ')) {
const terms = normalizedQuery.split(' AND ');
return terms.every(term => normalizedData.includes(term.trim()));
}
// NOT operator
if (normalizedQuery.startsWith('NOT ')) {
const term = normalizedQuery.slice(4);
return !normalizedData.includes(term);
}
// Wildcard search
if (normalizedQuery.includes('*')) {
const regex = new RegExp(normalizedQuery.replace(/\*/g, '.*'), 'i');
return regex.test(normalizedData);
}
// Default: simple contains search
return normalizedData.includes(normalizedQuery);
}
```
## Proxy Utilities
### Proxy Agent Creation
```typescript
import { HttpsProxyAgent } from 'https-proxy-agent';
import { SocksProxyAgent } from 'socks-proxy-agent';
type Proxy = {
host: string;
port: string;
protocol: 'http' | 'https' | 'socks4' | 'socks5';
username?: string;
password?: string;
};
function selectProxyAgent(proxyUrl: string): HttpsProxyAgent<string> | SocksProxyAgent {
const url = new URL(proxyUrl);
if (url.protocol === 'socks4:' || url.protocol === 'socks5:') {
return new SocksProxyAgent(proxyUrl);
} else {
return new HttpsProxyAgent(proxyUrl);
}
}
export function makeProxyAgent(proxy: Proxy): HttpsProxyAgent<string> | SocksProxyAgent | null {
if (!proxy.host || !proxy.port) {
return null;
}
let proxyUrl = `${proxy.protocol}://`;
if (proxy.username && proxy.password) {
proxyUrl += `${proxy.username}:${proxy.password}@`;
}
proxyUrl += `${proxy.host}:${proxy.port}`;
try {
return selectProxyAgent(proxyUrl);
} catch (error) {
console.error('Failed to create proxy agent:', error);
return null;
}
}
```
## Telemetry Utilities
### Telemetry Data Collection
```typescript
export interface TelemetryData {
route: string;
apiVersion: string;
timestamp: Date;
method?: string;
statusCode?: number;
responseTime?: number;
userAgent?: string;
instanceName?: string;
}
export const sendTelemetry = async (route: string): Promise<void> => {
try {
const telemetryData: TelemetryData = {
route,
apiVersion: packageJson.version,
timestamp: new Date(),
};
// Only send telemetry if enabled
if (process.env.DISABLE_TELEMETRY === 'true') {
return;
}
// Send to telemetry service (implement as needed)
await axios.post('https://telemetry.evolution-api.com/collect', telemetryData, {
timeout: 5000,
});
} catch (error) {
// Silently fail - don't affect main application
console.debug('Telemetry failed:', error.message);
}
};
```
## Internationalization Utilities
### i18n Setup
```typescript
import { ConfigService, Language } from '@config/env.config';
import fs from 'fs';
import i18next from 'i18next';
import path from 'path';
const __dirname = path.resolve(process.cwd(), 'src', 'utils');
const languages = ['en', 'pt-BR', 'es'];
const translationsPath = path.join(__dirname, 'translations');
const configService: ConfigService = new ConfigService();
const resources: any = {};
languages.forEach((language) => {
const languagePath = path.join(translationsPath, `${language}.json`);
if (fs.existsSync(languagePath)) {
const translationContent = fs.readFileSync(languagePath, 'utf8');
resources[language] = {
translation: JSON.parse(translationContent),
};
}
});
i18next.init({
resources,
fallbackLng: 'en',
lng: configService.get<Language>('LANGUAGE') || 'pt-BR',
interpolation: {
escapeValue: false,
},
});
export const t = i18next.t.bind(i18next);
export default i18next;
```
## Bot Trigger Utilities
### Bot Trigger Matching
```typescript
import { TriggerOperator, TriggerType } from '@prisma/client';
export function findBotByTrigger(
bots: any[],
content: string,
remoteJid: string,
): any | null {
for (const bot of bots) {
if (!bot.enabled) continue;
// Check ignore list
if (bot.ignoreJids && bot.ignoreJids.includes(remoteJid)) {
continue;
}
// Check trigger
if (matchesTrigger(content, bot.triggerType, bot.triggerOperator, bot.triggerValue)) {
return bot;
}
}
return null;
}
function matchesTrigger(
content: string,
triggerType: TriggerType,
triggerOperator: TriggerOperator,
triggerValue: string,
): boolean {
const normalizedContent = content.toLowerCase().trim();
const normalizedValue = triggerValue.toLowerCase().trim();
switch (triggerType) {
case TriggerType.ALL:
return true;
case TriggerType.KEYWORD:
return matchesKeyword(normalizedContent, triggerOperator, normalizedValue);
case TriggerType.REGEX:
try {
const regex = new RegExp(triggerValue, 'i');
return regex.test(content);
} catch {
return false;
}
default:
return false;
}
}
function matchesKeyword(
content: string,
operator: TriggerOperator,
value: string,
): boolean {
switch (operator) {
case TriggerOperator.EQUALS:
return content === value;
case TriggerOperator.CONTAINS:
return content.includes(value);
case TriggerOperator.STARTS_WITH:
return content.startsWith(value);
case TriggerOperator.ENDS_WITH:
return content.endsWith(value);
default:
return false;
}
}
```
## Server Utilities
### Server Status Check
```typescript
export class ServerUP {
private static instance: ServerUP;
private isServerUp: boolean = false;
private constructor() {}
public static getInstance(): ServerUP {
if (!ServerUP.instance) {
ServerUP.instance = new ServerUP();
}
return ServerUP.instance;
}
public setServerStatus(status: boolean): void {
this.isServerUp = status;
}
public getServerStatus(): boolean {
return this.isServerUp;
}
public async waitForServer(timeout: number = 30000): Promise<boolean> {
const startTime = Date.now();
while (!this.isServerUp && (Date.now() - startTime) < timeout) {
await new Promise(resolve => setTimeout(resolve, 100));
}
return this.isServerUp;
}
}
```
## Error Response Utilities
### Standardized Error Responses
```typescript
export function createMetaErrorResponse(error: any, context: string) {
const timestamp = new Date().toISOString();
if (error.response?.data) {
return {
status: error.response.status || 500,
error: {
message: error.response.data.error?.message || 'External API error',
type: error.response.data.error?.type || 'api_error',
code: error.response.data.error?.code || 'unknown_error',
context,
timestamp,
},
};
}
return {
status: 500,
error: {
message: error.message || 'Internal server error',
type: 'internal_error',
code: 'server_error',
context,
timestamp,
},
};
}
export function createValidationErrorResponse(errors: any[], context: string) {
return {
status: 400,
error: {
message: 'Validation failed',
type: 'validation_error',
code: 'invalid_input',
context,
details: errors,
timestamp: new Date().toISOString(),
},
};
}
```

View File

@ -0,0 +1,498 @@
---
description: Validation schemas and patterns for Evolution API
globs:
- "src/validate/**/*.ts"
alwaysApply: false
---
# Evolution API Validation Rules
## Validation Schema Structure
### JSONSchema7 Pattern (Evolution API Standard)
```typescript
import { JSONSchema7 } from 'json-schema';
import { v4 } from 'uuid';
const isNotEmpty = (...fields: string[]) => {
const properties = {};
fields.forEach((field) => {
properties[field] = {
if: { properties: { [field]: { type: 'string' } } },
then: { properties: { [field]: { minLength: 1 } } },
};
});
return {
allOf: Object.values(properties),
};
};
export const exampleSchema: JSONSchema7 = {
$id: v4(),
type: 'object',
properties: {
name: { type: 'string' },
description: { type: 'string' },
enabled: { type: 'boolean' },
settings: {
type: 'object',
properties: {
timeout: { type: 'number', minimum: 1000, maximum: 60000 },
retries: { type: 'number', minimum: 0, maximum: 5 },
},
},
tags: {
type: 'array',
items: { type: 'string' },
},
},
required: ['name', 'enabled'],
...isNotEmpty('name'),
};
```
## Message Validation Schemas
### Send Message Validation
```typescript
const numberDefinition = {
type: 'string',
pattern: '^\\d+[\\.@\\w-]+',
description: 'Invalid number',
};
export const sendTextSchema: JSONSchema7 = {
$id: v4(),
type: 'object',
properties: {
number: numberDefinition,
text: { type: 'string', minLength: 1, maxLength: 4096 },
delay: { type: 'number', minimum: 0, maximum: 60000 },
linkPreview: { type: 'boolean' },
mentionsEveryOne: { type: 'boolean' },
mentioned: {
type: 'array',
items: { type: 'string' },
},
},
required: ['number', 'text'],
...isNotEmpty('number', 'text'),
};
export const sendMediaSchema = Joi.object({
number: Joi.string().required().pattern(/^\d+$/),
mediatype: Joi.string().required().valid('image', 'video', 'audio', 'document'),
media: Joi.alternatives().try(
Joi.string().uri(),
Joi.string().base64(),
).required(),
caption: Joi.string().optional().max(1024),
fileName: Joi.string().optional().max(255),
delay: Joi.number().optional().min(0).max(60000),
}).required();
export const sendButtonsSchema = Joi.object({
number: Joi.string().required().pattern(/^\d+$/),
title: Joi.string().required().max(1024),
description: Joi.string().optional().max(1024),
footer: Joi.string().optional().max(60),
buttons: Joi.array().items(
Joi.object({
type: Joi.string().required().valid('replyButton', 'urlButton', 'callButton'),
displayText: Joi.string().required().max(20),
id: Joi.string().when('type', {
is: 'replyButton',
then: Joi.required().max(256),
otherwise: Joi.optional(),
}),
url: Joi.string().when('type', {
is: 'urlButton',
then: Joi.required().uri(),
otherwise: Joi.optional(),
}),
phoneNumber: Joi.string().when('type', {
is: 'callButton',
then: Joi.required().pattern(/^\+?\d+$/),
otherwise: Joi.optional(),
}),
})
).min(1).max(3).required(),
}).required();
```
## Instance Validation Schemas
### Instance Creation Validation
```typescript
export const instanceSchema = Joi.object({
instanceName: Joi.string().required().min(1).max(100).pattern(/^[a-zA-Z0-9_-]+$/),
integration: Joi.string().required().valid('WHATSAPP-BAILEYS', 'WHATSAPP-BUSINESS', 'EVOLUTION'),
token: Joi.string().when('integration', {
is: Joi.valid('WHATSAPP-BUSINESS', 'EVOLUTION'),
then: Joi.required().min(10),
otherwise: Joi.optional(),
}),
qrcode: Joi.boolean().optional().default(false),
number: Joi.string().optional().pattern(/^\d+$/),
businessId: Joi.string().when('integration', {
is: 'WHATSAPP-BUSINESS',
then: Joi.required(),
otherwise: Joi.optional(),
}),
}).required();
export const settingsSchema = Joi.object({
rejectCall: Joi.boolean().optional(),
msgCall: Joi.string().optional().max(500),
groupsIgnore: Joi.boolean().optional(),
alwaysOnline: Joi.boolean().optional(),
readMessages: Joi.boolean().optional(),
readStatus: Joi.boolean().optional(),
syncFullHistory: Joi.boolean().optional(),
wavoipToken: Joi.string().optional(),
}).optional();
export const proxySchema = Joi.object({
host: Joi.string().required().hostname(),
port: Joi.string().required().pattern(/^\d+$/).custom((value) => {
const port = parseInt(value);
if (port < 1 || port > 65535) {
throw new Error('Port must be between 1 and 65535');
}
return value;
}),
protocol: Joi.string().required().valid('http', 'https', 'socks4', 'socks5'),
username: Joi.string().optional(),
password: Joi.string().optional(),
}).optional();
```
## Webhook Validation Schemas
### Webhook Configuration Validation
```typescript
export const webhookSchema = Joi.object({
enabled: Joi.boolean().required(),
url: Joi.string().when('enabled', {
is: true,
then: Joi.required().uri({ scheme: ['http', 'https'] }),
otherwise: Joi.optional(),
}),
events: Joi.array().items(
Joi.string().valid(
'APPLICATION_STARTUP',
'INSTANCE_CREATE',
'INSTANCE_DELETE',
'QRCODE_UPDATED',
'CONNECTION_UPDATE',
'STATUS_INSTANCE',
'MESSAGES_SET',
'MESSAGES_UPSERT',
'MESSAGES_UPDATE',
'MESSAGES_DELETE',
'CONTACTS_SET',
'CONTACTS_UPSERT',
'CONTACTS_UPDATE',
'CHATS_SET',
'CHATS_UPDATE',
'CHATS_UPSERT',
'CHATS_DELETE',
'GROUPS_UPSERT',
'GROUPS_UPDATE',
'GROUP_PARTICIPANTS_UPDATE',
'CALL'
)
).min(1).when('enabled', {
is: true,
then: Joi.required(),
otherwise: Joi.optional(),
}),
headers: Joi.object().pattern(
Joi.string(),
Joi.string()
).optional(),
byEvents: Joi.boolean().optional().default(false),
base64: Joi.boolean().optional().default(false),
}).required();
```
## Chatbot Validation Schemas
### Base Chatbot Validation
```typescript
export const baseChatbotSchema = Joi.object({
enabled: Joi.boolean().required(),
description: Joi.string().required().min(1).max(500),
expire: Joi.number().optional().min(0).max(86400), // 24 hours in seconds
keywordFinish: Joi.string().optional().max(100),
delayMessage: Joi.number().optional().min(0).max(10000),
unknownMessage: Joi.string().optional().max(1000),
listeningFromMe: Joi.boolean().optional().default(false),
stopBotFromMe: Joi.boolean().optional().default(false),
keepOpen: Joi.boolean().optional().default(false),
debounceTime: Joi.number().optional().min(0).max(60000),
triggerType: Joi.string().required().valid('ALL', 'KEYWORD', 'REGEX'),
triggerOperator: Joi.string().when('triggerType', {
is: 'KEYWORD',
then: Joi.required().valid('EQUALS', 'CONTAINS', 'STARTS_WITH', 'ENDS_WITH'),
otherwise: Joi.optional(),
}),
triggerValue: Joi.string().when('triggerType', {
is: Joi.valid('KEYWORD', 'REGEX'),
then: Joi.required().min(1).max(500),
otherwise: Joi.optional(),
}),
ignoreJids: Joi.array().items(Joi.string()).optional(),
splitMessages: Joi.boolean().optional().default(false),
timePerChar: Joi.number().optional().min(10).max(1000).default(100),
}).required();
export const typebotSchema = baseChatbotSchema.keys({
url: Joi.string().required().uri({ scheme: ['http', 'https'] }),
typebot: Joi.string().required().min(1).max(100),
apiVersion: Joi.string().optional().valid('v1', 'v2').default('v1'),
}).required();
export const openaiSchema = baseChatbotSchema.keys({
apiKey: Joi.string().required().min(10),
model: Joi.string().optional().valid(
'gpt-3.5-turbo',
'gpt-3.5-turbo-16k',
'gpt-4',
'gpt-4-32k',
'gpt-4-turbo-preview'
).default('gpt-3.5-turbo'),
systemMessage: Joi.string().optional().max(2000),
maxTokens: Joi.number().optional().min(1).max(4000).default(1000),
temperature: Joi.number().optional().min(0).max(2).default(0.7),
}).required();
```
## Business API Validation Schemas
### Template Validation
```typescript
export const templateSchema = Joi.object({
name: Joi.string().required().min(1).max(512).pattern(/^[a-z0-9_]+$/),
category: Joi.string().required().valid('MARKETING', 'UTILITY', 'AUTHENTICATION'),
allowCategoryChange: Joi.boolean().required(),
language: Joi.string().required().pattern(/^[a-z]{2}_[A-Z]{2}$/), // e.g., pt_BR, en_US
components: Joi.array().items(
Joi.object({
type: Joi.string().required().valid('HEADER', 'BODY', 'FOOTER', 'BUTTONS'),
format: Joi.string().when('type', {
is: 'HEADER',
then: Joi.valid('TEXT', 'IMAGE', 'VIDEO', 'DOCUMENT'),
otherwise: Joi.optional(),
}),
text: Joi.string().when('type', {
is: Joi.valid('HEADER', 'BODY', 'FOOTER'),
then: Joi.required().min(1).max(1024),
otherwise: Joi.optional(),
}),
buttons: Joi.array().when('type', {
is: 'BUTTONS',
then: Joi.items(
Joi.object({
type: Joi.string().required().valid('QUICK_REPLY', 'URL', 'PHONE_NUMBER'),
text: Joi.string().required().min(1).max(25),
url: Joi.string().when('type', {
is: 'URL',
then: Joi.required().uri(),
otherwise: Joi.optional(),
}),
phone_number: Joi.string().when('type', {
is: 'PHONE_NUMBER',
then: Joi.required().pattern(/^\+?\d+$/),
otherwise: Joi.optional(),
}),
})
).min(1).max(10),
otherwise: Joi.optional(),
}),
})
).min(1).required(),
webhookUrl: Joi.string().optional().uri({ scheme: ['http', 'https'] }),
}).required();
export const catalogSchema = Joi.object({
number: Joi.string().optional().pattern(/^\d+$/),
limit: Joi.number().optional().min(1).max(1000).default(10),
cursor: Joi.string().optional(),
}).optional();
```
## Group Validation Schemas
### Group Management Validation
```typescript
export const createGroupSchema = Joi.object({
subject: Joi.string().required().min(1).max(100),
description: Joi.string().optional().max(500),
participants: Joi.array().items(
Joi.string().pattern(/^\d+$/)
).min(1).max(256).required(),
promoteParticipants: Joi.boolean().optional().default(false),
}).required();
export const updateGroupSchema = Joi.object({
subject: Joi.string().optional().min(1).max(100),
description: Joi.string().optional().max(500),
}).min(1).required();
export const groupParticipantsSchema = Joi.object({
participants: Joi.array().items(
Joi.string().pattern(/^\d+$/)
).min(1).max(50).required(),
action: Joi.string().required().valid('add', 'remove', 'promote', 'demote'),
}).required();
```
## Label Validation Schemas
### Label Management Validation
```typescript
export const labelSchema = Joi.object({
name: Joi.string().required().min(1).max(100),
color: Joi.string().required().pattern(/^#[0-9A-Fa-f]{6}$/), // Hex color
predefinedId: Joi.string().optional(),
}).required();
export const handleLabelSchema = Joi.object({
number: Joi.string().required().pattern(/^\d+$/),
labelId: Joi.string().required(),
action: Joi.string().required().valid('add', 'remove'),
}).required();
```
## Custom Validation Functions
### Phone Number Validation
```typescript
export function validatePhoneNumber(number: string): boolean {
// Remove any non-digit characters
const cleaned = number.replace(/\D/g, '');
// Check minimum and maximum length
if (cleaned.length < 10 || cleaned.length > 15) {
return false;
}
// Check for valid country codes (basic validation)
const validCountryCodes = ['1', '7', '20', '27', '30', '31', '32', '33', '34', '36', '39', '40', '41', '43', '44', '45', '46', '47', '48', '49', '51', '52', '53', '54', '55', '56', '57', '58', '60', '61', '62', '63', '64', '65', '66', '81', '82', '84', '86', '90', '91', '92', '93', '94', '95', '98'];
// Check if starts with valid country code
const startsWithValidCode = validCountryCodes.some(code => cleaned.startsWith(code));
return startsWithValidCode;
}
export const phoneNumberValidator = Joi.string().custom((value, helpers) => {
if (!validatePhoneNumber(value)) {
return helpers.error('any.invalid');
}
return value;
}, 'Phone number validation');
```
### Base64 Validation
```typescript
export function validateBase64(base64: string): boolean {
try {
// Check if it's a valid base64 string
const decoded = Buffer.from(base64, 'base64').toString('base64');
return decoded === base64;
} catch {
return false;
}
}
export const base64Validator = Joi.string().custom((value, helpers) => {
if (!validateBase64(value)) {
return helpers.error('any.invalid');
}
return value;
}, 'Base64 validation');
```
### URL Validation with Protocol Check
```typescript
export function validateWebhookUrl(url: string): boolean {
try {
const parsed = new URL(url);
return ['http:', 'https:'].includes(parsed.protocol);
} catch {
return false;
}
}
export const webhookUrlValidator = Joi.string().custom((value, helpers) => {
if (!validateWebhookUrl(value)) {
return helpers.error('any.invalid');
}
return value;
}, 'Webhook URL validation');
```
## Validation Error Handling
### Error Message Customization
```typescript
export const validationMessages = {
'any.required': 'O campo {#label} é obrigatório',
'string.empty': 'O campo {#label} não pode estar vazio',
'string.min': 'O campo {#label} deve ter pelo menos {#limit} caracteres',
'string.max': 'O campo {#label} deve ter no máximo {#limit} caracteres',
'string.pattern.base': 'O campo {#label} possui formato inválido',
'number.min': 'O campo {#label} deve ser maior ou igual a {#limit}',
'number.max': 'O campo {#label} deve ser menor ou igual a {#limit}',
'array.min': 'O campo {#label} deve ter pelo menos {#limit} itens',
'array.max': 'O campo {#label} deve ter no máximo {#limit} itens',
'any.only': 'O campo {#label} deve ser um dos valores: {#valids}',
};
export function formatValidationError(error: Joi.ValidationError): any {
return {
message: 'Dados de entrada inválidos',
details: error.details.map(detail => ({
field: detail.path.join('.'),
message: detail.message,
value: detail.context?.value,
})),
};
}
```
## Schema Composition
### Reusable Schema Components
```typescript
export const commonFields = {
instanceName: Joi.string().required().min(1).max(100).pattern(/^[a-zA-Z0-9_-]+$/),
number: phoneNumberValidator.required(),
delay: Joi.number().optional().min(0).max(60000),
enabled: Joi.boolean().optional().default(true),
};
export const mediaFields = {
mediatype: Joi.string().required().valid('image', 'video', 'audio', 'document'),
media: Joi.alternatives().try(
Joi.string().uri(),
base64Validator,
).required(),
caption: Joi.string().optional().max(1024),
fileName: Joi.string().optional().max(255),
};
// Compose schemas using common fields
export const quickMessageSchema = Joi.object({
...commonFields,
text: Joi.string().required().min(1).max(4096),
}).required();
export const quickMediaSchema = Joi.object({
...commonFields,
...mediaFields,
}).required();
```

View File

@ -1,3 +1,4 @@
SERVER_NAME=evolution
SERVER_TYPE=http
SERVER_PORT=8080
# Server URL - Set your application url
@ -8,6 +9,28 @@ SSL_CONF_FULLCHAIN=/path/to/cert.crt
SENTRY_DSN=
# Telemetry - Set to false to disable telemetry
TELEMETRY_ENABLED=true
TELEMETRY_URL=
# Prometheus metrics - Set to true to enable Prometheus metrics
PROMETHEUS_METRICS=false
METRICS_AUTH_REQUIRED=true
METRICS_USER=prometheus
METRICS_PASSWORD=secure_random_password_here
METRICS_ALLOWED_IPS=127.0.0.1,10.0.0.100,192.168.1.50
# Proxy configuration (optional)
PROXY_HOST=
PROXY_PORT=
PROXY_PROTOCOL=
PROXY_USERNAME=
PROXY_PASSWORD=
# Audio converter API (optional)
API_AUDIO_CONVERTER=
API_AUDIO_CONVERTER_KEY=
# Cors - * for all or set separate by commas - ex.: 'yourdomain1.com, yourdomain2.com'
CORS_ORIGIN=*
CORS_METHODS=GET,POST,PUT,DELETE
@ -96,9 +119,40 @@ SQS_SECRET_ACCESS_KEY=
SQS_ACCOUNT_ID=
SQS_REGION=
SQS_GLOBAL_ENABLED=false
SQS_GLOBAL_FORCE_SINGLE_QUEUE=false
SQS_GLOBAL_APPLICATION_STARTUP=false
SQS_GLOBAL_CALL=false
SQS_GLOBAL_CHATS_DELETE=false
SQS_GLOBAL_CHATS_SET=false
SQS_GLOBAL_CHATS_UPDATE=false
SQS_GLOBAL_CHATS_UPSERT=false
SQS_GLOBAL_CONNECTION_UPDATE=false
SQS_GLOBAL_CONTACTS_SET=false
SQS_GLOBAL_CONTACTS_UPDATE=false
SQS_GLOBAL_CONTACTS_UPSERT=false
SQS_GLOBAL_GROUP_PARTICIPANTS_UPDATE=false
SQS_GLOBAL_GROUPS_UPDATE=false
SQS_GLOBAL_GROUPS_UPSERT=false
SQS_GLOBAL_LABELS_ASSOCIATION=false
SQS_GLOBAL_LABELS_EDIT=false
SQS_GLOBAL_LOGOUT_INSTANCE=false
SQS_GLOBAL_MESSAGES_DELETE=false
SQS_GLOBAL_MESSAGES_EDITED=false
SQS_GLOBAL_MESSAGES_SET=false
SQS_GLOBAL_MESSAGES_UPDATE=false
SQS_GLOBAL_MESSAGES_UPSERT=false
SQS_GLOBAL_PRESENCE_UPDATE=false
SQS_GLOBAL_QRCODE_UPDATED=false
SQS_GLOBAL_REMOVE_INSTANCE=false
SQS_GLOBAL_SEND_MESSAGE=false
SQS_GLOBAL_TYPEBOT_CHANGE_STATUS=false
SQS_GLOBAL_TYPEBOT_START=false
# Websocket - Environment variables
WEBSOCKET_ENABLED=false
WEBSOCKET_GLOBAL_EVENTS=false
WEBSOCKET_ALLOWED_HOSTS=127.0.0.1,::1,::ffff:127.0.0.1
# Pusher - Environment variables
PUSHER_ENABLED=false

81
.github/ISSUE_TEMPLATE/bug_report.yml vendored Normal file
View File

@ -0,0 +1,81 @@
name: 🐛 Bug Report
description: Report a bug or unexpected behavior
title: "[BUG] "
labels: ["bug", "needs-triage"]
assignees: []
body:
- type: markdown
attributes:
value: |
Thanks for taking the time to fill out this bug report!
Please search existing issues before creating a new one.
- type: textarea
id: description
attributes:
label: 📋 Bug Description
description: A clear and concise description of what the bug is.
placeholder: Describe the bug...
validations:
required: true
- type: textarea
id: reproduction
attributes:
label: 🔄 Steps to Reproduce
description: Steps to reproduce the behavior
placeholder: |
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
4. See error
validations:
required: true
- type: textarea
id: expected
attributes:
label: ✅ Expected Behavior
description: A clear and concise description of what you expected to happen.
placeholder: What should happen?
validations:
required: true
- type: textarea
id: actual
attributes:
label: ❌ Actual Behavior
description: A clear and concise description of what actually happened.
placeholder: What actually happened?
validations:
required: true
- type: textarea
id: environment
attributes:
label: 🌍 Environment
description: Please provide information about your environment
value: |
- OS: [e.g. Ubuntu 20.04, Windows 10, macOS 12.0]
- Node.js version: [e.g. 18.17.0]
- Evolution API version: [e.g. 2.3.3]
- Database: [e.g. PostgreSQL 14, MySQL 8.0]
- Connection type: [e.g. Baileys, WhatsApp Business API]
validations:
required: true
- type: textarea
id: logs
attributes:
label: 📋 Logs
description: If applicable, add logs to help explain your problem.
placeholder: Paste relevant logs here...
render: shell
- type: textarea
id: additional
attributes:
label: 📝 Additional Context
description: Add any other context about the problem here.
placeholder: Any additional information...

View File

@ -0,0 +1,85 @@
name: ✨ Feature Request
description: Suggest a new feature or enhancement
title: "[FEATURE] "
labels: ["enhancement", "needs-triage"]
assignees: []
body:
- type: markdown
attributes:
value: |
Thanks for suggesting a new feature!
Please check our [Feature Requests on Canny](https://evolutionapi.canny.io/feature-requests) first.
- type: textarea
id: problem
attributes:
label: 🎯 Problem Statement
description: Is your feature request related to a problem? Please describe.
placeholder: A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
validations:
required: true
- type: textarea
id: solution
attributes:
label: 💡 Proposed Solution
description: Describe the solution you'd like
placeholder: A clear and concise description of what you want to happen.
validations:
required: true
- type: textarea
id: alternatives
attributes:
label: 🔄 Alternatives Considered
description: Describe alternatives you've considered
placeholder: A clear and concise description of any alternative solutions or features you've considered.
- type: dropdown
id: priority
attributes:
label: 📊 Priority
description: How important is this feature to you?
options:
- Low - Nice to have
- Medium - Would be helpful
- High - Important for my use case
- Critical - Blocking my work
validations:
required: true
- type: dropdown
id: component
attributes:
label: 🧩 Component
description: Which component does this feature relate to?
options:
- WhatsApp Integration (Baileys)
- WhatsApp Business API
- Chatwoot Integration
- Typebot Integration
- OpenAI Integration
- Dify Integration
- API Endpoints
- Database
- Authentication
- Webhooks
- File Storage
- Other
- type: textarea
id: use_case
attributes:
label: 🎯 Use Case
description: Describe your specific use case for this feature
placeholder: How would you use this feature? What problem does it solve for you?
validations:
required: true
- type: textarea
id: additional
attributes:
label: 📝 Additional Context
description: Add any other context, screenshots, or examples about the feature request here.
placeholder: Any additional information, mockups, or examples...

38
.github/dependabot.yml vendored Normal file
View File

@ -0,0 +1,38 @@
version: 2
updates:
# Enable version updates for npm
- package-ecosystem: "npm"
directory: "/"
schedule:
interval: "weekly"
day: "monday"
time: "09:00"
open-pull-requests-limit: 10
commit-message:
prefix: "chore"
prefix-development: "chore"
include: "scope"
# Enable version updates for GitHub Actions
- package-ecosystem: "github-actions"
directory: "/"
schedule:
interval: "weekly"
day: "monday"
time: "09:00"
open-pull-requests-limit: 5
commit-message:
prefix: "ci"
include: "scope"
# Enable version updates for Docker
- package-ecosystem: "docker"
directory: "/"
schedule:
interval: "weekly"
day: "monday"
time: "09:00"
open-pull-requests-limit: 5
commit-message:
prefix: "chore"
include: "scope"

41
.github/pull_request_template.md vendored Normal file
View File

@ -0,0 +1,41 @@
## 📋 Description
<!-- Describe your changes in detail -->
## 🔗 Related Issue
<!-- Link to the issue this PR addresses -->
Closes #(issue_number)
## 🧪 Type of Change
<!-- Mark with an `x` all the checkboxes that apply -->
- [ ] 🐛 Bug fix (non-breaking change which fixes an issue)
- [ ] ✨ New feature (non-breaking change which adds functionality)
- [ ] 💥 Breaking change (fix or feature that would cause existing functionality to not work as expected)
- [ ] 📚 Documentation update
- [ ] 🔧 Refactoring (no functional changes)
- [ ] ⚡ Performance improvement
- [ ] 🧹 Code cleanup
- [ ] 🔒 Security fix
## 🧪 Testing
<!-- Describe the testing you performed to verify your changes -->
- [ ] Manual testing completed
- [ ] Functionality verified in development environment
- [ ] No breaking changes introduced
- [ ] Tested with different connection types (if applicable)
## 📸 Screenshots (if applicable)
<!-- Add screenshots to help explain your changes -->
## ✅ Checklist
<!-- Mark with an `x` all the checkboxes that apply -->
- [ ] My code follows the project's style guidelines
- [ ] I have performed a self-review of my code
- [ ] I have commented my code, particularly in hard-to-understand areas
- [ ] I have made corresponding changes to the documentation
- [ ] My changes generate no new warnings
- [ ] I have manually tested my changes thoroughly
- [ ] I have verified the changes work with different scenarios
- [ ] Any dependent changes have been merged and published
## 📝 Additional Notes
<!-- Any additional information, concerns, or questions -->

View File

@ -1,6 +1,10 @@
name: Check Code Quality
on: [pull_request]
on:
pull_request:
branches: [ main, develop ]
push:
branches: [ main, develop ]
jobs:
check-lint-and-build:
@ -8,20 +12,28 @@ jobs:
timeout-minutes: 10
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v4
- name: Install Node
uses: actions/setup-node@v1
uses: actions/setup-node@v4
with:
node-version: 20.x
- name: Cache node modules
uses: actions/cache@v3
with:
path: ~/.npm
key: ${{ runner.os }}-node-${{ hashFiles('**/package-lock.json') }}
restore-keys: |
${{ runner.os }}-node-
- name: Install packages
run: npm install
run: npm ci
- name: Check linting
run: npm run lint:check
- name: Check build
- name: Generate Prisma client
run: npm run db:generate
- name: Check build

51
.github/workflows/security.yml vendored Normal file
View File

@ -0,0 +1,51 @@
name: Security Scan
on:
push:
branches: [ main, develop ]
pull_request:
branches: [ main, develop ]
schedule:
- cron: '0 0 * * 1' # Weekly on Mondays
jobs:
codeql:
name: CodeQL Analysis
runs-on: ubuntu-latest
timeout-minutes: 15
permissions:
actions: read
contents: read
security-events: write
strategy:
fail-fast: false
matrix:
language: [ 'javascript' ]
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Initialize CodeQL
uses: github/codeql-action/init@v3
with:
languages: ${{ matrix.language }}
- name: Autobuild
uses: github/codeql-action/autobuild@v3
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v3
with:
category: "/language:${{matrix.language}}"
dependency-review:
name: Dependency Review
runs-on: ubuntu-latest
if: github.event_name == 'pull_request'
steps:
- name: Checkout Repository
uses: actions/checkout@v4
- name: Dependency Review
uses: actions/dependency-review-action@v4

6
.gitignore vendored
View File

@ -1,13 +1,11 @@
# Repo
Baileys
# compiled output
/dist
/node_modules
.cursor*
/Docker/.env
.vscode
# Logs
logs/**.json
*.log

51
.husky/README.md Normal file
View File

@ -0,0 +1,51 @@
# Git Hooks Configuration
Este projeto usa [Husky](https://typicode.github.io/husky/) para automatizar verificações de qualidade de código.
## Hooks Configurados
### Pre-commit
- **Arquivo**: `.husky/pre-commit`
- **Executa**: `npx lint-staged`
- **Função**: Executa lint e correções automáticas apenas nos arquivos modificados
### Pre-push
- **Arquivo**: `.husky/pre-push`
- **Executa**: `npm run build` + `npm run lint:check`
- **Função**: Verifica se o projeto compila e não tem erros de lint antes do push
## Lint-staged Configuration
Configurado no `package.json`:
```json
"lint-staged": {
"src/**/*.{ts,js}": [
"eslint --fix",
"git add"
],
"src/**/*.ts": [
"npm run build"
]
}
```
## Como funciona
1. **Ao fazer commit**: Executa lint apenas nos arquivos modificados
2. **Ao fazer push**: Executa build completo e verificação de lint
3. **Se houver erros**: O commit/push é bloqueado até correção
## Comandos úteis
```bash
# Pular hooks (não recomendado)
git commit --no-verify
git push --no-verify
# Executar lint manualmente
npm run lint
# Executar build manualmente
npm run build
```

1
.husky/commit-msg Executable file
View File

@ -0,0 +1 @@
npx --no -- commitlint --edit $1

1
.husky/pre-commit Normal file
View File

@ -0,0 +1 @@
npx lint-staged

2
.husky/pre-push Executable file
View File

@ -0,0 +1,2 @@
npm run build
npm run lint:check

355
AGENTS.md Normal file
View File

@ -0,0 +1,355 @@
# Evolution API - AI Agent Guidelines
This document provides comprehensive guidelines for AI agents (Claude, GPT, Cursor, etc.) working with the Evolution API codebase.
## Project Overview
**Evolution API** is a production-ready, multi-tenant WhatsApp API platform built with Node.js, TypeScript, and Express.js. It supports multiple WhatsApp providers and extensive integrations with chatbots, CRM systems, and messaging platforms.
## Project Structure & Module Organization
### Core Directories
- **`src/`** TypeScript source code with modular architecture
- `api/controllers/` HTTP route handlers (thin layer)
- `api/services/` Business logic (core functionality)
- `api/routes/` Express route definitions (RouterBroker pattern)
- `api/integrations/` External service integrations
- `channel/` WhatsApp providers (Baileys, Business API, Evolution)
- `chatbot/` AI/Bot integrations (OpenAI, Dify, Typebot, Chatwoot)
- `event/` Event systems (WebSocket, RabbitMQ, SQS, NATS, Pusher)
- `storage/` File storage (S3, MinIO)
- `dto/` Data Transfer Objects (simple classes, no decorators)
- `guards/` Authentication/authorization middleware
- `types/` TypeScript type definitions
- `repository/` Data access layer (Prisma)
- **`prisma/`** Database schemas and migrations
- `postgresql-schema.prisma` / `mysql-schema.prisma` Provider-specific schemas
- `postgresql-migrations/` / `mysql-migrations/` Provider-specific migrations
- **`config/`** Environment and application configuration
- **`utils/`** Shared utilities and helper functions
- **`validate/`** JSONSchema7 validation schemas
- **`exceptions/`** Custom HTTP exception classes
- **`cache/`** Redis and local cache implementations
### Build & Deployment
- **`dist/`** Build output (do not edit directly)
- **`public/`** Static assets and media files
- **`Docker*`**, **`docker-compose*.yaml`** Containerization and local development stack
## Build, Test, and Development Commands
### Development Workflow
```bash
# Development server with hot reload
npm run dev:server
# Direct execution for testing
npm start
# Production build and run
npm run build
npm run start:prod
```
### Code Quality
```bash
# Linting and formatting
npm run lint # ESLint with auto-fix
npm run lint:check # ESLint check only
# Commit with conventional commits
npm run commit # Interactive commit with Commitizen
```
### Database Management
```bash
# Set database provider first (CRITICAL)
export DATABASE_PROVIDER=postgresql # or mysql
# Generate Prisma client
npm run db:generate
# Development migrations (with provider sync)
npm run db:migrate:dev # Unix/Mac
npm run db:migrate:dev:win # Windows
# Production deployment
npm run db:deploy # Unix/Mac
npm run db:deploy:win # Windows
# Database tools
npm run db:studio # Open Prisma Studio
```
### Docker Development
```bash
# Start local services (Redis, PostgreSQL, etc.)
docker-compose up -d
# Full development stack
docker-compose -f docker-compose.dev.yaml up -d
```
## Coding Standards & Architecture Patterns
### Code Style (Enforced by ESLint + Prettier)
- **TypeScript strict mode** with full type coverage
- **2-space indentation**, single quotes, trailing commas
- **120-character line limit**
- **Import order** via `simple-import-sort`
- **File naming**: `feature.kind.ts` (e.g., `whatsapp.baileys.service.ts`)
- **Naming conventions**:
- Classes: `PascalCase`
- Functions/variables: `camelCase`
- Constants: `UPPER_SNAKE_CASE`
- Files: `kebab-case.type.ts`
### Architecture Patterns
#### Service Layer Pattern
```typescript
export class ExampleService {
constructor(private readonly waMonitor: WAMonitoringService) {}
private readonly logger = new Logger('ExampleService');
public async create(instance: InstanceDto, data: ExampleDto) {
// Business logic here
return { example: { ...instance, data } };
}
public async find(instance: InstanceDto): Promise<ExampleDto | null> {
try {
const result = await this.waMonitor.waInstances[instance.instanceName].findData();
return result || null; // Return null on not found (Evolution pattern)
} catch (error) {
this.logger.error('Error finding data:', error);
return null; // Return null on error (Evolution pattern)
}
}
}
```
#### Controller Pattern (Thin Layer)
```typescript
export class ExampleController {
constructor(private readonly exampleService: ExampleService) {}
public async createExample(instance: InstanceDto, data: ExampleDto) {
return this.exampleService.create(instance, data);
}
}
```
#### RouterBroker Pattern
```typescript
export class ExampleRouter extends RouterBroker {
constructor(...guards: any[]) {
super();
this.router.post(this.routerPath('create'), ...guards, async (req, res) => {
const response = await this.dataValidate<ExampleDto>({
request: req,
schema: exampleSchema, // JSONSchema7
ClassRef: ExampleDto,
execute: (instance, data) => controller.createExample(instance, data),
});
res.status(201).json(response);
});
}
}
```
#### DTO Pattern (Simple Classes)
```typescript
// CORRECT - Evolution API pattern (no decorators)
export class ExampleDto {
name: string;
description?: string;
enabled: boolean;
}
// INCORRECT - Don't use class-validator decorators
export class BadExampleDto {
@IsString() // ❌ Evolution API doesn't use decorators
name: string;
}
```
#### Validation Pattern (JSONSchema7)
```typescript
import { JSONSchema7 } from 'json-schema';
import { v4 } from 'uuid';
export const exampleSchema: JSONSchema7 = {
$id: v4(),
type: 'object',
properties: {
name: { type: 'string' },
description: { type: 'string' },
enabled: { type: 'boolean' },
},
required: ['name', 'enabled'],
};
```
## Multi-Tenant Architecture
### Instance Isolation
- **CRITICAL**: All operations must be scoped by `instanceName` or `instanceId`
- **Database queries**: Always include `where: { instanceId: ... }`
- **Authentication**: Validate instance ownership before operations
- **Data isolation**: Complete separation between tenant instances
### WhatsApp Instance Management
```typescript
// Access instance via WAMonitoringService
const waInstance = this.waMonitor.waInstances[instance.instanceName];
if (!waInstance) {
throw new NotFoundException(`Instance ${instance.instanceName} not found`);
}
```
## Database Patterns
### Multi-Provider Support
- **PostgreSQL**: Uses `@db.Integer`, `@db.JsonB`, `@default(now())`
- **MySQL**: Uses `@db.Int`, `@db.Json`, `@default(now())`
- **Environment**: Set `DATABASE_PROVIDER=postgresql` or `mysql`
- **Migrations**: Provider-specific folders auto-selected
### Prisma Repository Pattern
```typescript
// Always use PrismaRepository for database operations
const result = await this.prismaRepository.instance.findUnique({
where: { name: instanceName },
});
```
## Integration Patterns
### Channel Integration (WhatsApp Providers)
- **Baileys**: WhatsApp Web with QR code authentication
- **Business API**: Official Meta WhatsApp Business API
- **Evolution API**: Custom WhatsApp integration
- **Pattern**: Extend base channel service classes
### Chatbot Integration
- **Base classes**: Extend `BaseChatbotService` and `BaseChatbotController`
- **Trigger system**: Support keyword, regex, and advanced triggers
- **Session management**: Handle conversation state per user
- **Available integrations**: EvolutionBot, OpenAI, Dify, Typebot, Chatwoot, Flowise, N8N, EvoAI
### Event Integration
- **Internal events**: EventEmitter2 for application events
- **External events**: WebSocket, RabbitMQ, SQS, NATS, Pusher
- **Webhook delivery**: Reliable delivery with retry logic
## Testing Guidelines
### Current State
- **No formal test suite** currently implemented
- **Manual testing** is the primary approach
- **Integration testing** in development environment
### Testing Strategy
```typescript
// Place tests in test/ directory as *.test.ts
// Run: npm test (watches test/all.test.ts)
describe('ExampleService', () => {
it('should create example', async () => {
// Mock external dependencies
// Test business logic
// Assert expected behavior
});
});
```
### Recommended Approach
- Focus on **critical business logic** in services
- **Mock external dependencies** (WhatsApp APIs, databases)
- **Integration tests** for API endpoints
- **Manual testing** for WhatsApp connection flows
## Commit & Pull Request Guidelines
### Conventional Commits (Enforced by commitlint)
```bash
# Use interactive commit tool
npm run commit
# Commit format: type(scope): subject (max 100 chars)
# Types: feat, fix, docs, style, refactor, perf, test, chore, ci, build, revert, security
```
### Examples
- `feat(api): add WhatsApp message status endpoint`
- `fix(baileys): resolve connection timeout issue`
- `docs(readme): update installation instructions`
- `refactor(service): extract common message validation logic`
### Pull Request Requirements
- **Clear description** of changes and motivation
- **Linked issues** if applicable
- **Migration impact** (specify database provider)
- **Local testing steps** with screenshots/logs
- **Breaking changes** clearly documented
## Security & Configuration
### Environment Setup
```bash
# Copy example environment file
cp .env.example .env
# NEVER commit secrets to version control
# Set DATABASE_PROVIDER before database commands
export DATABASE_PROVIDER=postgresql # or mysql
```
### Security Best Practices
- **API key authentication** via `apikey` header
- **Input validation** with JSONSchema7
- **Rate limiting** on all endpoints
- **Webhook signature validation**
- **Instance-based access control**
- **Secure defaults** for all configurations
### Vulnerability Reporting
- See `SECURITY.md` for security vulnerability reporting process
- Contact: `contato@evolution-api.com`
## Communication Standards
### Language Requirements
- **User communication**: Always respond in Portuguese (PT-BR)
- **Code/comments**: English for technical documentation
- **API responses**: English for consistency
- **Error messages**: Portuguese for user-facing errors
### Documentation Standards
- **Inline comments**: Document complex business logic
- **API documentation**: Document all public endpoints
- **Integration guides**: Document new integration patterns
- **Migration guides**: Document database schema changes
## Performance & Scalability
### Caching Strategy
- **Redis primary**: Distributed caching for production
- **Node-cache fallback**: Local caching when Redis unavailable
- **TTL strategy**: Appropriate cache expiration per data type
- **Cache invalidation**: Proper invalidation on data changes
### Connection Management
- **Database**: Prisma connection pooling
- **WhatsApp**: One connection per instance with lifecycle management
- **Redis**: Connection pooling and retry logic
- **External APIs**: Rate limiting and retry with exponential backoff
### Monitoring & Observability
- **Structured logging**: Pino logger with correlation IDs
- **Error tracking**: Comprehensive error scenarios
- **Health checks**: Instance status and connection monitoring
- **Telemetry**: Usage analytics (non-sensitive data only)

View File

@ -1,3 +1,35 @@
# 2.3.3 (2025-09-18)
### Features
* Add extra fields to object sent to Flowise bot
* Add Prometheus-compatible /metrics endpoint (gated by PROMETHEUS_METRICS)
* Implement linkPreview support for Evolution Bot
### Fixed
* Address Path Traversal vulnerability in /assets endpoint by implementing security checks
* Configure Husky and lint-staged for automated code quality checks on commits and pushes
* Convert mediaKey from media messages to avoid bad decrypt errors
* Improve code formatting for better readability in WhatsApp service files
* Format messageGroupId assignment for improved readability
* Improve linkPreview implementation based on PR feedback
* Clean up code formatting for linkPreview implementation
* Use 'unknown' as fallback for clientName label
* Remove abort process when status is paused, allowing the chatbot return after the time expires and after being paused due to human interaction (stopBotFromMe)
* Enhance message content sanitization in Baileys service and improve message retrieval logic in Chatwoot service
* Integrate Typebot status change events for webhook in chatbot controller and service
* Mimetype of videos video
### Security
* **CRITICAL**: Fixed Path Traversal vulnerability in /assets endpoint that allowed unauthenticated local file read
* Customizable Websockets Security
### Testing
* Baileys Updates: v7.0.0-rc.3 ([Link](https://github.com/WhiskeySockets/Baileys/releases/tag/v7.0.0-rc.3))
# 2.3.2 (2025-09-02)
### Features

223
CLAUDE.md Normal file
View File

@ -0,0 +1,223 @@
# CLAUDE.md
This file provides comprehensive guidance to Claude AI when working with the Evolution API codebase.
## Project Overview
**Evolution API** is a powerful, production-ready REST API for WhatsApp communication that supports multiple WhatsApp providers:
- **Baileys** (WhatsApp Web) - Open-source WhatsApp Web client
- **Meta Business API** - Official WhatsApp Business API
- **Evolution API** - Custom WhatsApp integration
Built with **Node.js 20+**, **TypeScript 5+**, and **Express.js**, it provides extensive integrations with chatbots, CRM systems, and messaging platforms in a **multi-tenant architecture**.
## Common Development Commands
### Build and Run
```bash
# Development
npm run dev:server # Run in development with hot reload (tsx watch)
# Production
npm run build # TypeScript check + tsup build
npm run start:prod # Run production build
# Direct execution
npm start # Run with tsx
```
### Code Quality
```bash
npm run lint # ESLint with auto-fix
npm run lint:check # ESLint check only
npm run commit # Interactive commit with commitizen
```
### Database Management
```bash
# Set database provider first
export DATABASE_PROVIDER=postgresql # or mysql
# Generate Prisma client (automatically uses DATABASE_PROVIDER env)
npm run db:generate
# Deploy migrations (production)
npm run db:deploy # Unix/Mac
npm run db:deploy:win # Windows
# Development migrations (with sync to provider folder)
npm run db:migrate:dev # Unix/Mac
npm run db:migrate:dev:win # Windows
# Open Prisma Studio
npm run db:studio
# Development migrations
npm run db:migrate:dev # Unix/Mac
npm run db:migrate:dev:win # Windows
```
### Testing
```bash
npm test # Run tests with watch mode
```
## Architecture Overview
### Core Structure
- **Multi-tenant SaaS**: Complete instance isolation with per-tenant authentication
- **Multi-provider database**: PostgreSQL and MySQL via Prisma ORM with provider-specific schemas and migrations
- **WhatsApp integrations**: Baileys, Meta Business API, and Evolution API with unified interface
- **Event-driven architecture**: EventEmitter2 for internal events + WebSocket, RabbitMQ, SQS, NATS, Pusher for external events
- **Microservices pattern**: Modular integrations for chatbots, storage, and external services
### Directory Layout
```
src/
├── api/
│ ├── controllers/ # HTTP route handlers (thin layer)
│ ├── services/ # Business logic (core functionality)
│ ├── repository/ # Data access layer (Prisma)
│ ├── dto/ # Data Transfer Objects (simple classes)
│ ├── guards/ # Authentication/authorization middleware
│ ├── integrations/ # External service integrations
│ │ ├── channel/ # WhatsApp providers (Baileys, Business API, Evolution)
│ │ ├── chatbot/ # AI/Bot integrations (OpenAI, Dify, Typebot, Chatwoot)
│ │ ├── event/ # Event systems (WebSocket, RabbitMQ, SQS, NATS, Pusher)
│ │ └── storage/ # File storage (S3, MinIO)
│ ├── routes/ # Express route definitions (RouterBroker pattern)
│ └── types/ # TypeScript type definitions
├── config/ # Environment and app configuration
├── cache/ # Redis and local cache implementations
├── exceptions/ # Custom HTTP exception classes
├── utils/ # Shared utilities and helpers
└── validate/ # JSONSchema7 validation schemas
```
### Key Integration Points
**Channel Integrations** (`src/api/integrations/channel/`):
- **Baileys**: WhatsApp Web client with QR code authentication
- **Business API**: Official Meta WhatsApp Business API
- **Evolution API**: Custom WhatsApp integration
- Connection lifecycle management per instance with automatic reconnection
**Chatbot Integrations** (`src/api/integrations/chatbot/`):
- **EvolutionBot**: Native chatbot with trigger system
- **Chatwoot**: Customer service platform integration
- **Typebot**: Visual chatbot flow builder
- **OpenAI**: AI capabilities including GPT and Whisper (audio transcription)
- **Dify**: AI agent workflow platform
- **Flowise**: LangChain visual builder
- **N8N**: Workflow automation platform
- **EvoAI**: Custom AI integration
**Event Integrations** (`src/api/integrations/event/`):
- **WebSocket**: Real-time Socket.io connections
- **RabbitMQ**: Message queue for async processing
- **Amazon SQS**: Cloud-based message queuing
- **NATS**: High-performance messaging system
- **Pusher**: Real-time push notifications
**Storage Integrations** (`src/api/integrations/storage/`):
- **AWS S3**: Cloud object storage
- **MinIO**: Self-hosted S3-compatible storage
- Media file management and URL generation
### Database Schema Management
- Separate schema files: `postgresql-schema.prisma` and `mysql-schema.prisma`
- Environment variable `DATABASE_PROVIDER` determines active database
- Migration folders are provider-specific and auto-selected during deployment
### Authentication & Security
- **API key-based authentication** via `apikey` header (global or per-instance)
- **Instance-specific tokens** for WhatsApp connection authentication
- **Guards system** for route protection and authorization
- **Input validation** using JSONSchema7 with RouterBroker `dataValidate`
- **Rate limiting** and security middleware
- **Webhook signature validation** for external integrations
## Important Implementation Details
### WhatsApp Instance Management
- Each WhatsApp connection is an "instance" with unique name
- Instance data stored in database with connection state
- Session persistence in database or file system (configurable)
- Automatic reconnection handling with exponential backoff
### Message Queue Architecture
- Supports RabbitMQ, Amazon SQS, and WebSocket for events
- Event types: message.received, message.sent, connection.update, etc.
- Configurable per instance which events to send
### Media Handling
- Local storage or S3/Minio for media files
- Automatic media download from WhatsApp
- Media URL generation for external access
- Support for audio transcription via OpenAI
### Multi-tenancy Support
- Instance isolation at database level
- Separate webhook configurations per instance
- Independent integration settings per instance
## Environment Configuration
Key environment variables are defined in `.env.example`. The system uses a strongly-typed configuration system via `src/config/env.config.ts`.
Critical configurations:
- `DATABASE_PROVIDER`: postgresql or mysql
- `DATABASE_CONNECTION_URI`: Database connection string
- `AUTHENTICATION_API_KEY`: Global API authentication
- `REDIS_ENABLED`: Enable Redis cache
- `RABBITMQ_ENABLED`/`SQS_ENABLED`: Message queue options
## Development Guidelines
The project follows comprehensive development standards defined in `.cursor/rules/`:
### Core Principles
- **Always respond in Portuguese (PT-BR)** for user communication
- **Follow established architecture patterns** (Service Layer, RouterBroker, etc.)
- **Robust error handling** with retry logic and graceful degradation
- **Multi-database compatibility** (PostgreSQL and MySQL)
- **Security-first approach** with input validation and rate limiting
- **Performance optimizations** with Redis caching and connection pooling
### Code Standards
- **TypeScript strict mode** with full type coverage
- **JSONSchema7** for input validation (not class-validator)
- **Conventional Commits** enforced by commitlint
- **ESLint + Prettier** for code formatting
- **Service Object pattern** for business logic
- **RouterBroker pattern** for route handling with `dataValidate`
### Architecture Patterns
- **Multi-tenant isolation** at database and instance level
- **Event-driven communication** with EventEmitter2
- **Microservices integration** pattern for external services
- **Connection pooling** and lifecycle management
- **Caching strategy** with Redis primary and Node-cache fallback
## Testing Approach
Currently, the project has minimal formal testing infrastructure:
- **Manual testing** is the primary approach
- **Integration testing** in development environment
- **No unit test suite** currently implemented
- Test files can be placed in `test/` directory as `*.test.ts`
- Run `npm test` for watch mode development testing
### Recommended Testing Strategy
- Focus on **critical business logic** in services
- **Mock external dependencies** (WhatsApp APIs, databases)
- **Integration tests** for API endpoints
- **Manual testing** for WhatsApp connection flows
## Deployment Considerations
- Docker support with `Dockerfile` and `docker-compose.yaml`
- Graceful shutdown handling for connections
- Health check endpoints for monitoring
- Sentry integration for error tracking
- Telemetry for usage analytics (non-sensitive data only)

19
Dockerfile.metrics Normal file
View File

@ -0,0 +1,19 @@
FROM evoapicloud/evolution-api:latest AS base
WORKDIR /evolution
# Copiamos apenas o necessário para recompilar o dist com as mudanças locais
COPY tsconfig.json tsup.config.ts package.json ./
COPY src ./src
# Recompila usando os node_modules já presentes na imagem base
RUN npm run build
# Runtime final: reaproveita a imagem oficial e apenas sobrepõe o dist
FROM evoapicloud/evolution-api:latest AS final
WORKDIR /evolution
COPY --from=base /evolution/dist ./dist
ENV PROMETHEUS_METRICS=true
# Entrada original da imagem oficial já sobe o app em /evolution

View File

@ -7,6 +7,9 @@
[![Discord Community](https://img.shields.io/badge/Discord-Community-blue)](https://evolution-api.com/discord)
[![Postman Collection](https://img.shields.io/badge/Postman-Collection-orange)](https://evolution-api.com/postman)
[![Documentation](https://img.shields.io/badge/Documentation-Official-green)](https://doc.evolution-api.com)
[![Feature Requests](https://img.shields.io/badge/Feature-Requests-purple)](https://evolutionapi.canny.io/feature-requests)
[![Roadmap](https://img.shields.io/badge/Roadmap-Community-blue)](https://evolutionapi.canny.io/feature-requests)
[![Changelog](https://img.shields.io/badge/Changelog-Updates-green)](https://evolutionapi.canny.io/changelog)
[![License](https://img.shields.io/badge/license-Apache--2.0-blue)](./LICENSE)
[![Support](https://img.shields.io/badge/Donation-picpay-green)](https://app.picpay.com/user/davidsongomes1998)
[![Sponsors](https://img.shields.io/badge/Github-sponsor-orange)](https://github.com/sponsors/EvolutionAPI)
@ -67,6 +70,24 @@ Evolution API supports various integrations to enhance its functionality. Below
- Amazon S3 / Minio:
- Store media files received in [Amazon S3](https://aws.amazon.com/pt/s3/) or [Minio](https://min.io/).
## Community & Feedback
We value community input and feedback to continuously improve Evolution API:
### 🚀 Feature Requests & Roadmap
- **[Feature Requests](https://evolutionapi.canny.io/feature-requests)**: Submit new feature ideas and vote on community proposals
- **[Roadmap](https://evolutionapi.canny.io/feature-requests)**: View planned features and development progress
- **[Changelog](https://evolutionapi.canny.io/changelog)**: Stay updated with the latest releases and improvements
### 💬 Community Support
- **[WhatsApp Group](https://evolution-api.com/whatsapp)**: Join our community for support and discussions
- **[Discord Community](https://evolution-api.com/discord)**: Real-time chat with developers and users
- **[GitHub Issues](https://github.com/EvolutionAPI/evolution-api/issues)**: Report bugs and technical issues
### 🔒 Security
- **[Security Policy](./SECURITY.md)**: Guidelines for reporting security vulnerabilities
- **Security Contact**: contato@evolution-api.com
## Telemetry Notice
To continuously improve our services, we have implemented telemetry that collects data on the routes used, the most accessed routes, and the version of the API in use. We would like to assure you that no sensitive or personal data is collected during this process. The telemetry helps us identify improvements and provide a better experience for users.

99
SECURITY.md Normal file
View File

@ -0,0 +1,99 @@
# Security Policy
## Supported Versions
We actively support the following versions of Evolution API with security updates:
| Version | Supported |
| ------- | ------------------ |
| 2.3.x | ✅ Yes |
| 2.2.x | ✅ Yes |
| 2.1.x | ⚠️ Critical fixes only |
| < 2.1 | No |
## Reporting a Vulnerability
We take security vulnerabilities seriously. If you discover a security vulnerability in Evolution API, please help us by reporting it responsibly.
### 🔒 Private Disclosure Process
**Please DO NOT create a public GitHub issue for security vulnerabilities.**
Instead, please report security vulnerabilities via email to:
**📧 contato@evolution-api.com**
### 📋 What to Include
When reporting a vulnerability, please include:
- **Description**: A clear description of the vulnerability
- **Impact**: What an attacker could achieve by exploiting this vulnerability
- **Steps to Reproduce**: Detailed steps to reproduce the issue
- **Proof of Concept**: If possible, include a minimal proof of concept
- **Environment**: Version of Evolution API, OS, Node.js version, etc.
- **Suggested Fix**: If you have ideas for how to fix the issue
### 🕐 Response Timeline
We will acknowledge receipt of your vulnerability report within **48 hours** and will send you regular updates about our progress.
- **Initial Response**: Within 48 hours
- **Status Update**: Within 7 days
- **Resolution Timeline**: Varies based on complexity, typically 30-90 days
### 🎯 Scope
This security policy applies to:
- Evolution API core application
- Official Docker images
- Documentation that could lead to security issues
### 🚫 Out of Scope
The following are generally considered out of scope:
- Third-party integrations (Chatwoot, Typebot, etc.) - please report to respective projects
- Issues in dependencies - please report to the dependency maintainers
- Social engineering attacks
- Physical attacks
- Denial of Service attacks
### 🏆 Recognition
We believe in recognizing security researchers who help us keep Evolution API secure:
- We will acknowledge your contribution in our security advisories (unless you prefer to remain anonymous)
- For significant vulnerabilities, we may feature you in our Hall of Fame
- We will work with you on coordinated disclosure timing
### 📚 Security Best Practices
For users deploying Evolution API:
- Always use the latest supported version
- Keep your dependencies up to date
- Use strong authentication methods
- Implement proper network security
- Monitor your logs for suspicious activity
- Follow the principle of least privilege
### 🔄 Security Updates
Security updates will be:
- Released as patch versions (e.g., 2.3.1 → 2.3.2)
- Documented in our [CHANGELOG.md](./CHANGELOG.md)
- Announced in our community channels
- Tagged with security labels in GitHub releases
## Contact
For any questions about this security policy, please contact:
- **Email**: contato@evolution-api.com
---
Thank you for helping keep Evolution API and our community safe! 🛡️

34
commitlint.config.js Normal file
View File

@ -0,0 +1,34 @@
module.exports = {
extends: ['@commitlint/config-conventional'],
rules: {
'type-enum': [
2,
'always',
[
'feat', // New feature
'fix', // Bug fix
'docs', // Documentation changes
'style', // Code style changes (formatting, etc)
'refactor', // Code refactoring
'perf', // Performance improvements
'test', // Adding or updating tests
'chore', // Maintenance tasks
'ci', // CI/CD changes
'build', // Build system changes
'revert', // Reverting changes
'security', // Security fixes
],
],
'type-case': [2, 'always', 'lower-case'],
'type-empty': [2, 'never'],
'scope-case': [2, 'always', 'lower-case'],
'subject-case': [2, 'never', ['sentence-case', 'start-case', 'pascal-case', 'upper-case']],
'subject-empty': [2, 'never'],
'subject-full-stop': [2, 'never', '.'],
'header-max-length': [2, 'always', 100],
'body-leading-blank': [1, 'always'],
'body-max-line-length': [0, 'always', 150],
'footer-leading-blank': [1, 'always'],
'footer-max-line-length': [0, 'always', 150],
},
};

View File

@ -3,7 +3,7 @@ version: "3.8"
services:
api:
container_name: evolution_api
image: evoapicloud/evolution-api:latest
image: evolution/api:metrics
restart: always
depends_on:
- redis

View File

@ -0,0 +1,238 @@
{
"dashboard": {
"id": null,
"title": "Evolution API Monitoring",
"tags": ["evolution-api", "whatsapp", "monitoring"],
"style": "dark",
"timezone": "browser",
"panels": [
{
"id": 1,
"title": "API Status",
"type": "stat",
"targets": [
{
"expr": "up{job=\"evolution-api\"}",
"legendFormat": "API Status"
}
],
"fieldConfig": {
"defaults": {
"mappings": [
{
"options": {
"0": {
"text": "DOWN",
"color": "red"
},
"1": {
"text": "UP",
"color": "green"
}
},
"type": "value"
}
]
}
},
"gridPos": {
"h": 8,
"w": 12,
"x": 0,
"y": 0
}
},
{
"id": 2,
"title": "Total Instances",
"type": "stat",
"targets": [
{
"expr": "evolution_instances_total",
"legendFormat": "Total Instances"
}
],
"gridPos": {
"h": 8,
"w": 12,
"x": 12,
"y": 0
}
},
{
"id": 3,
"title": "Instance Status Overview",
"type": "piechart",
"targets": [
{
"expr": "sum by (state) (evolution_instance_state)",
"legendFormat": "{{ state }}"
}
],
"gridPos": {
"h": 9,
"w": 12,
"x": 0,
"y": 8
}
},
{
"id": 4,
"title": "Instances by Integration Type",
"type": "piechart",
"targets": [
{
"expr": "sum by (integration) (evolution_instance_up)",
"legendFormat": "{{ integration }}"
}
],
"gridPos": {
"h": 9,
"w": 12,
"x": 12,
"y": 8
}
},
{
"id": 5,
"title": "Instance Uptime",
"type": "table",
"targets": [
{
"expr": "evolution_instance_up",
"format": "table",
"instant": true
}
],
"transformations": [
{
"id": "organize",
"options": {
"excludeByName": {
"Time": true,
"__name__": true
},
"renameByName": {
"instance": "Instance Name",
"integration": "Integration Type",
"Value": "Status"
}
}
}
],
"fieldConfig": {
"overrides": [
{
"matcher": {
"id": "byName",
"options": "Status"
},
"properties": [
{
"id": "mappings",
"value": [
{
"options": {
"0": {
"text": "DOWN",
"color": "red"
},
"1": {
"text": "UP",
"color": "green"
}
},
"type": "value"
}
]
}
]
}
]
},
"gridPos": {
"h": 9,
"w": 24,
"x": 0,
"y": 17
}
},
{
"id": 6,
"title": "Instance Status Timeline",
"type": "timeseries",
"targets": [
{
"expr": "evolution_instance_up",
"legendFormat": "{{ instance }} ({{ integration }})"
}
],
"fieldConfig": {
"defaults": {
"custom": {
"drawStyle": "line",
"lineInterpolation": "stepAfter",
"lineWidth": 2,
"fillOpacity": 10,
"gradientMode": "none",
"spanNulls": false,
"insertNulls": false,
"showPoints": "never",
"pointSize": 5,
"stacking": {
"mode": "none",
"group": "A"
},
"axisPlacement": "auto",
"axisLabel": "",
"scaleDistribution": {
"type": "linear"
},
"hideFrom": {
"legend": false,
"tooltip": false,
"vis": false
},
"thresholdsStyle": {
"mode": "off"
}
},
"min": 0,
"max": 1
}
},
"gridPos": {
"h": 8,
"w": 24,
"x": 0,
"y": 26
}
}
],
"time": {
"from": "now-1h",
"to": "now"
},
"timepicker": {},
"templating": {
"list": []
},
"annotations": {
"list": [
{
"builtIn": 1,
"datasource": "-- Grafana --",
"enable": true,
"hide": true,
"iconColor": "rgba(0, 211, 255, 1)",
"name": "Annotations & Alerts",
"type": "dashboard"
}
]
},
"refresh": "30s",
"schemaVersion": 27,
"version": 0,
"links": []
}
}

6392
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -1,6 +1,6 @@
{
"name": "evolution-api",
"version": "2.3.2",
"version": "2.3.3",
"description": "Rest api for communication with WhatsApp",
"main": "./dist/main.js",
"type": "commonjs",
@ -12,12 +12,15 @@
"test": "tsx watch ./test/all.test.ts",
"lint": "eslint --fix --ext .ts src",
"lint:check": "eslint --ext .ts src",
"commit": "cz",
"commitlint": "commitlint --edit",
"db:generate": "node runWithProvider.js \"npx prisma generate --schema ./prisma/DATABASE_PROVIDER-schema.prisma\"",
"db:deploy": "node runWithProvider.js \"rm -rf ./prisma/migrations && cp -r ./prisma/DATABASE_PROVIDER-migrations ./prisma/migrations && npx prisma migrate deploy --schema ./prisma/DATABASE_PROVIDER-schema.prisma\"",
"db:deploy:win": "node runWithProvider.js \"xcopy /E /I prisma\\DATABASE_PROVIDER-migrations prisma\\migrations && npx prisma migrate deploy --schema prisma\\DATABASE_PROVIDER-schema.prisma\"",
"db:studio": "node runWithProvider.js \"npx prisma studio --schema ./prisma/DATABASE_PROVIDER-schema.prisma\"",
"db:migrate:dev": "node runWithProvider.js \"rm -rf ./prisma/migrations && cp -r ./prisma/DATABASE_PROVIDER-migrations ./prisma/migrations && npx prisma migrate dev --schema ./prisma/DATABASE_PROVIDER-schema.prisma && cp -r ./prisma/migrations/* ./prisma/DATABASE_PROVIDER-migrations\"",
"db:migrate:dev:win": "node runWithProvider.js \"xcopy /E /I prisma\\DATABASE_PROVIDER-migrations prisma\\migrations && npx prisma migrate dev --schema prisma\\DATABASE_PROVIDER-schema.prisma\""
"db:migrate:dev:win": "node runWithProvider.js \"xcopy /E /I prisma\\DATABASE_PROVIDER-migrations prisma\\migrations && npx prisma migrate dev --schema prisma\\DATABASE_PROVIDER-schema.prisma\"",
"prepare": "husky"
},
"repository": {
"type": "git",
@ -48,6 +51,19 @@
"url": "https://github.com/EvolutionAPI/evolution-api/issues"
},
"homepage": "https://github.com/EvolutionAPI/evolution-api#readme",
"lint-staged": {
"src/**/*.{ts,js}": [
"eslint --fix"
],
"src/**/*.ts": [
"sh -c 'npm run build'"
]
},
"config": {
"commitizen": {
"path": "cz-conventional-changelog"
}
},
"dependencies": {
"@adiwajshing/keyed-db": "^0.2.4",
"@aws-sdk/client-sqs": "^3.723.0",
@ -60,7 +76,7 @@
"amqplib": "^0.10.5",
"audio-decode": "^2.2.3",
"axios": "^1.7.9",
"baileys": "github:WhiskeySockets/Baileys",
"baileys": "^7.0.0-rc.3",
"class-validator": "^0.14.1",
"compression": "^1.7.5",
"cors": "^2.8.5",
@ -105,6 +121,8 @@
"tsup": "^8.3.5"
},
"devDependencies": {
"@commitlint/cli": "^19.8.1",
"@commitlint/config-conventional": "^19.8.1",
"@types/compression": "^1.7.5",
"@types/cors": "^2.8.17",
"@types/express": "^4.17.18",
@ -118,14 +136,18 @@
"@types/uuid": "^10.0.0",
"@typescript-eslint/eslint-plugin": "^6.21.0",
"@typescript-eslint/parser": "^6.21.0",
"commitizen": "^4.3.1",
"cz-conventional-changelog": "^3.3.0",
"eslint": "^8.45.0",
"eslint-config-prettier": "^9.1.0",
"eslint-plugin-import": "^2.31.0",
"eslint-plugin-prettier": "^5.2.1",
"eslint-plugin-simple-import-sort": "^10.0.0",
"husky": "^9.1.7",
"lint-staged": "^16.1.6",
"prettier": "^3.4.2",
"tsconfig-paths": "^4.2.0",
"tsx": "^4.20.3",
"tsx": "^4.20.5",
"typescript": "^5.7.2"
}
}

76
prometheus.yml.example Normal file
View File

@ -0,0 +1,76 @@
# Prometheus configuration example for Evolution API
# Copy this file to prometheus.yml and adjust the settings
global:
scrape_interval: 15s
evaluation_interval: 15s
rule_files:
# - "first_rules.yml"
# - "second_rules.yml"
scrape_configs:
# Evolution API metrics
- job_name: 'evolution-api'
static_configs:
- targets: ['localhost:8080'] # Adjust to your Evolution API URL
# Metrics endpoint path
metrics_path: '/metrics'
# Scrape interval for this job
scrape_interval: 30s
# Basic authentication (if METRICS_AUTH_REQUIRED=true)
basic_auth:
username: 'prometheus' # Should match METRICS_USER
password: 'secure_random_password_here' # Should match METRICS_PASSWORD
# Optional: Add custom labels
relabel_configs:
- source_labels: [__address__]
target_label: __param_target
- source_labels: [__param_target]
target_label: instance
- target_label: __address__
replacement: localhost:8080 # Evolution API address
# Alerting configuration (optional)
alerting:
alertmanagers:
- static_configs:
- targets:
# - alertmanager:9093
# Example alert rules for Evolution API
# Create a file called evolution_alerts.yml with these rules:
#
# groups:
# - name: evolution-api
# rules:
# - alert: EvolutionAPIDown
# expr: up{job="evolution-api"} == 0
# for: 1m
# labels:
# severity: critical
# annotations:
# summary: "Evolution API is down"
# description: "Evolution API has been down for more than 1 minute."
#
# - alert: EvolutionInstanceDown
# expr: evolution_instance_up == 0
# for: 2m
# labels:
# severity: warning
# annotations:
# summary: "Evolution instance {{ $labels.instance }} is down"
# description: "Instance {{ $labels.instance }} has been down for more than 2 minutes."
#
# - alert: HighInstanceCount
# expr: evolution_instances_total > 100
# for: 5m
# labels:
# severity: warning
# annotations:
# summary: "High number of Evolution instances"
# description: "Evolution API is managing {{ $value }} instances."

View File

@ -13,7 +13,7 @@ import { chatbotController } from '@api/server.module';
import { CacheService } from '@api/services/cache.service';
import { ChannelStartupService } from '@api/services/channel.service';
import { Events, wa } from '@api/types/wa.types';
import { Chatwoot, ConfigService, Openai, S3 } from '@config/env.config';
import { AudioConverter, Chatwoot, ConfigService, Openai, S3 } from '@config/env.config';
import { BadRequestException, InternalServerErrorException } from '@exceptions';
import { createJid } from '@utils/createJid';
import axios from 'axios';
@ -622,7 +622,8 @@ export class EvolutionStartupService extends ChannelStartupService {
number = number.replace(/\D/g, '');
const hash = `${number}-${new Date().getTime()}`;
if (process.env.API_AUDIO_CONVERTER) {
const audioConverterConfig = this.configService.get<AudioConverter>('AUDIO_CONVERTER');
if (audioConverterConfig.API_URL) {
try {
this.logger.verbose('Using audio converter API');
const formData = new FormData();
@ -640,10 +641,10 @@ export class EvolutionStartupService extends ChannelStartupService {
formData.append('format', 'mp4');
const response = await axios.post(process.env.API_AUDIO_CONVERTER, formData, {
const response = await axios.post(audioConverterConfig.API_URL, formData, {
headers: {
...formData.getHeaders(),
apikey: process.env.API_AUDIO_CONVERTER_KEY,
apikey: audioConverterConfig.API_KEY,
},
});

View File

@ -20,7 +20,7 @@ import { chatbotController } from '@api/server.module';
import { CacheService } from '@api/services/cache.service';
import { ChannelStartupService } from '@api/services/channel.service';
import { Events, wa } from '@api/types/wa.types';
import { Chatwoot, ConfigService, Database, Openai, S3, WaBusiness } from '@config/env.config';
import { AudioConverter, Chatwoot, ConfigService, Database, Openai, S3, WaBusiness } from '@config/env.config';
import { BadRequestException, InternalServerErrorException } from '@exceptions';
import { createJid } from '@utils/createJid';
import { status } from '@utils/renderStatus';
@ -459,6 +459,15 @@ export class BusinessStartupService extends ChannelStartupService {
mediaType = 'video';
}
if (mediaType == 'video' && !this.configService.get<S3>('S3').SAVE_VIDEO) {
this.logger?.info?.('Video upload attempted but is disabled by configuration.');
return {
success: false,
message:
'Video upload is currently disabled. Please contact support if you need this feature enabled.',
};
}
const mimetype = result.data?.mime_type || result.headers['content-type'];
const contentDisposition = result.headers['content-disposition'];
@ -1291,7 +1300,8 @@ export class BusinessStartupService extends ChannelStartupService {
number = number.replace(/\D/g, '');
const hash = `${number}-${new Date().getTime()}`;
if (process.env.API_AUDIO_CONVERTER) {
const audioConverterConfig = this.configService.get<AudioConverter>('AUDIO_CONVERTER');
if (audioConverterConfig.API_URL) {
this.logger.verbose('Using audio converter API');
const formData = new FormData();
@ -1308,10 +1318,10 @@ export class BusinessStartupService extends ChannelStartupService {
formData.append('format', 'mp3');
const response = await axios.post(process.env.API_AUDIO_CONVERTER, formData, {
const response = await axios.post(audioConverterConfig.API_URL, formData, {
headers: {
...formData.getHeaders(),
apikey: process.env.API_AUDIO_CONVERTER_KEY,
apikey: audioConverterConfig.API_KEY,
},
});

View File

@ -62,6 +62,7 @@ import { ChannelStartupService } from '@api/services/channel.service';
import { Events, MessageSubtype, TypeMediaMessage, wa } from '@api/types/wa.types';
import { CacheEngine } from '@cache/cacheengine';
import {
AudioConverter,
CacheConf,
Chatwoot,
ConfigService,
@ -110,7 +111,7 @@ import makeWASocket, {
isJidBroadcast,
isJidGroup,
isJidNewsletter,
isJidUser,
isPnUser,
makeCacheableSignalKeyStore,
MessageUpsertType,
MessageUserReceiptUpdate,
@ -151,6 +152,19 @@ import { v4 } from 'uuid';
import { BaileysMessageProcessor } from './baileysMessage.processor';
import { useVoiceCallsBaileys } from './voiceCalls/useVoiceCallsBaileys';
export interface ExtendedMessageKey extends WAMessageKey {
senderPn?: string;
previousRemoteJid?: string | null;
}
export interface ExtendedIMessageKey extends proto.IMessageKey {
senderPn?: string;
remoteJidAlt?: string;
participantAlt?: string;
server_id?: string;
isViewOnce?: boolean;
}
const groupMetadataCache = new CacheService(new CacheEngine(configService, 'groups').getEngine());
// Adicione a função getVideoDuration no início do arquivo
@ -484,9 +498,13 @@ export class BaileysStartupService extends ChannelStartupService {
private async getMessage(key: proto.IMessageKey, full = false) {
try {
const webMessageInfo = (await this.prismaRepository.message.findMany({
where: { instanceId: this.instanceId, key: { path: ['id'], equals: key.id } },
})) as unknown as proto.IWebMessageInfo[];
// Use raw SQL to avoid JSON path issues
const webMessageInfo = (await this.prismaRepository.$queryRaw`
SELECT * FROM "Message"
WHERE "instanceId" = ${this.instanceId}
AND "key"->>'id' = ${key.id}
`) as proto.IWebMessageInfo[];
if (full) {
return webMessageInfo[0];
}
@ -982,8 +1000,8 @@ export class BaileysStartupService extends ChannelStartupService {
continue;
}
if (m.key.remoteJid?.includes('@lid') && m.key.senderPn) {
m.key.remoteJid = m.key.senderPn;
if (m.key.remoteJid?.includes('@lid') && (m.key as ExtendedIMessageKey).senderPn) {
m.key.remoteJid = (m.key as ExtendedIMessageKey).senderPn;
}
if (Long.isLong(m?.messageTimestamp)) {
@ -1048,9 +1066,9 @@ export class BaileysStartupService extends ChannelStartupService {
) => {
try {
for (const received of messages) {
if (received.key.remoteJid?.includes('@lid') && received.key.senderPn) {
(received.key as { previousRemoteJid?: string | null }).previousRemoteJid = received.key.remoteJid;
received.key.remoteJid = received.key.senderPn;
if (received.key.remoteJid?.includes('@lid') && (received.key as ExtendedMessageKey).senderPn) {
(received.key as ExtendedMessageKey).previousRemoteJid = received.key.remoteJid;
received.key.remoteJid = (received.key as ExtendedMessageKey).senderPn;
}
if (
received?.messageStubParameters?.some?.((param) =>
@ -1188,6 +1206,8 @@ export class BaileysStartupService extends ChannelStartupService {
received?.message?.ptvMessage ||
received?.message?.audioMessage;
const isVideo = received?.message?.videoMessage;
if (this.localSettings.readMessages && received.key.id !== 'status@broadcast') {
await this.client.readMessages([received.key]);
}
@ -1258,6 +1278,12 @@ export class BaileysStartupService extends ChannelStartupService {
if (isMedia) {
if (this.configService.get<S3>('S3').ENABLE) {
try {
if (isVideo && !this.configService.get<S3>('S3').SAVE_VIDEO) {
this.logger.warn('Video upload is disabled. Skipping video upload.');
// Skip video upload by returning early from this block
return;
}
const message: any = received;
// Verificação adicional para garantir que há conteúdo de mídia real
@ -1332,6 +1358,10 @@ export class BaileysStartupService extends ChannelStartupService {
}
}
if (messageRaw.key.remoteJid?.includes('@lid') && messageRaw.key.remoteJidAlt) {
messageRaw.key.remoteJid = messageRaw.key.remoteJidAlt;
}
this.logger.log(messageRaw);
this.sendDataWebhook(Events.MESSAGES_UPSERT, messageRaw);
@ -1407,8 +1437,8 @@ export class BaileysStartupService extends ChannelStartupService {
continue;
}
if (key.remoteJid?.includes('@lid') && key.senderPn) {
key.remoteJid = key.senderPn;
if (key.remoteJid?.includes('@lid') && key.remoteJidAlt) {
key.remoteJid = key.remoteJidAlt;
}
const updateKey = `${this.instance.id}_${key.id}_${update.status}`;
@ -1459,9 +1489,14 @@ export class BaileysStartupService extends ChannelStartupService {
let findMessage: any;
const configDatabaseData = this.configService.get<Database>('DATABASE').SAVE_DATA;
if (configDatabaseData.HISTORIC || configDatabaseData.NEW_MESSAGE) {
findMessage = await this.prismaRepository.message.findFirst({
where: { instanceId: this.instanceId, key: { path: ['id'], equals: key.id } },
});
// Use raw SQL to avoid JSON path issues
const messages = (await this.prismaRepository.$queryRaw`
SELECT * FROM "Message"
WHERE "instanceId" = ${this.instanceId}
AND "key"->>'id' = ${key.id}
LIMIT 1
`) as any[];
findMessage = messages[0] || null;
if (findMessage) message.messageId = findMessage.id;
}
@ -1910,7 +1945,7 @@ export class BaileysStartupService extends ChannelStartupService {
quoted,
});
const id = await this.client.relayMessage(sender, message, { messageId });
m.key = { id: id, remoteJid: sender, participant: isJidUser(sender) ? sender : undefined, fromMe: true };
m.key = { id: id, remoteJid: sender, participant: isPnUser(sender) ? sender : undefined, fromMe: true };
for (const [key, value] of Object.entries(m)) {
if (!value || (isArray(value) && value.length) === 0) {
delete m[key];
@ -2146,6 +2181,8 @@ export class BaileysStartupService extends ChannelStartupService {
messageSent?.message?.ptvMessage ||
messageSent?.message?.audioMessage;
const isVideo = messageSent?.message?.videoMessage;
if (this.configService.get<Chatwoot>('CHATWOOT').ENABLED && this.localChatwoot?.enabled && !isIntegration) {
this.chatwootService.eventWhatsapp(
Events.SEND_MESSAGE,
@ -2170,6 +2207,10 @@ export class BaileysStartupService extends ChannelStartupService {
if (isMedia && this.configService.get<S3>('S3').ENABLE) {
try {
if (isVideo && !this.configService.get<S3>('S3').SAVE_VIDEO) {
throw new Error('Video upload is disabled.');
}
const message: any = messageRaw;
// Verificação adicional para garantir que há conteúdo de mídia real
@ -2568,6 +2609,13 @@ export class BaileysStartupService extends ChannelStartupService {
}
}
if (mediaMessage?.fileName) {
mimetype = mimeTypes.lookup(mediaMessage.fileName).toString();
if (mimetype === 'application/mp4') {
mimetype = 'video/mp4';
}
}
prepareMedia[mediaType].caption = mediaMessage?.caption;
prepareMedia[mediaType].mimetype = mimetype;
prepareMedia[mediaType].fileName = mediaMessage.fileName;
@ -2794,7 +2842,8 @@ export class BaileysStartupService extends ChannelStartupService {
}
public async processAudio(audio: string): Promise<Buffer> {
if (process.env.API_AUDIO_CONVERTER) {
const audioConverterConfig = this.configService.get<AudioConverter>('AUDIO_CONVERTER');
if (audioConverterConfig.API_URL) {
this.logger.verbose('Using audio converter API');
const formData = new FormData();
@ -2804,8 +2853,8 @@ export class BaileysStartupService extends ChannelStartupService {
formData.append('base64', audio);
}
const { data } = await axios.post(process.env.API_AUDIO_CONVERTER, formData, {
headers: { ...formData.getHeaders(), apikey: process.env.API_AUDIO_CONVERTER_KEY },
const { data } = await axios.post(audioConverterConfig.API_URL, formData, {
headers: { ...formData.getHeaders(), apikey: audioConverterConfig.API_KEY },
});
if (!data.audio) {
@ -3367,7 +3416,7 @@ export class BaileysStartupService extends ChannelStartupService {
try {
const keys: proto.IMessageKey[] = [];
data.readMessages.forEach((read) => {
if (isJidGroup(read.remoteJid) || isJidUser(read.remoteJid)) {
if (isJidGroup(read.remoteJid) || isPnUser(read.remoteJid)) {
keys.push({ remoteJid: read.remoteJid, fromMe: read.fromMe, id: read.id });
}
});
@ -3579,7 +3628,7 @@ export class BaileysStartupService extends ChannelStartupService {
}
if (typeof mediaMessage['mediaKey'] === 'object') {
msg.message = JSON.parse(JSON.stringify(msg.message));
msg.message[mediaType].mediaKey = Uint8Array.from(Object.values(mediaMessage['mediaKey']));
}
let buffer: Buffer;
@ -4299,22 +4348,50 @@ export class BaileysStartupService extends ChannelStartupService {
throw new Error('Method not available in the Baileys service');
}
private convertLongToNumber(obj: any): any {
if (obj === null || obj === undefined) {
return obj;
}
if (Long.isLong(obj)) {
return obj.toNumber();
}
if (Array.isArray(obj)) {
return obj.map((item) => this.convertLongToNumber(item));
}
if (typeof obj === 'object') {
const converted: any = {};
for (const key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
converted[key] = this.convertLongToNumber(obj[key]);
}
}
return converted;
}
return obj;
}
private prepareMessage(message: proto.IWebMessageInfo): any {
const contentType = getContentType(message.message);
const contentMsg = message?.message[contentType] as any;
const messageRaw = {
key: message.key,
key: message.key, // Save key exactly as it comes from Baileys
pushName:
message.pushName ||
(message.key.fromMe
? 'Você'
: message?.participant || (message.key?.participant ? message.key.participant.split('@')[0] : null)),
status: status[message.status],
message: { ...message.message },
contextInfo: contentMsg?.contextInfo,
message: this.convertLongToNumber({ ...message.message }),
contextInfo: this.convertLongToNumber(contentMsg?.contextInfo),
messageType: contentType || 'unknown',
messageTimestamp: message.messageTimestamp as number,
messageTimestamp: Long.isLong(message.messageTimestamp)
? message.messageTimestamp.toNumber()
: (message.messageTimestamp as number),
instanceId: this.instanceId,
source: getDevice(message.key.id),
};
@ -4357,7 +4434,22 @@ export class BaileysStartupService extends ChannelStartupService {
const prepare = (message: any) => this.prepareMessage(message);
this.chatwootService.syncLostMessages({ instanceName: this.instance.name }, chatwootConfig, prepare);
// Generate ID for this cron task and store in cache
const cronId = cuid();
const cronKey = `chatwoot:syncLostMessages`;
await this.chatwootService.getCache()?.hSet(cronKey, this.instance.name, cronId);
const task = cron.schedule('0,30 * * * *', async () => {
// Check ID before executing (only if cache is available)
const cache = this.chatwootService.getCache();
if (cache) {
const storedId = await cache.hGet(cronKey, this.instance.name);
if (storedId && storedId !== cronId) {
this.logger.info(`Stopping syncChatwootLostMessages cron - ID mismatch: ${cronId} vs ${storedId}`);
task.stop();
return;
}
}
this.chatwootService.syncLostMessages({ instanceName: this.instance.name }, chatwootConfig, prepare);
});
task.start();
@ -4367,24 +4459,23 @@ export class BaileysStartupService extends ChannelStartupService {
private async updateMessagesReadedByTimestamp(remoteJid: string, timestamp?: number): Promise<number> {
if (timestamp === undefined || timestamp === null) return 0;
const result = await this.prismaRepository.message.updateMany({
where: {
AND: [
{ key: { path: ['remoteJid'], equals: remoteJid } },
{ key: { path: ['fromMe'], equals: false } },
{ messageTimestamp: { lte: timestamp } },
{ OR: [{ status: null }, { status: status[3] }] },
],
},
data: { status: status[4] },
});
// Use raw SQL to avoid JSON path issues
const result = await this.prismaRepository.$executeRaw`
UPDATE "Message"
SET "status" = ${status[4]}
WHERE "instanceId" = ${this.instanceId}
AND "key"->>'remoteJid' = ${remoteJid}
AND ("key"->>'fromMe')::boolean = false
AND "messageTimestamp" <= ${timestamp}
AND ("status" IS NULL OR "status" = ${status[3]})
`;
if (result) {
if (result.count > 0) {
if (result > 0) {
this.updateChatUnreadMessages(remoteJid);
}
return result.count;
return result;
}
return 0;
@ -4393,15 +4484,14 @@ export class BaileysStartupService extends ChannelStartupService {
private async updateChatUnreadMessages(remoteJid: string): Promise<number> {
const [chat, unreadMessages] = await Promise.all([
this.prismaRepository.chat.findFirst({ where: { remoteJid } }),
this.prismaRepository.message.count({
where: {
AND: [
{ key: { path: ['remoteJid'], equals: remoteJid } },
{ key: { path: ['fromMe'], equals: false } },
{ status: { equals: status[3] } },
],
},
}),
// Use raw SQL to avoid JSON path issues
this.prismaRepository.$queryRaw`
SELECT COUNT(*)::int as count FROM "Message"
WHERE "instanceId" = ${this.instanceId}
AND "key"->>'remoteJid' = ${remoteJid}
AND ("key"->>'fromMe')::boolean = false
AND "status" = ${status[3]}
`.then((result: any[]) => result[0]?.count || 0),
]);
if (chat && chat.unreadMessages !== unreadMessages) {
@ -4649,12 +4739,7 @@ export class BaileysStartupService extends ChannelStartupService {
}
public async fetchMessages(query: Query<Message>) {
const keyFilters = query?.where?.key as {
id?: string;
fromMe?: boolean;
remoteJid?: string;
participants?: string;
};
const keyFilters = query?.where?.key as ExtendedIMessageKey;
const timestampFilter = {};
if (query?.where?.messageTimestamp) {
@ -4677,7 +4762,13 @@ export class BaileysStartupService extends ChannelStartupService {
keyFilters?.id ? { key: { path: ['id'], equals: keyFilters?.id } } : {},
keyFilters?.fromMe ? { key: { path: ['fromMe'], equals: keyFilters?.fromMe } } : {},
keyFilters?.remoteJid ? { key: { path: ['remoteJid'], equals: keyFilters?.remoteJid } } : {},
keyFilters?.participants ? { key: { path: ['participants'], equals: keyFilters?.participants } } : {},
keyFilters?.participant ? { key: { path: ['participant'], equals: keyFilters?.participant } } : {},
{
OR: [
keyFilters?.remoteJid ? { key: { path: ['remoteJid'], equals: keyFilters?.remoteJid } } : {},
keyFilters?.senderPn ? { key: { path: ['senderPn'], equals: keyFilters?.senderPn } } : {},
],
},
],
},
});
@ -4701,7 +4792,13 @@ export class BaileysStartupService extends ChannelStartupService {
keyFilters?.id ? { key: { path: ['id'], equals: keyFilters?.id } } : {},
keyFilters?.fromMe ? { key: { path: ['fromMe'], equals: keyFilters?.fromMe } } : {},
keyFilters?.remoteJid ? { key: { path: ['remoteJid'], equals: keyFilters?.remoteJid } } : {},
keyFilters?.participants ? { key: { path: ['participants'], equals: keyFilters?.participants } } : {},
keyFilters?.participant ? { key: { path: ['participant'], equals: keyFilters?.participant } } : {},
{
OR: [
keyFilters?.remoteJid ? { key: { path: ['remoteJid'], equals: keyFilters?.remoteJid } } : {},
keyFilters?.senderPn ? { key: { path: ['senderPn'], equals: keyFilters?.senderPn } } : {},
],
},
],
},
orderBy: { messageTimestamp: 'desc' },

View File

@ -2,6 +2,7 @@ import { IgnoreJidDto } from '@api/dto/chatbot.dto';
import { InstanceDto } from '@api/dto/instance.dto';
import { PrismaRepository } from '@api/repository/repository.service';
import { WAMonitoringService } from '@api/services/monitor.service';
import { Events } from '@api/types/wa.types';
import { Logger } from '@config/logger.config';
import { BadRequestException } from '@exceptions';
import { TriggerOperator, TriggerType } from '@prisma/client';
@ -446,6 +447,16 @@ export abstract class BaseChatbotController<BotType = any, BotData extends BaseC
const remoteJid = data.remoteJid;
const status = data.status;
const session = await this.getSession(remoteJid, instance);
if (this.integrationName === 'Typebot') {
const typebotData = {
remoteJid: remoteJid,
status: status,
session,
};
this.waMonitor.waInstances[instance.instanceName].sendDataWebhook(Events.TYPEBOT_CHANGE_STATUS, typebotData);
}
if (status === 'delete') {
await this.sessionRepository.deleteMany({
@ -867,6 +878,16 @@ export abstract class BaseChatbotController<BotType = any, BotData extends BaseC
status: 'paused',
},
});
if (this.integrationName === 'Typebot') {
const typebotData = {
remoteJid: remoteJid,
status: 'paused',
session,
};
this.waMonitor.waInstances[instance.instanceName].sendDataWebhook(Events.TYPEBOT_CHANGE_STATUS, typebotData);
}
return;
}
@ -880,12 +901,6 @@ export abstract class BaseChatbotController<BotType = any, BotData extends BaseC
return;
}
// Skip if session exists and status is paused
if (session && session.status === 'paused') {
this.logger.warn(`Session for ${remoteJid} is paused, skipping message processing`);
return;
}
// Merged settings
const mergedSettings = {
...settings,

View File

@ -1,5 +1,6 @@
import { InstanceDto } from '@api/dto/instance.dto';
import { Options, Quoted, SendAudioDto, SendMediaDto, SendTextDto } from '@api/dto/sendMessage.dto';
import { ExtendedMessageKey } from '@api/integrations/channel/whatsapp/whatsapp.baileys.service';
import { ChatwootDto } from '@api/integrations/chatbot/chatwoot/dto/chatwoot.dto';
import { postgresClient } from '@api/integrations/chatbot/chatwoot/libs/postgres.client';
import { chatwootImport } from '@api/integrations/chatbot/chatwoot/utils/chatwoot-import-helper';
@ -567,13 +568,6 @@ export class ChatwootService {
}
public async createConversation(instance: InstanceDto, body: any) {
if (!body?.key) {
this.logger.warn(
`body.key is null or undefined in createConversation. Full body object: ${JSON.stringify(body)}`,
);
return null;
}
const isLid = body.key.previousRemoteJid?.includes('@lid') && body.key.senderPn;
const remoteJid = body.key.remoteJid;
const cacheKey = `${instance.instanceName}:createConversation-${remoteJid}`;
@ -1291,12 +1285,7 @@ export class ChatwootService {
});
if (message) {
const key = message.key as {
id: string;
remoteJid: string;
fromMe: boolean;
participant: string;
};
const key = message.key as ExtendedMessageKey;
await waInstance?.client.sendMessage(key.remoteJid, { delete: key });
@ -1494,12 +1483,7 @@ export class ChatwootService {
},
});
if (lastMessage && !lastMessage.chatwootIsRead) {
const key = lastMessage.key as {
id: string;
fromMe: boolean;
remoteJid: string;
participant?: string;
};
const key = lastMessage.key as ExtendedMessageKey;
waInstance?.markMessageAsRead({
readMessages: [
@ -1557,33 +1541,24 @@ export class ChatwootService {
chatwootMessageIds: ChatwootMessage,
instance: InstanceDto,
) {
const key = message.key as {
id: string;
fromMe: boolean;
remoteJid: string;
participant?: string;
};
const key = message.key as ExtendedMessageKey;
if (!chatwootMessageIds.messageId || !key?.id) {
return;
}
await this.prismaRepository.message.updateMany({
where: {
key: {
path: ['id'],
equals: key.id,
},
instanceId: instance.instanceId,
},
data: {
chatwootMessageId: chatwootMessageIds.messageId,
chatwootConversationId: chatwootMessageIds.conversationId,
chatwootInboxId: chatwootMessageIds.inboxId,
chatwootContactInboxSourceId: chatwootMessageIds.contactInboxSourceId,
chatwootIsRead: chatwootMessageIds.isRead,
},
});
// Use raw SQL to avoid JSON path issues
await this.prismaRepository.$executeRaw`
UPDATE "Message"
SET
"chatwootMessageId" = ${chatwootMessageIds.messageId},
"chatwootConversationId" = ${chatwootMessageIds.conversationId},
"chatwootInboxId" = ${chatwootMessageIds.inboxId},
"chatwootContactInboxSourceId" = ${chatwootMessageIds.contactInboxSourceId},
"chatwootIsRead" = ${chatwootMessageIds.isRead || false}
WHERE "instanceId" = ${instance.instanceId}
AND "key"->>'id' = ${key.id}
`;
if (this.isImportHistoryAvailable()) {
chatwootImport.updateMessageSourceID(chatwootMessageIds.messageId, key.id);
@ -1591,17 +1566,15 @@ export class ChatwootService {
}
private async getMessageByKeyId(instance: InstanceDto, keyId: string): Promise<MessageModel> {
const messages = await this.prismaRepository.message.findFirst({
where: {
key: {
path: ['id'],
equals: keyId,
},
instanceId: instance.instanceId,
},
});
// Use raw SQL query to avoid JSON path issues with Prisma
const messages = await this.prismaRepository.$queryRaw`
SELECT * FROM "Message"
WHERE "instanceId" = ${instance.instanceId}
AND "key"->>'id' = ${keyId}
LIMIT 1
`;
return messages || null;
return (messages as MessageModel[])[0] || null;
}
private async getReplyToIds(
@ -1636,12 +1609,7 @@ export class ChatwootService {
},
});
const key = message?.key as {
id: string;
fromMe: boolean;
remoteJid: string;
participant?: string;
};
const key = message?.key as ExtendedMessageKey;
if (message && key?.id) {
return {
@ -1900,12 +1868,6 @@ export class ChatwootService {
public async eventWhatsapp(event: string, instance: InstanceDto, body: any) {
try {
// Ignore events that are not messages (like EPHEMERAL_SYNC_RESPONSE)
if (body?.type && body.type !== 'message' && body.type !== 'conversation') {
this.logger.verbose(`Ignoring non-message event type: ${body.type}`);
return;
}
const waInstance = this.waMonitor.waInstances[instance.instanceName];
if (!waInstance) {
@ -1951,11 +1913,6 @@ export class ChatwootService {
}
if (event === 'messages.upsert' || event === 'send.message') {
if (!body?.key) {
this.logger.warn(`body.key is null or undefined. Full body object: ${JSON.stringify(body)}`);
return;
}
if (body.key.remoteJid === 'status@broadcast') {
return;
}
@ -2278,29 +2235,17 @@ export class ChatwootService {
}
if (event === 'messages.edit' || event === 'send.message.update') {
// Ignore events that are not messages (like EPHEMERAL_SYNC_RESPONSE)
if (body?.type && body.type !== 'message') {
this.logger.verbose(`Ignoring non-message event type: ${body.type}`);
return;
}
if (!body?.key?.id) {
this.logger.warn(
`body.key.id is null or undefined in messages.edit. Full body object: ${JSON.stringify(body)}`,
);
return;
}
const editedText = `${
body?.editedMessage?.conversation || body?.editedMessage?.extendedTextMessage?.text
}\n\n_\`${i18next.t('cw.message.edited')}.\`_`;
const message = await this.getMessageByKeyId(instance, body.key.id);
const key = message.key as {
id: string;
fromMe: boolean;
remoteJid: string;
participant?: string;
};
const message = await this.getMessageByKeyId(instance, body?.key?.id);
if (!message) {
this.logger.warn('Message not found for edit event');
return;
}
const key = message.key as ExtendedMessageKey;
const messageType = key?.fromMe ? 'outgoing' : 'incoming';
@ -2578,7 +2523,7 @@ export class ChatwootService {
const savedMessages = await this.prismaRepository.message.findMany({
where: {
Instance: { name: instance.instanceName },
messageTimestamp: { gte: dayjs().subtract(6, 'hours').unix() },
messageTimestamp: { gte: Number(dayjs().subtract(6, 'hours').unix()) },
AND: ids.map((id) => ({ key: { path: ['id'], not: id } })),
},
});

View File

@ -106,15 +106,37 @@ export class EvolutionBotService extends BaseChatbotService<EvolutionBot, Evolut
};
}
// Sanitize payload for logging (remove sensitive data)
const sanitizedPayload = {
...payload,
inputs: {
...payload.inputs,
apiKey: payload.inputs.apiKey ? '[REDACTED]' : undefined,
},
};
this.logger.debug(`[EvolutionBot] Sending request to endpoint: ${endpoint}`);
this.logger.debug(`[EvolutionBot] Request payload: ${JSON.stringify(sanitizedPayload, null, 2)}`);
const response = await axios.post(endpoint, payload, {
headers,
});
this.logger.debug(`[EvolutionBot] Response received - Status: ${response.status}`);
if (instance.integration === Integration.WHATSAPP_BAILEYS) {
await instance.client.sendPresenceUpdate('paused', remoteJid);
}
let message = response?.data?.message;
const rawLinkPreview = response?.data?.linkPreview;
// Validate linkPreview is boolean and default to true for backward compatibility
const linkPreview = typeof rawLinkPreview === 'boolean' ? rawLinkPreview : true;
this.logger.debug(
`[EvolutionBot] Processing response - Message length: ${message?.length || 0}, LinkPreview: ${linkPreview}`,
);
if (message && typeof message === 'string' && message.startsWith("'") && message.endsWith("'")) {
const innerContent = message.slice(1, -1);
@ -124,8 +146,19 @@ export class EvolutionBotService extends BaseChatbotService<EvolutionBot, Evolut
}
if (message) {
// Use the base class method to send the message to WhatsApp
await this.sendMessageWhatsApp(instance, remoteJid, message, settings);
// Send message directly with validated linkPreview option
await instance.textMessage(
{
number: remoteJid.split('@')[0],
delay: settings?.delayMessage || 1000,
text: message,
linkPreview, // Always boolean, defaults to true
},
false,
);
this.logger.debug(`[EvolutionBot] Message sent successfully with linkPreview: ${linkPreview}`);
} else {
this.logger.warn(`[EvolutionBot] No message content received from bot response`);
}
// Send telemetry

View File

@ -57,6 +57,8 @@ export class FlowiseService extends BaseChatbotService<FlowiseModel> {
overrideConfig: {
sessionId: remoteJid,
vars: {
messageId: msg?.key?.id,
fromMe: msg?.key?.fromMe,
remoteJid: remoteJid,
pushName: pushName,
instanceName: instance.instanceName,

View File

@ -1,5 +1,6 @@
import { PrismaRepository } from '@api/repository/repository.service';
import { WAMonitoringService } from '@api/services/monitor.service';
import { Events } from '@api/types/wa.types';
import { Auth, ConfigService, HttpServer, Typebot } from '@config/env.config';
import { Instance, IntegrationSession, Message, Typebot as TypebotModel } from '@prisma/client';
import { getConversationMessage } from '@utils/getConversationMessage';
@ -151,6 +152,14 @@ export class TypebotService extends BaseChatbotService<TypebotModel, any> {
},
});
}
const typebotData = {
remoteJid: data.remoteJid,
status: 'opened',
session,
};
this.waMonitor.waInstances[instance.name].sendDataWebhook(Events.TYPEBOT_CHANGE_STATUS, typebotData);
return { ...request.data, session };
} catch (error) {
this.logger.error(error);
@ -399,12 +408,14 @@ export class TypebotService extends BaseChatbotService<TypebotModel, any> {
},
});
} else {
let statusChange = 'closed';
if (!settings?.keepOpen) {
await prismaRepository.integrationSession.deleteMany({
where: {
id: session.id,
},
});
statusChange = 'delete';
} else {
await prismaRepository.integrationSession.update({
where: {
@ -415,6 +426,13 @@ export class TypebotService extends BaseChatbotService<TypebotModel, any> {
},
});
}
const typebotData = {
remoteJid: session.remoteJid,
status: statusChange,
session,
};
instance.sendDataWebhook(Events.TYPEBOT_CHANGE_STATUS, typebotData);
}
}
@ -639,6 +657,7 @@ export class TypebotService extends BaseChatbotService<TypebotModel, any> {
}
if (keywordFinish && content.toLowerCase() === keywordFinish.toLowerCase()) {
let statusChange = 'closed';
if (keepOpen) {
await this.prismaRepository.integrationSession.update({
where: {
@ -649,6 +668,7 @@ export class TypebotService extends BaseChatbotService<TypebotModel, any> {
},
});
} else {
statusChange = 'delete';
await this.prismaRepository.integrationSession.deleteMany({
where: {
botId: findTypebot.id,
@ -656,6 +676,14 @@ export class TypebotService extends BaseChatbotService<TypebotModel, any> {
},
});
}
const typebotData = {
remoteJid: remoteJid,
status: statusChange,
session,
};
waInstance.sendDataWebhook(Events.TYPEBOT_CHANGE_STATUS, typebotData);
return;
}
@ -788,6 +816,7 @@ export class TypebotService extends BaseChatbotService<TypebotModel, any> {
}
if (keywordFinish && content.toLowerCase() === keywordFinish.toLowerCase()) {
let statusChange = 'closed';
if (keepOpen) {
await this.prismaRepository.integrationSession.update({
where: {
@ -798,6 +827,7 @@ export class TypebotService extends BaseChatbotService<TypebotModel, any> {
},
});
} else {
statusChange = 'delete';
await this.prismaRepository.integrationSession.deleteMany({
where: {
botId: findTypebot.id,
@ -806,6 +836,13 @@ export class TypebotService extends BaseChatbotService<TypebotModel, any> {
});
}
const typebotData = {
remoteJid: remoteJid,
status: statusChange,
session,
};
waInstance.sendDataWebhook(Events.TYPEBOT_CHANGE_STATUS, typebotData);
return;
}
@ -881,6 +918,7 @@ export class TypebotService extends BaseChatbotService<TypebotModel, any> {
}
if (keywordFinish && content.toLowerCase() === keywordFinish.toLowerCase()) {
let statusChange = 'closed';
if (keepOpen) {
await this.prismaRepository.integrationSession.update({
where: {
@ -891,6 +929,7 @@ export class TypebotService extends BaseChatbotService<TypebotModel, any> {
},
});
} else {
statusChange = 'delete';
await this.prismaRepository.integrationSession.deleteMany({
where: {
botId: findTypebot.id,
@ -898,6 +937,15 @@ export class TypebotService extends BaseChatbotService<TypebotModel, any> {
},
});
}
const typebotData = {
remoteJid: remoteJid,
status: statusChange,
session,
};
waInstance.sendDataWebhook(Events.TYPEBOT_CHANGE_STATUS, typebotData);
return;
}

View File

@ -1,7 +1,8 @@
import * as s3Service from '@api/integrations/storage/s3/libs/minio.server';
import { PrismaRepository } from '@api/repository/repository.service';
import { WAMonitoringService } from '@api/services/monitor.service';
import { CreateQueueCommand, DeleteQueueCommand, ListQueuesCommand, SQS } from '@aws-sdk/client-sqs';
import { configService, Log, Sqs } from '@config/env.config';
import { configService, HttpServer, Log, S3, Sqs } from '@config/env.config';
import { Logger } from '@config/logger.config';
import { EmitData, EventController, EventControllerInterface } from '../event.controller';
@ -15,27 +16,29 @@ export class SqsController extends EventController implements EventControllerInt
super(prismaRepository, waMonitor, configService.get<Sqs>('SQS')?.ENABLED, 'sqs');
}
public init(): void {
public async init(): Promise<void> {
if (!this.status) {
return;
}
new Promise<void>((resolve) => {
const awsConfig = configService.get<Sqs>('SQS');
const awsConfig = configService.get<Sqs>('SQS');
this.sqs = new SQS({
credentials: {
accessKeyId: awsConfig.ACCESS_KEY_ID,
secretAccessKey: awsConfig.SECRET_ACCESS_KEY,
},
this.sqs = new SQS({
credentials: {
accessKeyId: awsConfig.ACCESS_KEY_ID,
secretAccessKey: awsConfig.SECRET_ACCESS_KEY,
},
region: awsConfig.REGION,
});
this.logger.info('SQS initialized');
resolve();
region: awsConfig.REGION,
});
this.logger.info('SQS initialized');
const sqsConfig = configService.get<Sqs>('SQS');
if (this.sqs && sqsConfig.GLOBAL_ENABLED) {
const sqsEvents = Object.keys(sqsConfig.EVENTS).filter((e) => sqsConfig.EVENTS[e]);
await this.saveQueues(sqsConfig.GLOBAL_PREFIX_NAME, sqsEvents, true);
}
}
private set channel(sqs: SQS) {
@ -47,7 +50,7 @@ export class SqsController extends EventController implements EventControllerInt
}
override async set(instanceName: string, data: EventDto): Promise<any> {
if (!this.status) {
if (!this.status || configService.get<Sqs>('SQS').GLOBAL_ENABLED) {
return;
}
@ -75,6 +78,7 @@ export class SqsController extends EventController implements EventControllerInt
instanceId: this.monitor.waInstances[instanceName].instanceId,
},
};
console.log('*** payload: ', payload);
return this.prisma[this.name].upsert(payload);
}
@ -98,100 +102,153 @@ export class SqsController extends EventController implements EventControllerInt
return;
}
const instanceSqs = await this.get(instanceName);
const sqsLocal = instanceSqs?.events;
const we = event.replace(/[.-]/gm, '_').toUpperCase();
if (this.sqs) {
const serverConfig = configService.get<HttpServer>('SERVER');
const sqsConfig = configService.get<Sqs>('SQS');
if (instanceSqs?.enabled) {
if (this.sqs) {
if (Array.isArray(sqsLocal) && sqsLocal.includes(we)) {
const eventFormatted = `${event.replace('.', '_').toLowerCase()}`;
const queueName = `${instanceName}_${eventFormatted}.fifo`;
const sqsConfig = configService.get<Sqs>('SQS');
const sqsUrl = `https://sqs.${sqsConfig.REGION}.amazonaws.com/${sqsConfig.ACCOUNT_ID}/${queueName}`;
const we = event.replace(/[.-]/gm, '_').toUpperCase();
const message = {
event,
instance: instanceName,
data,
server_url: serverUrl,
date_time: dateTime,
sender,
apikey: apiKey,
};
const params = {
MessageBody: JSON.stringify(message),
MessageGroupId: 'evolution',
MessageDeduplicationId: `${instanceName}_${eventFormatted}_${Date.now()}`,
QueueUrl: sqsUrl,
};
this.sqs.sendMessage(params, (err) => {
if (err) {
this.logger.error({
local: `${origin}.sendData-SQS`,
message: err?.message,
hostName: err?.hostname,
code: err?.code,
stack: err?.stack,
name: err?.name,
url: queueName,
server_url: serverUrl,
});
} else {
if (configService.get<Log>('LOG').LEVEL.includes('WEBHOOKS')) {
const logData = {
local: `${origin}.sendData-SQS`,
...message,
};
this.logger.log(logData);
}
}
});
let sqsEvents = [];
if (sqsConfig.GLOBAL_ENABLED) {
sqsEvents = Object.keys(sqsConfig.EVENTS).filter((e) => sqsConfig.EVENTS[e]);
} else {
const instanceSqs = await this.get(instanceName);
if (instanceSqs?.enabled && Array.isArray(instanceSqs?.events)) {
sqsEvents = instanceSqs?.events;
}
}
if (Array.isArray(sqsEvents) && sqsEvents.includes(we)) {
const prefixName = sqsConfig.GLOBAL_ENABLED ? sqsConfig.GLOBAL_PREFIX_NAME : instanceName;
const eventFormatted =
sqsConfig.GLOBAL_ENABLED && sqsConfig.GLOBAL_FORCE_SINGLE_QUEUE
? 'singlequeue'
: `${event.replace('.', '_').toLowerCase()}`;
const queueName = `${prefixName}_${eventFormatted}.fifo`;
const sqsUrl = `https://sqs.${sqsConfig.REGION}.amazonaws.com/${sqsConfig.ACCOUNT_ID}/${queueName}`;
const message = {
event,
instance: instanceName,
dataType: 'json',
data,
server: serverConfig.NAME,
server_url: serverUrl,
date_time: dateTime,
sender,
apikey: apiKey,
};
const jsonStr = JSON.stringify(message);
const size = Buffer.byteLength(jsonStr, 'utf8');
if (size > sqsConfig.MAX_PAYLOAD_SIZE) {
if (!configService.get<S3>('S3').ENABLE) {
this.logger.error(
`${instanceName} - ${eventFormatted} - SQS ignored: payload (${size} bytes) exceeds SQS size limit (${sqsConfig.MAX_PAYLOAD_SIZE} bytes) and S3 storage is not enabled.`,
);
return;
}
const buffer = Buffer.from(jsonStr, 'utf8');
const fullName = `messages/${instanceName}_${eventFormatted}_${Date.now()}.json`;
await s3Service.uploadFile(fullName, buffer, size, {
'Content-Type': 'application/json',
'Cache-Control': 'no-store',
});
const fileUrl = await s3Service.getObjectUrl(fullName);
message.data = { fileUrl };
message.dataType = 's3';
}
const messageGroupId = sqsConfig.GLOBAL_ENABLED
? `${serverConfig.NAME}-${eventFormatted}-${instanceName}`
: 'evolution';
const isGlobalEnabled = sqsConfig.GLOBAL_ENABLED;
const params = {
MessageBody: JSON.stringify(message),
MessageGroupId: messageGroupId,
QueueUrl: sqsUrl,
...(!isGlobalEnabled && {
MessageDeduplicationId: `${instanceName}_${eventFormatted}_${Date.now()}`,
}),
};
this.sqs.sendMessage(params, (err) => {
if (err) {
this.logger.error({
local: `${origin}.sendData-SQS`,
params: JSON.stringify(message),
sqsUrl: sqsUrl,
message: err?.message,
hostName: err?.hostname,
code: err?.code,
stack: err?.stack,
name: err?.name,
url: queueName,
server_url: serverUrl,
});
} else if (configService.get<Log>('LOG').LEVEL.includes('WEBHOOKS')) {
const logData = {
local: `${origin}.sendData-SQS`,
...message,
};
this.logger.log(logData);
}
});
}
}
}
private async saveQueues(instanceName: string, events: string[], enable: boolean) {
private async saveQueues(prefixName: string, events: string[], enable: boolean) {
if (enable) {
const eventsFinded = await this.listQueuesByInstance(instanceName);
const sqsConfig = configService.get<Sqs>('SQS');
const eventsFinded = await this.listQueues(prefixName);
console.log('eventsFinded', eventsFinded);
for (const event of events) {
const normalizedEvent = event.toLowerCase();
const normalizedEvent =
sqsConfig.GLOBAL_ENABLED && sqsConfig.GLOBAL_FORCE_SINGLE_QUEUE ? 'singlequeue' : event.toLowerCase();
if (eventsFinded.includes(normalizedEvent)) {
this.logger.info(`A queue para o evento "${normalizedEvent}" já existe. Ignorando criação.`);
continue;
}
const queueName = `${instanceName}_${normalizedEvent}.fifo`;
const queueName = `${prefixName}_${normalizedEvent}.fifo`;
try {
const isGlobalEnabled = sqsConfig.GLOBAL_ENABLED;
const createCommand = new CreateQueueCommand({
QueueName: queueName,
Attributes: {
FifoQueue: 'true',
...(isGlobalEnabled && { ContentBasedDeduplication: 'true' }),
},
});
const data = await this.sqs.send(createCommand);
this.logger.info(`Queue ${queueName} criada: ${data.QueueUrl}`);
} catch (err: any) {
this.logger.error(`Erro ao criar queue ${queueName}: ${err.message}`);
}
if (sqsConfig.GLOBAL_ENABLED && sqsConfig.GLOBAL_FORCE_SINGLE_QUEUE) {
break;
}
}
}
}
private async listQueuesByInstance(instanceName: string) {
private async listQueues(prefixName: string) {
let existingQueues: string[] = [];
try {
const listCommand = new ListQueuesCommand({
QueueNamePrefix: `${instanceName}_`,
QueueNamePrefix: `${prefixName}_`,
});
const listData = await this.sqs.send(listCommand);
if (listData.QueueUrls && listData.QueueUrls.length > 0) {
// Extrai o nome da fila a partir da URL
@ -201,7 +258,7 @@ export class SqsController extends EventController implements EventControllerInt
});
}
} catch (error: any) {
this.logger.error(`Erro ao listar filas para a instância ${instanceName}: ${error.message}`);
this.logger.error(`Erro ao listar filas para ${prefixName}: ${error.message}`);
return;
}
@ -209,8 +266,8 @@ export class SqsController extends EventController implements EventControllerInt
return existingQueues
.map((queueName) => {
// Espera-se que o nome seja `${instanceName}_${event}.fifo`
if (queueName.startsWith(`${instanceName}_`) && queueName.endsWith('.fifo')) {
return queueName.substring(instanceName.length + 1, queueName.length - 5).toLowerCase();
if (queueName.startsWith(`${prefixName}_`) && queueName.endsWith('.fifo')) {
return queueName.substring(prefixName.length + 1, queueName.length - 5).toLowerCase();
}
return '';
})
@ -218,15 +275,15 @@ export class SqsController extends EventController implements EventControllerInt
}
// Para uma futura feature de exclusão forçada das queues
private async removeQueuesByInstance(instanceName: string) {
private async removeQueuesByInstance(prefixName: string) {
try {
const listCommand = new ListQueuesCommand({
QueueNamePrefix: `${instanceName}_`,
QueueNamePrefix: `${prefixName}_`,
});
const listData = await this.sqs.send(listCommand);
if (!listData.QueueUrls || listData.QueueUrls.length === 0) {
this.logger.info(`No queues found for instance ${instanceName}`);
this.logger.info(`No queues found for ${prefixName}`);
return;
}
@ -240,7 +297,7 @@ export class SqsController extends EventController implements EventControllerInt
}
}
} catch (err: any) {
this.logger.error(`Error listing queues for instance ${instanceName}: ${err.message}`);
this.logger.error(`Error listing queues for ${prefixName}: ${err.message}`);
}
}
}

View File

@ -31,11 +31,14 @@ export class WebsocketController extends EventController implements EventControl
const params = new URLSearchParams(url.search);
const { remoteAddress } = req.socket;
const isLocalhost =
remoteAddress === '127.0.0.1' || remoteAddress === '::1' || remoteAddress === '::ffff:127.0.0.1';
const websocketConfig = configService.get<Websocket>('WEBSOCKET');
const allowedHosts = websocketConfig.ALLOWED_HOSTS || '127.0.0.1,::1,::ffff:127.0.0.1';
const isAllowedHost = allowedHosts
.split(',')
.map((h) => h.trim())
.includes(remoteAddress);
// Permite conexões internas do Socket.IO (EIO=4 é o Engine.IO v4)
if (params.has('EIO') && isLocalhost) {
if (params.has('EIO') && isAllowedHost) {
return callback(null, true);
}

View File

@ -26,7 +26,7 @@ const minioClient = (() => {
}
})();
const bucketName = process.env.S3_BUCKET;
const bucketName = BUCKET.BUCKET_NAME;
const bucketExists = async () => {
if (minioClient) {

View File

@ -1,6 +1,7 @@
import { RouterBroker } from '@api/abstract/abstract.router';
import { NumberDto } from '@api/dto/chat.dto';
import { businessController } from '@api/server.module';
import { createMetaErrorResponse } from '@utils/errorResponse';
import { catalogSchema, collectionsSchema } from '@validate/validate.schema';
import { RequestHandler, Router } from 'express';
@ -11,25 +12,43 @@ export class BusinessRouter extends RouterBroker {
super();
this.router
.post(this.routerPath('getCatalog'), ...guards, async (req, res) => {
const response = await this.dataValidate<NumberDto>({
request: req,
schema: catalogSchema,
ClassRef: NumberDto,
execute: (instance, data) => businessController.fetchCatalog(instance, data),
});
try {
const response = await this.dataValidate<NumberDto>({
request: req,
schema: catalogSchema,
ClassRef: NumberDto,
execute: (instance, data) => businessController.fetchCatalog(instance, data),
});
return res.status(HttpStatus.OK).json(response);
return res.status(HttpStatus.OK).json(response);
} catch (error) {
// Log error for debugging
console.error('Business catalog error:', error);
// Use utility function to create standardized error response
const errorResponse = createMetaErrorResponse(error, 'business_catalog');
return res.status(errorResponse.status).json(errorResponse);
}
})
.post(this.routerPath('getCollections'), ...guards, async (req, res) => {
const response = await this.dataValidate<NumberDto>({
request: req,
schema: collectionsSchema,
ClassRef: NumberDto,
execute: (instance, data) => businessController.fetchCollections(instance, data),
});
try {
const response = await this.dataValidate<NumberDto>({
request: req,
schema: collectionsSchema,
ClassRef: NumberDto,
execute: (instance, data) => businessController.fetchCollections(instance, data),
});
return res.status(HttpStatus.OK).json(response);
return res.status(HttpStatus.OK).json(response);
} catch (error) {
// Log error for debugging
console.error('Business collections error:', error);
// Use utility function to create standardized error response
const errorResponse = createMetaErrorResponse(error, 'business_collections');
return res.status(errorResponse.status).json(errorResponse);
}
});
}

View File

@ -5,9 +5,10 @@ import { ChannelRouter } from '@api/integrations/channel/channel.router';
import { ChatbotRouter } from '@api/integrations/chatbot/chatbot.router';
import { EventRouter } from '@api/integrations/event/event.router';
import { StorageRouter } from '@api/integrations/storage/storage.router';
import { configService } from '@config/env.config';
import { waMonitor } from '@api/server.module';
import { configService, Database, Facebook } from '@config/env.config';
import { fetchLatestWaWebVersion } from '@utils/fetchLatestWaWebVersion';
import { Router } from 'express';
import { NextFunction, Request, Response, Router } from 'express';
import fs from 'fs';
import mimeTypes from 'mime-types';
import path from 'path';
@ -36,23 +37,149 @@ enum HttpStatus {
const router: Router = Router();
const serverConfig = configService.get('SERVER');
const databaseConfig = configService.get<Database>('DATABASE');
const guards = [instanceExistsGuard, instanceLoggedGuard, authGuard['apikey']];
const telemetry = new Telemetry();
const packageJson = JSON.parse(fs.readFileSync('./package.json', 'utf8'));
// Middleware for metrics IP whitelist
const metricsIPWhitelist = (req: Request, res: Response, next: NextFunction) => {
const metricsConfig = configService.get('METRICS');
const allowedIPs = metricsConfig.ALLOWED_IPS?.split(',').map((ip) => ip.trim()) || ['127.0.0.1'];
const clientIP = req.ip || req.connection.remoteAddress || req.socket.remoteAddress;
if (!allowedIPs.includes(clientIP)) {
return res.status(403).send('Forbidden: IP not allowed');
}
next();
};
// Middleware for metrics Basic Authentication
const metricsBasicAuth = (req: Request, res: Response, next: NextFunction) => {
const metricsConfig = configService.get('METRICS');
const metricsUser = metricsConfig.USER;
const metricsPass = metricsConfig.PASSWORD;
if (!metricsUser || !metricsPass) {
return res.status(500).send('Metrics authentication not configured');
}
const auth = req.get('Authorization');
if (!auth || !auth.startsWith('Basic ')) {
res.set('WWW-Authenticate', 'Basic realm="Evolution API Metrics"');
return res.status(401).send('Authentication required');
}
const credentials = Buffer.from(auth.slice(6), 'base64').toString();
const [user, pass] = credentials.split(':');
if (user !== metricsUser || pass !== metricsPass) {
return res.status(401).send('Invalid credentials');
}
next();
};
// Expose Prometheus metrics when enabled by env flag
const metricsConfig = configService.get('METRICS');
if (metricsConfig.ENABLED) {
const metricsMiddleware = [];
// Add IP whitelist if configured
if (metricsConfig.ALLOWED_IPS) {
metricsMiddleware.push(metricsIPWhitelist);
}
// Add Basic Auth if required
if (metricsConfig.AUTH_REQUIRED) {
metricsMiddleware.push(metricsBasicAuth);
}
router.get('/metrics', ...metricsMiddleware, async (req, res) => {
res.set('Content-Type', 'text/plain; version=0.0.4; charset=utf-8');
res.set('Cache-Control', 'no-cache, no-store, must-revalidate');
const escapeLabel = (value: unknown) =>
String(value ?? '')
.replace(/\\/g, '\\\\')
.replace(/\n/g, '\\n')
.replace(/"/g, '\\"');
const lines: string[] = [];
const clientName = databaseConfig.CONNECTION.CLIENT_NAME || 'unknown';
const serverUrl = serverConfig.URL || '';
// environment info
lines.push('# HELP evolution_environment_info Environment information');
lines.push('# TYPE evolution_environment_info gauge');
lines.push(
`evolution_environment_info{version="${escapeLabel(packageJson.version)}",clientName="${escapeLabel(
clientName,
)}",serverUrl="${escapeLabel(serverUrl)}"} 1`,
);
const instances = (waMonitor && waMonitor.waInstances) || {};
const instanceEntries = Object.entries(instances);
// total instances
lines.push('# HELP evolution_instances_total Total number of instances');
lines.push('# TYPE evolution_instances_total gauge');
lines.push(`evolution_instances_total ${instanceEntries.length}`);
// per-instance status
lines.push('# HELP evolution_instance_up 1 if instance state is open, else 0');
lines.push('# TYPE evolution_instance_up gauge');
lines.push('# HELP evolution_instance_state Instance state as a labelled metric');
lines.push('# TYPE evolution_instance_state gauge');
for (const [name, instance] of instanceEntries) {
const state = instance?.connectionStatus?.state || 'unknown';
const integration = instance?.integration || '';
const up = state === 'open' ? 1 : 0;
lines.push(
`evolution_instance_up{instance="${escapeLabel(name)}",integration="${escapeLabel(integration)}"} ${up}`,
);
lines.push(
`evolution_instance_state{instance="${escapeLabel(name)}",integration="${escapeLabel(
integration,
)}",state="${escapeLabel(state)}"} 1`,
);
}
res.send(lines.join('\n') + '\n');
});
}
if (!serverConfig.DISABLE_MANAGER) router.use('/manager', new ViewsRouter().router);
router.get('/assets/*', (req, res) => {
const fileName = req.params[0];
// Security: Reject paths containing traversal patterns
if (!fileName || fileName.includes('..') || fileName.includes('\\') || path.isAbsolute(fileName)) {
return res.status(403).send('Forbidden');
}
const basePath = path.join(process.cwd(), 'manager', 'dist');
const assetsPath = path.join(basePath, 'assets');
const filePath = path.join(assetsPath, fileName);
const filePath = path.join(basePath, 'assets/', fileName);
// Security: Ensure the resolved path is within the assets directory
const resolvedPath = path.resolve(filePath);
const resolvedAssetsPath = path.resolve(assetsPath);
if (fs.existsSync(filePath)) {
res.set('Content-Type', mimeTypes.lookup(filePath) || 'text/css');
res.send(fs.readFileSync(filePath));
if (!resolvedPath.startsWith(resolvedAssetsPath + path.sep) && resolvedPath !== resolvedAssetsPath) {
return res.status(403).send('Forbidden');
}
if (fs.existsSync(resolvedPath)) {
res.set('Content-Type', mimeTypes.lookup(resolvedPath) || 'text/css');
res.send(fs.readFileSync(resolvedPath));
} else {
res.status(404).send('File not found');
}
@ -66,19 +193,20 @@ router
status: HttpStatus.OK,
message: 'Welcome to the Evolution API, it is working!',
version: packageJson.version,
clientName: process.env.DATABASE_CONNECTION_CLIENT_NAME,
clientName: databaseConfig.CONNECTION.CLIENT_NAME,
manager: !serverConfig.DISABLE_MANAGER ? `${req.protocol}://${req.get('host')}/manager` : undefined,
documentation: `https://doc.evolution-api.com`,
whatsappWebVersion: (await fetchLatestWaWebVersion({})).version.join('.'),
});
})
.post('/verify-creds', authGuard['apikey'], async (req, res) => {
const facebookConfig = configService.get<Facebook>('FACEBOOK');
return res.status(HttpStatus.OK).json({
status: HttpStatus.OK,
message: 'Credentials are valid',
facebookAppId: process.env.FACEBOOK_APP_ID,
facebookConfigId: process.env.FACEBOOK_CONFIG_ID,
facebookUserToken: process.env.FACEBOOK_USER_TOKEN,
facebookAppId: facebookConfig.APP_ID,
facebookConfigId: facebookConfig.CONFIG_ID,
facebookUserToken: facebookConfig.USER_TOKEN,
});
})
.use('/instance', new InstanceRouter(configService, ...guards).router)

View File

@ -3,6 +3,7 @@ import { InstanceDto } from '@api/dto/instance.dto';
import { TemplateDto } from '@api/dto/template.dto';
import { templateController } from '@api/server.module';
import { ConfigService } from '@config/env.config';
import { createMetaErrorResponse } from '@utils/errorResponse';
import { instanceSchema, templateSchema } from '@validate/validate.schema';
import { RequestHandler, Router } from 'express';
@ -16,24 +17,42 @@ export class TemplateRouter extends RouterBroker {
super();
this.router
.post(this.routerPath('create'), ...guards, async (req, res) => {
const response = await this.dataValidate<TemplateDto>({
request: req,
schema: templateSchema,
ClassRef: TemplateDto,
execute: (instance, data) => templateController.createTemplate(instance, data),
});
try {
const response = await this.dataValidate<TemplateDto>({
request: req,
schema: templateSchema,
ClassRef: TemplateDto,
execute: (instance, data) => templateController.createTemplate(instance, data),
});
res.status(HttpStatus.CREATED).json(response);
res.status(HttpStatus.CREATED).json(response);
} catch (error) {
// Log error for debugging
console.error('Template creation error:', error);
// Use utility function to create standardized error response
const errorResponse = createMetaErrorResponse(error, 'template_creation');
res.status(errorResponse.status).json(errorResponse);
}
})
.get(this.routerPath('find'), ...guards, async (req, res) => {
const response = await this.dataValidate<InstanceDto>({
request: req,
schema: instanceSchema,
ClassRef: InstanceDto,
execute: (instance) => templateController.findTemplate(instance),
});
try {
const response = await this.dataValidate<InstanceDto>({
request: req,
schema: instanceSchema,
ClassRef: InstanceDto,
execute: (instance) => templateController.findTemplate(instance),
});
res.status(HttpStatus.OK).json(response);
res.status(HttpStatus.OK).json(response);
} catch (error) {
// Log error for debugging
console.error('Template find error:', error);
// Use utility function to create standardized error response
const errorResponse = createMetaErrorResponse(error, 'template_find');
res.status(errorResponse.status).json(errorResponse);
}
});
}

View File

@ -9,7 +9,7 @@ import { TypebotService } from '@api/integrations/chatbot/typebot/services/typeb
import { PrismaRepository, Query } from '@api/repository/repository.service';
import { eventManager, waMonitor } from '@api/server.module';
import { Events, wa } from '@api/types/wa.types';
import { Auth, Chatwoot, ConfigService, HttpServer } from '@config/env.config';
import { Auth, Chatwoot, ConfigService, HttpServer, Proxy } from '@config/env.config';
import { Logger } from '@config/logger.config';
import { NotFoundException } from '@exceptions';
import { Contact, Message, Prisma } from '@prisma/client';
@ -364,13 +364,14 @@ export class ChannelStartupService {
public async loadProxy() {
this.localProxy.enabled = false;
if (process.env.PROXY_HOST) {
const proxyConfig = this.configService.get<Proxy>('PROXY');
if (proxyConfig.HOST) {
this.localProxy.enabled = true;
this.localProxy.host = process.env.PROXY_HOST;
this.localProxy.port = process.env.PROXY_PORT || '80';
this.localProxy.protocol = process.env.PROXY_PROTOCOL || 'http';
this.localProxy.username = process.env.PROXY_USERNAME;
this.localProxy.password = process.env.PROXY_PASSWORD;
this.localProxy.host = proxyConfig.HOST;
this.localProxy.port = proxyConfig.PORT || '80';
this.localProxy.protocol = proxyConfig.PROTOCOL || 'http';
this.localProxy.username = proxyConfig.USERNAME;
this.localProxy.password = proxyConfig.PASSWORD;
}
const data = await this.prismaRepository.proxy.findUnique({

View File

@ -29,6 +29,8 @@ export class WAMonitoringService {
Object.assign(this.db, configService.get<Database>('DATABASE'));
Object.assign(this.redis, configService.get<CacheConf>('CACHE'));
(this as any).providerSession = Object.freeze(configService.get<ProviderSession>('PROVIDER'));
}
private readonly db: Partial<Database> = {};
@ -37,7 +39,7 @@ export class WAMonitoringService {
private readonly logger = new Logger('WAMonitoringService');
public readonly waInstances: Record<string, any> = {};
private readonly providerSession = Object.freeze(this.configService.get<ProviderSession>('PROVIDER'));
private readonly providerSession: ProviderSession;
public delInstanceTime(instance: string) {
const time = this.configService.get<DelInstance>('DEL_INSTANCE');

View File

@ -60,6 +60,13 @@ export class TemplateService {
const response = await this.requestTemplate(postData, 'POST');
if (!response || response.error) {
// If there's an error from WhatsApp API, throw it with the real error data
if (response && response.error) {
// Create an error object that includes the template field for Meta errors
const metaError = new Error(response.error.message || 'WhatsApp API Error');
(metaError as any).template = response.error;
throw metaError;
}
throw new Error('Error to create template');
}
@ -75,8 +82,9 @@ export class TemplateService {
return template;
} catch (error) {
this.logger.error(error);
throw new Error('Error to create template');
this.logger.error('Error in create template: ' + error);
// Propagate the real error instead of "engolindo" it
throw error;
}
}
@ -86,6 +94,7 @@ export class TemplateService {
const version = this.configService.get<WaBusiness>('WA_BUSINESS').VERSION;
urlServer = `${urlServer}/${version}/${this.businessId}/message_templates`;
const headers = { 'Content-Type': 'application/json', Authorization: `Bearer ${this.token}` };
if (method === 'GET') {
const result = await axios.get(urlServer, { headers });
return result.data;
@ -94,8 +103,17 @@ export class TemplateService {
return result.data;
}
} catch (e) {
this.logger.error(e.response.data);
return e.response.data.error;
this.logger.error(
'WhatsApp API request error: ' + (e.response?.data ? JSON.stringify(e.response?.data) : e.message),
);
// Return the complete error response from WhatsApp API
if (e.response?.data) {
return e.response.data;
}
// If no response data, throw connection error
throw new Error(`Connection error: ${e.message}`);
}
}
}

View File

@ -4,6 +4,7 @@ import dotenv from 'dotenv';
dotenv.config();
export type HttpServer = {
NAME: string;
TYPE: 'http' | 'https';
PORT: number;
URL: string;
@ -113,15 +114,49 @@ export type Nats = {
export type Sqs = {
ENABLED: boolean;
GLOBAL_ENABLED: boolean;
GLOBAL_FORCE_SINGLE_QUEUE: boolean;
GLOBAL_PREFIX_NAME: string;
ACCESS_KEY_ID: string;
SECRET_ACCESS_KEY: string;
ACCOUNT_ID: string;
REGION: string;
MAX_PAYLOAD_SIZE: number;
EVENTS: {
APPLICATION_STARTUP: boolean;
CALL: boolean;
CHATS_DELETE: boolean;
CHATS_SET: boolean;
CHATS_UPDATE: boolean;
CHATS_UPSERT: boolean;
CONNECTION_UPDATE: boolean;
CONTACTS_SET: boolean;
CONTACTS_UPDATE: boolean;
CONTACTS_UPSERT: boolean;
GROUP_PARTICIPANTS_UPDATE: boolean;
GROUPS_UPDATE: boolean;
GROUPS_UPSERT: boolean;
LABELS_ASSOCIATION: boolean;
LABELS_EDIT: boolean;
LOGOUT_INSTANCE: boolean;
MESSAGES_DELETE: boolean;
MESSAGES_EDITED: boolean;
MESSAGES_SET: boolean;
MESSAGES_UPDATE: boolean;
MESSAGES_UPSERT: boolean;
PRESENCE_UPDATE: boolean;
QRCODE_UPDATED: boolean;
REMOVE_INSTANCE: boolean;
SEND_MESSAGE: boolean;
TYPEBOT_CHANGE_STATUS: boolean;
TYPEBOT_START: boolean;
};
};
export type Websocket = {
ENABLED: boolean;
GLOBAL_EVENTS: boolean;
ALLOWED_HOSTS?: string;
};
export type WaBusiness = {
@ -282,9 +317,50 @@ export type S3 = {
USE_SSL?: boolean;
REGION?: string;
SKIP_POLICY?: boolean;
SAVE_VIDEO?: boolean;
};
export type CacheConf = { REDIS: CacheConfRedis; LOCAL: CacheConfLocal };
export type Metrics = {
ENABLED: boolean;
AUTH_REQUIRED: boolean;
USER?: string;
PASSWORD?: string;
ALLOWED_IPS?: string;
};
export type Telemetry = {
ENABLED: boolean;
URL?: string;
};
export type Proxy = {
HOST?: string;
PORT?: string;
PROTOCOL?: string;
USERNAME?: string;
PASSWORD?: string;
};
export type AudioConverter = {
API_URL?: string;
API_KEY?: string;
};
export type Facebook = {
APP_ID?: string;
CONFIG_ID?: string;
USER_TOKEN?: string;
};
export type Sentry = {
DSN?: string;
};
export type EventEmitter = {
MAX_LISTENERS: number;
};
export type Production = boolean;
export interface Env {
@ -316,6 +392,13 @@ export interface Env {
CACHE: CacheConf;
S3?: S3;
AUTHENTICATION: Auth;
METRICS: Metrics;
TELEMETRY: Telemetry;
PROXY: Proxy;
AUDIO_CONVERTER: AudioConverter;
FACEBOOK: Facebook;
SENTRY: Sentry;
EVENT_EMITTER: EventEmitter;
PRODUCTION?: Production;
}
@ -344,6 +427,7 @@ export class ConfigService {
private envProcess(): Env {
return {
SERVER: {
NAME: process.env?.SERVER_NAME || 'evolution',
TYPE: (process.env.SERVER_TYPE as 'http' | 'https') || 'http',
PORT: Number.parseInt(process.env.SERVER_PORT) || 8080,
URL: process.env.SERVER_URL,
@ -465,14 +549,48 @@ export class ConfigService {
},
SQS: {
ENABLED: process.env?.SQS_ENABLED === 'true',
GLOBAL_ENABLED: process.env?.SQS_GLOBAL_ENABLED === 'true',
GLOBAL_FORCE_SINGLE_QUEUE: process.env?.SQS_GLOBAL_FORCE_SINGLE_QUEUE === 'true',
GLOBAL_PREFIX_NAME: process.env?.SQS_GLOBAL_PREFIX_NAME || 'global',
ACCESS_KEY_ID: process.env.SQS_ACCESS_KEY_ID || '',
SECRET_ACCESS_KEY: process.env.SQS_SECRET_ACCESS_KEY || '',
ACCOUNT_ID: process.env.SQS_ACCOUNT_ID || '',
REGION: process.env.SQS_REGION || '',
MAX_PAYLOAD_SIZE: Number.parseInt(process.env.SQS_MAX_PAYLOAD_SIZE ?? '1048576'),
EVENTS: {
APPLICATION_STARTUP: process.env?.SQS_GLOBAL_APPLICATION_STARTUP === 'true',
CALL: process.env?.SQS_GLOBAL_CALL === 'true',
CHATS_DELETE: process.env?.SQS_GLOBAL_CHATS_DELETE === 'true',
CHATS_SET: process.env?.SQS_GLOBAL_CHATS_SET === 'true',
CHATS_UPDATE: process.env?.SQS_GLOBAL_CHATS_UPDATE === 'true',
CHATS_UPSERT: process.env?.SQS_GLOBAL_CHATS_UPSERT === 'true',
CONNECTION_UPDATE: process.env?.SQS_GLOBAL_CONNECTION_UPDATE === 'true',
CONTACTS_SET: process.env?.SQS_GLOBAL_CONTACTS_SET === 'true',
CONTACTS_UPDATE: process.env?.SQS_GLOBAL_CONTACTS_UPDATE === 'true',
CONTACTS_UPSERT: process.env?.SQS_GLOBAL_CONTACTS_UPSERT === 'true',
GROUP_PARTICIPANTS_UPDATE: process.env?.SQS_GLOBAL_GROUP_PARTICIPANTS_UPDATE === 'true',
GROUPS_UPDATE: process.env?.SQS_GLOBAL_GROUPS_UPDATE === 'true',
GROUPS_UPSERT: process.env?.SQS_GLOBAL_GROUPS_UPSERT === 'true',
LABELS_ASSOCIATION: process.env?.SQS_GLOBAL_LABELS_ASSOCIATION === 'true',
LABELS_EDIT: process.env?.SQS_GLOBAL_LABELS_EDIT === 'true',
LOGOUT_INSTANCE: process.env?.SQS_GLOBAL_LOGOUT_INSTANCE === 'true',
MESSAGES_DELETE: process.env?.SQS_GLOBAL_MESSAGES_DELETE === 'true',
MESSAGES_EDITED: process.env?.SQS_GLOBAL_MESSAGES_EDITED === 'true',
MESSAGES_SET: process.env?.SQS_GLOBAL_MESSAGES_SET === 'true',
MESSAGES_UPDATE: process.env?.SQS_GLOBAL_MESSAGES_UPDATE === 'true',
MESSAGES_UPSERT: process.env?.SQS_GLOBAL_MESSAGES_UPSERT === 'true',
PRESENCE_UPDATE: process.env?.SQS_GLOBAL_PRESENCE_UPDATE === 'true',
QRCODE_UPDATED: process.env?.SQS_GLOBAL_QRCODE_UPDATED === 'true',
REMOVE_INSTANCE: process.env?.SQS_GLOBAL_REMOVE_INSTANCE === 'true',
SEND_MESSAGE: process.env?.SQS_GLOBAL_SEND_MESSAGE === 'true',
TYPEBOT_CHANGE_STATUS: process.env?.SQS_GLOBAL_TYPEBOT_CHANGE_STATUS === 'true',
TYPEBOT_START: process.env?.SQS_GLOBAL_TYPEBOT_START === 'true',
},
},
WEBSOCKET: {
ENABLED: process.env?.WEBSOCKET_ENABLED === 'true',
GLOBAL_EVENTS: process.env?.WEBSOCKET_GLOBAL_EVENTS === 'true',
ALLOWED_HOSTS: process.env?.WEBSOCKET_ALLOWED_HOSTS,
},
PUSHER: {
ENABLED: process.env?.PUSHER_ENABLED === 'true',
@ -653,6 +771,7 @@ export class ConfigService {
USE_SSL: process.env?.S3_USE_SSL === 'true',
REGION: process.env?.S3_REGION,
SKIP_POLICY: process.env?.S3_SKIP_POLICY === 'true',
SAVE_VIDEO: process.env?.S3_SAVE_VIDEO === 'true',
},
AUTHENTICATION: {
API_KEY: {
@ -660,6 +779,39 @@ export class ConfigService {
},
EXPOSE_IN_FETCH_INSTANCES: process.env?.AUTHENTICATION_EXPOSE_IN_FETCH_INSTANCES === 'true',
},
METRICS: {
ENABLED: process.env?.PROMETHEUS_METRICS === 'true',
AUTH_REQUIRED: process.env?.METRICS_AUTH_REQUIRED === 'true',
USER: process.env?.METRICS_USER,
PASSWORD: process.env?.METRICS_PASSWORD,
ALLOWED_IPS: process.env?.METRICS_ALLOWED_IPS,
},
TELEMETRY: {
ENABLED: process.env?.TELEMETRY_ENABLED === undefined || process.env?.TELEMETRY_ENABLED === 'true',
URL: process.env?.TELEMETRY_URL,
},
PROXY: {
HOST: process.env?.PROXY_HOST,
PORT: process.env?.PROXY_PORT,
PROTOCOL: process.env?.PROXY_PROTOCOL,
USERNAME: process.env?.PROXY_USERNAME,
PASSWORD: process.env?.PROXY_PASSWORD,
},
AUDIO_CONVERTER: {
API_URL: process.env?.API_AUDIO_CONVERTER,
API_KEY: process.env?.API_AUDIO_CONVERTER_KEY,
},
FACEBOOK: {
APP_ID: process.env?.FACEBOOK_APP_ID,
CONFIG_ID: process.env?.FACEBOOK_CONFIG_ID,
USER_TOKEN: process.env?.FACEBOOK_USER_TOKEN,
},
SENTRY: {
DSN: process.env?.SENTRY_DSN,
},
EVENT_EMITTER: {
MAX_LISTENERS: Number.parseInt(process.env?.EVENT_EMITTER_MAX_LISTENERS) || 50,
},
};
}
}

View File

@ -1,10 +1,11 @@
import { configService, EventEmitter as EventEmitterConfig } from '@config/env.config';
import EventEmitter2 from 'eventemitter2';
const maxListeners = parseInt(process.env.EVENT_EMITTER_MAX_LISTENERS, 10) || 50;
const eventEmitterConfig = configService.get<EventEmitterConfig>('EVENT_EMITTER');
export const eventEmitter = new EventEmitter2({
delimiter: '.',
newListener: false,
ignoreErrors: false,
maxListeners: maxListeners,
maxListeners: eventEmitterConfig.MAX_LISTENERS,
});

View File

@ -6,7 +6,15 @@ import { ProviderFiles } from '@api/provider/sessions';
import { PrismaRepository } from '@api/repository/repository.service';
import { HttpStatus, router } from '@api/routes/index.router';
import { eventManager, waMonitor } from '@api/server.module';
import { Auth, configService, Cors, HttpServer, ProviderSession, Webhook } from '@config/env.config';
import {
Auth,
configService,
Cors,
HttpServer,
ProviderSession,
Sentry as SentryConfig,
Webhook,
} from '@config/env.config';
import { onUnexpectedError } from '@config/error.config';
import { Logger } from '@config/logger.config';
import { ROOT_DIR } from '@config/path.config';
@ -140,7 +148,8 @@ async function bootstrap() {
eventManager.init(server);
if (process.env.SENTRY_DSN) {
const sentryConfig = configService.get<SentryConfig>('SENTRY');
if (sentryConfig.DSN) {
logger.info('Sentry - ON');
// Add this after all routes,

View File

@ -0,0 +1,47 @@
import { HttpStatus } from '@api/routes/index.router';
export interface MetaErrorResponse {
status: number;
error: string;
message: string;
details: {
whatsapp_error: string;
whatsapp_code: string | number;
error_user_title: string;
error_user_msg: string;
error_type: string;
error_subcode: number | null;
fbtrace_id: string | null;
context: string;
type: string;
};
timestamp: string;
}
/**
* Creates standardized error response for Meta/WhatsApp API errors
*/
export function createMetaErrorResponse(error: any, context: string): MetaErrorResponse {
// Extract Meta/WhatsApp specific error fields
const metaError = error.template || error;
const errorUserTitle = metaError.error_user_title || metaError.message || 'Unknown error';
const errorUserMsg = metaError.error_user_msg || metaError.message || 'Unknown error';
return {
status: HttpStatus.BAD_REQUEST,
error: 'Bad Request',
message: errorUserTitle,
details: {
whatsapp_error: errorUserMsg,
whatsapp_code: metaError.code || 'UNKNOWN_ERROR',
error_user_title: errorUserTitle,
error_user_msg: errorUserMsg,
error_type: metaError.type || 'UNKNOWN',
error_subcode: metaError.error_subcode || null,
fbtrace_id: metaError.fbtrace_id || null,
context,
type: 'whatsapp_api_error',
},
timestamp: new Date().toISOString(),
};
}

View File

@ -3,7 +3,13 @@ import { configService, S3 } from '@config/env.config';
const getTypeMessage = (msg: any) => {
let mediaId: string;
if (configService.get<S3>('S3').ENABLE) mediaId = msg.message?.mediaUrl;
if (
configService.get<S3>('S3').ENABLE &&
(configService.get<S3>('S3').SAVE_VIDEO ||
(msg?.message?.videoMessage === undefined &&
msg?.message?.viewOnceMessageV2?.message?.videoMessage === undefined))
)
mediaId = msg.message?.mediaUrl;
else mediaId = msg.key?.id;
const types = {

View File

@ -3,6 +3,8 @@ import fs from 'fs';
import i18next from 'i18next';
import path from 'path';
const __dirname = path.resolve(process.cwd(), 'src', 'utils');
const languages = ['en', 'pt-BR', 'es'];
const translationsPath = path.join(__dirname, 'translations');
const configService: ConfigService = new ConfigService();
@ -12,8 +14,9 @@ const resources: any = {};
languages.forEach((language) => {
const languagePath = path.join(translationsPath, `${language}.json`);
if (fs.existsSync(languagePath)) {
const translationContent = fs.readFileSync(languagePath, 'utf8');
resources[language] = {
translation: require(languagePath),
translation: JSON.parse(translationContent),
};
}
});

View File

@ -1,10 +1,11 @@
import { configService, Sentry as SentryConfig } from '@config/env.config';
import * as Sentry from '@sentry/node';
const dsn = process.env.SENTRY_DSN;
const sentryConfig = configService.get<SentryConfig>('SENTRY');
if (dsn) {
if (sentryConfig.DSN) {
Sentry.init({
dsn: dsn,
dsn: sentryConfig.DSN,
environment: process.env.NODE_ENV || 'development',
tracesSampleRate: 1.0,
profilesSampleRate: 1.0,

View File

@ -1,3 +1,4 @@
import { configService, Telemetry } from '@config/env.config';
import axios from 'axios';
import fs from 'fs';
@ -10,9 +11,9 @@ export interface TelemetryData {
}
export const sendTelemetry = async (route: string): Promise<void> => {
const enabled = process.env.TELEMETRY_ENABLED === undefined || process.env.TELEMETRY_ENABLED === 'true';
const telemetryConfig = configService.get<Telemetry>('TELEMETRY');
if (!enabled) {
if (!telemetryConfig.ENABLED) {
return;
}
@ -27,9 +28,7 @@ export const sendTelemetry = async (route: string): Promise<void> => {
};
const url =
process.env.TELEMETRY_URL && process.env.TELEMETRY_URL !== ''
? process.env.TELEMETRY_URL
: 'https://log.evolution-api.com/telemetry';
telemetryConfig.URL && telemetryConfig.URL !== '' ? telemetryConfig.URL : 'https://log.evolution-api.com/telemetry';
axios
.post(url, telemetry)

View File

@ -1,5 +1,6 @@
import { prismaRepository } from '@api/server.module';
import { CacheService } from '@api/services/cache.service';
import { CacheConf, configService } from '@config/env.config';
import { INSTANCE_DIR } from '@config/path.config';
import { AuthenticationState, BufferJSON, initAuthCreds, WAProto as proto } from 'baileys';
import fs from 'fs/promises';
@ -85,9 +86,10 @@ export default async function useMultiFileAuthStatePrisma(
async function writeData(data: any, key: string): Promise<any> {
const dataString = JSON.stringify(data, BufferJSON.replacer);
const cacheConfig = configService.get<CacheConf>('CACHE');
if (key != 'creds') {
if (process.env.CACHE_REDIS_ENABLED === 'true') {
if (cacheConfig.REDIS.ENABLED) {
return await cache.hSet(sessionId, key, data);
} else {
await fs.writeFile(localFile(key), dataString);
@ -101,9 +103,10 @@ export default async function useMultiFileAuthStatePrisma(
async function readData(key: string): Promise<any> {
try {
let rawData;
const cacheConfig = configService.get<CacheConf>('CACHE');
if (key != 'creds') {
if (process.env.CACHE_REDIS_ENABLED === 'true') {
if (cacheConfig.REDIS.ENABLED) {
return await cache.hGet(sessionId, key);
} else {
if (!(await fileExists(localFile(key)))) return null;
@ -123,8 +126,10 @@ export default async function useMultiFileAuthStatePrisma(
async function removeData(key: string): Promise<any> {
try {
const cacheConfig = configService.get<CacheConf>('CACHE');
if (key != 'creds') {
if (process.env.CACHE_REDIS_ENABLED === 'true') {
if (cacheConfig.REDIS.ENABLED) {
return await cache.hDelete(sessionId, key);
} else {
await fs.unlink(localFile(key));
@ -153,7 +158,7 @@ export default async function useMultiFileAuthStatePrisma(
ids.map(async (id) => {
let value = await readData(`${type}-${id}`);
if (type === 'app-state-sync-key' && value) {
value = proto.Message.AppStateSyncKeyData.fromObject(value);
value = proto.Message.AppStateSyncKeyData.create(value);
}
data[id] = value;

View File

@ -100,7 +100,7 @@ export class AuthStateProvider {
ids.map(async (id) => {
let value = await readData(`${type}-${id}`);
if (type === 'app-state-sync-key' && value) {
value = proto.Message.AppStateSyncKeyData.fromObject(value);
value = proto.Message.AppStateSyncKeyData.create(value);
}
data[id] = value;

View File

@ -50,7 +50,7 @@ export async function useMultiFileAuthStateRedisDb(
ids.map(async (id) => {
let value = await readData(`${type}-${id}`);
if (type === 'app-state-sync-key' && value) {
value = proto.Message.AppStateSyncKeyData.fromObject(value);
value = proto.Message.AppStateSyncKeyData.create(value);
}
data[id] = value;