Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(message): keep a caller-supplied batch id readable
Yudhi Armyndharis613a7d429af2
diff --git a/docs/06-api-specification.md b/docs/06-api-specification.mdindex 3eeb7f971..5960130df 100644--- a/docs/06-api-specification.md+++ b/docs/06-api-specification.md@@ -2268,7 +2268,7 @@ The rendered text is bounded the same way, by `TEMPLATE_RENDER_MAX_CHARS` (defau**Response** `202`-`202 Accepted` (via `@HttpCode`). `statusUrl` points at the batch-status route below.+`202 Accepted` (via `@HttpCode`). `statusUrl` points at the batch-status route below, with the session id and `batchId` percent-encoded.```json{diff --git a/openapi.json b/openapi.jsonindex b54a229d6..59a2d12db 100644--- a/openapi.json+++ b/openapi.json@@ -3182,6 +3182,97 @@]}},+ "/api/sessions/{sessionId}/messages/batch/{batchId}": {+ "get": {+ "operationId": "MessageController_getBatchStatus",+ "parameters": [+ {+ "name": "sessionId",+ "required": true,+ "in": "path",+ "description": "Session ID",+ "schema": {+ "type": "string"+ }+ },+ {+ "name": "batchId",+ "required": true,+ "in": "path",+ "description": "Batch ID",+ "schema": {+ "type": "string"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "Batch status and progress",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/BatchStatusResponseDto"+ }+ }+ }+ },+ "404": {+ "description": "Batch not found"+ }+ },+ "summary": "Get batch processing status",+ "tags": [+ "messages"+ ]+ }+ },+ "/api/sessions/{sessionId}/messages/batch/{batchId}/cancel": {+ "post": {+ "operationId": "MessageController_cancelBatch",+ "parameters": [+ {+ "name": "sessionId",+ "required": true,+ "in": "path",+ "description": "Session ID",+ "schema": {+ "type": "string"+ }+ },+ {+ "name": "batchId",+ "required": true,+ "in": "path",+ "description": "Batch ID",+ "schema": {+ "type": "string"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "Batch cancelled",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/BatchCancelResponseDto"+ }+ }+ }+ },+ "400": {+ "description": "Batch already completed, cancelled, or failed (terminal statuses are exclusive)"+ },+ "404": {+ "description": "Batch not found"+ }+ },+ "summary": "Cancel a running batch",+ "tags": [+ "messages"+ ]+ }+ },"/api/sessions/{sessionId}/messages/{chatId}/history": {"get": {"description": "Reads messages directly from the WhatsApp client for the given chat, bypassing the local DB. Useful for retrieving messages that arrived before the gateway was started.",@@ -3766,97 +3857,6 @@]}},- "/api/sessions/{sessionId}/messages/batch/{batchId}": {- "get": {- "operationId": "MessageController_getBatchStatus",- "parameters": [- {- "name": "sessionId",- "required": true,- "in": "path",- "description": "Session ID",- "schema": {- "type": "string"- }- },- {- "name": "batchId",- "required": true,- "in": "path",- "description": "Batch ID",- "schema": {- "type": "string"- }- }- ],- "responses": {- "200": {- "description": "Batch status and progress",- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/BatchStatusResponseDto"- }- }- }- },- "404": {- "description": "Batch not found"- }- },- "summary": "Get batch processing status",- "tags": [- "messages"- ]- }- },- "/api/sessions/{sessionId}/messages/batch/{batchId}/cancel": {- "post": {- "operationId": "MessageController_cancelBatch",- "parameters": [- {- "name": "sessionId",- "required": true,- "in": "path",- "description": "Session ID",- "schema": {- "type": "string"- }- },- {- "name": "batchId",- "required": true,- "in": "path",- "description": "Batch ID",- "schema": {- "type": "string"- }- }- ],- "responses": {- "200": {- "description": "Batch cancelled",- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/BatchCancelResponseDto"- }- }- }- },- "400": {- "description": "Batch already completed, cancelled, or failed (terminal statuses are exclusive)"- },- "404": {- "description": "Batch not found"- }- },- "summary": "Cancel a running batch",- "tags": [- "messages"- ]- }- },"/api/sessions/{sessionId}/templates": {"post": {"operationId": "TemplateController_create",@@ -12118,47 +12118,214 @@"success"]},- "ChatHistoryCallDto": {+ "BatchProgressDto": {"type": "object","properties": {- "video": {- "type": "boolean",- "description": "Video (true) vs voice (false) call.",- "example": false+ "total": {+ "type": "number",+ "example": 10},- "missed": {- "type": "boolean",- "description": "Whether an incoming call went unanswered.",- "example": true+ "sent": {+ "type": "number",+ "example": 7+ },+ "failed": {+ "type": "number",+ "example": 1+ },+ "pending": {+ "type": "number",+ "example": 2+ },+ "cancelled": {+ "type": "number",+ "example": 0}},"required": [- "video",- "missed"+ "total",+ "sent",+ "failed",+ "pending",+ "cancelled"]},- "ChatHistoryContactDto": {+ "BatchMessageErrorDto": {"type": "object","properties": {- "id": {+ "code": {"type": "string",- "description": "Sender JID (`…@c.us` or a `…@lid` privacy id).",- "example": "[email protected]"+ "description": "Machine-readable failure code.",+ "example": "RECIPIENT_UNREACHABLE"},- "number": {+ "message": {"type": "string",- "description": "Phone digits, best-effort.",- "example": "628123456789"- },- "name": {+ "example": "The number is not registered on WhatsApp"+ }+ },+ "required": [+ "code",+ "message"+ ]+ },+ "BatchMessageResultDto": {+ "type": "object",+ "properties": {+ "chatId": {"type": "string",- "example": "Alice"+ "example": "[email protected]"},- "pushName": {+ "status": {"type": "string",- "example": "Alice"+ "enum": [+ "pending",+ "sent",+ "failed",+ "cancelled"+ ],+ "example": "sent"},- "shortName": {+ "messageId": {+ "type": "string",+ "description": "Assigned on a successful send.",+ "example": "[email protected]_3EB0123456789"+ },+ "error": {+ "description": "Present on a failed send.",+ "allOf": [+ {+ "$ref": "#/components/schemas/BatchMessageErrorDto"+ }+ ]+ },+ "sentAt": {+ "type": "string",+ "format": "date-time",+ "description": "When the send completed."+ }+ },+ "required": [+ "chatId",+ "status"+ ]+ },+ "BatchStatusResponseDto": {+ "type": "object",+ "properties": {+ "batchId": {+ "type": "string",+ "example": "batch_abc123"+ },+ "status": {+ "type": "string",+ "enum": [+ "pending",+ "processing",+ "completed",+ "cancelled",+ "failed"+ ],+ "example": "processing"+ },+ "progress": {+ "$ref": "#/components/schemas/BatchProgressDto"+ },+ "results": {+ "description": "One entry per recipient already attempted.",+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/BatchMessageResultDto"+ }+ },+ "startedAt": {+ "type": "string",+ "format": "date-time",+ "nullable": true,+ "description": "When processing started; null while the batch is pending."+ },+ "completedAt": {+ "type": "string",+ "format": "date-time",+ "nullable": true,+ "description": "When the batch reached a terminal status; null while it is still running."+ }+ },+ "required": [+ "batchId",+ "status",+ "progress",+ "results"+ ]+ },+ "BatchCancelResponseDto": {+ "type": "object",+ "properties": {+ "batchId": {+ "type": "string",+ "example": "batch_abc123"+ },+ "status": {+ "type": "string",+ "enum": [+ "pending",+ "processing",+ "completed",+ "cancelled",+ "failed"+ ],+ "example": "cancelled"+ },+ "progress": {+ "$ref": "#/components/schemas/BatchProgressDto"+ }+ },+ "required": [+ "batchId",+ "status",+ "progress"+ ]+ },+ "ChatHistoryCallDto": {+ "type": "object",+ "properties": {+ "video": {+ "type": "boolean",+ "description": "Video (true) vs voice (false) call.",+ "example": false+ },+ "missed": {+ "type": "boolean",+ "description": "Whether an incoming call went unanswered.",+ "example": true+ }+ },+ "required": [+ "video",+ "missed"+ ]+ },+ "ChatHistoryContactDto": {+ "type": "object",+ "properties": {+ "id": {+ "type": "string",+ "description": "Sender JID (`…@c.us` or a `…@lid` privacy id).",+ "example": "[email protected]"+ },+ "number": {+ "type": "string",+ "description": "Phone digits, best-effort.",+ "example": "628123456789"+ },+ "name": {+ "type": "string",+ "example": "Alice"+ },+ "pushName": {+ "type": "string",+ "example": "Alice"+ },+ "shortName": {"type": "string","example": "Al"},@@ -12868,173 +13035,6 @@"statusUrl"]},- "BatchProgressDto": {- "type": "object",- "properties": {- "total": {- "type": "number",- "example": 10- },- "sent": {- "type": "number",- "example": 7- },- "failed": {- "type": "number",- "example": 1- },- "pending": {- "type": "number",- "example": 2- },- "cancelled": {- "type": "number",- "example": 0- }- },- "required": [- "total",- "sent",- "failed",- "pending",- "cancelled"- ]- },- "BatchMessageErrorDto": {- "type": "object",- "properties": {- "code": {- "type": "string",- "description": "Machine-readable failure code.",- "example": "RECIPIENT_UNREACHABLE"- },- "message": {- "type": "string",- "example": "The number is not registered on WhatsApp"- }- },- "required": [- "code",- "message"- ]- },- "BatchMessageResultDto": {- "type": "object",- "properties": {- "chatId": {- "type": "string",- "example": "[email protected]"- },- "status": {- "type": "string",- "enum": [- "pending",- "sent",- "failed",- "cancelled"- ],- "example": "sent"- },- "messageId": {- "type": "string",- "description": "Assigned on a successful send.",- "example": "[email protected]_3EB0123456789"- },- "error": {- "description": "Present on a failed send.",- "allOf": [- {- "$ref": "#/components/schemas/BatchMessageErrorDto"- }- ]- },- "sentAt": {- "type": "string",- "format": "date-time",- "description": "When the send completed."- }- },- "required": [- "chatId",- "status"- ]- },- "BatchStatusResponseDto": {- "type": "object",- "properties": {- "batchId": {- "type": "string",- "example": "batch_abc123"- },- "status": {- "type": "string",- "enum": [- "pending",- "processing",- "completed",- "cancelled",- "failed"- ],- "example": "processing"- },- "progress": {- "$ref": "#/components/schemas/BatchProgressDto"- },- "results": {- "description": "One entry per recipient already attempted.",- "type": "array",- "items": {- "$ref": "#/components/schemas/BatchMessageResultDto"- }- },- "startedAt": {- "type": "string",- "format": "date-time",- "nullable": true,- "description": "When processing started; null while the batch is pending."- },- "completedAt": {- "type": "string",- "format": "date-time",- "nullable": true,- "description": "When the batch reached a terminal status; null while it is still running."- }- },- "required": [- "batchId",- "status",- "progress",- "results"- ]- },- "BatchCancelResponseDto": {- "type": "object",- "properties": {- "batchId": {- "type": "string",- "example": "batch_abc123"- },- "status": {- "type": "string",- "enum": [- "pending",- "processing",- "completed",- "cancelled",- "failed"- ],- "example": "cancelled"- },- "progress": {- "$ref": "#/components/schemas/BatchProgressDto"- }- },- "required": [- "batchId",- "status",- "progress"- ]- },"CreateTemplateDto": {"type": "object","properties": {diff --git a/src/modules/message/bulk-message.service.spec.ts b/src/modules/message/bulk-message.service.spec.tsindex 7036dd7e1..901cd118b 100644--- a/src/modules/message/bulk-message.service.spec.ts+++ b/src/modules/message/bulk-message.service.spec.ts@@ -1285,6 +1285,17 @@ describe('BulkMessageService.createBatch base64 media cap', () => {expect((service as unknown as { inFlightBatches: number }).inFlightBatches).toBe(0);});+ it.each(['.', '..'])('rejects the dot-segment batchId %p, which no URL can address', async batchId => {+ const create = service.createBatch('s1', {+ batchId,+ messages: [{ chatId: '[email protected]', type: 'text', content: { text: 'hi' } }],+ } as unknown as SendBulkMessageDto);++ await expect(create).rejects.toBeInstanceOf(BadRequestException);+ await expect(create).rejects.toThrow(`Batch ID '${batchId}' is not allowed`);+ expect(repo.save).not.toHaveBeenCalled();+ });+it('scopes the batchId uniqueness check to the session (no cross-session collision/oracle)', async () => {// Simulate a DB where batchId 'dup' exists only under session 's1'.repo.findOne.mockImplementation((opts: { where: { batchId?: string; sessionId?: string } }) => {diff --git a/src/modules/message/bulk-message.service.ts b/src/modules/message/bulk-message.service.tsindex bedf68220..71f0b553d 100644--- a/src/modules/message/bulk-message.service.ts+++ b/src/modules/message/bulk-message.service.ts@@ -220,6 +220,11 @@ export class BulkMessageService implements OnApplicationBootstrap {}const batchId = dto.batchId || `batch_${randomUUID().split('-')[0]}`;+ // '.' and '..' are dot segments: URL clients collapse them, so the statusUrl and the status and+ // cancel routes for such a batch would resolve to a different path and it could never be reached.+ if (batchId === '.' || batchId === '..') {+ throw new BadRequestException(`Batch ID '${batchId}' is not allowed`);+ }// Check if this batchId already exists FOR THIS SESSION. Scoping by sessionId (matching how// getBatchStatus/cancelBatch already query) makes (sessionId, batchId) the namespace: one sessiondiff --git a/src/modules/message/message.controller.spec.ts b/src/modules/message/message.controller.spec.tsindex b924712e6..51f742724 100644--- a/src/modules/message/message.controller.spec.ts+++ b/src/modules/message/message.controller.spec.ts@@ -1,8 +1,12 @@import { StreamableFile } from '@nestjs/common';import { RESPONSE_PASSTHROUGH_METADATA } from '@nestjs/common/constants';+import { Test } from '@nestjs/testing';+import request from 'supertest';+import type { Server } from 'http';import { MessageController } from './message.controller';-import type { MessageService } from './message.service';-import type { BulkMessageService } from './bulk-message.service';+import { MessageService } from './message.service';+import { BulkMessageService } from './bulk-message.service';+import type { SendBulkMessageDto } from './dto/bulk-message.dto';import type { Response } from 'express';/**@@ -112,3 +116,47 @@ describe('MessageController - inlineMedia is opt-out', () => {expect(await afterFor(' db-42 ')).toBe('db-42');});});++/**+ * A caller may pick its own batchId. 'history' shares the two-segment shape of ':chatId/history',+ * and an id with a reserved character must survive the statusUrl handed back on creation.+ */+describe('MessageController - caller-supplied batch ids', () => {+ const bulk = {+ getBatchStatus: jest.fn().mockResolvedValue({ batchId: 'history', status: 'processing' }),+ createBatch: jest.fn().mockResolvedValue({ batchId: 'run/1?x', status: 'pending', messages: [] }),+ };+ const messages = { getChatHistory: jest.fn().mockResolvedValue([]) };++ it("routes GET batch/history to the batch status, not the history of chat 'batch'", async () => {+ const moduleRef = await Test.createTestingModule({+ controllers: [MessageController],+ providers: [+ { provide: MessageService, useValue: messages },+ { provide: BulkMessageService, useValue: bulk },+ ],+ }).compile();+ const app = moduleRef.createNestApplication();+ await app.init();+ try {+ await request(app.getHttpServer() as Server)+ .get('/sessions/s1/messages/batch/history')+ .expect(200);+ expect(bulk.getBatchStatus).toHaveBeenCalledWith('s1', 'history');+ expect(messages.getChatHistory).not.toHaveBeenCalled();+ } finally {+ await app.close();+ }+ });++ it('percent-encodes the batch id in the returned statusUrl', async () => {+ const controller = new MessageController(+ messages as unknown as MessageService,+ bulk as unknown as BulkMessageService,+ );++ const res = await controller.sendBulk('s1', {} as SendBulkMessageDto);++ expect(res.statusUrl).toBe('/api/sessions/s1/messages/batch/run%2F1%3Fx');+ });+});diff --git a/src/modules/message/message.controller.ts b/src/modules/message/message.controller.tsindex e48662287..a32ff2ca7 100644--- a/src/modules/message/message.controller.ts+++ b/src/modules/message/message.controller.ts@@ -436,6 +436,61 @@ export class MessageController {return { success: true };}+ // Declared before ':chatId/history': Express takes the first matching route, so a batch whose+ // caller-supplied id is 'history' would otherwise be read as the chat history of chat 'batch'.+ @Get('batch/:batchId')+ @ApiOperation({ summary: 'Get batch processing status' })+ @ApiParam({ name: 'sessionId', description: 'Session ID' })+ @ApiParam({ name: 'batchId', description: 'Batch ID' })+ @ApiResponse({+ status: 200,+ description: 'Batch status and progress',+ type: BatchStatusResponseDto,+ })+ @ApiResponse({+ status: 404,+ description: 'Batch not found',+ })+ async getBatchStatus(@Param('sessionId') sessionId: string, @Param('batchId') batchId: string) {+ const batch = await this.bulkMessageService.getBatchStatus(sessionId, batchId);+ return {+ batchId: batch.batchId,+ status: batch.status,+ progress: batch.progress,+ results: batch.results,+ startedAt: batch.startedAt,+ completedAt: batch.completedAt,+ };+ }++ @Post('batch/:batchId/cancel')+ @RequireRole(ApiKeyRole.OPERATOR)+ @HttpCode(HttpStatus.OK)+ @ApiOperation({ summary: 'Cancel a running batch' })+ @ApiParam({ name: 'sessionId', description: 'Session ID' })+ @ApiParam({ name: 'batchId', description: 'Batch ID' })+ @ApiResponse({+ status: 200,+ description: 'Batch cancelled',+ type: BatchCancelResponseDto,+ })+ @ApiResponse({+ status: 400,+ description: 'Batch already completed, cancelled, or failed (terminal statuses are exclusive)',+ })+ @ApiResponse({+ status: 404,+ description: 'Batch not found',+ })+ async cancelBatch(@Param('sessionId') sessionId: string, @Param('batchId') batchId: string) {+ const batch = await this.bulkMessageService.cancelBatch(sessionId, batchId);+ return {+ batchId: batch.batchId,+ status: batch.status,+ progress: batch.progress,+ };+ }+@Get(':chatId/history')@ApiOperation({summary: 'Fetch chat history live from WhatsApp',@@ -764,60 +819,7 @@ export class MessageController {status: batch.status,totalMessages: batch.messages.length,estimatedCompletionTime: estimatedTime.toISOString(),- statusUrl: `/api/sessions/${sessionId}/messages/batch/${batch.batchId}`,- };- }-- @Get('batch/:batchId')- @ApiOperation({ summary: 'Get batch processing status' })- @ApiParam({ name: 'sessionId', description: 'Session ID' })- @ApiParam({ name: 'batchId', description: 'Batch ID' })- @ApiResponse({- status: 200,- description: 'Batch status and progress',- type: BatchStatusResponseDto,- })- @ApiResponse({- status: 404,- description: 'Batch not found',- })- async getBatchStatus(@Param('sessionId') sessionId: string, @Param('batchId') batchId: string) {- const batch = await this.bulkMessageService.getBatchStatus(sessionId, batchId);- return {- batchId: batch.batchId,- status: batch.status,- progress: batch.progress,- results: batch.results,- startedAt: batch.startedAt,- completedAt: batch.completedAt,- };- }-- @Post('batch/:batchId/cancel')- @RequireRole(ApiKeyRole.OPERATOR)- @HttpCode(HttpStatus.OK)- @ApiOperation({ summary: 'Cancel a running batch' })- @ApiParam({ name: 'sessionId', description: 'Session ID' })- @ApiParam({ name: 'batchId', description: 'Batch ID' })- @ApiResponse({- status: 200,- description: 'Batch cancelled',- type: BatchCancelResponseDto,- })- @ApiResponse({- status: 400,- description: 'Batch already completed, cancelled, or failed (terminal statuses are exclusive)',- })- @ApiResponse({- status: 404,- description: 'Batch not found',- })- async cancelBatch(@Param('sessionId') sessionId: string, @Param('batchId') batchId: string) {- const batch = await this.bulkMessageService.cancelBatch(sessionId, batchId);- return {- batchId: batch.batchId,- status: batch.status,- progress: batch.progress,+ statusUrl: `/api/sessions/${encodeURIComponent(sessionId)}/messages/batch/${encodeURIComponent(batch.batchId)}`,};}}