Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
refactor(message): extract MessageSendService for the outbound send family
Yudhi Armyndharise8b45a582a5b
diff --git a/src/modules/message/message-send.service.spec.ts b/src/modules/message/message-send.service.spec.tsnew file mode 100644index 000000000..debd70294--- /dev/null+++ b/src/modules/message/message-send.service.spec.ts@@ -0,0 +1,1252 @@+import { Test, TestingModule } from '@nestjs/testing';+import { getRepositoryToken } from '@nestjs/typeorm';+import { Repository } from 'typeorm';+import { BadRequestException, NotFoundException, PayloadTooLargeException } from '@nestjs/common';+import { MessageSendService } from './message-send.service';+import { Message, MessageDirection, MessageStatus } from './entities/message.entity';+import { SessionService } from '../session/session.service';+import { EngineRegistry } from '../../engine/engine-registry.service';+import type { IWhatsAppEngine } from '../../engine/interfaces/whatsapp-engine.interface';+import { HookManager } from '../../core/hooks';+import { TemplateService } from '../template/template.service';+import { Template } from '../template/entities/template.entity';+import { SsrfBlockedError } from '../../common/security/ssrf-guard';+import { SendPacingService } from './send-pacing.service';++/** Pacing is off by default in these tests; the governor's own spec covers its behaviour. */+const inertPacing = (): SendPacingService =>+ ({+ assertSendAllowed: jest.fn().mockResolvedValue(undefined),+ recordSendFailure: jest.fn(),+ recordSendSuccess: jest.fn(),+ }) as unknown as SendPacingService;++const mockEngineResult = { id: 'wa-msg-1', timestamp: 1706868000 };++function createMockEngine() {+ return {+ sendTextMessage: jest.fn().mockResolvedValue(mockEngineResult),+ sendImageMessage: jest.fn().mockResolvedValue(mockEngineResult),+ sendVideoMessage: jest.fn().mockResolvedValue(mockEngineResult),+ sendAudioMessage: jest.fn().mockResolvedValue(mockEngineResult),+ sendDocumentMessage: jest.fn().mockResolvedValue(mockEngineResult),+ sendStickerMessage: jest.fn().mockResolvedValue(mockEngineResult),+ sendLocationMessage: jest.fn().mockResolvedValue(mockEngineResult),+ sendContactMessage: jest.fn().mockResolvedValue(mockEngineResult),+ sendPollMessage: jest.fn().mockResolvedValue(mockEngineResult),+ replyToMessage: jest.fn().mockResolvedValue(mockEngineResult),+ forwardMessage: jest.fn().mockResolvedValue(mockEngineResult),+ sendChatState: jest.fn().mockResolvedValue(undefined),+ };+}++describe('MessageSendService', () => {+ let service: MessageSendService;+ let repository: jest.Mocked<Partial<Repository<Message>>>;+ let sessionService: jest.Mocked<Partial<SessionService>>;+ let engines: EngineRegistry;+ let hookManager: jest.Mocked<Partial<HookManager>>;+ let templateService: jest.Mocked<Partial<TemplateService>>;+ let mockEngine: ReturnType<typeof createMockEngine>;++ // Auto-typing is on by default; disable it for the unrelated send tests so they don't incur the+ // real setTimeout delay and don't add an extra sendChatState call. The auto-typing suite opts in.+ beforeEach(() => {+ process.env.SIMULATE_TYPING = 'false';+ });+ afterEach(() => {+ delete process.env.SIMULATE_TYPING;+ delete process.env.SIMULATE_TYPING_MAX_MS;+ });++ beforeEach(async () => {+ repository = {+ create: jest.fn().mockImplementation((data: Partial<Message>) => ({ id: 'msg-uuid-1', ...data }) as Message),+ save: jest.fn().mockImplementation(msg => Promise.resolve(msg)),+ findOne: jest.fn().mockResolvedValue(null),+ update: jest.fn().mockResolvedValue({ affected: 1 }),+ delete: jest.fn().mockResolvedValue({ affected: 1 }),+ };++ mockEngine = createMockEngine();++ sessionService = {+ findOne: jest.fn().mockResolvedValue({ id: 'sess-1', phone: '628123456789' }),+ };++ engines = new EngineRegistry();+ engines.set('sess-1', mockEngine as unknown as IWhatsAppEngine);++ hookManager = {+ // Echo the input straight back so the message:sending gate is a pass-through by default; specific+ // tests override with continue:false (block) or a modified input.+ execute: jest+ .fn()+ .mockImplementation((_event: string, data: unknown) => Promise.resolve({ continue: true, data })),+ };++ templateService = {+ resolve: jest.fn(),+ };++ const module: TestingModule = await Test.createTestingModule({+ providers: [+ MessageSendService,+ {+ provide: SendPacingService,+ useValue: {+ assertSendAllowed: jest.fn().mockResolvedValue(undefined),+ recordSendFailure: jest.fn(),+ recordSendSuccess: jest.fn(),+ },+ },+ { provide: getRepositoryToken(Message, 'data'), useValue: repository },+ { provide: SessionService, useValue: sessionService },+ { provide: EngineRegistry, useValue: engines },+ { provide: HookManager, useValue: hookManager },+ { provide: TemplateService, useValue: templateService },+ ],+ }).compile();++ service = module.get<MessageSendService>(MessageSendService);+ });++ // ── sendText ──────────────────────────────────────────────────────++ describe('auto-typing before send (SIMULATE_TYPING, on by default)', () => {+ it('sends a typing presence before the message by default', async () => {+ delete process.env.SIMULATE_TYPING; // default = on+ process.env.SIMULATE_TYPING_MAX_MS = '1'; // keep the humanising delay ~instant in tests++ await service.sendText('sess-1', { chatId: '[email protected]', text: 'Hello' });++ expect(mockEngine.sendChatState).toHaveBeenCalledWith('[email protected]', 'typing');+ expect(mockEngine.sendTextMessage).toHaveBeenCalledWith('[email protected]', 'Hello');+ });++ it('does not send typing presence when SIMULATE_TYPING=false', async () => {+ process.env.SIMULATE_TYPING = 'false';+ await service.sendText('sess-1', { chatId: '[email protected]', text: 'Hello' });+ expect(mockEngine.sendChatState).not.toHaveBeenCalled();+ });+ });++ describe('sendText', () => {+ it('should send text message and return messageId + timestamp', async () => {+ const result = await service.sendText('sess-1', {+ chatId: '[email protected]',+ text: 'Hello',+ });++ expect(result.messageId).toBe('wa-msg-1');+ expect(result.timestamp).toBe(1706868000);+ expect(mockEngine.sendTextMessage).toHaveBeenCalledWith('[email protected]', 'Hello');+ });++ it('threads mentions through to the engine (#530)', async () => {+ const input = { chatId: '[email protected]', text: 'hi @62811', mentions: ['[email protected]'] };+ (hookManager.execute as jest.Mock).mockResolvedValueOnce({+ continue: true,+ data: { sessionId: 'sess-1', input, type: 'text' },+ });+ await service.sendText('sess-1', input);+ expect(mockEngine.sendTextMessage).toHaveBeenCalledWith('[email protected]', 'hi @62811', ['[email protected]']);+ });++ // The parameter is only guaranteed in its suppressing direction, so what matters is that `false`+ // reaches the engine and that everything else leaves the existing call shape alone.+ it('threads a link-preview suppression through to the engine', async () => {+ const input = { chatId: '[email protected]', text: 'see https://example.com', linkPreview: false };+ (hookManager.execute as jest.Mock).mockResolvedValueOnce({+ continue: true,+ data: { sessionId: 'sess-1', input, type: 'text' },+ });++ await service.sendText('sess-1', input);++ expect(mockEngine.sendTextMessage).toHaveBeenCalledWith(+ '[email protected]',+ 'see https://example.com',+ undefined,+ { linkPreview: false },+ );+ });++ // A send that asks for nothing must keep the exact call it made before this option existed —+ // a trailing undefined would be harmless to the engines but would rewrite every existing send.+ it('leaves the plain send shape untouched when no preview choice is made', async () => {+ await service.sendText('sess-1', { chatId: '[email protected]', text: 'hi' });++ expect(mockEngine.sendTextMessage).toHaveBeenCalledWith('[email protected]', 'hi');+ });++ it('threads a caller-supplied preview through to the engine', async () => {+ const input = {+ chatId: '[email protected]',+ text: 'see https://example.com',+ customLinkPreview: { url: 'https://example.com', title: 'Example', description: 'A site' },+ };+ (hookManager.execute as jest.Mock).mockResolvedValueOnce({+ continue: true,+ data: { sessionId: 'sess-1', input, type: 'text' },+ });++ await service.sendText('sess-1', input);++ expect(mockEngine.sendTextMessage).toHaveBeenCalledWith(+ '[email protected]',+ 'see https://example.com',+ undefined,+ { customPreview: { url: 'https://example.com', title: 'Example', description: 'A site' } },+ );+ });++ // Suppressing the preview and supplying one are opposite requests; guessing which was meant+ // would send a message the caller did not ask for either way.+ it('refuses a suppression combined with a supplied preview, before reaching the engine', async () => {+ await expect(+ service.sendText('sess-1', {+ chatId: '[email protected]',+ text: 'hi',+ linkPreview: false,+ customLinkPreview: { url: 'https://example.com', title: 'Example' },+ }),+ ).rejects.toBeInstanceOf(BadRequestException);++ expect(mockEngine.sendTextMessage).not.toHaveBeenCalled();+ });++ it('should save outgoing message as pending before sending, then update to sent', async () => {+ await service.sendText('sess-1', {+ chatId: '[email protected]',+ text: 'Hello',+ });++ // First save: pending message before engine send+ expect(repository.create).toHaveBeenCalledWith(+ expect.objectContaining({+ sessionId: 'sess-1',+ direction: MessageDirection.OUTGOING,+ type: 'text',+ body: 'Hello',+ status: MessageStatus.PENDING,+ }),+ );+ // save called twice: once for initial pending, once for status update to sent+ expect(repository.save).toHaveBeenCalledTimes(2);+ });++ it('returns success (not FAILED) when persisting the SENT state fails after a successful send', async () => {+ // 1st save (PENDING) ok; 2nd save (SENT-state, after WhatsApp already accepted the message) throws.+ (repository.save as jest.Mock)+ .mockImplementationOnce((msg: unknown) => Promise.resolve(msg))+ .mockRejectedValueOnce(new Error('transient db fault'));++ const result = await service.sendText('sess-1', { chatId: '[email protected]', text: 'Hello' });++ // The send succeeded, so it is reported as success — not rethrown, not marked FAILED.+ expect(result.messageId).toBe('wa-msg-1');+ expect(result.timestamp).toBe(1706868000);+ expect(hookManager.execute).not.toHaveBeenCalledWith('message:failed', expect.anything(), expect.anything());+ });++ it('executes the message:sending hook (message:sent now fires once from the engine message_create path)', async () => {+ await service.sendText('sess-1', {+ chatId: '[email protected]',+ text: 'Hello',+ });++ expect(hookManager.execute).toHaveBeenCalledWith(+ 'message:sending',+ expect.objectContaining({ type: 'text' }),+ expect.any(Object),+ );+ // message:sent is no longer fired here — it is emitted solely by the onMessageCreate wiring in+ // SessionEngineLifecycle (via MessageProjector)+ // with a consistent IncomingMessage payload for ALL sends (avoids the prior double dispatch).+ expect(hookManager.execute).not.toHaveBeenCalledWith('message:sent', expect.anything(), expect.anything());+ });++ it('emits message:persisted on BOTH the pending save and the finalized sent save (#906)', async () => {+ await service.sendText('sess-1', { chatId: '[email protected]', text: 'hello' });++ const calls = (hookManager.execute as jest.Mock).mock.calls.filter(+ ([ev]: unknown[]) => ev === 'message:persisted',+ ) as unknown[][];+ expect(calls).toHaveLength(2);+ expect(calls[0][1]).toMatchObject({+ sessionId: 'sess-1',+ message: { chatId: '[email protected]', status: MessageStatus.PENDING },+ });+ expect(calls[1][1]).toMatchObject({+ sessionId: 'sess-1',+ message: { status: MessageStatus.SENT, waMessageId: 'wa-msg-1' },+ });+ expect(calls[0][2]).toMatchObject({ sessionId: 'sess-1', source: 'MessageService' });+ });++ it('re-emits message:persisted with FAILED when the send itself fails (#906)', async () => {+ mockEngine.sendTextMessage.mockRejectedValueOnce(new Error('engine down'));++ await expect(service.sendText('sess-1', { chatId: '[email protected]', text: 'hi' })).rejects.toThrow();++ const calls = (hookManager.execute as jest.Mock).mock.calls.filter(+ ([ev]: unknown[]) => ev === 'message:persisted',+ ) as unknown[][];+ expect(calls).toHaveLength(2);+ expect(calls[0][1]).toMatchObject({ message: { status: MessageStatus.PENDING } });+ expect(calls[1][1]).toMatchObject({ message: { status: MessageStatus.FAILED } });+ });++ it('reconciles provider indexes when the send echo won the race: upsert the surviving row + drop the ghost (#906)', async () => {+ const echoRow = {+ id: 'echo-uuid-9',+ sessionId: 'sess-1',+ waMessageId: 'wa-msg-1',+ status: MessageStatus.SENT,+ } as Message;+ (repository.save as jest.Mock)+ .mockImplementationOnce((msg: unknown) => Promise.resolve(msg)) // PENDING save+ .mockRejectedValueOnce(+ Object.assign(new Error('UNIQUE constraint failed'), { code: 'SQLITE_CONSTRAINT_UNIQUE' }),+ ); // SENT save collides with the echo row+ (repository.findOne as jest.Mock).mockResolvedValueOnce(echoRow);++ await service.sendText('sess-1', { chatId: '[email protected]', text: 'hi' });++ // SENT state merged onto the echo row; the redundant PENDING row dropped.+ expect(repository.update).toHaveBeenCalledWith(+ { sessionId: 'sess-1', waMessageId: 'wa-msg-1' },+ expect.objectContaining({ status: MessageStatus.SENT }),+ );+ expect(repository.delete).toHaveBeenCalledWith({ id: 'msg-uuid-1' });+ const persisted = (hookManager.execute as jest.Mock).mock.calls.filter(+ ([ev]: unknown[]) => ev === 'message:persisted',+ ) as unknown[][];+ // PENDING + the surviving echo row (the failed SENT save itself emits nothing).+ expect(persisted).toHaveLength(2);+ expect(persisted[1][1]).toMatchObject({ message: { id: 'echo-uuid-9' } });+ const deleted = (hookManager.execute as jest.Mock).mock.calls.filter(+ ([ev]: unknown[]) => ev === 'message:deleted',+ ) as unknown[][];+ expect(deleted).toHaveLength(1);+ expect(deleted[0][1]).toMatchObject({ sessionId: 'sess-1', message: { id: 'msg-uuid-1' } });+ expect(deleted[0][2]).toMatchObject({ sessionId: 'sess-1', source: 'MessageService' });+ });++ it('should throw BadRequestException when plugin blocks sending', async () => {+ (hookManager.execute as jest.Mock).mockResolvedValueOnce({ continue: false, data: {} });++ await expect(service.sendText('sess-1', { chatId: '[email protected]', text: 'blocked' })).rejects.toThrow(+ 'Message sending blocked by plugin',+ );+ });++ it('should throw BadRequestException if session is not active', async () => {+ engines.delete('sess-1');++ await expect(service.sendText('inactive', { chatId: '[email protected]', text: 'hello' })).rejects.toThrow(+ BadRequestException,+ );+ });+ });++ // ── sendTemplate ──────────────────────────────────────────────────++ describe('sendTemplate', () => {+ function mockTemplate(overrides: Partial<Template> = {}): Template {+ return {+ id: 'tpl-1',+ sessionId: 'sess-1',+ name: 'order-confirmation',+ body: 'Hi {{customer}}, your order {{orderId}} shipped.',+ header: null,+ footer: null,+ createdAt: new Date(),+ updatedAt: new Date(),+ session: undefined as unknown as Template['session'],+ ...overrides,+ };+ }++ beforeEach(() => {+ // Echo the supplied input back through the hook so the rendered text+ // reaches the engine via the delegated sendText path.+ (hookManager.execute as jest.Mock).mockImplementation((event: string, data: unknown) =>+ Promise.resolve({ continue: true, data }),+ );+ });++ it('should resolve the template, render variables, and delegate to sendText', async () => {+ (templateService.resolve as jest.Mock).mockResolvedValue(mockTemplate());++ const result = await service.sendTemplate('sess-1', {+ chatId: '[email protected]',+ templateName: 'order-confirmation',+ vars: { customer: 'Alice', orderId: '1234' },+ });++ expect(templateService.resolve).toHaveBeenCalledWith('sess-1', {+ templateId: undefined,+ templateName: 'order-confirmation',+ });+ expect(mockEngine.sendTextMessage).toHaveBeenCalledWith(+ '[email protected]',+ 'Hi Alice, your order 1234 shipped.',+ );+ expect(result.messageId).toBe('wa-msg-1');+ });++ it('should flatten header and footer around the body with blank lines', async () => {+ (templateService.resolve as jest.Mock).mockResolvedValue(+ mockTemplate({ header: 'OpenWA Store', body: 'Hello {{customer}}', footer: 'Reply STOP to opt out' }),+ );++ await service.sendTemplate('sess-1', {+ chatId: '[email protected]',+ templateId: 'tpl-1',+ vars: { customer: 'Bob' },+ });++ expect(mockEngine.sendTextMessage).toHaveBeenCalledWith(+ '[email protected]',+ 'OpenWA Store\n\nHello Bob\n\nReply STOP to opt out',+ );+ });++ it('should leave unmatched placeholders literal', async () => {+ (templateService.resolve as jest.Mock).mockResolvedValue(mockTemplate({ body: 'Hi {{customer}} {{unknown}}' }));++ await service.sendTemplate('sess-1', {+ chatId: '[email protected]',+ templateId: 'tpl-1',+ vars: { customer: 'Alice' },+ });++ expect(mockEngine.sendTextMessage).toHaveBeenCalledWith('[email protected]', 'Hi Alice {{unknown}}');+ });++ it('should propagate NotFoundException when the template cannot be resolved', async () => {+ (templateService.resolve as jest.Mock).mockRejectedValue(new NotFoundException('Template not found'));++ await expect(service.sendTemplate('sess-1', { chatId: '[email protected]', templateName: 'missing' })).rejects.toThrow(+ NotFoundException,+ );+ expect(mockEngine.sendTextMessage).not.toHaveBeenCalled();+ });++ it('rejects an over-cap render with a 400 naming the limit (never truncated silently)', async () => {+ (templateService.resolve as jest.Mock).mockResolvedValue(mockTemplate({ body: 'Hi {{customer}}' }));++ const error = await service+ .sendTemplate('sess-1', {+ chatId: '[email protected]',+ templateId: 'tpl-1',+ vars: { customer: 'x'.repeat(70_000) },+ })+ .catch((e: unknown) => e);++ expect(error).toBeInstanceOf(BadRequestException);+ expect((error as Error).message).toContain('over the 65536-character limit');+ expect(mockEngine.sendTextMessage).not.toHaveBeenCalled();+ });++ it('renders at-or-under the cap unchanged', async () => {+ (templateService.resolve as jest.Mock).mockResolvedValue(mockTemplate({ body: 'Hi {{customer}}' }));+ // 'Hi ' + name lands exactly on the 64 KiB default cap — at the cap is NOT over it.+ const name = 'y'.repeat(64 * 1024 - 3);++ await service.sendTemplate('sess-1', { chatId: '[email protected]', templateId: 'tpl-1', vars: { customer: name } });++ expect(mockEngine.sendTextMessage).toHaveBeenCalledWith('[email protected]', `Hi ${name}`);+ });++ it('honors a configured template.renderMaxChars override', async () => {+ const configService = {+ get: (key: string, fallback: unknown) => (key === 'template.renderMaxChars' ? 10 : fallback),+ } as unknown as ConstructorParameters<typeof MessageSendService>[6];+ const capped = new MessageSendService(+ repository as Repository<Message>,+ sessionService as unknown as SessionService,+ engines,+ hookManager as HookManager,+ templateService as unknown as TemplateService,+ inertPacing(),+ configService,+ );+ (templateService.resolve as jest.Mock).mockResolvedValue(mockTemplate({ body: 'Hello {{customer}}' }));++ await expect(+ capped.sendTemplate('sess-1', { chatId: '[email protected]', templateId: 'tpl-1', vars: { customer: 'Alice' } }),+ ).rejects.toThrow(/over the 10-character limit/);+ expect(mockEngine.sendTextMessage).not.toHaveBeenCalled();+ });+ });++ // ── send-hook chokepoint ──────────────────────────────────────────++ describe('send-hook chokepoint (message:sending gate + message:failed across all senders)', () => {+ it('runs the message:sending gate for a media send (sendImage) tagged with the media type', async () => {+ await service.sendImage('sess-1', { chatId: '[email protected]', url: 'https://e.com/i.jpg', caption: 'hi' });+ expect(hookManager.execute).toHaveBeenCalledWith(+ 'message:sending',+ expect.objectContaining({ type: 'image' }),+ expect.any(Object),+ );+ });++ it('runs the message:sending gate for an extended send (sendPoll)', async () => {+ await service.sendPoll('sess-1', { chatId: '[email protected]', name: 'Q?', options: ['a', 'b'] });+ expect(hookManager.execute).toHaveBeenCalledWith(+ 'message:sending',+ expect.objectContaining({ type: 'poll' }),+ expect.any(Object),+ );+ });++ it('lets a plugin block a media send (continue:false) before the engine is called', async () => {+ (hookManager.execute as jest.Mock).mockResolvedValueOnce({ continue: false, data: {} });+ await expect(service.sendImage('sess-1', { chatId: '[email protected]', url: 'https://e.com/i.jpg' })).rejects.toThrow(+ 'Message sending blocked by plugin',+ );+ expect(mockEngine.sendImageMessage).not.toHaveBeenCalled();+ });++ it('threads a plugin-modified media input through to the engine', async () => {+ (hookManager.execute as jest.Mock).mockResolvedValueOnce({+ continue: true,+ data: {+ sessionId: 'sess-1',+ type: 'image',+ input: { chatId: '[email protected]', url: 'https://e.com/mod.jpg', caption: 'edited' },+ },+ });+ await service.sendImage('sess-1', { chatId: '[email protected]', url: 'https://e.com/i.jpg', caption: 'orig' });+ expect(mockEngine.sendImageMessage).toHaveBeenCalledWith(+ '[email protected]',+ expect.objectContaining({ data: 'https://e.com/mod.jpg', caption: 'edited' }),+ );+ });++ it('fires message:failed when a media send fails (previously only sendText did)', async () => {+ mockEngine.sendImageMessage.mockRejectedValueOnce(new Error('engine down'));+ await expect(service.sendImage('sess-1', { chatId: '[email protected]', url: 'https://e.com/i.jpg' })).rejects.toThrow(+ 'engine down',+ );+ expect(hookManager.execute).toHaveBeenCalledWith(+ 'message:failed',+ expect.objectContaining({ type: 'image', error: 'engine down' }),+ expect.any(Object),+ );+ });+ });++ // ── sendImage ─────────────────────────────────────────────────────++ describe('sendImage', () => {+ it('should send image via URL', async () => {+ const result = await service.sendImage('sess-1', {+ chatId: '[email protected]',+ url: 'https://example.com/img.jpg',+ caption: 'My image',+ });++ expect(result.messageId).toBe('wa-msg-1');+ expect(mockEngine.sendImageMessage).toHaveBeenCalledWith(+ '[email protected]',+ expect.objectContaining({ data: 'https://example.com/img.jpg', caption: 'My image' }),+ );+ });++ it('should send image via base64 with mimetype', async () => {+ await service.sendImage('sess-1', {+ chatId: '[email protected]',+ base64: 'iVBORw0KGgoAAAAN...',+ mimetype: 'image/png',+ });++ expect(mockEngine.sendImageMessage).toHaveBeenCalledWith(+ '[email protected]',+ expect.objectContaining({ data: 'iVBORw0KGgoAAAAN...', mimetype: 'image/png' }),+ );+ });++ it('threads media mentions into the MediaInput (#530)', async () => {+ await service.sendImage('sess-1', {+ chatId: '[email protected]',+ base64: 'AAAA',+ mimetype: 'image/png',+ caption: 'look @62811',+ mentions: ['[email protected]'],+ });+ expect(mockEngine.sendImageMessage).toHaveBeenCalledWith(+ '[email protected]',+ expect.objectContaining({ mentions: ['[email protected]'] }),+ );+ });++ it('maps a blocked-media-URL SSRF error to HTTP 400 with a generic message (no internal IP leak)', async () => {+ mockEngine.sendImageMessage.mockRejectedValueOnce(+ new SsrfBlockedError('Host x resolves to a blocked internal address: 169.254.169.254'),+ );++ // Generic client message — the resolved internal IP must NOT reach the caller (recon oracle).+ await expect(+ service.sendImage('sess-1', { chatId: '[email protected]', url: 'http://127.0.0.1/x.png' }),+ ).rejects.toMatchObject({ response: { message: 'Destination address is not allowed' } });+ });++ it('does not leak the SSRF internal address into the message:failed hook payload (media sends now route there)', async () => {+ mockEngine.sendImageMessage.mockRejectedValueOnce(+ new SsrfBlockedError('Host x resolves to a blocked internal address: 169.254.169.254'),+ );++ await expect(+ service.sendImage('sess-1', { chatId: '[email protected]', url: 'http://127.0.0.1/x.png' }),+ ).rejects.toThrow();++ const calls = (hookManager.execute as jest.Mock).mock.calls as [string, { error?: string }, unknown][];+ const failedCall = calls.find(c => c[0] === 'message:failed');+ expect(failedCall).toBeDefined();+ // The hook payload (now delivered to plugins for media sends) carries the generic message, NOT+ // the resolved internal IP that the raw SsrfBlockedError.message contains.+ expect(failedCall![1].error).toBe('Destination address is not allowed');+ expect(failedCall![1].error).not.toContain('169.254.169.254');+ });++ it('rejects a base64 image over the media cap before sending or persisting', async () => {+ process.env.MEDIA_DOWNLOAD_MAX_BYTES = '1024';+ try {+ await expect(+ service.sendImage('sess-1', {+ chatId: '[email protected]',+ base64: Buffer.alloc(1025).toString('base64'),+ mimetype: 'image/png',+ }),+ ).rejects.toBeInstanceOf(PayloadTooLargeException);+ expect(mockEngine.sendImageMessage).not.toHaveBeenCalled();+ } finally {+ delete process.env.MEDIA_DOWNLOAD_MAX_BYTES;+ }+ });++ it('strips the base64 payload from a FAILED media row but keeps mimetype/filename', async () => {+ mockEngine.sendImageMessage.mockRejectedValueOnce(new Error('engine down'));++ await expect(+ service.sendImage('sess-1', {+ chatId: '[email protected]',+ base64: 'QUJDREVGISBhIGJpZyBwYXlsb2Fk',+ mimetype: 'image/png',+ filename: 'pic.png',+ }),+ ).rejects.toThrow();++ // The persisted FAILED row must not retain the (often multi-MB) base64 — it's never displayed+ // or retried — but should keep the descriptive mimetype/filename.+ const calls = (repository.save as jest.Mock).mock.calls as [Message][];+ const saved = calls.at(-1)![0];+ expect(saved.status).toBe(MessageStatus.FAILED);+ const media = (saved.metadata as { media?: { data?: unknown; mimetype?: string; filename?: string } }).media;+ expect(media?.data).toBeUndefined();+ expect(media?.mimetype).toBe('image/png');+ expect(media?.filename).toBe('pic.png');+ });+ });++ // ── sendVideo / sendAudio / sendDocument / sendSticker ────────────++ describe('sendVideo', () => {+ it('should call engine.sendVideoMessage', async () => {+ await service.sendVideo('sess-1', {+ chatId: '[email protected]',+ url: 'https://example.com/video.mp4',+ });+ expect(mockEngine.sendVideoMessage).toHaveBeenCalled();+ });+ });++ describe('sendAudio', () => {+ it('should call engine.sendAudioMessage', async () => {+ await service.sendAudio('sess-1', {+ chatId: '[email protected]',+ url: 'https://example.com/audio.ogg',+ });+ expect(mockEngine.sendAudioMessage).toHaveBeenCalled();+ });++ it('sends a voice note (ptt) and defaults the mimetype to ogg/opus when omitted', async () => {+ await service.sendAudio('sess-1', {+ chatId: '[email protected]',+ url: 'https://example.com/voice',+ ptt: true,+ });+ expect(mockEngine.sendAudioMessage).toHaveBeenCalledWith(+ '[email protected]',+ expect.objectContaining({ ptt: true, mimetype: 'audio/ogg; codecs=opus' }),+ );+ });++ it('respects a caller-supplied mimetype for a voice note', async () => {+ await service.sendAudio('sess-1', {+ chatId: '[email protected]',+ url: 'https://example.com/voice.ogg',+ mimetype: 'audio/ogg',+ ptt: true,+ });+ expect(mockEngine.sendAudioMessage).toHaveBeenCalledWith(+ '[email protected]',+ expect.objectContaining({ ptt: true, mimetype: 'audio/ogg' }),+ );+ });++ it('persists a voice note as type "voice"', async () => {+ await service.sendAudio('sess-1', { chatId: '[email protected]', url: 'https://example.com/voice', ptt: true });+ expect(repository.create).toHaveBeenCalledWith(expect.objectContaining({ type: 'voice' }));+ });++ it('labels the message:sending gate "voice" for a voice note (matches the persisted/failed type)', async () => {+ await service.sendAudio('sess-1', { chatId: '[email protected]', url: 'https://example.com/voice', ptt: true });+ expect(hookManager.execute).toHaveBeenCalledWith(+ 'message:sending',+ expect.objectContaining({ type: 'voice' }),+ expect.any(Object),+ );+ });++ it('labels the message:sending gate "audio" for a plain (non-ptt) audio send', async () => {+ await service.sendAudio('sess-1', { chatId: '[email protected]', url: 'https://example.com/audio.ogg' });+ expect(hookManager.execute).toHaveBeenCalledWith(+ 'message:sending',+ expect.objectContaining({ type: 'audio' }),+ expect.any(Object),+ );+ });++ it('persists a plain audio send (no ptt) as type "audio"', async () => {+ await service.sendAudio('sess-1', { chatId: '[email protected]', url: 'https://example.com/audio.ogg' });+ expect(repository.create).toHaveBeenCalledWith(expect.objectContaining({ type: 'audio' }));+ });+ });++ describe('sendDocument', () => {+ it('should call engine.sendDocumentMessage with filename', async () => {+ await service.sendDocument('sess-1', {+ chatId: '[email protected]',+ url: 'https://example.com/doc.pdf',+ filename: 'report.pdf',+ });+ expect(mockEngine.sendDocumentMessage).toHaveBeenCalledWith(+ '[email protected]',+ expect.objectContaining({ filename: 'report.pdf' }),+ );+ });+ });++ describe('sendSticker', () => {+ it('should call engine.sendStickerMessage', async () => {+ await service.sendSticker('sess-1', {+ chatId: '[email protected]',+ url: 'https://example.com/sticker.webp',+ });+ expect(mockEngine.sendStickerMessage).toHaveBeenCalled();+ });+ });++ // ── sendLocation ──────────────────────────────────────────────────++ describe('sendLocation', () => {+ it('should send location with lat/lng', async () => {+ const result = await service.sendLocation('sess-1', {+ chatId: '[email protected]',+ latitude: -6.2088,+ longitude: 106.8456,+ description: 'Jakarta',+ });++ expect(result.messageId).toBe('wa-msg-1');+ expect(mockEngine.sendLocationMessage).toHaveBeenCalledWith(+ '[email protected]',+ expect.objectContaining({ latitude: -6.2088, longitude: 106.8456 }),+ );+ });+ });++ // ── sendContact ───────────────────────────────────────────────────++ describe('sendContact', () => {+ it('should send contact with name and number', async () => {+ const result = await service.sendContact('sess-1', {+ chatId: '[email protected]',+ contactName: 'John Doe',+ contactNumber: '+628123456789',+ });++ expect(result.messageId).toBe('wa-msg-1');+ expect(mockEngine.sendContactMessage).toHaveBeenCalledWith(+ '[email protected]',+ expect.objectContaining({ name: 'John Doe', number: '+628123456789' }),+ );+ });+ });++ // ── sendPoll ──────────────────────────────────────────────────────++ describe('sendPoll', () => {+ it('should send a poll and default to single choice', async () => {+ const result = await service.sendPoll('sess-1', {+ chatId: '[email protected]',+ name: 'Where should we meet?',+ options: ['Park', 'Beach'],+ });++ expect(result.messageId).toBe('wa-msg-1');+ expect(mockEngine.sendPollMessage).toHaveBeenCalledWith('[email protected]', {+ name: 'Where should we meet?',+ options: ['Park', 'Beach'],+ allowMultipleAnswers: false,+ });+ // A poll has no plain-text body, so it is persisted as type 'poll' with the question as the body.+ expect(repository.create).toHaveBeenCalledWith(+ expect.objectContaining({ type: 'poll', body: '📊 Where should we meet?' }),+ );+ });++ it('should pass allowMultipleAnswers through to the engine', async () => {+ await service.sendPoll('sess-1', {+ chatId: '[email protected]',+ name: 'Pick toppings',+ options: ['Cheese', 'Ham', 'Olives'],+ allowMultipleAnswers: true,+ });++ expect(mockEngine.sendPollMessage).toHaveBeenCalledWith(+ '[email protected]',+ expect.objectContaining({ allowMultipleAnswers: true }),+ );+ });+ });++ // ── quoted sends (issue #1271) ────────────────────────────────────++ describe('quotedMessageId on the send endpoints', () => {+ // One case per sender rather than the media funnel alone: location, contact and poll each build+ // their own engine payload, so a thread that covered only buildMediaInput would leave three+ // endpoints accepting the field and silently discarding it.+ it('sendImage forwards quotedMessageId in the media payload', async () => {+ await service.sendImage('sess-1', {+ chatId: '[email protected]',+ url: 'https://example.com/a.png',+ quotedMessageId: 'wa-quoted-9',+ });++ expect(mockEngine.sendImageMessage).toHaveBeenCalledWith(+ '[email protected]',+ expect.objectContaining({ quotedMessageId: 'wa-quoted-9' }),+ );+ });++ it('sendLocation forwards quotedMessageId', async () => {+ await service.sendLocation('sess-1', {+ chatId: '[email protected]',+ latitude: 1,+ longitude: 2,+ quotedMessageId: 'wa-quoted-9',+ });++ expect(mockEngine.sendLocationMessage).toHaveBeenCalledWith(+ '[email protected]',+ expect.objectContaining({ quotedMessageId: 'wa-quoted-9' }),+ );+ });++ it('sendContact forwards quotedMessageId', async () => {+ await service.sendContact('sess-1', {+ chatId: '[email protected]',+ contactName: 'Alice',+ contactNumber: '628999',+ quotedMessageId: 'wa-quoted-9',+ });++ expect(mockEngine.sendContactMessage).toHaveBeenCalledWith(+ '[email protected]',+ expect.objectContaining({ quotedMessageId: 'wa-quoted-9' }),+ );+ });++ it('sendPoll forwards quotedMessageId', async () => {+ await service.sendPoll('sess-1', {+ chatId: '[email protected]',+ name: 'Q',+ options: ['a', 'b'],+ quotedMessageId: 'wa-quoted-9',+ });++ expect(mockEngine.sendPollMessage).toHaveBeenCalledWith(+ '[email protected]',+ expect.objectContaining({ quotedMessageId: 'wa-quoted-9' }),+ );+ });++ it('sendText forwards quotedMessageId through the options bag', async () => {+ await service.sendText('sess-1', {+ chatId: '[email protected]',+ text: 'hi',+ quotedMessageId: 'wa-quoted-9',+ });++ expect(mockEngine.sendTextMessage).toHaveBeenCalledWith(+ '[email protected]',+ 'hi',+ undefined,+ expect.objectContaining({ quotedMessageId: 'wa-quoted-9' }),+ );+ });++ // Known-negative control: a plain text send must keep its narrow call shape. Without this an+ // implementation that always passed an options object would satisfy the assertion above while+ // rewriting every existing send.+ it('leaves an unquoted text send on its existing two-argument call shape', async () => {+ await service.sendText('sess-1', { chatId: '[email protected]', text: 'hi' });++ expect(mockEngine.sendTextMessage).toHaveBeenCalledWith('[email protected]', 'hi');+ });+ });++ // ── reply / forward ───────────────────────────────────────────────++ describe('reply', () => {+ it('should call engine.replyToMessage with quotedMessageId', async () => {+ await service.reply('sess-1', {+ chatId: '[email protected]',+ quotedMessageId: 'wa-quoted-1',+ text: 'This is a reply',+ });++ expect(mockEngine.replyToMessage).toHaveBeenCalledWith('[email protected]', 'wa-quoted-1', 'This is a reply');+ });+ });++ describe('forward', () => {+ it('should call engine.forwardMessage with from/to chats', async () => {+ await service.forward('sess-1', {+ fromChatId: '[email protected]',+ toChatId: '[email protected]',+ messageId: 'wa-msg-to-fwd',+ });++ expect(mockEngine.forwardMessage).toHaveBeenCalledWith('[email protected]', '[email protected]', 'wa-msg-to-fwd');+ });++ it('should save forwarded message with toChatId', async () => {+ await service.forward('sess-1', {+ fromChatId: '[email protected]',+ toChatId: '[email protected]',+ messageId: 'wa-msg-to-fwd',+ });++ expect(repository.create).toHaveBeenCalledWith(+ expect.objectContaining({+ chatId: '[email protected]',+ body: '[Forwarded]',+ type: 'forward',+ }),+ );+ });++ it('gates the forward against pacing by its destination chat', async () => {+ // ForwardMessageDto has no `chatId` — the gate must fall back to `toChatId`, or forwards skip+ // the cold-reachout rule entirely while their persisted row still drains the cold budget.+ const { assertSendAllowed } = (service as unknown as { pacing: { assertSendAllowed: jest.Mock } }).pacing;++ await service.forward('sess-1', {+ fromChatId: '[email protected]',+ toChatId: '[email protected]',+ messageId: 'wa-msg-to-fwd',+ });++ expect(assertSendAllowed).toHaveBeenCalledWith('sess-1', '[email protected]');+ });+ });++ // ── buildMediaInput (via sendImage) ───────────────────────────────++ describe('buildMediaInput validation', () => {+ it('should throw when neither url nor base64 is provided', async () => {+ await expect(service.sendImage('sess-1', { chatId: '[email protected]' })).rejects.toThrow(+ 'Either url or base64 must be provided',+ );+ });++ it('should throw when base64 is provided without mimetype', async () => {+ await expect(+ service.sendImage('sess-1', {+ chatId: '[email protected]',+ base64: 'data...',+ }),+ ).rejects.toThrow('mimetype is required when using base64 data');+ });++ it('prefers base64 over url when both are provided (#670)', async () => {+ // When both are sent, base64 is the explicit local payload and must win over `url` — otherwise+ // a stale `url` is fetched and silently shadows the image. This aligns the send selection with+ // the base64-first persisted metadata and the `@ValidateIf((o) => !o.base64)` intent on `url`.+ await service.sendImage('sess-1', {+ chatId: '[email protected]',+ url: 'https://example.com/img.jpg',+ base64: 'iVBORw0KGgoAAAAN...',+ mimetype: 'image/png',+ });++ expect(mockEngine.sendImageMessage).toHaveBeenCalledWith(+ '[email protected]',+ expect.objectContaining({ data: 'iVBORw0KGgoAAAAN...' }),+ );+ expect(mockEngine.sendImageMessage).not.toHaveBeenCalledWith(+ '[email protected]',+ expect.objectContaining({ data: 'https://example.com/img.jpg' }),+ );+ });++ it('strips a data-URI prefix before passing base64 bytes to the engine', async () => {+ await service.sendImage('sess-1', {+ chatId: '[email protected]',+ base64: 'data:image/png;base64,QUJD',+ mimetype: 'image/png',+ });++ expect(mockEngine.sendImageMessage).toHaveBeenCalledWith(+ '[email protected]',+ expect.objectContaining({ data: 'QUJD' }),+ );+ });++ it('rejects a data URI with no encoded payload', async () => {+ await expect(+ service.sendImage('sess-1', {+ chatId: '[email protected]',+ base64: 'data:image/png;base64,',+ mimetype: 'image/png',+ }),+ ).rejects.toThrow('Either url or base64 must be provided');+ expect(mockEngine.sendImageMessage).not.toHaveBeenCalled();+ });+ });++ /**+ * The empty id is the engine's "sent, but I couldn't read the id back" signal (#757). It has to reach+ * the DB as NULL: UQ_messages_sessionId_waMessageId is NOT partial, so '' collides with the next+ * id-less send in the same session, while NULLs stay exempt. In the bulk path that violation is+ * swallowed into a warning, so the row would vanish with nothing surfacing.+ */+ describe('saveOutgoingMessage id normalization (#757)', () => {+ it('stores an empty engine id as NULL rather than an empty string', async () => {+ await service.saveOutgoingMessage('sess-1', { waMessageId: '', chatId: '[email protected]', type: 'text' });++ expect(repository.create).toHaveBeenCalledWith(expect.objectContaining({ waMessageId: undefined }));+ });++ it('leaves a real id untouched', async () => {+ await service.saveOutgoingMessage('sess-1', {+ waMessageId: '[email protected]_ABC',+ chatId: '[email protected]',+ type: 'text',+ });++ expect(repository.create).toHaveBeenCalledWith(expect.objectContaining({ waMessageId: '[email protected]_ABC' }));+ });+ });++ // The bulk path persists AFTER the send with the engine id already known, so it races the own-send+ // echo on UNIQUE(sessionId, waMessageId). Losing that race used to drop the batch's media payload.+ describe('saveOutgoingMessage vs the own-send echo (dedup race)', () => {+ const uniqueViolation = new Error('UNIQUE constraint failed: messages.sessionId, messages.waMessageId');+ const bulkRow = {+ waMessageId: 'wa-bulk-1',+ chatId: '[email protected]',+ type: 'image',+ status: MessageStatus.SENT,+ timestamp: 1706868000,+ metadata: { media: { mimetype: 'image/png', data: 'QUJD', filename: 'a.png' } },+ };++ it('merges the media payload onto the echo row instead of losing it', async () => {+ (repository.save as jest.Mock).mockRejectedValueOnce(uniqueViolation);+ (repository.findOne as jest.Mock).mockResolvedValueOnce({ id: 'echo-row', ...bulkRow });++ const saved = await service.saveOutgoingMessage('sess-1', bulkRow);++ expect(repository.update).toHaveBeenCalledWith(+ { sessionId: 'sess-1', waMessageId: 'wa-bulk-1' },+ expect.objectContaining({+ status: MessageStatus.SENT,+ timestamp: 1706868000,+ metadata: bulkRow.metadata,+ }),+ );+ expect(saved).toEqual(expect.objectContaining({ id: 'echo-row' }));+ });++ it('does not overwrite the echo row’s downloaded bytes with a URL pointer', async () => {+ // A wwjs echo carries the media it downloaded; a URL-based send carries only the URL string.+ // Merging ours over theirs would discard bytes the gateway already holds — and leave a row+ // the archive cannot use.+ (repository.save as jest.Mock).mockRejectedValueOnce(uniqueViolation);+ (repository.findOne as jest.Mock).mockResolvedValueOnce({ id: 'echo-row' });++ await service.saveOutgoingMessage('sess-1', {+ ...bulkRow,+ metadata: { media: { mimetype: 'image/png', data: 'https://example.com/cat.png' } },+ });++ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access+ const patch = (repository.update as jest.Mock).mock.calls[0]?.[1] as Record<string, unknown>;+ expect(patch).not.toHaveProperty('metadata');+ });++ it('leaves the echo row metadata alone when this write carries none', async () => {+ (repository.save as jest.Mock).mockRejectedValueOnce(uniqueViolation);+ (repository.findOne as jest.Mock).mockResolvedValueOnce({ id: 'echo-row' });++ await service.saveOutgoingMessage('sess-1', { ...bulkRow, type: 'text', metadata: undefined });++ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access+ const patch = (repository.update as jest.Mock).mock.calls[0]?.[1] as Record<string, unknown>;+ expect(patch).not.toHaveProperty('metadata');+ });++ it('rethrows a transient (non-unique) persist error', async () => {+ (repository.save as jest.Mock).mockRejectedValueOnce(new Error('SQLITE_BUSY: database is locked'));++ await expect(service.saveOutgoingMessage('sess-1', bulkRow)).rejects.toThrow('SQLITE_BUSY');+ expect(repository.update).not.toHaveBeenCalled();+ });++ it('rethrows when there is no engine id to merge onto', async () => {+ (repository.save as jest.Mock).mockRejectedValueOnce(uniqueViolation);++ await expect(service.saveOutgoingMessage('sess-1', { chatId: '[email protected]', type: 'text' })).rejects.toThrow(+ uniqueViolation,+ );+ expect(repository.update).not.toHaveBeenCalled();+ });+ });++ describe('persistSentState vs the own-send echo (dedup race)', () => {+ it('merges state onto the echo row, then drops the redundant PENDING row', async () => {+ // The engine's message_create echo (onMessageCreate) won the insert race, so the SENT-state save+ // collides on UNIQUE(sessionId, waMessageId). The echo row carries only what the engine reported+ // — for a Baileys API send, a media-less marker — so the merge must land status/timestamp/metadata+ // on it BEFORE the placeholder is deleted, or the payload is lost. The send still succeeds.+ (repository.save as jest.Mock)+ .mockImplementationOnce(msg => Promise.resolve(msg)) // saveOutgoingMessage (PENDING)+ .mockRejectedValueOnce(new Error('UNIQUE constraint failed: messages.sessionId, messages.waMessageId'));++ const result = await service.sendText('sess-1', { chatId: '[email protected]', text: 'hi' });++ expect(result.messageId).toBe('wa-msg-1'); // send reported success+ expect(repository.update).toHaveBeenCalledWith(+ { sessionId: 'sess-1', waMessageId: 'wa-msg-1' },+ expect.objectContaining({ status: MessageStatus.SENT, timestamp: 1706868000 }),+ );+ expect(repository.delete).toHaveBeenCalledWith({ id: 'msg-uuid-1' });+ });++ it('merges the media payload onto the echo row for a media send (no data loss after reload)', async () => {+ (repository.save as jest.Mock)+ .mockImplementationOnce(msg => Promise.resolve(msg))+ .mockRejectedValueOnce(new Error('UNIQUE constraint failed: messages.sessionId, messages.waMessageId'));++ await service.sendImage('sess-1', { chatId: '[email protected]', base64: 'QUJD', mimetype: 'image/png' });++ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access+ const patch = (repository.update as jest.Mock).mock.calls[0]?.[1] as Record<string, unknown> | undefined;+ expect((patch?.metadata as { media?: { data?: string } } | undefined)?.media?.data).toBe('QUJD');+ expect(repository.delete).toHaveBeenCalledWith({ id: 'msg-uuid-1' });+ });++ it('keeps the echo row’s downloaded bytes rather than merging a URL pointer over them', async () => {+ (repository.save as jest.Mock)+ .mockImplementationOnce(msg => Promise.resolve(msg))+ .mockRejectedValueOnce(new Error('UNIQUE constraint failed: messages.sessionId, messages.waMessageId'));++ await service.sendImage('sess-1', { chatId: '[email protected]', url: 'https://example.com/cat.png' });++ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access+ const patch = (repository.update as jest.Mock).mock.calls[0]?.[1] as Record<string, unknown> | undefined;+ expect(patch).not.toHaveProperty('metadata');+ });++ it('does NOT delete anything on a transient (non-unique) persist error', async () => {+ (repository.save as jest.Mock)+ .mockImplementationOnce(msg => Promise.resolve(msg))+ .mockRejectedValueOnce(new Error('SQLITE_BUSY: database is locked'));++ const result = await service.sendText('sess-1', { chatId: '[email protected]', text: 'hi' });++ expect(result.messageId).toBe('wa-msg-1'); // transient persist faults never fail the send+ expect(repository.delete).not.toHaveBeenCalled();+ });+ });++ // ── outbound archiving (CHAT_MEDIA_ARCHIVE_OUTBOUND) ─────────────++ describe('archiving media this account sent', () => {+ const withFlag = (archiveOutbound: boolean, archive: { archive: jest.Mock }): MessageSendService =>+ new MessageSendService(+ repository as Repository<Message>,+ sessionService as unknown as SessionService,+ engines,+ hookManager as HookManager,+ templateService as unknown as TemplateService,+ inertPacing(),+ {+ get: (key: string, fallback?: unknown) => (key === 'chatMedia.archiveOutbound' ? archiveOutbound : fallback),+ } as never,+ archive as never,+ );++ it('archives a SENT outbound row when the flag is on', async () => {+ const archive = { archive: jest.fn().mockResolvedValue('chat-media/k') };+ const svc = withFlag(true, archive);++ await svc.saveOutgoingMessage('sess-1', {+ waMessageId: 'wa-1',+ chatId: '[email protected]',+ type: 'image',+ status: MessageStatus.SENT,+ metadata: { media: { mimetype: 'image/png', data: 'QUJD' } },+ });++ expect(archive.archive).toHaveBeenCalledWith(expect.objectContaining({ waMessageId: 'wa-1' }));+ });++ it('archives nothing while the flag is off', async () => {+ const archive = { archive: jest.fn() };+ const svc = withFlag(false, archive);++ await svc.saveOutgoingMessage('sess-1', {+ waMessageId: 'wa-1',+ chatId: '[email protected]',+ type: 'image',+ status: MessageStatus.SENT,+ metadata: { media: { mimetype: 'image/png', data: 'QUJD' } },+ });++ expect(archive.archive).not.toHaveBeenCalled();+ });++ it('never archives a PENDING row — the merge may delete it and the reaper may rewrite it', async () => {+ const archive = { archive: jest.fn() };+ const svc = withFlag(true, archive);++ await svc.saveOutgoingMessage('sess-1', {+ chatId: '[email protected]',+ type: 'image',+ metadata: { media: { mimetype: 'image/png', data: 'QUJD' } },+ });++ expect(archive.archive).not.toHaveBeenCalled();+ });+ });+});diff --git a/src/modules/message/message-send.service.ts b/src/modules/message/message-send.service.tsnew file mode 100644index 000000000..f84b4aaa7--- /dev/null+++ b/src/modules/message/message-send.service.ts@@ -0,0 +1,769 @@+import { Injectable, BadRequestException, Optional } from '@nestjs/common';+import { ConfigService } from '@nestjs/config';+import { InjectRepository } from '@nestjs/typeorm';+import { Repository, QueryDeepPartialEntity } from 'typeorm';+import { SessionService } from '../session/session.service';+import { EngineRegistry } from '../../engine/engine-registry.service';+import { SendTextMessageDto, SendMediaMessageDto, SendAudioMessageDto, MessageResponseDto } from './dto';+import { SendTemplateMessageDto } from './dto/send-template.dto';+import { assertBase64WithinMediaCap, stripBase64DataUri } from './media-cap.util';+import { MediaInput, IWhatsAppEngine, MessageResult } from '../../engine/interfaces/whatsapp-engine.interface';+import { Message, MessageDirection, MessageStatus } from './entities/message.entity';+import { HookManager, applySendingGate } from '../../core/hooks';+import { SendPacingService, countsTowardSendBreaker } from './send-pacing.service';+import { TemplateService } from '../template/template.service';+import { renderTemplate } from '../../common/utils/template-render';+import { createLogger } from '../../common/services/logger.service';+import { SsrfBlockedError, SSRF_BLOCKED_CLIENT_MESSAGE } from '../../common/security/ssrf-guard';+import { resolveFeatureFlags } from '../../config/feature-flags';+import { isUniqueConstraintError } from '../../common/utils/unique-constraint.util';+import { ChatMediaArchiveService } from '../chat-media/chat-media-archive.service';++/** Default cap on a rendered template's final text; overridable via TEMPLATE_RENDER_MAX_CHARS. */+export const DEFAULT_TEMPLATE_RENDER_MAX_CHARS = 64 * 1024;++/**+ * True when this write's media is only a remote-URL pointer (a URL-based send, whose bytes the+ * engine fetches and discards). Merging such metadata onto an echo row would REPLACE bytes the+ * gateway already downloaded — wwjs enriches its own-send echo with the real payload — leaving a+ * row that renders as a bare marker and that the archive cannot use.+ */+function isUrlPointerMetadata(metadata: Record<string, unknown> | undefined): boolean {+ const data = (metadata as { media?: { data?: unknown } } | undefined)?.media?.data;+ return typeof data === 'string' && /^https?:\/\//i.test(data);+}++/** Persistence payload for one outbound row written by {@link MessageSendService.saveOutgoingMessage}. */+export interface SaveOutgoingMessageData {+ waMessageId?: string;+ chatId: string;+ body?: string;+ type: string;+ timestamp?: number;+ status?: MessageStatus;+ metadata?: Record<string, unknown>;+ /**+ * Quoted id for a send that is a reply. Folded into `metadata.quotedMessage` here rather than+ * by each sender so the nine send paths and `reply()` persist one shape — a row that quoted a+ * message but records nothing is simply wrong history, and the dashboard reads this key to+ * render the reply preview. The body is left empty: unlike `reply()`, the send paths do not+ * look the quoted message up, and '' is already reply()'s own value when that lookup fails.+ */+ quotedMessageId?: string;+}++/**+ * Outbound sends are executed directly against the WhatsApp engine, not via a BullMQ queue.+ *+ * The engine is single-threaded per session (a Puppeteer page for the whatsapp-web.js adapter, a+ * single socket for Baileys) and is therefore itself the serialization point for that session's+ * outbound traffic. Routing sends through a queue would add request latency and a Redis hard+ * dependency to the hot path for no throughput benefit — the engine cannot go faster than it+ * already does. BullMQ is reserved for genuine side-effects that benefit from durable+ * retry/back-pressure (webhook delivery, integration ingress); see `QUEUE_NAMES` in+ * `queue-names.ts`, which intentionally defines no MESSAGE queue.+ *+ * Backpressure is applied at the edges instead: bulk sends self-throttle via+ * `delayBetweenMessages` (default 3s) and a per-process concurrent-batch cap (see+ * `BulkMessageService`), and the global throttler enforces per-key rate limits.+ */+@Injectable()+export class MessageSendService {+ private readonly logger = createLogger('MessageSend');++ constructor(+ @InjectRepository(Message, 'data')+ private readonly messageRepository: Repository<Message>,+ private readonly sessionService: SessionService,+ private readonly engines: EngineRegistry,+ private readonly hookManager: HookManager,+ private readonly templateService: TemplateService,+ // Required, not @Optional: a missing pacing service would silently mean "no pacing", which is+ // the one failure mode this feature must not have. The service itself no-ops when disabled.+ private readonly pacing: SendPacingService,+ @Optional()+ private readonly configService?: ConfigService,+ // Optional so standalone constructions keep working; absent means outbound media is never+ // archived — the inline row copy and the read endpoint are unaffected either way.+ @Optional()+ private readonly chatMediaArchive?: ChatMediaArchiveService,+ ) {}++ async sendText(sessionId: string, dto: SendTextMessageDto): Promise<MessageResponseDto> {+ // Asking to suppress the preview AND to attach one is a contradiction, and guessing which half+ // the caller meant would send a message they did not ask for either way.+ if (dto.linkPreview === false && dto.customLinkPreview) {+ throw new BadRequestException('linkPreview: false cannot be combined with customLinkPreview');+ }+ const finalDto = await this.applySendingGate(sessionId, 'text', dto);++ const engine = this.getEngine(sessionId);++ // Save message as pending BEFORE sending+ const message = await this.saveOutgoingMessage(sessionId, {+ chatId: finalDto.chatId,+ body: finalDto.text,+ type: 'text',+ quotedMessageId: finalDto.quotedMessageId,+ });++ // Opt-in humanising "typing…" pause before the actual send (anti-automation signal).+ await this.simulateTypingIfEnabled(engine, finalDto.chatId, finalDto.text);++ let result: MessageResult;+ try {+ // The call is widened ONLY as far as the caller actually asked. A send with neither mentions+ // nor a preview choice keeps its two-argument shape, and one with mentions alone keeps its+ // three — trailing `undefined`s would be harmless to the engines but would rewrite the call+ // shape of every existing send for no behavioural gain.+ const { linkPreview, customLinkPreview, quotedMessageId } = finalDto;+ if (linkPreview !== undefined || customLinkPreview || quotedMessageId) {+ result = await engine.sendTextMessage(finalDto.chatId, finalDto.text, finalDto.mentions, {+ ...(linkPreview === undefined ? {} : { linkPreview }),+ ...(customLinkPreview ? { customPreview: customLinkPreview } : {}),+ ...(quotedMessageId ? { quotedMessageId } : {}),+ });+ } else if (finalDto.mentions?.length) {+ result = await engine.sendTextMessage(finalDto.chatId, finalDto.text, finalDto.mentions);+ } else {+ result = await engine.sendTextMessage(finalDto.chatId, finalDto.text);+ }+ } catch (error) {+ // The SEND itself failed — mark FAILED + fire message:failed (a post-send persistence fault is+ // handled separately by persistSentState and must NOT land here).+ return this.failSend(sessionId, 'text', message, finalDto, error);+ }++ // Note: the `message:sent` hook is emitted solely by the onMessageCreate wiring in+ // SessionEngineLifecycle (engine `message_create`, handled by MessageProjector) with a+ // consistent IncomingMessage payload for ALL sends (text, media,+ // and phone-composed), so it is intentionally not fired here to avoid a double dispatch.+ return this.persistSentState(message, result);+ }++ /**+ * Run the pre-send `message:sending` plugin gate for one outbound message and return the+ * (possibly plugin-modified) input, or throw BadRequestException if a plugin blocked the send.+ * Centralised so EVERY public sender — text, media, extended (location/contact/poll/sticker/+ * reply/forward) and edit — passes through the same moderation chokepoint, instead of only+ * `sendText`. The implementation is shared with StatusService via core/hooks/sending-gate.+ */+ private async applySendingGate<T extends object>(sessionId: string, type: string, input: T): Promise<T> {+ // Pacing runs BEFORE the plugin gate, so a send that policy forbids never reaches a plugin at+ // all — plugins should not be asked to moderate, or given the chance to rewrite, traffic that is+ // not going to be sent. The consequence is deliberate and documented in the hook contract: a+ // paced-out send fires no `message:sending`, so a plugin cannot observe it. Refusals are a 429+ // carrying `code: SEND_PACING_LIMITED`; a plugin veto stays a 400.+ // Every gated sender's DTO addresses its destination as `chatId` except forward, which uses+ // `toChatId` — without the fallback a forward skipped the cold-reachout gate entirely, while+ // its persisted row still drained the cold budget. Edit carries a chatId too; the edited+ // message's own row already makes that chat warm, so the gate is a no-op there.+ const target = input as { chatId?: string; toChatId?: string };+ await this.pacing.assertSendAllowed(sessionId, target.chatId ?? target.toChatId);+ return applySendingGate(this.hookManager, sessionId, type, input, 'MessageService');+ }++ /**+ * Mark a send as FAILED, fire the `message:failed` plugin hook, then throw a client-facing error.+ * Centralised so failure notifications cover every sender (previously only `sendText` fired+ * `message:failed`; media/extended sends failed silently to plugins). The post-send persistence-fault+ * path (persistSentState) deliberately does NOT route here — a message the engine already accepted+ * must never be reported as a send failure.+ */+ private async failSend(+ sessionId: string,+ type: string,+ message: Message,+ input: unknown,+ error: unknown,+ ): Promise<never> {+ // Only failures that say something about the account's standing feed the breaker: adapters also+ // raise client-fault and engine-state errors from inside this call (a blocked media URL, an+ // unsupported capability, a disconnected socket), and counting those let a client sending bad+ // requests trip the breaker on a healthy session.+ if (countsTowardSendBreaker(error)) {+ this.pacing.recordSendFailure(sessionId);+ }+ await this.saveFailedMessage(message);+ // Sanitize the hook payload: an SSRF block's raw .message names the resolved internal address+ // (a recon/DNS-rebind oracle) — the client-facing throw below already maps it to a generic+ // message via toClientFacingError, and the message:failed hook must not expose more than the+ // client sees. Now that every media/extended sender routes here, this is the chokepoint that+ // keeps SSRF detail out of plugin hands (bulk does the same via sanitizeBatchError).+ const hookError =+ error instanceof SsrfBlockedError+ ? SSRF_BLOCKED_CLIENT_MESSAGE+ : error instanceof Error+ ? error.message+ : String(error);+ await this.hookManager.execute(+ 'message:failed',+ { sessionId, error: hookError, input, type },+ { sessionId, source: 'MessageService' },+ );+ throw this.toClientFacingError(error);+ }++ /**+ * Resolve a stored template, render its body (with optional header/footer+ * flattened using newlines) using the supplied variables, and delegate to the+ * existing {@link sendText} path so plugin hooks, persistence, and status+ * tracking are reused. Throws NotFoundException when the template cannot be+ * resolved by id or name.+ *+ * The FINAL rendered text is capped at template.renderMaxChars (default 64 KiB): caller-supplied+ * variables can inflate a small template unboundedly, so an over-cap render is rejected with a+ * 400 naming the limit rather than truncated silently or pushed to the engine/DB as-is.+ */+ async sendTemplate(sessionId: string, dto: SendTemplateMessageDto): Promise<MessageResponseDto> {+ const template = await this.templateService.resolve(sessionId, {+ templateId: dto.templateId,+ templateName: dto.templateName,+ });++ const vars = dto.vars ?? {};+ const segments = [template.header, template.body, template.footer]+ .filter((segment): segment is string => segment != null && segment.length > 0)+ .map(segment => renderTemplate(segment, vars));+ const text = segments.join('\n\n');++ const maxChars =+ this.configService?.get<number>('template.renderMaxChars', DEFAULT_TEMPLATE_RENDER_MAX_CHARS) ??+ DEFAULT_TEMPLATE_RENDER_MAX_CHARS;+ if (text.length > maxChars) {+ throw new BadRequestException(+ `Rendered template is ${text.length} characters, over the ${maxChars}-character limit`,+ );+ }++ return this.sendText(sessionId, { chatId: dto.chatId, text });+ }++ async sendImage(sessionId: string, dto: SendMediaMessageDto): Promise<MessageResponseDto> {+ const finalDto = await this.applySendingGate(sessionId, 'image', dto);+ const engine = this.getEngine(sessionId);+ const media = this.buildMediaInput(finalDto);++ // Save message as pending BEFORE sending+ const message = await this.saveOutgoingMessage(sessionId, {+ chatId: finalDto.chatId,+ body: finalDto.caption || '',+ type: 'image',+ quotedMessageId: finalDto.quotedMessageId,+ metadata: {+ media: { mimetype: finalDto.mimetype, filename: finalDto.filename, data: media.data },+ },+ });++ let result: MessageResult;+ try {+ result = await engine.sendImageMessage(finalDto.chatId, media);+ } catch (error) {+ return this.failSend(sessionId, 'image', message, finalDto, error);+ }+ return this.persistSentState(message, result);+ }++ async sendVideo(sessionId: string, dto: SendMediaMessageDto): Promise<MessageResponseDto> {+ const finalDto = await this.applySendingGate(sessionId, 'video', dto);+ const engine = this.getEngine(sessionId);+ const media = this.buildMediaInput(finalDto);++ // Save message as pending BEFORE sending+ const message = await this.saveOutgoingMessage(sessionId, {+ chatId: finalDto.chatId,+ body: finalDto.caption || '',+ type: 'video',+ quotedMessageId: finalDto.quotedMessageId,+ metadata: {+ media: { mimetype: finalDto.mimetype, filename: finalDto.filename, data: media.data },+ },+ });++ let result: MessageResult;+ try {+ result = await engine.sendVideoMessage(finalDto.chatId, media);+ } catch (error) {+ return this.failSend(sessionId, 'video', message, finalDto, error);+ }+ return this.persistSentState(message, result);+ }++ async sendAudio(sessionId: string, dto: SendAudioMessageDto): Promise<MessageResponseDto> {+ // Label a PTT send 'voice' in the gate (not 'audio') so message:sending, message:failed, and the+ // persisted row all carry the same type for one outbound voice note — failSend and the saved row+ // already use `finalDto.ptt ? 'voice' : 'audio'`.+ const finalDto = await this.applySendingGate(sessionId, dto.ptt ? 'voice' : 'audio', dto);+ const engine = this.getEngine(sessionId);+ // Voice notes need a real audio codec; default to ogg/opus when the caller omits a mimetype so the+ // wire message and the persisted record agree. Resolved BEFORE buildMediaInput so its base64+ // mimetype guard sees the effective type. buildMediaInput itself stays generic (shared by all media).+ const audioDto =+ finalDto.ptt && !finalDto.mimetype ? { ...finalDto, mimetype: 'audio/ogg; codecs=opus' } : finalDto;+ const media = this.buildMediaInput(audioDto);+ media.ptt = finalDto.ptt;++ // Save message as pending BEFORE sending. A PTT send is a 'voice' note (matches inbound+ // classification, the outbound webhook echo, stats, and the dashboard), not a plain 'audio' file.+ const message = await this.saveOutgoingMessage(sessionId, {+ chatId: finalDto.chatId,+ type: finalDto.ptt ? 'voice' : 'audio',+ metadata: {+ media: { mimetype: audioDto.mimetype, filename: finalDto.filename, data: media.data },+ },+ quotedMessageId: finalDto.quotedMessageId,+ });++ let result: MessageResult;+ try {+ result = await engine.sendAudioMessage(finalDto.chatId, media);+ } catch (error) {+ return this.failSend(sessionId, finalDto.ptt ? 'voice' : 'audio', message, finalDto, error);+ }+ return this.persistSentState(message, result);+ }++ async sendDocument(sessionId: string, dto: SendMediaMessageDto): Promise<MessageResponseDto> {+ const finalDto = await this.applySendingGate(sessionId, 'document', dto);+ const engine = this.getEngine(sessionId);+ const media = this.buildMediaInput(finalDto);++ // Save message as pending BEFORE sending+ const message = await this.saveOutgoingMessage(sessionId, {+ chatId: finalDto.chatId,+ body: finalDto.caption || finalDto.filename || '',+ type: 'document',+ quotedMessageId: finalDto.quotedMessageId,+ metadata: {+ media: { mimetype: finalDto.mimetype, filename: finalDto.filename, data: media.data },+ },+ });++ let result: MessageResult;+ try {+ result = await engine.sendDocumentMessage(finalDto.chatId, media);+ } catch (error) {+ return this.failSend(sessionId, 'document', message, finalDto, error);+ }+ return this.persistSentState(message, result);+ }++ async sendLocation(+ sessionId: string,+ dto: {+ chatId: string;+ latitude: number;+ longitude: number;+ description?: string;+ address?: string;+ quotedMessageId?: string;+ },+ ): Promise<MessageResponseDto> {+ const finalDto = await this.applySendingGate(sessionId, 'location', dto);+ const engine = this.getEngine(sessionId);++ // Save message as pending BEFORE sending+ const message = await this.saveOutgoingMessage(sessionId, {+ chatId: finalDto.chatId,+ body: `📍 ${finalDto.description || 'Location'}`,+ type: 'location',+ quotedMessageId: finalDto.quotedMessageId,+ });++ let result: MessageResult;+ try {+ result = await engine.sendLocationMessage(finalDto.chatId, {+ latitude: finalDto.latitude,+ longitude: finalDto.longitude,+ description: finalDto.description,+ address: finalDto.address,+ quotedMessageId: finalDto.quotedMessageId,+ });+ } catch (error) {+ return this.failSend(sessionId, 'location', message, finalDto, error);+ }+ return this.persistSentState(message, result);+ }++ async sendContact(+ sessionId: string,+ dto: { chatId: string; contactName: string; contactNumber: string; quotedMessageId?: string },+ ): Promise<MessageResponseDto> {+ const finalDto = await this.applySendingGate(sessionId, 'contact', dto);+ const engine = this.getEngine(sessionId);++ // Save message as pending BEFORE sending+ const message = await this.saveOutgoingMessage(sessionId, {+ chatId: finalDto.chatId,+ body: `📇 ${finalDto.contactName}`,+ type: 'contact',+ quotedMessageId: finalDto.quotedMessageId,+ });++ let result: MessageResult;+ try {+ result = await engine.sendContactMessage(finalDto.chatId, {+ name: finalDto.contactName,+ number: finalDto.contactNumber,+ quotedMessageId: finalDto.quotedMessageId,+ });+ } catch (error) {+ return this.failSend(sessionId, 'contact', message, finalDto, error);+ }+ return this.persistSentState(message, result);+ }++ async sendPoll(+ sessionId: string,+ dto: { chatId: string; name: string; options: string[]; allowMultipleAnswers?: boolean; quotedMessageId?: string },+ ): Promise<MessageResponseDto> {+ const finalDto = await this.applySendingGate(sessionId, 'poll', dto);+ const engine = this.getEngine(sessionId);++ // Save message as pending BEFORE sending. A poll has no plain-text body, so store the+ // question — that keeps the message history readable.+ const message = await this.saveOutgoingMessage(sessionId, {+ chatId: finalDto.chatId,+ body: `📊 ${finalDto.name}`,+ type: 'poll',+ quotedMessageId: finalDto.quotedMessageId,+ });++ let result: MessageResult;+ try {+ result = await engine.sendPollMessage(finalDto.chatId, {+ name: finalDto.name,+ options: finalDto.options,+ allowMultipleAnswers: finalDto.allowMultipleAnswers === true,+ quotedMessageId: finalDto.quotedMessageId,+ });+ } catch (error) {+ return this.failSend(sessionId, 'poll', message, finalDto, error);+ }+ return this.persistSentState(message, result);+ }++ async sendSticker(sessionId: string, dto: SendMediaMessageDto): Promise<MessageResponseDto> {+ const finalDto = await this.applySendingGate(sessionId, 'sticker', dto);+ const engine = this.getEngine(sessionId);+ const media = this.buildMediaInput(finalDto);++ // Save message as pending BEFORE sending+ const message = await this.saveOutgoingMessage(sessionId, {+ chatId: finalDto.chatId,+ type: 'sticker',+ quotedMessageId: finalDto.quotedMessageId,+ metadata: {+ media: { mimetype: finalDto.mimetype, filename: finalDto.filename, data: media.data },+ },+ });++ let result: MessageResult;+ try {+ result = await engine.sendStickerMessage(finalDto.chatId, media);+ } catch (error) {+ return this.failSend(sessionId, 'sticker', message, finalDto, error);+ }+ return this.persistSentState(message, result);+ }++ async reply(+ sessionId: string,+ dto: { chatId: string; quotedMessageId: string; text: string },+ ): Promise<MessageResponseDto> {+ const finalDto = await this.applySendingGate(sessionId, 'reply', dto);+ const engine = this.getEngine(sessionId);++ // Resolve the quoted message body (best-effort) so the dashboard can render the reply preview.+ let quotedBody = '';+ try {+ const quoted = await this.messageRepository.findOne({+ where: { sessionId, waMessageId: finalDto.quotedMessageId },+ });+ quotedBody = quoted?.body || '';+ } catch (err) {+ this.logger.warn(`Failed to resolve quoted message ${finalDto.quotedMessageId}`, { error: String(err) });+ }++ // Save message as pending BEFORE sending+ const message = await this.saveOutgoingMessage(sessionId, {+ chatId: finalDto.chatId,+ body: finalDto.text,+ type: 'text',+ metadata: {+ quotedMessage: { id: finalDto.quotedMessageId, body: quotedBody },+ },+ });++ let result: MessageResult;+ try {+ result = await engine.replyToMessage(finalDto.chatId, finalDto.quotedMessageId, finalDto.text);+ } catch (error) {+ return this.failSend(sessionId, 'reply', message, finalDto, error);+ }+ return this.persistSentState(message, result);+ }++ async forward(+ sessionId: string,+ dto: { fromChatId: string; toChatId: string; messageId: string },+ ): Promise<MessageResponseDto> {+ const finalDto = await this.applySendingGate(sessionId, 'forward', dto);+ const engine = this.getEngine(sessionId);++ // Save message as pending BEFORE sending+ const message = await this.saveOutgoingMessage(sessionId, {+ chatId: finalDto.toChatId,+ body: '[Forwarded]',+ type: 'forward',+ });++ let result: MessageResult;+ try {+ result = await engine.forwardMessage(finalDto.fromChatId, finalDto.toChatId, finalDto.messageId);+ } catch (error) {+ return this.failSend(sessionId, 'forward', message, finalDto, error);+ }+ // persistSentState preserves the empty-id rule: a forward whose engine couldn't recover the sent+ // copy's id leaves waMessageId NULL so no ack mis-matches it.+ return this.persistSentState(message, result);+ }++ /**+ * Save outgoing message to database.+ * When called before sending, creates a record with PENDING status; bulk send reuses this after a+ * successful send (status SENT) so batch messages are persisted like single sends.+ *+ * A caller that already knows the engine id races the own-send echo on+ * UNIQUE(sessionId, waMessageId) — only the bulk path does today, since every single send persists+ * its PENDING row before the id exists. Losing that race merges onto the echo's row rather than+ * failing, mirroring `persistSentState`: the echo carries only what the engine reported (for a+ * Baileys API send, a media-less marker), so dropping this write would lose the media payload.+ */+ async saveOutgoingMessage(sessionId: string, data: SaveOutgoingMessageData): Promise<Message> {+ const session = await this.sessionService.findOne(sessionId);+ const message = this.messageRepository.create({+ sessionId,+ // An engine that sent a message but could not read its id back reports an empty id (see the+ // whatsapp-web.js adapter's `toMessageResult`). Store NULL rather than '': the+ // (sessionId, waMessageId) unique index is not partial, so a second id-less send in the same+ // session collides on '' while NULLs stay exempt — and in the bulk path that violation is+ // swallowed into a warning, losing the row silently. Normalizing at this one chokepoint covers+ // every caller instead of relying on each to remember.+ waMessageId: data.waMessageId || undefined,+ chatId: data.chatId,+ from: session?.phone || 'me',+ to: data.chatId,+ body: data.body,+ type: data.type,+ direction: MessageDirection.OUTGOING,+ timestamp: data.timestamp,+ status: data.status ?? MessageStatus.PENDING,+ metadata: data.quotedMessageId+ ? { ...data.metadata, quotedMessage: { id: data.quotedMessageId, body: '' } }+ : data.metadata,+ });+ const saved = await this.messageRepository.save(message).catch(async (err: unknown) => {+ const waMessageId = message.waMessageId;+ if (!waMessageId || !isUniqueConstraintError(err)) throw err;+ const patch: QueryDeepPartialEntity<Message> = {+ status: message.status,+ timestamp: message.timestamp,+ };+ // Only when this write actually carries metadata worth merging: a text item must not blank+ // the echo's, and a URL pointer must not replace bytes the engine already downloaded.+ if (message.metadata && !isUrlPointerMetadata(message.metadata)) {+ patch.metadata = message.metadata as QueryDeepPartialEntity<Record<string, unknown>>;+ }+ await this.messageRepository.update({ sessionId, waMessageId }, patch);+ const surviving = await this.messageRepository.findOne({ where: { sessionId, waMessageId } });+ if (!surviving) throw err;+ return surviving;+ });+ this.emitPersisted(sessionId, saved);+ return saved;+ }++ // Fire-and-forget: a plugin handler must never break the send path. The built-in FTS search provider+ // is DB-synced and does NOT consume this; it exists for plugin providers (Spec 2) + general use.+ // Emitted for EVERY persisted state of an outbound row — the initial PENDING write AND each later+ // transition (SENT / FAILED / merge) — so a provider's copy never stays stuck at PENDING (#906).+ // The payload is a shallow snapshot: the same entity instance is mutated as the send progresses+ // (PENDING → SENT/FAILED), and fire-and-forget execution must still see the state at emission time.+ //+ // Outbound archiving rides the same chokepoint rather than a call at each of the four persist+ // sites: every terminal state of an outbound row passes here. Gated on SENT because a PENDING row+ // may still be deleted by the dedup merge or rewritten by the pending reaper, and a FAILED one has+ // had its payload stripped — archiving either would strand a file the row never points at.+ //+ // Hook emissions keep `source: 'MessageService'` — the string is part of the observable hook+ // contract plugins may filter on, so the send seam must not change it.+ private emitPersisted(sessionId: string, message: Message): void {+ void this.hookManager+ .execute('message:persisted', { sessionId, message: { ...message } }, { sessionId, source: 'MessageService' })+ .catch(() => undefined);+ if (message.status === MessageStatus.SENT && this.archiveOutboundEnabled) {+ void this.chatMediaArchive?.archive(message).catch(() => undefined);+ }+ }++ /** Whether media this account sent is archived too — a sub-flag of the archive itself. */+ private get archiveOutboundEnabled(): boolean {+ return this.configService?.get<boolean>('chatMedia.archiveOutbound', false) === true;+ }++ /**+ * Persist a send as FAILED, dropping any outbound media payload first. A failed row's media base64+ * (often multi-MB) is never displayed or retried, so keeping it only bloats the messages table; the+ * mimetype/filename are kept so the row still describes what was attempted.+ */+ private async saveFailedMessage(message: Message): Promise<void> {+ const media = (message.metadata as { media?: { data?: unknown } } | undefined)?.media;+ if (media) {+ delete media.data;+ }+ message.status = MessageStatus.FAILED;+ await this.messageRepository.save(message);+ // Reconcile the earlier PENDING emission (#906): a provider must see the terminal FAILED state.+ this.emitPersisted(message.sessionId, message);+ }++ /**+ * Persist the SENT state AFTER the engine has already accepted the message. The send already+ * succeeded, so a failure to write the SENT row must NOT be surfaced as a send failure — a transient+ * DB fault would otherwise mark a delivered message permanently FAILED and (for text) fire+ * `message:failed`. Log and return success instead.+ */+ private async persistSentState(message: Message, result: MessageResult): Promise<MessageResponseDto> {+ // A send whose engine couldn't read the sent message's id back reports an empty id — a forward that+ // can't recover the copy, or a WhatsApp Web build that renamed the id field out from under the+ // engine. Leave waMessageId unset (NULL) so no ack mis-matches it.+ // The engine accepted the message, so whatever streak the breaker was tracking is over. Recorded+ // here rather than at each call site for the same reason failSend is: one funnel, twelve senders.+ this.pacing.recordSendSuccess(message.sessionId);+ if (result.id) message.waMessageId = result.id;+ message.status = MessageStatus.SENT;+ message.timestamp = result.timestamp;+ try {+ await this.messageRepository.save(message);+ // Reconcile the earlier PENDING emission with the finalized row (#906).+ this.emitPersisted(message.sessionId, message);+ } catch (persistError) {+ if (result.id && isUniqueConstraintError(persistError)) {+ // The engine's own-send echo (onMessageCreate) won the race and already persisted a row with+ // this waMessageId. That row carries only what the engine reported — for a Baileys API send,+ // a media-less marker — so merge our SENT state AND our metadata (the actual media payload)+ // onto it BEFORE dropping this redundant PENDING row, or the payload-bearing row is the one+ // that gets deleted and the media is gone after a reload.+ // Best-effort throughout: the send itself already succeeded.+ this.logger.debug(+ `Send echo already persisted ${result.id}; merging state and dropping the redundant pending row`,+ {+ messageId: message.id,+ },+ );+ const patch: QueryDeepPartialEntity<Message> = { status: MessageStatus.SENT, timestamp: result.timestamp };+ if (message.metadata && !isUrlPointerMetadata(message.metadata)) {+ patch.metadata = message.metadata as QueryDeepPartialEntity<Record<string, unknown>>;+ }+ await this.messageRepository+ .update({ sessionId: message.sessionId, waMessageId: result.id }, patch)+ .catch(err =>+ this.logger.warn(`Merging SENT state onto the echo-persisted row failed (id=${result.id})`, {+ error: err instanceof Error ? err.message : String(err),+ }),+ );+ await this.messageRepository.delete({ id: message.id }).catch(() => undefined);+ // Reconcile provider indexes (#906): upsert the surviving echo row (now carrying our SENT+ // state + media) and drop the ghost PENDING document this redundant row produced earlier.+ const surviving = await this.messageRepository+ .findOne({ where: { sessionId: message.sessionId, waMessageId: result.id } })+ .catch(() => null);+ if (surviving) this.emitPersisted(message.sessionId, surviving);+ void this.hookManager+ .execute(+ 'message:deleted',+ { sessionId: message.sessionId, message: { ...message } },+ { sessionId: message.sessionId, source: 'MessageService' },+ )+ .catch(() => undefined);+ } else {+ this.logger.warn(`Persisting SENT state failed after a successful send (id=${result.id})`, {+ error: persistError instanceof Error ? persistError.message : String(persistError),+ });+ }+ }+ return { messageId: result.id, timestamp: result.timestamp };+ }++ private getEngine(sessionId: string) {+ return this.engines.require(+ sessionId,+ () => new BadRequestException(`Session '${sessionId}' is not active. Start the session first.`),+ );+ }++ /**+ * Humanising delay: show the engine's typing indicator and pause for a length-scaled, jittered+ * interval before the real send, so automated single sends don't look instantaneous (anti-ban).+ * ON by default — set `SIMULATE_TYPING=false` to disable. Engine-agnostic (goes through+ * `sendChatState`) and strictly best-effort — it never throws and never blocks the send if presence+ * fails or the engine has no presence concept. `SIMULATE_TYPING_MAX_MS` (default 5000) caps the pause.+ * Note: this covers single sends only; bulk sends use their own `delayBetweenMessages` throttle.+ */+ private async simulateTypingIfEnabled(engine: IWhatsAppEngine, chatId: string, text: string): Promise<void> {+ const { simulateTyping, simulateTypingMaxMs } = resolveFeatureFlags(this.configService);+ if (!simulateTyping) return;+ try {+ await engine.sendChatState(chatId, 'typing');+ const maxMs = simulateTypingMaxMs;+ const planned = Math.min(maxMs, 500 + text.length * 45);+ const jittered = Math.round(planned * (0.85 + Math.random() * 0.3)); // ±15% so it isn't metronomic+ await new Promise(resolve => setTimeout(resolve, jittered));+ } catch (error) {+ this.logger.warn(`simulateTyping skipped: ${error instanceof Error ? error.message : String(error)}`);+ }+ }++ /**+ * Map a blocked outbound media fetch (SSRF guard) to an HTTP 400 so a+ * caller-supplied internal/unsafe URL returns a client error instead of a 500.+ * The raw guard message names the resolved internal IP (a recon/DNS-rebind oracle), so return a+ * generic message to the client and keep the detail in the server log only. Others pass through.+ */+ private toClientFacingError(error: unknown): unknown {+ if (error instanceof SsrfBlockedError) {+ this.logger.warn(`Outbound media fetch blocked by SSRF guard: ${error.message}`);+ return new BadRequestException(SSRF_BLOCKED_CLIENT_MESSAGE);+ }+ return error;+ }++ private buildMediaInput(dto: SendMediaMessageDto): MediaInput {+ const base64 = stripBase64DataUri(dto.base64);+ if (!dto.url && !base64) {+ throw new BadRequestException('Either url or base64 must be provided');+ }++ if (base64 && !dto.mimetype) {+ throw new BadRequestException('mimetype is required when using base64 data');+ }++ // Bound an outbound base64 payload to the same byte cap as URL/inbound media, before it is+ // persisted or handed to the engine. URL media is already capped while streaming.+ assertBase64WithinMediaCap(base64);++ return {+ mimetype: dto.mimetype || 'application/octet-stream',+ // base64 wins over url when both are present: it is the explicit local payload, and a stale+ // `url` (e.g. a Swagger/example default left in the body) must not be fetched in its place.+ // Aligns the send selection with the base64-first persisted metadata and the url field's+ // `@ValidateIf((o) => !o.base64)` (which skips @IsUrl when base64 is present) — #670.+ data: base64 || dto.url!,+ filename: dto.filename,+ caption: dto.caption,+ mentions: dto.mentions,+ quotedMessageId: dto.quotedMessageId,+ };+ }+}diff --git a/src/modules/message/message.module.ts b/src/modules/message/message.module.tsindex d9d145b3f..a1603fb4f 100644--- a/src/modules/message/message.module.ts+++ b/src/modules/message/message.module.ts@@ -1,6 +1,7 @@import { Module } from '@nestjs/common';import { TypeOrmModule } from '@nestjs/typeorm';import { MessageService } from './message.service';+import { MessageSendService } from './message-send.service';import { BulkMessageService } from './bulk-message.service';import { MessageTypeBackfillService } from './message-type-backfill.service';import { PendingMessageReaperService } from './pending-message-reaper.service';@@ -23,6 +24,7 @@ import { MessageBatch } from './entities/message-batch.entity';controllers: [MessageController],providers: [MessageService,+ MessageSendService,BulkMessageService,MessageTypeBackfillService,PendingMessageReaperService,diff --git a/src/modules/message/message.service.spec.ts b/src/modules/message/message.service.spec.tsindex 8e8c87c7e..16aa517c6 100644--- a/src/modules/message/message.service.spec.ts+++ b/src/modules/message/message.service.spec.ts@@ -1,17 +1,14 @@import { Test, TestingModule } from '@nestjs/testing';import { getRepositoryToken } from '@nestjs/typeorm';import { In, Repository } from 'typeorm';-import { BadRequestException, NotFoundException, PayloadTooLargeException } from '@nestjs/common';+import { BadRequestException, NotFoundException } from '@nestjs/common';import { MessageService, spendInlineMediaBudget } from './message.service';-import { Message, MessageDirection, MessageStatus } from './entities/message.entity';-import { SessionService } from '../session/session.service';+import { MessageSendService } from './message-send.service';+import { Message, MessageDirection } from './entities/message.entity';import { EngineRegistry } from '../../engine/engine-registry.service';import { MessageProjector } from '../session/message-projector.service';import type { IWhatsAppEngine } from '../../engine/interfaces/whatsapp-engine.interface';import { HookManager } from '../../core/hooks';-import { TemplateService } from '../template/template.service';-import { Template } from '../template/entities/template.entity';-import { SsrfBlockedError } from '../../common/security/ssrf-guard';import { LidMappingStoreService } from '../../engine/identity/lid-mapping-store.service';import { SendPacingService } from './send-pacing.service';@@ -23,21 +20,8 @@ const inertPacing = (): SendPacingService =>recordSendSuccess: jest.fn(),}) as unknown as SendPacingService;-const mockEngineResult = { id: 'wa-msg-1', timestamp: 1706868000 };-function createMockEngine() {return {- sendTextMessage: jest.fn().mockResolvedValue(mockEngineResult),- sendImageMessage: jest.fn().mockResolvedValue(mockEngineResult),- sendVideoMessage: jest.fn().mockResolvedValue(mockEngineResult),- sendAudioMessage: jest.fn().mockResolvedValue(mockEngineResult),- sendDocumentMessage: jest.fn().mockResolvedValue(mockEngineResult),- sendStickerMessage: jest.fn().mockResolvedValue(mockEngineResult),- sendLocationMessage: jest.fn().mockResolvedValue(mockEngineResult),- sendContactMessage: jest.fn().mockResolvedValue(mockEngineResult),- sendPollMessage: jest.fn().mockResolvedValue(mockEngineResult),- replyToMessage: jest.fn().mockResolvedValue(mockEngineResult),- forwardMessage: jest.fn().mockResolvedValue(mockEngineResult),reactToMessage: jest.fn().mockResolvedValue(undefined),getMessageReactions: jest.fn().mockResolvedValue([]),deleteMessage: jest.fn().mockResolvedValue(undefined),@@ -45,33 +29,20 @@ function createMockEngine() {starMessage: jest.fn().mockResolvedValue(undefined),votePoll: jest.fn().mockResolvedValue(undefined),unpinMessage: jest.fn().mockResolvedValue(undefined),- editMessage: jest.fn().mockResolvedValue(mockEngineResult),+ editMessage: jest.fn().mockResolvedValue({ id: 'wa-msg-1', timestamp: 1706868000 }),getChatHistory: jest.fn().mockResolvedValue([]),- sendChatState: jest.fn().mockResolvedValue(undefined),};}describe('MessageService', () => {let service: MessageService;let repository: jest.Mocked<Partial<Repository<Message>>>;- let sessionService: jest.Mocked<Partial<SessionService>>;let engines: EngineRegistry;let messageProjector: { recordOutboundMessageEdit: jest.Mock };let hookManager: jest.Mocked<Partial<HookManager>>;- let templateService: jest.Mocked<Partial<TemplateService>>;let lidMappingStore: { lidsForPhone: jest.Mock; getCached: jest.Mock };let mockEngine: ReturnType<typeof createMockEngine>;- // Auto-typing is on by default; disable it for the unrelated send tests so they don't incur the- // real setTimeout delay and don't add an extra sendChatState call. The auto-typing suite opts in.- beforeEach(() => {- process.env.SIMULATE_TYPING = 'false';- });- afterEach(() => {- delete process.env.SIMULATE_TYPING;- delete process.env.SIMULATE_TYPING_MAX_MS;- });-beforeEach(async () => {repository = {create: jest.fn().mockImplementation((data: Partial<Message>) => ({ id: 'msg-uuid-1', ...data }) as Message),@@ -84,32 +55,27 @@ describe('MessageService', () => {mockEngine = createMockEngine();- sessionService = {- findOne: jest.fn().mockResolvedValue({ id: 'sess-1', phone: '628123456789' }),- };-messageProjector = { recordOutboundMessageEdit: jest.fn().mockResolvedValue(undefined) };engines = new EngineRegistry();engines.set('sess-1', mockEngine as unknown as IWhatsAppEngine);hookManager = {- // Echo the input straight back so the message:sending gate is a pass-through by default; specific- // tests override with continue:false (block) or a modified input.+ // Echo the input straight back so the message:sending gate is a pass-through by default; the+ // edit tests override with continue:false (block) or a modified input.execute: jest.fn().mockImplementation((_event: string, data: unknown) => Promise.resolve({ continue: true, data })),};- templateService = {- resolve: jest.fn(),- };-lidMappingStore = { lidsForPhone: jest.fn().mockReturnValue([]), getCached: jest.fn().mockReturnValue(undefined) };const module: TestingModule = await Test.createTestingModule({providers: [MessageService,+ // The send family lives on MessageSendService; nothing here exercises it, so a bare stub+ // stands in for the delegation target.+ { provide: MessageSendService, useValue: {} },{provide: SendPacingService,useValue: {@@ -119,11 +85,9 @@ describe('MessageService', () => {},},{ provide: getRepositoryToken(Message, 'data'), useValue: repository },- { provide: SessionService, useValue: sessionService },{ provide: EngineRegistry, useValue: engines },{ provide: MessageProjector, useValue: messageProjector },{ provide: HookManager, useValue: hookManager },- { provide: TemplateService, useValue: templateService },{ provide: LidMappingStoreService, useValue: lidMappingStore },],}).compile();@@ -131,548 +95,25 @@ describe('MessageService', () => {service = module.get<MessageService>(MessageService);});- // ── sendText ──────────────────────────────────────────────────────-- describe('auto-typing before send (SIMULATE_TYPING, on by default)', () => {- it('sends a typing presence before the message by default', async () => {- delete process.env.SIMULATE_TYPING; // default = on- process.env.SIMULATE_TYPING_MAX_MS = '1'; // keep the humanising delay ~instant in tests-- await service.sendText('sess-1', { chatId: '[email protected]', text: 'Hello' });-- expect(mockEngine.sendChatState).toHaveBeenCalledWith('[email protected]', 'typing');- expect(mockEngine.sendTextMessage).toHaveBeenCalledWith('[email protected]', 'Hello');- });-- it('does not send typing presence when SIMULATE_TYPING=false', async () => {- process.env.SIMULATE_TYPING = 'false';- await service.sendText('sess-1', { chatId: '[email protected]', text: 'Hello' });- expect(mockEngine.sendChatState).not.toHaveBeenCalled();- });- });-- describe('sendText', () => {- it('should send text message and return messageId + timestamp', async () => {- const result = await service.sendText('sess-1', {- chatId: '[email protected]',- text: 'Hello',- });-- expect(result.messageId).toBe('wa-msg-1');- expect(result.timestamp).toBe(1706868000);- expect(mockEngine.sendTextMessage).toHaveBeenCalledWith('[email protected]', 'Hello');- });-- it('threads mentions through to the engine (#530)', async () => {- const input = { chatId: '[email protected]', text: 'hi @62811', mentions: ['[email protected]'] };- (hookManager.execute as jest.Mock).mockResolvedValueOnce({- continue: true,- data: { sessionId: 'sess-1', input, type: 'text' },- });- await service.sendText('sess-1', input);- expect(mockEngine.sendTextMessage).toHaveBeenCalledWith('[email protected]', 'hi @62811', ['[email protected]']);- });-- // The parameter is only guaranteed in its suppressing direction, so what matters is that `false`- // reaches the engine and that everything else leaves the existing call shape alone.- it('threads a link-preview suppression through to the engine', async () => {- const input = { chatId: '[email protected]', text: 'see https://example.com', linkPreview: false };- (hookManager.execute as jest.Mock).mockResolvedValueOnce({- continue: true,- data: { sessionId: 'sess-1', input, type: 'text' },- });-- await service.sendText('sess-1', input);-- expect(mockEngine.sendTextMessage).toHaveBeenCalledWith(- '[email protected]',- 'see https://example.com',- undefined,- { linkPreview: false },- );- });-- // A send that asks for nothing must keep the exact call it made before this option existed —- // a trailing undefined would be harmless to the engines but would rewrite every existing send.- it('leaves the plain send shape untouched when no preview choice is made', async () => {- await service.sendText('sess-1', { chatId: '[email protected]', text: 'hi' });-- expect(mockEngine.sendTextMessage).toHaveBeenCalledWith('[email protected]', 'hi');- });-- it('threads a caller-supplied preview through to the engine', async () => {- const input = {- chatId: '[email protected]',- text: 'see https://example.com',- customLinkPreview: { url: 'https://example.com', title: 'Example', description: 'A site' },- };- (hookManager.execute as jest.Mock).mockResolvedValueOnce({- continue: true,- data: { sessionId: 'sess-1', input, type: 'text' },- });-- await service.sendText('sess-1', input);-- expect(mockEngine.sendTextMessage).toHaveBeenCalledWith(- '[email protected]',- 'see https://example.com',- undefined,- { customPreview: { url: 'https://example.com', title: 'Example', description: 'A site' } },- );- });-- // Suppressing the preview and supplying one are opposite requests; guessing which was meant- // would send a message the caller did not ask for either way.- it('refuses a suppression combined with a supplied preview, before reaching the engine', async () => {- await expect(- service.sendText('sess-1', {- chatId: '[email protected]',- text: 'hi',- linkPreview: false,- customLinkPreview: { url: 'https://example.com', title: 'Example' },- }),- ).rejects.toBeInstanceOf(BadRequestException);-- expect(mockEngine.sendTextMessage).not.toHaveBeenCalled();- });-- it('should save outgoing message as pending before sending, then update to sent', async () => {- await service.sendText('sess-1', {- chatId: '[email protected]',- text: 'Hello',- });-- // First save: pending message before engine send- expect(repository.create).toHaveBeenCalledWith(- expect.objectContaining({- sessionId: 'sess-1',- direction: MessageDirection.OUTGOING,- type: 'text',- body: 'Hello',- status: MessageStatus.PENDING,- }),- );- // save called twice: once for initial pending, once for status update to sent- expect(repository.save).toHaveBeenCalledTimes(2);- });-- it('returns success (not FAILED) when persisting the SENT state fails after a successful send', async () => {- // 1st save (PENDING) ok; 2nd save (SENT-state, after WhatsApp already accepted the message) throws.- (repository.save as jest.Mock)- .mockImplementationOnce((msg: unknown) => Promise.resolve(msg))- .mockRejectedValueOnce(new Error('transient db fault'));-- const result = await service.sendText('sess-1', { chatId: '[email protected]', text: 'Hello' });-- // The send succeeded, so it is reported as success — not rethrown, not marked FAILED.- expect(result.messageId).toBe('wa-msg-1');- expect(result.timestamp).toBe(1706868000);- expect(hookManager.execute).not.toHaveBeenCalledWith('message:failed', expect.anything(), expect.anything());- });-- it('executes the message:sending hook (message:sent now fires once from the engine message_create path)', async () => {- await service.sendText('sess-1', {- chatId: '[email protected]',- text: 'Hello',- });-- expect(hookManager.execute).toHaveBeenCalledWith(- 'message:sending',- expect.objectContaining({ type: 'text' }),- expect.any(Object),- );- // message:sent is no longer fired here — it is emitted solely by the onMessageCreate wiring in- // SessionEngineLifecycle (via MessageProjector)- // with a consistent IncomingMessage payload for ALL sends (avoids the prior double dispatch).- expect(hookManager.execute).not.toHaveBeenCalledWith('message:sent', expect.anything(), expect.anything());- });-- it('emits message:persisted on BOTH the pending save and the finalized sent save (#906)', async () => {- await service.sendText('sess-1', { chatId: '[email protected]', text: 'hello' });-- const calls = (hookManager.execute as jest.Mock).mock.calls.filter(- ([ev]: unknown[]) => ev === 'message:persisted',- ) as unknown[][];- expect(calls).toHaveLength(2);- expect(calls[0][1]).toMatchObject({- sessionId: 'sess-1',- message: { chatId: '[email protected]', status: MessageStatus.PENDING },- });- expect(calls[1][1]).toMatchObject({- sessionId: 'sess-1',- message: { status: MessageStatus.SENT, waMessageId: 'wa-msg-1' },- });- expect(calls[0][2]).toMatchObject({ sessionId: 'sess-1', source: 'MessageService' });- });-- it('re-emits message:persisted with FAILED when the send itself fails (#906)', async () => {- mockEngine.sendTextMessage.mockRejectedValueOnce(new Error('engine down'));-- await expect(service.sendText('sess-1', { chatId: '[email protected]', text: 'hi' })).rejects.toThrow();-- const calls = (hookManager.execute as jest.Mock).mock.calls.filter(- ([ev]: unknown[]) => ev === 'message:persisted',- ) as unknown[][];- expect(calls).toHaveLength(2);- expect(calls[0][1]).toMatchObject({ message: { status: MessageStatus.PENDING } });- expect(calls[1][1]).toMatchObject({ message: { status: MessageStatus.FAILED } });- });-- it('reconciles provider indexes when the send echo won the race: upsert the surviving row + drop the ghost (#906)', async () => {- const echoRow = {- id: 'echo-uuid-9',- sessionId: 'sess-1',- waMessageId: 'wa-msg-1',- status: MessageStatus.SENT,- } as Message;- (repository.save as jest.Mock)- .mockImplementationOnce((msg: unknown) => Promise.resolve(msg)) // PENDING save- .mockRejectedValueOnce(- Object.assign(new Error('UNIQUE constraint failed'), { code: 'SQLITE_CONSTRAINT_UNIQUE' }),- ); // SENT save collides with the echo row- (repository.findOne as jest.Mock).mockResolvedValueOnce(echoRow);-- await service.sendText('sess-1', { chatId: '[email protected]', text: 'hi' });-- // SENT state merged onto the echo row; the redundant PENDING row dropped.- expect(repository.update).toHaveBeenCalledWith(- { sessionId: 'sess-1', waMessageId: 'wa-msg-1' },- expect.objectContaining({ status: MessageStatus.SENT }),- );- expect(repository.delete).toHaveBeenCalledWith({ id: 'msg-uuid-1' });- const persisted = (hookManager.execute as jest.Mock).mock.calls.filter(- ([ev]: unknown[]) => ev === 'message:persisted',- ) as unknown[][];- // PENDING + the surviving echo row (the failed SENT save itself emits nothing).- expect(persisted).toHaveLength(2);- expect(persisted[1][1]).toMatchObject({ message: { id: 'echo-uuid-9' } });- const deleted = (hookManager.execute as jest.Mock).mock.calls.filter(- ([ev]: unknown[]) => ev === 'message:deleted',- ) as unknown[][];- expect(deleted).toHaveLength(1);- expect(deleted[0][1]).toMatchObject({ sessionId: 'sess-1', message: { id: 'msg-uuid-1' } });- expect(deleted[0][2]).toMatchObject({ sessionId: 'sess-1', source: 'MessageService' });- });-- it('should throw BadRequestException when plugin blocks sending', async () => {- (hookManager.execute as jest.Mock).mockResolvedValueOnce({ continue: false, data: {} });-- await expect(service.sendText('sess-1', { chatId: '[email protected]', text: 'blocked' })).rejects.toThrow(- 'Message sending blocked by plugin',- );- });-- it('should throw BadRequestException if session is not active', async () => {- engines.delete('sess-1');-- await expect(service.sendText('inactive', { chatId: '[email protected]', text: 'hello' })).rejects.toThrow(- BadRequestException,- );- });- });-- // ── sendTemplate ──────────────────────────────────────────────────-- describe('sendTemplate', () => {- function mockTemplate(overrides: Partial<Template> = {}): Template {- return {- id: 'tpl-1',- sessionId: 'sess-1',- name: 'order-confirmation',- body: 'Hi {{customer}}, your order {{orderId}} shipped.',- header: null,- footer: null,- createdAt: new Date(),- updatedAt: new Date(),- session: undefined as unknown as Template['session'],- ...overrides,- };- }-- beforeEach(() => {- // Echo the supplied input back through the hook so the rendered text- // reaches the engine via the delegated sendText path.- (hookManager.execute as jest.Mock).mockImplementation((event: string, data: unknown) =>- Promise.resolve({ continue: true, data }),- );- });-- it('should resolve the template, render variables, and delegate to sendText', async () => {- (templateService.resolve as jest.Mock).mockResolvedValue(mockTemplate());-- const result = await service.sendTemplate('sess-1', {- chatId: '[email protected]',- templateName: 'order-confirmation',- vars: { customer: 'Alice', orderId: '1234' },- });-- expect(templateService.resolve).toHaveBeenCalledWith('sess-1', {- templateId: undefined,- templateName: 'order-confirmation',- });- expect(mockEngine.sendTextMessage).toHaveBeenCalledWith(- '[email protected]',- 'Hi Alice, your order 1234 shipped.',- );- expect(result.messageId).toBe('wa-msg-1');- });-- it('should flatten header and footer around the body with blank lines', async () => {- (templateService.resolve as jest.Mock).mockResolvedValue(- mockTemplate({ header: 'OpenWA Store', body: 'Hello {{customer}}', footer: 'Reply STOP to opt out' }),- );-- await service.sendTemplate('sess-1', {- chatId: '[email protected]',- templateId: 'tpl-1',- vars: { customer: 'Bob' },- });-- expect(mockEngine.sendTextMessage).toHaveBeenCalledWith(- '[email protected]',- 'OpenWA Store\n\nHello Bob\n\nReply STOP to opt out',- );- });-- it('should leave unmatched placeholders literal', async () => {- (templateService.resolve as jest.Mock).mockResolvedValue(mockTemplate({ body: 'Hi {{customer}} {{unknown}}' }));-- await service.sendTemplate('sess-1', {- chatId: '[email protected]',- templateId: 'tpl-1',- vars: { customer: 'Alice' },- });-- expect(mockEngine.sendTextMessage).toHaveBeenCalledWith('[email protected]', 'Hi Alice {{unknown}}');- });-- it('should propagate NotFoundException when the template cannot be resolved', async () => {- (templateService.resolve as jest.Mock).mockRejectedValue(new NotFoundException('Template not found'));-- await expect(service.sendTemplate('sess-1', { chatId: '[email protected]', templateName: 'missing' })).rejects.toThrow(- NotFoundException,- );- expect(mockEngine.sendTextMessage).not.toHaveBeenCalled();- });-- it('rejects an over-cap render with a 400 naming the limit (never truncated silently)', async () => {- (templateService.resolve as jest.Mock).mockResolvedValue(mockTemplate({ body: 'Hi {{customer}}' }));-- const error = await service- .sendTemplate('sess-1', {- chatId: '[email protected]',- templateId: 'tpl-1',- vars: { customer: 'x'.repeat(70_000) },- })- .catch((e: unknown) => e);-- expect(error).toBeInstanceOf(BadRequestException);- expect((error as Error).message).toContain('over the 65536-character limit');- expect(mockEngine.sendTextMessage).not.toHaveBeenCalled();- });-- it('renders at-or-under the cap unchanged', async () => {- (templateService.resolve as jest.Mock).mockResolvedValue(mockTemplate({ body: 'Hi {{customer}}' }));- // 'Hi ' + name lands exactly on the 64 KiB default cap — at the cap is NOT over it.- const name = 'y'.repeat(64 * 1024 - 3);-- await service.sendTemplate('sess-1', { chatId: '[email protected]', templateId: 'tpl-1', vars: { customer: name } });+ // ── outbound send delegation ──────────────────────────────────────- expect(mockEngine.sendTextMessage).toHaveBeenCalledWith('[email protected]', `Hi ${name}`);- });-- it('honors a configured template.renderMaxChars override', async () => {- const configService = {- get: (key: string, fallback: unknown) => (key === 'template.renderMaxChars' ? 10 : fallback),- } as unknown as ConstructorParameters<typeof MessageService>[8];- const capped = new MessageService(+ describe('outbound send delegation', () => {+ it('passes a send request straight through to MessageSendService and returns its answer', async () => {+ const sendText = jest.fn().mockResolvedValue({ messageId: 'wa-msg-1', timestamp: 1706868000 });+ const facade = new MessageService(repository as Repository<Message>,- sessionService as unknown as SessionService,engines,messageProjector as unknown as MessageProjector,hookManager as HookManager,- templateService as unknown as TemplateService,lidMappingStore as unknown as LidMappingStoreService,inertPacing(),- configService,- );- (templateService.resolve as jest.Mock).mockResolvedValue(mockTemplate({ body: 'Hello {{customer}}' }));-- await expect(- capped.sendTemplate('sess-1', { chatId: '[email protected]', templateId: 'tpl-1', vars: { customer: 'Alice' } }),- ).rejects.toThrow(/over the 10-character limit/);- expect(mockEngine.sendTextMessage).not.toHaveBeenCalled();- });- });-- // ── send-hook chokepoint ──────────────────────────────────────────-- describe('send-hook chokepoint (message:sending gate + message:failed across all senders)', () => {- it('runs the message:sending gate for a media send (sendImage) tagged with the media type', async () => {- await service.sendImage('sess-1', { chatId: '[email protected]', url: 'https://e.com/i.jpg', caption: 'hi' });- expect(hookManager.execute).toHaveBeenCalledWith(- 'message:sending',- expect.objectContaining({ type: 'image' }),- expect.any(Object),- );- });-- it('runs the message:sending gate for an extended send (sendPoll)', async () => {- await service.sendPoll('sess-1', { chatId: '[email protected]', name: 'Q?', options: ['a', 'b'] });- expect(hookManager.execute).toHaveBeenCalledWith(- 'message:sending',- expect.objectContaining({ type: 'poll' }),- expect.any(Object),- );- });-- it('lets a plugin block a media send (continue:false) before the engine is called', async () => {- (hookManager.execute as jest.Mock).mockResolvedValueOnce({ continue: false, data: {} });- await expect(service.sendImage('sess-1', { chatId: '[email protected]', url: 'https://e.com/i.jpg' })).rejects.toThrow(- 'Message sending blocked by plugin',- );- expect(mockEngine.sendImageMessage).not.toHaveBeenCalled();- });-- it('threads a plugin-modified media input through to the engine', async () => {- (hookManager.execute as jest.Mock).mockResolvedValueOnce({- continue: true,- data: {- sessionId: 'sess-1',- type: 'image',- input: { chatId: '[email protected]', url: 'https://e.com/mod.jpg', caption: 'edited' },- },- });- await service.sendImage('sess-1', { chatId: '[email protected]', url: 'https://e.com/i.jpg', caption: 'orig' });- expect(mockEngine.sendImageMessage).toHaveBeenCalledWith(- '[email protected]',- expect.objectContaining({ data: 'https://e.com/mod.jpg', caption: 'edited' }),- );- });-- it('fires message:failed when a media send fails (previously only sendText did)', async () => {- mockEngine.sendImageMessage.mockRejectedValueOnce(new Error('engine down'));- await expect(service.sendImage('sess-1', { chatId: '[email protected]', url: 'https://e.com/i.jpg' })).rejects.toThrow(- 'engine down',- );- expect(hookManager.execute).toHaveBeenCalledWith(- 'message:failed',- expect.objectContaining({ type: 'image', error: 'engine down' }),- expect.any(Object),- );- });- });-- // ── sendImage ─────────────────────────────────────────────────────-- describe('sendImage', () => {- it('should send image via URL', async () => {- const result = await service.sendImage('sess-1', {- chatId: '[email protected]',- url: 'https://example.com/img.jpg',- caption: 'My image',- });-- expect(result.messageId).toBe('wa-msg-1');- expect(mockEngine.sendImageMessage).toHaveBeenCalledWith(- '[email protected]',- expect.objectContaining({ data: 'https://example.com/img.jpg', caption: 'My image' }),- );- });-- it('should send image via base64 with mimetype', async () => {- await service.sendImage('sess-1', {- chatId: '[email protected]',- base64: 'iVBORw0KGgoAAAAN...',- mimetype: 'image/png',- });-- expect(mockEngine.sendImageMessage).toHaveBeenCalledWith(- '[email protected]',- expect.objectContaining({ data: 'iVBORw0KGgoAAAAN...', mimetype: 'image/png' }),- );- });-- it('threads media mentions into the MediaInput (#530)', async () => {- await service.sendImage('sess-1', {- chatId: '[email protected]',- base64: 'AAAA',- mimetype: 'image/png',- caption: 'look @62811',- mentions: ['[email protected]'],- });- expect(mockEngine.sendImageMessage).toHaveBeenCalledWith(- '[email protected]',- expect.objectContaining({ mentions: ['[email protected]'] }),- );- });-- it('maps a blocked-media-URL SSRF error to HTTP 400 with a generic message (no internal IP leak)', async () => {- mockEngine.sendImageMessage.mockRejectedValueOnce(- new SsrfBlockedError('Host x resolves to a blocked internal address: 169.254.169.254'),+ { sendText } as unknown as MessageSendService,);- // Generic client message — the resolved internal IP must NOT reach the caller (recon oracle).- await expect(- service.sendImage('sess-1', { chatId: '[email protected]', url: 'http://127.0.0.1/x.png' }),- ).rejects.toMatchObject({ response: { message: 'Destination address is not allowed' } });- });+ const result = await facade.sendText('sess-1', { chatId: '[email protected]', text: 'hi' });- it('does not leak the SSRF internal address into the message:failed hook payload (media sends now route there)', async () => {- mockEngine.sendImageMessage.mockRejectedValueOnce(- new SsrfBlockedError('Host x resolves to a blocked internal address: 169.254.169.254'),- );-- await expect(- service.sendImage('sess-1', { chatId: '[email protected]', url: 'http://127.0.0.1/x.png' }),- ).rejects.toThrow();-- const calls = (hookManager.execute as jest.Mock).mock.calls as [string, { error?: string }, unknown][];- const failedCall = calls.find(c => c[0] === 'message:failed');- expect(failedCall).toBeDefined();- // The hook payload (now delivered to plugins for media sends) carries the generic message, NOT- // the resolved internal IP that the raw SsrfBlockedError.message contains.- expect(failedCall![1].error).toBe('Destination address is not allowed');- expect(failedCall![1].error).not.toContain('169.254.169.254');- });-- it('rejects a base64 image over the media cap before sending or persisting', async () => {- process.env.MEDIA_DOWNLOAD_MAX_BYTES = '1024';- try {- await expect(- service.sendImage('sess-1', {- chatId: '[email protected]',- base64: Buffer.alloc(1025).toString('base64'),- mimetype: 'image/png',- }),- ).rejects.toBeInstanceOf(PayloadTooLargeException);- expect(mockEngine.sendImageMessage).not.toHaveBeenCalled();- } finally {- delete process.env.MEDIA_DOWNLOAD_MAX_BYTES;- }- });-- it('strips the base64 payload from a FAILED media row but keeps mimetype/filename', async () => {- mockEngine.sendImageMessage.mockRejectedValueOnce(new Error('engine down'));-- await expect(- service.sendImage('sess-1', {- chatId: '[email protected]',- base64: 'QUJDREVGISBhIGJpZyBwYXlsb2Fk',- mimetype: 'image/png',- filename: 'pic.png',- }),- ).rejects.toThrow();-- // The persisted FAILED row must not retain the (often multi-MB) base64 — it's never displayed- // or retried — but should keep the descriptive mimetype/filename.- const calls = (repository.save as jest.Mock).mock.calls as [Message][];- const saved = calls.at(-1)![0];- expect(saved.status).toBe(MessageStatus.FAILED);- const media = (saved.metadata as { media?: { data?: unknown; mimetype?: string; filename?: string } }).media;- expect(media?.data).toBeUndefined();- expect(media?.mimetype).toBe('image/png');- expect(media?.filename).toBe('pic.png');+ expect(sendText).toHaveBeenCalledWith('sess-1', { chatId: '[email protected]', text: 'hi' });+ expect(result).toEqual({ messageId: 'wa-msg-1', timestamp: 1706868000 });});});@@ -975,321 +416,6 @@ describe('MessageService', () => {});});- // ── sendVideo / sendAudio / sendDocument / sendSticker ────────────-- describe('sendVideo', () => {- it('should call engine.sendVideoMessage', async () => {- await service.sendVideo('sess-1', {- chatId: '[email protected]',- url: 'https://example.com/video.mp4',- });- expect(mockEngine.sendVideoMessage).toHaveBeenCalled();- });- });-- describe('sendAudio', () => {- it('should call engine.sendAudioMessage', async () => {- await service.sendAudio('sess-1', {- chatId: '[email protected]',- url: 'https://example.com/audio.ogg',- });- expect(mockEngine.sendAudioMessage).toHaveBeenCalled();- });-- it('sends a voice note (ptt) and defaults the mimetype to ogg/opus when omitted', async () => {- await service.sendAudio('sess-1', {- chatId: '[email protected]',- url: 'https://example.com/voice',- ptt: true,- });- expect(mockEngine.sendAudioMessage).toHaveBeenCalledWith(- '[email protected]',- expect.objectContaining({ ptt: true, mimetype: 'audio/ogg; codecs=opus' }),- );- });-- it('respects a caller-supplied mimetype for a voice note', async () => {- await service.sendAudio('sess-1', {- chatId: '[email protected]',- url: 'https://example.com/voice.ogg',- mimetype: 'audio/ogg',- ptt: true,- });- expect(mockEngine.sendAudioMessage).toHaveBeenCalledWith(- '[email protected]',- expect.objectContaining({ ptt: true, mimetype: 'audio/ogg' }),- );- });-- it('persists a voice note as type "voice"', async () => {- await service.sendAudio('sess-1', { chatId: '[email protected]', url: 'https://example.com/voice', ptt: true });- expect(repository.create).toHaveBeenCalledWith(expect.objectContaining({ type: 'voice' }));- });-- it('labels the message:sending gate "voice" for a voice note (matches the persisted/failed type)', async () => {- await service.sendAudio('sess-1', { chatId: '[email protected]', url: 'https://example.com/voice', ptt: true });- expect(hookManager.execute).toHaveBeenCalledWith(- 'message:sending',- expect.objectContaining({ type: 'voice' }),- expect.any(Object),- );- });-- it('labels the message:sending gate "audio" for a plain (non-ptt) audio send', async () => {- await service.sendAudio('sess-1', { chatId: '[email protected]', url: 'https://example.com/audio.ogg' });- expect(hookManager.execute).toHaveBeenCalledWith(- 'message:sending',- expect.objectContaining({ type: 'audio' }),- expect.any(Object),- );- });-- it('persists a plain audio send (no ptt) as type "audio"', async () => {- await service.sendAudio('sess-1', { chatId: '[email protected]', url: 'https://example.com/audio.ogg' });- expect(repository.create).toHaveBeenCalledWith(expect.objectContaining({ type: 'audio' }));- });- });-- describe('sendDocument', () => {- it('should call engine.sendDocumentMessage with filename', async () => {- await service.sendDocument('sess-1', {- chatId: '[email protected]',- url: 'https://example.com/doc.pdf',- filename: 'report.pdf',- });- expect(mockEngine.sendDocumentMessage).toHaveBeenCalledWith(- '[email protected]',- expect.objectContaining({ filename: 'report.pdf' }),- );- });- });-- describe('sendSticker', () => {- it('should call engine.sendStickerMessage', async () => {- await service.sendSticker('sess-1', {- chatId: '[email protected]',- url: 'https://example.com/sticker.webp',- });- expect(mockEngine.sendStickerMessage).toHaveBeenCalled();- });- });-- // ── sendLocation ──────────────────────────────────────────────────-- describe('sendLocation', () => {- it('should send location with lat/lng', async () => {- const result = await service.sendLocation('sess-1', {- chatId: '[email protected]',- latitude: -6.2088,- longitude: 106.8456,- description: 'Jakarta',- });-- expect(result.messageId).toBe('wa-msg-1');- expect(mockEngine.sendLocationMessage).toHaveBeenCalledWith(- '[email protected]',- expect.objectContaining({ latitude: -6.2088, longitude: 106.8456 }),- );- });- });-- // ── sendContact ───────────────────────────────────────────────────-- describe('sendContact', () => {- it('should send contact with name and number', async () => {- const result = await service.sendContact('sess-1', {- chatId: '[email protected]',- contactName: 'John Doe',- contactNumber: '+628123456789',- });-- expect(result.messageId).toBe('wa-msg-1');- expect(mockEngine.sendContactMessage).toHaveBeenCalledWith(- '[email protected]',- expect.objectContaining({ name: 'John Doe', number: '+628123456789' }),- );- });- });-- // ── sendPoll ──────────────────────────────────────────────────────-- describe('sendPoll', () => {- it('should send a poll and default to single choice', async () => {- const result = await service.sendPoll('sess-1', {- chatId: '[email protected]',- name: 'Where should we meet?',- options: ['Park', 'Beach'],- });-- expect(result.messageId).toBe('wa-msg-1');- expect(mockEngine.sendPollMessage).toHaveBeenCalledWith('[email protected]', {- name: 'Where should we meet?',- options: ['Park', 'Beach'],- allowMultipleAnswers: false,- });- // A poll has no plain-text body, so it is persisted as type 'poll' with the question as the body.- expect(repository.create).toHaveBeenCalledWith(- expect.objectContaining({ type: 'poll', body: '📊 Where should we meet?' }),- );- });-- it('should pass allowMultipleAnswers through to the engine', async () => {- await service.sendPoll('sess-1', {- chatId: '[email protected]',- name: 'Pick toppings',- options: ['Cheese', 'Ham', 'Olives'],- allowMultipleAnswers: true,- });-- expect(mockEngine.sendPollMessage).toHaveBeenCalledWith(- '[email protected]',- expect.objectContaining({ allowMultipleAnswers: true }),- );- });- });-- // ── quoted sends (issue #1271) ────────────────────────────────────-- describe('quotedMessageId on the send endpoints', () => {- // One case per sender rather than the media funnel alone: location, contact and poll each build- // their own engine payload, so a thread that covered only buildMediaInput would leave three- // endpoints accepting the field and silently discarding it.- it('sendImage forwards quotedMessageId in the media payload', async () => {- await service.sendImage('sess-1', {- chatId: '[email protected]',- url: 'https://example.com/a.png',- quotedMessageId: 'wa-quoted-9',- });-- expect(mockEngine.sendImageMessage).toHaveBeenCalledWith(- '[email protected]',- expect.objectContaining({ quotedMessageId: 'wa-quoted-9' }),- );- });-- it('sendLocation forwards quotedMessageId', async () => {- await service.sendLocation('sess-1', {- chatId: '[email protected]',- latitude: 1,- longitude: 2,- quotedMessageId: 'wa-quoted-9',- });-- expect(mockEngine.sendLocationMessage).toHaveBeenCalledWith(- '[email protected]',- expect.objectContaining({ quotedMessageId: 'wa-quoted-9' }),- );- });-- it('sendContact forwards quotedMessageId', async () => {- await service.sendContact('sess-1', {- chatId: '[email protected]',- contactName: 'Alice',- contactNumber: '628999',- quotedMessageId: 'wa-quoted-9',- });-- expect(mockEngine.sendContactMessage).toHaveBeenCalledWith(- '[email protected]',- expect.objectContaining({ quotedMessageId: 'wa-quoted-9' }),- );- });-- it('sendPoll forwards quotedMessageId', async () => {- await service.sendPoll('sess-1', {- chatId: '[email protected]',- name: 'Q',- options: ['a', 'b'],- quotedMessageId: 'wa-quoted-9',- });-- expect(mockEngine.sendPollMessage).toHaveBeenCalledWith(- '[email protected]',- expect.objectContaining({ quotedMessageId: 'wa-quoted-9' }),- );- });-- it('sendText forwards quotedMessageId through the options bag', async () => {- await service.sendText('sess-1', {- chatId: '[email protected]',- text: 'hi',- quotedMessageId: 'wa-quoted-9',- });-- expect(mockEngine.sendTextMessage).toHaveBeenCalledWith(- '[email protected]',- 'hi',- undefined,- expect.objectContaining({ quotedMessageId: 'wa-quoted-9' }),- );- });-- // Known-negative control: a plain text send must keep its narrow call shape. Without this an- // implementation that always passed an options object would satisfy the assertion above while- // rewriting every existing send.- it('leaves an unquoted text send on its existing two-argument call shape', async () => {- await service.sendText('sess-1', { chatId: '[email protected]', text: 'hi' });-- expect(mockEngine.sendTextMessage).toHaveBeenCalledWith('[email protected]', 'hi');- });- });-- // ── reply / forward ───────────────────────────────────────────────-- describe('reply', () => {- it('should call engine.replyToMessage with quotedMessageId', async () => {- await service.reply('sess-1', {- chatId: '[email protected]',- quotedMessageId: 'wa-quoted-1',- text: 'This is a reply',- });-- expect(mockEngine.replyToMessage).toHaveBeenCalledWith('[email protected]', 'wa-quoted-1', 'This is a reply');- });- });-- describe('forward', () => {- it('should call engine.forwardMessage with from/to chats', async () => {- await service.forward('sess-1', {- fromChatId: '[email protected]',- toChatId: '[email protected]',- messageId: 'wa-msg-to-fwd',- });-- expect(mockEngine.forwardMessage).toHaveBeenCalledWith('[email protected]', '[email protected]', 'wa-msg-to-fwd');- });-- it('should save forwarded message with toChatId', async () => {- await service.forward('sess-1', {- fromChatId: '[email protected]',- toChatId: '[email protected]',- messageId: 'wa-msg-to-fwd',- });-- expect(repository.create).toHaveBeenCalledWith(- expect.objectContaining({- chatId: '[email protected]',- body: '[Forwarded]',- type: 'forward',- }),- );- });-- it('gates the forward against pacing by its destination chat', async () => {- // ForwardMessageDto has no `chatId` — the gate must fall back to `toChatId`, or forwards skip- // the cold-reachout rule entirely while their persisted row still drains the cold budget.- const { assertSendAllowed } = (service as unknown as { pacing: { assertSendAllowed: jest.Mock } }).pacing;-- await service.forward('sess-1', {- fromChatId: '[email protected]',- toChatId: '[email protected]',- messageId: 'wa-msg-to-fwd',- });-- expect(assertSendAllowed).toHaveBeenCalledWith('sess-1', '[email protected]');- });- });-// ── saveIncomingMessage ───────────────────────────────────────────describe('saveIncomingMessage', () => {@@ -1310,70 +436,6 @@ describe('MessageService', () => {});});- // ── buildMediaInput (via sendImage) ───────────────────────────────-- describe('buildMediaInput validation', () => {- it('should throw when neither url nor base64 is provided', async () => {- await expect(service.sendImage('sess-1', { chatId: '[email protected]' })).rejects.toThrow(- 'Either url or base64 must be provided',- );- });-- it('should throw when base64 is provided without mimetype', async () => {- await expect(- service.sendImage('sess-1', {- chatId: '[email protected]',- base64: 'data...',- }),- ).rejects.toThrow('mimetype is required when using base64 data');- });-- it('prefers base64 over url when both are provided (#670)', async () => {- // When both are sent, base64 is the explicit local payload and must win over `url` — otherwise- // a stale `url` is fetched and silently shadows the image. This aligns the send selection with- // the base64-first persisted metadata and the `@ValidateIf((o) => !o.base64)` intent on `url`.- await service.sendImage('sess-1', {- chatId: '[email protected]',- url: 'https://example.com/img.jpg',- base64: 'iVBORw0KGgoAAAAN...',- mimetype: 'image/png',- });-- expect(mockEngine.sendImageMessage).toHaveBeenCalledWith(- '[email protected]',- expect.objectContaining({ data: 'iVBORw0KGgoAAAAN...' }),- );- expect(mockEngine.sendImageMessage).not.toHaveBeenCalledWith(- '[email protected]',- expect.objectContaining({ data: 'https://example.com/img.jpg' }),- );- });-- it('strips a data-URI prefix before passing base64 bytes to the engine', async () => {- await service.sendImage('sess-1', {- chatId: '[email protected]',- base64: 'data:image/png;base64,QUJD',- mimetype: 'image/png',- });-- expect(mockEngine.sendImageMessage).toHaveBeenCalledWith(- '[email protected]',- expect.objectContaining({ data: 'QUJD' }),- );- });-- it('rejects a data URI with no encoded payload', async () => {- await expect(- service.sendImage('sess-1', {- chatId: '[email protected]',- base64: 'data:image/png;base64,',- mimetype: 'image/png',- }),- ).rejects.toThrow('Either url or base64 must be provided');- expect(mockEngine.sendImageMessage).not.toHaveBeenCalled();- });- });-// ── reactToMessage / deleteMessage ────────────────────────────────describe('reactToMessage', () => {@@ -1544,161 +606,6 @@ describe('MessageService', () => {});});- /**- * The empty id is the engine's "sent, but I couldn't read the id back" signal (#757). It has to reach- * the DB as NULL: UQ_messages_sessionId_waMessageId is NOT partial, so '' collides with the next- * id-less send in the same session, while NULLs stay exempt. In the bulk path that violation is- * swallowed into a warning, so the row would vanish with nothing surfacing.- */- describe('saveOutgoingMessage id normalization (#757)', () => {- it('stores an empty engine id as NULL rather than an empty string', async () => {- await service.saveOutgoingMessage('sess-1', { waMessageId: '', chatId: '[email protected]', type: 'text' });-- expect(repository.create).toHaveBeenCalledWith(expect.objectContaining({ waMessageId: undefined }));- });-- it('leaves a real id untouched', async () => {- await service.saveOutgoingMessage('sess-1', {- waMessageId: '[email protected]_ABC',- chatId: '[email protected]',- type: 'text',- });-- expect(repository.create).toHaveBeenCalledWith(expect.objectContaining({ waMessageId: '[email protected]_ABC' }));- });- });-- // The bulk path persists AFTER the send with the engine id already known, so it races the own-send- // echo on UNIQUE(sessionId, waMessageId). Losing that race used to drop the batch's media payload.- describe('saveOutgoingMessage vs the own-send echo (dedup race)', () => {- const uniqueViolation = new Error('UNIQUE constraint failed: messages.sessionId, messages.waMessageId');- const bulkRow = {- waMessageId: 'wa-bulk-1',- chatId: '[email protected]',- type: 'image',- status: MessageStatus.SENT,- timestamp: 1706868000,- metadata: { media: { mimetype: 'image/png', data: 'QUJD', filename: 'a.png' } },- };-- it('merges the media payload onto the echo row instead of losing it', async () => {- (repository.save as jest.Mock).mockRejectedValueOnce(uniqueViolation);- (repository.findOne as jest.Mock).mockResolvedValueOnce({ id: 'echo-row', ...bulkRow });-- const saved = await service.saveOutgoingMessage('sess-1', bulkRow);-- expect(repository.update).toHaveBeenCalledWith(- { sessionId: 'sess-1', waMessageId: 'wa-bulk-1' },- expect.objectContaining({- status: MessageStatus.SENT,- timestamp: 1706868000,- metadata: bulkRow.metadata,- }),- );- expect(saved).toEqual(expect.objectContaining({ id: 'echo-row' }));- });-- it('does not overwrite the echo row’s downloaded bytes with a URL pointer', async () => {- // A wwjs echo carries the media it downloaded; a URL-based send carries only the URL string.- // Merging ours over theirs would discard bytes the gateway already holds — and leave a row- // the archive cannot use.- (repository.save as jest.Mock).mockRejectedValueOnce(uniqueViolation);- (repository.findOne as jest.Mock).mockResolvedValueOnce({ id: 'echo-row' });-- await service.saveOutgoingMessage('sess-1', {- ...bulkRow,- metadata: { media: { mimetype: 'image/png', data: 'https://example.com/cat.png' } },- });-- // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access- const patch = (repository.update as jest.Mock).mock.calls[0]?.[1] as Record<string, unknown>;- expect(patch).not.toHaveProperty('metadata');- });-- it('leaves the echo row metadata alone when this write carries none', async () => {- (repository.save as jest.Mock).mockRejectedValueOnce(uniqueViolation);- (repository.findOne as jest.Mock).mockResolvedValueOnce({ id: 'echo-row' });-- await service.saveOutgoingMessage('sess-1', { ...bulkRow, type: 'text', metadata: undefined });-- // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access- const patch = (repository.update as jest.Mock).mock.calls[0]?.[1] as Record<string, unknown>;- expect(patch).not.toHaveProperty('metadata');- });-- it('rethrows a transient (non-unique) persist error', async () => {- (repository.save as jest.Mock).mockRejectedValueOnce(new Error('SQLITE_BUSY: database is locked'));-- await expect(service.saveOutgoingMessage('sess-1', bulkRow)).rejects.toThrow('SQLITE_BUSY');- expect(repository.update).not.toHaveBeenCalled();- });-- it('rethrows when there is no engine id to merge onto', async () => {- (repository.save as jest.Mock).mockRejectedValueOnce(uniqueViolation);-- await expect(service.saveOutgoingMessage('sess-1', { chatId: '[email protected]', type: 'text' })).rejects.toThrow(- uniqueViolation,- );- expect(repository.update).not.toHaveBeenCalled();- });- });-- describe('persistSentState vs the own-send echo (dedup race)', () => {- it('merges state onto the echo row, then drops the redundant PENDING row', async () => {- // The engine's message_create echo (onMessageCreate) won the insert race, so the SENT-state save- // collides on UNIQUE(sessionId, waMessageId). The echo row carries only what the engine reported- // — for a Baileys API send, a media-less marker — so the merge must land status/timestamp/metadata- // on it BEFORE the placeholder is deleted, or the payload is lost. The send still succeeds.- (repository.save as jest.Mock)- .mockImplementationOnce(msg => Promise.resolve(msg)) // saveOutgoingMessage (PENDING)- .mockRejectedValueOnce(new Error('UNIQUE constraint failed: messages.sessionId, messages.waMessageId'));-- const result = await service.sendText('sess-1', { chatId: '[email protected]', text: 'hi' });-- expect(result.messageId).toBe('wa-msg-1'); // send reported success- expect(repository.update).toHaveBeenCalledWith(- { sessionId: 'sess-1', waMessageId: 'wa-msg-1' },- expect.objectContaining({ status: MessageStatus.SENT, timestamp: 1706868000 }),- );- expect(repository.delete).toHaveBeenCalledWith({ id: 'msg-uuid-1' });- });-- it('merges the media payload onto the echo row for a media send (no data loss after reload)', async () => {- (repository.save as jest.Mock)- .mockImplementationOnce(msg => Promise.resolve(msg))- .mockRejectedValueOnce(new Error('UNIQUE constraint failed: messages.sessionId, messages.waMessageId'));-- await service.sendImage('sess-1', { chatId: '[email protected]', base64: 'QUJD', mimetype: 'image/png' });-- // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access- const patch = (repository.update as jest.Mock).mock.calls[0]?.[1] as Record<string, unknown> | undefined;- expect((patch?.metadata as { media?: { data?: string } } | undefined)?.media?.data).toBe('QUJD');- expect(repository.delete).toHaveBeenCalledWith({ id: 'msg-uuid-1' });- });-- it('keeps the echo row’s downloaded bytes rather than merging a URL pointer over them', async () => {- (repository.save as jest.Mock)- .mockImplementationOnce(msg => Promise.resolve(msg))- .mockRejectedValueOnce(new Error('UNIQUE constraint failed: messages.sessionId, messages.waMessageId'));-- await service.sendImage('sess-1', { chatId: '[email protected]', url: 'https://example.com/cat.png' });-- // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access- const patch = (repository.update as jest.Mock).mock.calls[0]?.[1] as Record<string, unknown> | undefined;- expect(patch).not.toHaveProperty('metadata');- });-- it('does NOT delete anything on a transient (non-unique) persist error', async () => {- (repository.save as jest.Mock)- .mockImplementationOnce(msg => Promise.resolve(msg))- .mockRejectedValueOnce(new Error('SQLITE_BUSY: database is locked'));-- const result = await service.sendText('sess-1', { chatId: '[email protected]', text: 'hi' });-- expect(result.messageId).toBe('wa-msg-1'); // transient persist faults never fail the send- expect(repository.delete).not.toHaveBeenCalled();- });- });// ── pin / unpin ───────────────────────────────────────────────────describe('pinMessage / unpinMessage', () => {@@ -1754,14 +661,12 @@ describe('MessageService', () => {const build = (archive: unknown, store: unknown): MessageService =>new MessageService(repository as Repository<Message>,- sessionService as unknown as SessionService,engines,messageProjector as unknown as MessageProjector,hookManager as HookManager,- templateService as unknown as TemplateService,lidMappingStore as unknown as LidMappingStoreService,inertPacing(),- undefined,+ {} as MessageSendService,archive as never,store as never,);@@ -1802,71 +707,6 @@ describe('MessageService', () => {await expect(svc.getChatMedia('sess-1', '[email protected]', 'wa-1')).rejects.toThrow(NotFoundException);});- // ── outbound archiving (CHAT_MEDIA_ARCHIVE_OUTBOUND) ─────────────-- describe('archiving media this account sent', () => {- const withFlag = (archiveOutbound: boolean, archive: { archive: jest.Mock }): MessageService =>- new MessageService(- repository as Repository<Message>,- sessionService as unknown as SessionService,- engines,- messageProjector as unknown as MessageProjector,- hookManager as HookManager,- templateService as unknown as TemplateService,- lidMappingStore as unknown as LidMappingStoreService,- inertPacing(),- {- get: (key: string, fallback?: unknown) =>- key === 'chatMedia.archiveOutbound' ? archiveOutbound : fallback,- } as never,- archive as never,- undefined,- );-- it('archives a SENT outbound row when the flag is on', async () => {- const archive = { archive: jest.fn().mockResolvedValue('chat-media/k') };- const svc = withFlag(true, archive);-- await svc.saveOutgoingMessage('sess-1', {- waMessageId: 'wa-1',- chatId: '[email protected]',- type: 'image',- status: MessageStatus.SENT,- metadata: { media: { mimetype: 'image/png', data: 'QUJD' } },- });-- expect(archive.archive).toHaveBeenCalledWith(expect.objectContaining({ waMessageId: 'wa-1' }));- });-- it('archives nothing while the flag is off', async () => {- const archive = { archive: jest.fn() };- const svc = withFlag(false, archive);-- await svc.saveOutgoingMessage('sess-1', {- waMessageId: 'wa-1',- chatId: '[email protected]',- type: 'image',- status: MessageStatus.SENT,- metadata: { media: { mimetype: 'image/png', data: 'QUJD' } },- });-- expect(archive.archive).not.toHaveBeenCalled();- });-- it('never archives a PENDING row — the merge may delete it and the reaper may rewrite it', async () => {- const archive = { archive: jest.fn() };- const svc = withFlag(true, archive);-- await svc.saveOutgoingMessage('sess-1', {- chatId: '[email protected]',- type: 'image',- metadata: { media: { mimetype: 'image/png', data: 'QUJD' } },- });-- expect(archive.archive).not.toHaveBeenCalled();- });- });-it('does not swallow a genuine storage fault as a 404', async () => {const svc = build(archived('image/png'), { getFile: jest.fn().mockRejectedValue(new Error('S3 500')) });await expect(svc.getChatMedia('sess-1', '[email protected]', 'wa-1')).rejects.toThrow('S3 500');diff --git a/src/modules/message/message.service.ts b/src/modules/message/message.service.tsindex 03e424fad..fcb8b55c9 100644--- a/src/modules/message/message.service.ts+++ b/src/modules/message/message.service.ts@@ -1,28 +1,22 @@import { Injectable, BadRequestException, NotFoundException, Optional } from '@nestjs/common';-import { ConfigService } from '@nestjs/config';import { InjectRepository } from '@nestjs/typeorm';import { In, Repository } from 'typeorm';-import { QueryDeepPartialEntity } from 'typeorm';-import { SessionService } from '../session/session.service';import { EngineRegistry } from '../../engine/engine-registry.service';import { MessageProjector } from '../session/message-projector.service';import { SendTextMessageDto, SendMediaMessageDto, SendAudioMessageDto, MessageResponseDto } from './dto';import { SendTemplateMessageDto } from './dto/send-template.dto';-import { assertBase64WithinMediaCap, stripBase64DataUri } from './media-cap.util';-import { MediaInput, IWhatsAppEngine, MessageResult } from '../../engine/interfaces/whatsapp-engine.interface';-import { Message, MessageDirection, MessageStatus } from './entities/message.entity';+import { Message, MessageDirection } from './entities/message.entity';import { HookManager, applySendingGate } from '../../core/hooks';-import { SendPacingService, countsTowardSendBreaker } from './send-pacing.service';-import { TemplateService } from '../template/template.service';-import { renderTemplate } from '../../common/utils/template-render';+import { SendPacingService } from './send-pacing.service';import { createLogger } from '../../common/services/logger.service';-import { SsrfBlockedError, SSRF_BLOCKED_CLIENT_MESSAGE } from '../../common/security/ssrf-guard';import { parseWaId } from '../../engine/identity/wa-id';-import { resolveFeatureFlags } from '../../config/feature-flags';import { LidMappingStoreService } from '../../engine/identity/lid-mapping-store.service';-import { isUniqueConstraintError } from '../../common/utils/unique-constraint.util';import { ChatMediaArchiveService } from '../chat-media/chat-media-archive.service';import { StorageService, isMissingObjectError } from '../../common/storage/storage.service';+import { MessageSendService, SaveOutgoingMessageData } from './message-send.service';++// Re-exported for existing importers (bulk send shares the rendered-template cap with the send path).+export { DEFAULT_TEMPLATE_RENDER_MAX_CHARS } from './message-send.service';export interface GetMessagesOptions {chatId?: string;@@ -32,9 +26,6 @@ export interface GetMessagesOptions {offset?: number;}-/** Default cap on a rendered template's final text; overridable via TEMPLATE_RENDER_MAX_CHARS. */-export const DEFAULT_TEMPLATE_RENDER_MAX_CHARS = 64 * 1024;-/*** Aggregate budget for the inline base64 media ONE message-list response may carry, counted in the* encoded bytes that actually land in the JSON body. Override with@@ -117,32 +108,6 @@ function inertMimetype(mimetype: string): string {return INERT_MEDIA_MIMETYPE.test(mimetype) ? mimetype : 'application/octet-stream';}-/**- * True when this write's media is only a remote-URL pointer (a URL-based send, whose bytes the- * engine fetches and discards). Merging such metadata onto an echo row would REPLACE bytes the- * gateway already downloaded — wwjs enriches its own-send echo with the real payload — leaving a- * row that renders as a bare marker and that the archive cannot use.- */-function isUrlPointerMetadata(metadata: Record<string, unknown> | undefined): boolean {- const data = (metadata as { media?: { data?: unknown } } | undefined)?.media?.data;- return typeof data === 'string' && /^https?:\/\//i.test(data);-}--/**- * Outbound sends are executed directly against the WhatsApp engine, not via a BullMQ queue.- *- * The engine is single-threaded per session (a Puppeteer page for the whatsapp-web.js adapter, a- * single socket for Baileys) and is therefore itself the serialization point for that session's- * outbound traffic. Routing sends through a queue would add request latency and a Redis hard- * dependency to the hot path for no throughput benefit — the engine cannot go faster than it- * already does. BullMQ is reserved for genuine side-effects that benefit from durable- * retry/back-pressure (webhook delivery, integration ingress); see `QUEUE_NAMES` in- * `queue-names.ts`, which intentionally defines no MESSAGE queue.- *- * Backpressure is applied at the edges instead: bulk sends self-throttle via- * `delayBetweenMessages` (default 3s) and a per-process concurrent-batch cap (see- * `BulkMessageService`), and the global throttler enforces per-key rate limits.- */@Injectable()export class MessageService {private readonly logger = createLogger('MessageService');@@ -150,17 +115,14 @@ export class MessageService {constructor(@InjectRepository(Message, 'data')private readonly messageRepository: Repository<Message>,- private readonly sessionService: SessionService,private readonly engines: EngineRegistry,private readonly messageProjector: MessageProjector,private readonly hookManager: HookManager,- private readonly templateService: TemplateService,private readonly lidMappingStore: LidMappingStoreService,// Required, not @Optional: a missing pacing service would silently mean "no pacing", which is// the one failure mode this feature must not have. The service itself no-ops when disabled.private readonly pacing: SendPacingService,- @Optional()- private readonly configService?: ConfigService,+ private readonly sender: MessageSendService,// Optional so the existing standalone constructions keep working; absent (like a disabled// archive) means the media read endpoint serves only the inline row copy, never archived files.@Optional()@@ -169,263 +131,85 @@ export class MessageService {private readonly storageService?: StorageService,) {}- async sendText(sessionId: string, dto: SendTextMessageDto): Promise<MessageResponseDto> {- // Asking to suppress the preview AND to attach one is a contradiction, and guessing which half- // the caller meant would send a message they did not ask for either way.- if (dto.linkPreview === false && dto.customLinkPreview) {- throw new BadRequestException('linkPreview: false cannot be combined with customLinkPreview');- }- const finalDto = await this.applySendingGate(sessionId, 'text', dto);+ // ========== Outbound sends (delegated) ==========+ //+ // The send family lives on MessageSendService; these pass-throughs keep the MessageService+ // surface stable for the controller, agent tools, plugin capabilities and bulk send, which were+ // all wired here before the split.- const engine = this.getEngine(sessionId);+ sendText(sessionId: string, dto: SendTextMessageDto): Promise<MessageResponseDto> {+ return this.sender.sendText(sessionId, dto);+ }- // Save message as pending BEFORE sending- const message = await this.saveOutgoingMessage(sessionId, {- chatId: finalDto.chatId,- body: finalDto.text,- type: 'text',- quotedMessageId: finalDto.quotedMessageId,- });+ sendTemplate(sessionId: string, dto: SendTemplateMessageDto): Promise<MessageResponseDto> {+ return this.sender.sendTemplate(sessionId, dto);+ }- // Opt-in humanising "typing…" pause before the actual send (anti-automation signal).- await this.simulateTypingIfEnabled(engine, finalDto.chatId, finalDto.text);+ sendImage(sessionId: string, dto: SendMediaMessageDto): Promise<MessageResponseDto> {+ return this.sender.sendImage(sessionId, dto);+ }- let result: MessageResult;- try {- // The call is widened ONLY as far as the caller actually asked. A send with neither mentions- // nor a preview choice keeps its two-argument shape, and one with mentions alone keeps its- // three — trailing `undefined`s would be harmless to the engines but would rewrite the call- // shape of every existing send for no behavioural gain.- const { linkPreview, customLinkPreview, quotedMessageId } = finalDto;- if (linkPreview !== undefined || customLinkPreview || quotedMessageId) {- result = await engine.sendTextMessage(finalDto.chatId, finalDto.text, finalDto.mentions, {- ...(linkPreview === undefined ? {} : { linkPreview }),- ...(customLinkPreview ? { customPreview: customLinkPreview } : {}),- ...(quotedMessageId ? { quotedMessageId } : {}),- });- } else if (finalDto.mentions?.length) {- result = await engine.sendTextMessage(finalDto.chatId, finalDto.text, finalDto.mentions);- } else {- result = await engine.sendTextMessage(finalDto.chatId, finalDto.text);- }- } catch (error) {- // The SEND itself failed — mark FAILED + fire message:failed (a post-send persistence fault is- // handled separately by persistSentState and must NOT land here).- return this.failSend(sessionId, 'text', message, finalDto, error);- }+ sendVideo(sessionId: string, dto: SendMediaMessageDto): Promise<MessageResponseDto> {+ return this.sender.sendVideo(sessionId, dto);+ }- // Note: the `message:sent` hook is emitted solely by the onMessageCreate wiring in- // SessionEngineLifecycle (engine `message_create`, handled by MessageProjector) with a- // consistent IncomingMessage payload for ALL sends (text, media,- // and phone-composed), so it is intentionally not fired here to avoid a double dispatch.- return this.persistSentState(message, result);+ sendAudio(sessionId: string, dto: SendAudioMessageDto): Promise<MessageResponseDto> {+ return this.sender.sendAudio(sessionId, dto);}- /**- * Run the pre-send `message:sending` plugin gate for one outbound message and return the- * (possibly plugin-modified) input, or throw BadRequestException if a plugin blocked the send.- * Centralised so EVERY public sender — text, media, extended (location/contact/poll/sticker/- * reply/forward) and edit — passes through the same moderation chokepoint, instead of only- * `sendText`. The implementation is shared with StatusService via core/hooks/sending-gate.- */- private async applySendingGate<T extends object>(sessionId: string, type: string, input: T): Promise<T> {- // Pacing runs BEFORE the plugin gate, so a send that policy forbids never reaches a plugin at- // all — plugins should not be asked to moderate, or given the chance to rewrite, traffic that is- // not going to be sent. The consequence is deliberate and documented in the hook contract: a- // paced-out send fires no `message:sending`, so a plugin cannot observe it. Refusals are a 429- // carrying `code: SEND_PACING_LIMITED`; a plugin veto stays a 400.- // Every gated sender's DTO addresses its destination as `chatId` except forward, which uses- // `toChatId` — without the fallback a forward skipped the cold-reachout gate entirely, while- // its persisted row still drained the cold budget. Edit carries a chatId too; the edited- // message's own row already makes that chat warm, so the gate is a no-op there.- const target = input as { chatId?: string; toChatId?: string };- await this.pacing.assertSendAllowed(sessionId, target.chatId ?? target.toChatId);- return applySendingGate(this.hookManager, sessionId, type, input, 'MessageService');+ sendDocument(sessionId: string, dto: SendMediaMessageDto): Promise<MessageResponseDto> {+ return this.sender.sendDocument(sessionId, dto);}- /**- * Mark a send as FAILED, fire the `message:failed` plugin hook, then throw a client-facing error.- * Centralised so failure notifications cover every sender (previously only `sendText` fired- * `message:failed`; media/extended sends failed silently to plugins). The post-send persistence-fault- * path (persistSentState) deliberately does NOT route here — a message the engine already accepted- * must never be reported as a send failure.- */- private async failSend(+ sendLocation(sessionId: string,- type: string,- message: Message,- input: unknown,- error: unknown,- ): Promise<never> {- // Only failures that say something about the account's standing feed the breaker: adapters also- // raise client-fault and engine-state errors from inside this call (a blocked media URL, an- // unsupported capability, a disconnected socket), and counting those let a client sending bad- // requests trip the breaker on a healthy session.- if (countsTowardSendBreaker(error)) {- this.pacing.recordSendFailure(sessionId);- }- await this.saveFailedMessage(message);- // Sanitize the hook payload: an SSRF block's raw .message names the resolved internal address- // (a recon/DNS-rebind oracle) — the client-facing throw below already maps it to a generic- // message via toClientFacingError, and the message:failed hook must not expose more than the- // client sees. Now that every media/extended sender routes here, this is the chokepoint that- // keeps SSRF detail out of plugin hands (bulk does the same via sanitizeBatchError).- const hookError =- error instanceof SsrfBlockedError- ? SSRF_BLOCKED_CLIENT_MESSAGE- : error instanceof Error- ? error.message- : String(error);- await this.hookManager.execute(- 'message:failed',- { sessionId, error: hookError, input, type },- { sessionId, source: 'MessageService' },- );- throw this.toClientFacingError(error);+ dto: {+ chatId: string;+ latitude: number;+ longitude: number;+ description?: string;+ address?: string;+ quotedMessageId?: string;+ },+ ): Promise<MessageResponseDto> {+ return this.sender.sendLocation(sessionId, dto);}- /**- * Resolve a stored template, render its body (with optional header/footer- * flattened using newlines) using the supplied variables, and delegate to the- * existing {@link sendText} path so plugin hooks, persistence, and status- * tracking are reused. Throws NotFoundException when the template cannot be- * resolved by id or name.- *- * The FINAL rendered text is capped at template.renderMaxChars (default 64 KiB): caller-supplied- * variables can inflate a small template unboundedly, so an over-cap render is rejected with a- * 400 naming the limit rather than truncated silently or pushed to the engine/DB as-is.- */- async sendTemplate(sessionId: string, dto: SendTemplateMessageDto): Promise<MessageResponseDto> {- const template = await this.templateService.resolve(sessionId, {- templateId: dto.templateId,- templateName: dto.templateName,- });-- const vars = dto.vars ?? {};- const segments = [template.header, template.body, template.footer]- .filter((segment): segment is string => segment != null && segment.length > 0)- .map(segment => renderTemplate(segment, vars));- const text = segments.join('\n\n');-- const maxChars =- this.configService?.get<number>('template.renderMaxChars', DEFAULT_TEMPLATE_RENDER_MAX_CHARS) ??- DEFAULT_TEMPLATE_RENDER_MAX_CHARS;- if (text.length > maxChars) {- throw new BadRequestException(- `Rendered template is ${text.length} characters, over the ${maxChars}-character limit`,- );- }-- return this.sendText(sessionId, { chatId: dto.chatId, text });+ sendContact(+ sessionId: string,+ dto: { chatId: string; contactName: string; contactNumber: string; quotedMessageId?: string },+ ): Promise<MessageResponseDto> {+ return this.sender.sendContact(sessionId, dto);}- async sendImage(sessionId: string, dto: SendMediaMessageDto): Promise<MessageResponseDto> {- const finalDto = await this.applySendingGate(sessionId, 'image', dto);- const engine = this.getEngine(sessionId);- const media = this.buildMediaInput(finalDto);-- // Save message as pending BEFORE sending- const message = await this.saveOutgoingMessage(sessionId, {- chatId: finalDto.chatId,- body: finalDto.caption || '',- type: 'image',- quotedMessageId: finalDto.quotedMessageId,- metadata: {- media: { mimetype: finalDto.mimetype, filename: finalDto.filename, data: media.data },- },- });-- let result: MessageResult;- try {- result = await engine.sendImageMessage(finalDto.chatId, media);- } catch (error) {- return this.failSend(sessionId, 'image', message, finalDto, error);- }- return this.persistSentState(message, result);+ sendPoll(+ sessionId: string,+ dto: { chatId: string; name: string; options: string[]; allowMultipleAnswers?: boolean; quotedMessageId?: string },+ ): Promise<MessageResponseDto> {+ return this.sender.sendPoll(sessionId, dto);}- async sendVideo(sessionId: string, dto: SendMediaMessageDto): Promise<MessageResponseDto> {- const finalDto = await this.applySendingGate(sessionId, 'video', dto);- const engine = this.getEngine(sessionId);- const media = this.buildMediaInput(finalDto);-- // Save message as pending BEFORE sending- const message = await this.saveOutgoingMessage(sessionId, {- chatId: finalDto.chatId,- body: finalDto.caption || '',- type: 'video',- quotedMessageId: finalDto.quotedMessageId,- metadata: {- media: { mimetype: finalDto.mimetype, filename: finalDto.filename, data: media.data },- },- });-- let result: MessageResult;- try {- result = await engine.sendVideoMessage(finalDto.chatId, media);- } catch (error) {- return this.failSend(sessionId, 'video', message, finalDto, error);- }- return this.persistSentState(message, result);+ sendSticker(sessionId: string, dto: SendMediaMessageDto): Promise<MessageResponseDto> {+ return this.sender.sendSticker(sessionId, dto);}- async sendAudio(sessionId: string, dto: SendAudioMessageDto): Promise<MessageResponseDto> {- // Label a PTT send 'voice' in the gate (not 'audio') so message:sending, message:failed, and the- // persisted row all carry the same type for one outbound voice note — failSend and the saved row- // already use `finalDto.ptt ? 'voice' : 'audio'`.- const finalDto = await this.applySendingGate(sessionId, dto.ptt ? 'voice' : 'audio', dto);- const engine = this.getEngine(sessionId);- // Voice notes need a real audio codec; default to ogg/opus when the caller omits a mimetype so the- // wire message and the persisted record agree. Resolved BEFORE buildMediaInput so its base64- // mimetype guard sees the effective type. buildMediaInput itself stays generic (shared by all media).- const audioDto =- finalDto.ptt && !finalDto.mimetype ? { ...finalDto, mimetype: 'audio/ogg; codecs=opus' } : finalDto;- const media = this.buildMediaInput(audioDto);- media.ptt = finalDto.ptt;-- // Save message as pending BEFORE sending. A PTT send is a 'voice' note (matches inbound- // classification, the outbound webhook echo, stats, and the dashboard), not a plain 'audio' file.- const message = await this.saveOutgoingMessage(sessionId, {- chatId: finalDto.chatId,- type: finalDto.ptt ? 'voice' : 'audio',- metadata: {- media: { mimetype: audioDto.mimetype, filename: finalDto.filename, data: media.data },- },- quotedMessageId: finalDto.quotedMessageId,- });-- let result: MessageResult;- try {- result = await engine.sendAudioMessage(finalDto.chatId, media);- } catch (error) {- return this.failSend(sessionId, finalDto.ptt ? 'voice' : 'audio', message, finalDto, error);- }- return this.persistSentState(message, result);+ reply(+ sessionId: string,+ dto: { chatId: string; quotedMessageId: string; text: string },+ ): Promise<MessageResponseDto> {+ return this.sender.reply(sessionId, dto);}- async sendDocument(sessionId: string, dto: SendMediaMessageDto): Promise<MessageResponseDto> {- const finalDto = await this.applySendingGate(sessionId, 'document', dto);- const engine = this.getEngine(sessionId);- const media = this.buildMediaInput(finalDto);-- // Save message as pending BEFORE sending- const message = await this.saveOutgoingMessage(sessionId, {- chatId: finalDto.chatId,- body: finalDto.caption || finalDto.filename || '',- type: 'document',- quotedMessageId: finalDto.quotedMessageId,- metadata: {- media: { mimetype: finalDto.mimetype, filename: finalDto.filename, data: media.data },- },- });+ forward(+ sessionId: string,+ dto: { fromChatId: string; toChatId: string; messageId: string },+ ): Promise<MessageResponseDto> {+ return this.sender.forward(sessionId, dto);+ }- let result: MessageResult;- try {- result = await engine.sendDocumentMessage(finalDto.chatId, media);- } catch (error) {- return this.failSend(sessionId, 'document', message, finalDto, error);- }- return this.persistSentState(message, result);+ /** Persist an outbound row; exposed for the bulk path, which reuses the send-persistence rules. */+ saveOutgoingMessage(sessionId: string, data: SaveOutgoingMessageData): Promise<Message> {+ return this.sender.saveOutgoingMessage(sessionId, data);}/**@@ -516,189 +300,6 @@ export class MessageService {return [...candidates];}- // ========== Phase 3: Extended Messaging ==========-- async sendLocation(- sessionId: string,- dto: {- chatId: string;- latitude: number;- longitude: number;- description?: string;- address?: string;- quotedMessageId?: string;- },- ): Promise<MessageResponseDto> {- const finalDto = await this.applySendingGate(sessionId, 'location', dto);- const engine = this.getEngine(sessionId);-- // Save message as pending BEFORE sending- const message = await this.saveOutgoingMessage(sessionId, {- chatId: finalDto.chatId,- body: `📍 ${finalDto.description || 'Location'}`,- type: 'location',- quotedMessageId: finalDto.quotedMessageId,- });-- let result: MessageResult;- try {- result = await engine.sendLocationMessage(finalDto.chatId, {- latitude: finalDto.latitude,- longitude: finalDto.longitude,- description: finalDto.description,- address: finalDto.address,- quotedMessageId: finalDto.quotedMessageId,- });- } catch (error) {- return this.failSend(sessionId, 'location', message, finalDto, error);- }- return this.persistSentState(message, result);- }-- async sendContact(- sessionId: string,- dto: { chatId: string; contactName: string; contactNumber: string; quotedMessageId?: string },- ): Promise<MessageResponseDto> {- const finalDto = await this.applySendingGate(sessionId, 'contact', dto);- const engine = this.getEngine(sessionId);-- // Save message as pending BEFORE sending- const message = await this.saveOutgoingMessage(sessionId, {- chatId: finalDto.chatId,- body: `📇 ${finalDto.contactName}`,- type: 'contact',- quotedMessageId: finalDto.quotedMessageId,- });-- let result: MessageResult;- try {- result = await engine.sendContactMessage(finalDto.chatId, {- name: finalDto.contactName,- number: finalDto.contactNumber,- quotedMessageId: finalDto.quotedMessageId,- });- } catch (error) {- return this.failSend(sessionId, 'contact', message, finalDto, error);- }- return this.persistSentState(message, result);- }-- async sendPoll(- sessionId: string,- dto: { chatId: string; name: string; options: string[]; allowMultipleAnswers?: boolean; quotedMessageId?: string },- ): Promise<MessageResponseDto> {- const finalDto = await this.applySendingGate(sessionId, 'poll', dto);- const engine = this.getEngine(sessionId);-- // Save message as pending BEFORE sending. A poll has no plain-text body, so store the- // question — that keeps the message history readable.- const message = await this.saveOutgoingMessage(sessionId, {- chatId: finalDto.chatId,- body: `📊 ${finalDto.name}`,- type: 'poll',- quotedMessageId: finalDto.quotedMessageId,- });-- let result: MessageResult;- try {- result = await engine.sendPollMessage(finalDto.chatId, {- name: finalDto.name,- options: finalDto.options,- allowMultipleAnswers: finalDto.allowMultipleAnswers === true,- quotedMessageId: finalDto.quotedMessageId,- });- } catch (error) {- return this.failSend(sessionId, 'poll', message, finalDto, error);- }- return this.persistSentState(message, result);- }-- async sendSticker(sessionId: string, dto: SendMediaMessageDto): Promise<MessageResponseDto> {- const finalDto = await this.applySendingGate(sessionId, 'sticker', dto);- const engine = this.getEngine(sessionId);- const media = this.buildMediaInput(finalDto);-- // Save message as pending BEFORE sending- const message = await this.saveOutgoingMessage(sessionId, {- chatId: finalDto.chatId,- type: 'sticker',- quotedMessageId: finalDto.quotedMessageId,- metadata: {- media: { mimetype: finalDto.mimetype, filename: finalDto.filename, data: media.data },- },- });-- let result: MessageResult;- try {- result = await engine.sendStickerMessage(finalDto.chatId, media);- } catch (error) {- return this.failSend(sessionId, 'sticker', message, finalDto, error);- }- return this.persistSentState(message, result);- }-- async reply(- sessionId: string,- dto: { chatId: string; quotedMessageId: string; text: string },- ): Promise<MessageResponseDto> {- const finalDto = await this.applySendingGate(sessionId, 'reply', dto);- const engine = this.getEngine(sessionId);-- // Resolve the quoted message body (best-effort) so the dashboard can render the reply preview.- let quotedBody = '';- try {- const quoted = await this.messageRepository.findOne({- where: { sessionId, waMessageId: finalDto.quotedMessageId },- });- quotedBody = quoted?.body || '';- } catch (err) {- this.logger.warn(`Failed to resolve quoted message ${finalDto.quotedMessageId}`, { error: String(err) });- }-- // Save message as pending BEFORE sending- const message = await this.saveOutgoingMessage(sessionId, {- chatId: finalDto.chatId,- body: finalDto.text,- type: 'text',- metadata: {- quotedMessage: { id: finalDto.quotedMessageId, body: quotedBody },- },- });-- let result: MessageResult;- try {- result = await engine.replyToMessage(finalDto.chatId, finalDto.quotedMessageId, finalDto.text);- } catch (error) {- return this.failSend(sessionId, 'reply', message, finalDto, error);- }- return this.persistSentState(message, result);- }-- async forward(- sessionId: string,- dto: { fromChatId: string; toChatId: string; messageId: string },- ): Promise<MessageResponseDto> {- const finalDto = await this.applySendingGate(sessionId, 'forward', dto);- const engine = this.getEngine(sessionId);-- // Save message as pending BEFORE sending- const message = await this.saveOutgoingMessage(sessionId, {- chatId: finalDto.toChatId,- body: '[Forwarded]',- type: 'forward',- });-- let result: MessageResult;- try {- result = await engine.forwardMessage(finalDto.fromChatId, finalDto.toChatId, finalDto.messageId);- } catch (error) {- return this.failSend(sessionId, 'forward', message, finalDto, error);- }- // persistSentState preserves the empty-id rule: a forward whose engine couldn't recover the sent- // copy's id leaves waMessageId NULL so no ack mis-matches it.- return this.persistSentState(message, result);- }-/*** Save incoming message (called from session webhook dispatch)*/@@ -711,189 +312,6 @@ export class MessageService {return this.messageRepository.save(message);}- /**- * Save outgoing message to database.- * When called before sending, creates a record with PENDING status; bulk send reuses this after a- * successful send (status SENT) so batch messages are persisted like single sends.- *- * A caller that already knows the engine id races the own-send echo on- * UNIQUE(sessionId, waMessageId) — only the bulk path does today, since every single send persists- * its PENDING row before the id exists. Losing that race merges onto the echo's row rather than- * failing, mirroring `persistSentState`: the echo carries only what the engine reported (for a- * Baileys API send, a media-less marker), so dropping this write would lose the media payload.- */- async saveOutgoingMessage(- sessionId: string,- data: {- waMessageId?: string;- chatId: string;- body?: string;- type: string;- timestamp?: number;- status?: MessageStatus;- metadata?: Record<string, unknown>;- /**- * Quoted id for a send that is a reply. Folded into `metadata.quotedMessage` here rather than- * by each sender so the nine send paths and `reply()` persist one shape — a row that quoted a- * message but records nothing is simply wrong history, and the dashboard reads this key to- * render the reply preview. The body is left empty: unlike `reply()`, the send paths do not- * look the quoted message up, and '' is already reply()'s own value when that lookup fails.- */- quotedMessageId?: string;- },- ): Promise<Message> {- const session = await this.sessionService.findOne(sessionId);- const message = this.messageRepository.create({- sessionId,- // An engine that sent a message but could not read its id back reports an empty id (see the- // whatsapp-web.js adapter's `toMessageResult`). Store NULL rather than '': the- // (sessionId, waMessageId) unique index is not partial, so a second id-less send in the same- // session collides on '' while NULLs stay exempt — and in the bulk path that violation is- // swallowed into a warning, losing the row silently. Normalizing at this one chokepoint covers- // every caller instead of relying on each to remember.- waMessageId: data.waMessageId || undefined,- chatId: data.chatId,- from: session?.phone || 'me',- to: data.chatId,- body: data.body,- type: data.type,- direction: MessageDirection.OUTGOING,- timestamp: data.timestamp,- status: data.status ?? MessageStatus.PENDING,- metadata: data.quotedMessageId- ? { ...data.metadata, quotedMessage: { id: data.quotedMessageId, body: '' } }- : data.metadata,- });- const saved = await this.messageRepository.save(message).catch(async (err: unknown) => {- const waMessageId = message.waMessageId;- if (!waMessageId || !isUniqueConstraintError(err)) throw err;- const patch: QueryDeepPartialEntity<Message> = {- status: message.status,- timestamp: message.timestamp,- };- // Only when this write actually carries metadata worth merging: a text item must not blank- // the echo's, and a URL pointer must not replace bytes the engine already downloaded.- if (message.metadata && !isUrlPointerMetadata(message.metadata)) {- patch.metadata = message.metadata as QueryDeepPartialEntity<Record<string, unknown>>;- }- await this.messageRepository.update({ sessionId, waMessageId }, patch);- const surviving = await this.messageRepository.findOne({ where: { sessionId, waMessageId } });- if (!surviving) throw err;- return surviving;- });- this.emitPersisted(sessionId, saved);- return saved;- }-- // Fire-and-forget: a plugin handler must never break the send path. The built-in FTS search provider- // is DB-synced and does NOT consume this; it exists for plugin providers (Spec 2) + general use.- // Emitted for EVERY persisted state of an outbound row — the initial PENDING write AND each later- // transition (SENT / FAILED / merge) — so a provider's copy never stays stuck at PENDING (#906).- // The payload is a shallow snapshot: the same entity instance is mutated as the send progresses- // (PENDING → SENT/FAILED), and fire-and-forget execution must still see the state at emission time.- //- // Outbound archiving rides the same chokepoint rather than a call at each of the four persist- // sites: every terminal state of an outbound row passes here. Gated on SENT because a PENDING row- // may still be deleted by the dedup merge or rewritten by the pending reaper, and a FAILED one has- // had its payload stripped — archiving either would strand a file the row never points at.- private emitPersisted(sessionId: string, message: Message): void {- void this.hookManager- .execute('message:persisted', { sessionId, message: { ...message } }, { sessionId, source: 'MessageService' })- .catch(() => undefined);- if (message.status === MessageStatus.SENT && this.archiveOutboundEnabled) {- void this.chatMediaArchive?.archive(message).catch(() => undefined);- }- }-- /** Whether media this account sent is archived too — a sub-flag of the archive itself. */- private get archiveOutboundEnabled(): boolean {- return this.configService?.get<boolean>('chatMedia.archiveOutbound', false) === true;- }-- /**- * Persist a send as FAILED, dropping any outbound media payload first. A failed row's media base64- * (often multi-MB) is never displayed or retried, so keeping it only bloats the messages table; the- * mimetype/filename are kept so the row still describes what was attempted.- */- private async saveFailedMessage(message: Message): Promise<void> {- const media = (message.metadata as { media?: { data?: unknown } } | undefined)?.media;- if (media) {- delete media.data;- }- message.status = MessageStatus.FAILED;- await this.messageRepository.save(message);- // Reconcile the earlier PENDING emission (#906): a provider must see the terminal FAILED state.- this.emitPersisted(message.sessionId, message);- }-- /**- * Persist the SENT state AFTER the engine has already accepted the message. The send already- * succeeded, so a failure to write the SENT row must NOT be surfaced as a send failure — a transient- * DB fault would otherwise mark a delivered message permanently FAILED and (for text) fire- * `message:failed`. Log and return success instead.- */- private async persistSentState(message: Message, result: MessageResult): Promise<MessageResponseDto> {- // A send whose engine couldn't read the sent message's id back reports an empty id — a forward that- // can't recover the copy, or a WhatsApp Web build that renamed the id field out from under the- // engine. Leave waMessageId unset (NULL) so no ack mis-matches it.- // The engine accepted the message, so whatever streak the breaker was tracking is over. Recorded- // here rather than at each call site for the same reason failSend is: one funnel, twelve senders.- this.pacing.recordSendSuccess(message.sessionId);- if (result.id) message.waMessageId = result.id;- message.status = MessageStatus.SENT;- message.timestamp = result.timestamp;- try {- await this.messageRepository.save(message);- // Reconcile the earlier PENDING emission with the finalized row (#906).- this.emitPersisted(message.sessionId, message);- } catch (persistError) {- if (result.id && isUniqueConstraintError(persistError)) {- // The engine's own-send echo (onMessageCreate) won the race and already persisted a row with- // this waMessageId. That row carries only what the engine reported — for a Baileys API send,- // a media-less marker — so merge our SENT state AND our metadata (the actual media payload)- // onto it BEFORE dropping this redundant PENDING row, or the payload-bearing row is the one- // that gets deleted and the media is gone after a reload.- // Best-effort throughout: the send itself already succeeded.- this.logger.debug(- `Send echo already persisted ${result.id}; merging state and dropping the redundant pending row`,- {- messageId: message.id,- },- );- const patch: QueryDeepPartialEntity<Message> = { status: MessageStatus.SENT, timestamp: result.timestamp };- if (message.metadata && !isUrlPointerMetadata(message.metadata)) {- patch.metadata = message.metadata as QueryDeepPartialEntity<Record<string, unknown>>;- }- await this.messageRepository- .update({ sessionId: message.sessionId, waMessageId: result.id }, patch)- .catch(err =>- this.logger.warn(`Merging SENT state onto the echo-persisted row failed (id=${result.id})`, {- error: err instanceof Error ? err.message : String(err),- }),- );- await this.messageRepository.delete({ id: message.id }).catch(() => undefined);- // Reconcile provider indexes (#906): upsert the surviving echo row (now carrying our SENT- // state + media) and drop the ghost PENDING document this redundant row produced earlier.- const surviving = await this.messageRepository- .findOne({ where: { sessionId: message.sessionId, waMessageId: result.id } })- .catch(() => null);- if (surviving) this.emitPersisted(message.sessionId, surviving);- void this.hookManager- .execute(- 'message:deleted',- { sessionId: message.sessionId, message: { ...message } },- { sessionId: message.sessionId, source: 'MessageService' },- )- .catch(() => undefined);- } else {- this.logger.warn(`Persisting SENT state failed after a successful send (id=${result.id})`, {- error: persistError instanceof Error ? persistError.message : String(persistError),- });- }- }- return { messageId: result.id, timestamp: result.timestamp };- }-// ========== Phase 3: Reactions ==========async reactToMessage(sessionId: string, dto: { chatId: string; messageId: string; emoji: string }): Promise<void> {@@ -1078,74 +496,32 @@ export class MessageService {return { messageId: result.id, timestamp: result.timestamp };}+ /**+ * Run the pre-send `message:sending` plugin gate for one outbound message and return the+ * (possibly plugin-modified) input, or throw BadRequestException if a plugin blocked the send.+ * Centralised so EVERY public sender — text, media, extended (location/contact/poll/sticker/+ * reply/forward) and edit — passes through the same moderation chokepoint, instead of only+ * `sendText`. The implementation is shared with StatusService via core/hooks/sending-gate.+ */+ private async applySendingGate<T extends object>(sessionId: string, type: string, input: T): Promise<T> {+ // Pacing runs BEFORE the plugin gate, so a send that policy forbids never reaches a plugin at+ // all — plugins should not be asked to moderate, or given the chance to rewrite, traffic that is+ // not going to be sent. The consequence is deliberate and documented in the hook contract: a+ // paced-out send fires no `message:sending`, so a plugin cannot observe it. Refusals are a 429+ // carrying `code: SEND_PACING_LIMITED`; a plugin veto stays a 400.+ // Every gated sender's DTO addresses its destination as `chatId` except forward, which uses+ // `toChatId` — without the fallback a forward skipped the cold-reachout gate entirely, while+ // its persisted row still drained the cold budget. Edit carries a chatId too; the edited+ // message's own row already makes that chat warm, so the gate is a no-op there.+ const target = input as { chatId?: string; toChatId?: string };+ await this.pacing.assertSendAllowed(sessionId, target.chatId ?? target.toChatId);+ return applySendingGate(this.hookManager, sessionId, type, input, 'MessageService');+ }+private getEngine(sessionId: string) {return this.engines.require(sessionId,() => new BadRequestException(`Session '${sessionId}' is not active. Start the session first.`),);}-- /**- * Humanising delay: show the engine's typing indicator and pause for a length-scaled, jittered- * interval before the real send, so automated single sends don't look instantaneous (anti-ban).- * ON by default — set `SIMULATE_TYPING=false` to disable. Engine-agnostic (goes through- * `sendChatState`) and strictly best-effort — it never throws and never blocks the send if presence- * fails or the engine has no presence concept. `SIMULATE_TYPING_MAX_MS` (default 5000) caps the pause.- * Note: this covers single sends only; bulk sends use their own `delayBetweenMessages` throttle.- */- private async simulateTypingIfEnabled(engine: IWhatsAppEngine, chatId: string, text: string): Promise<void> {- const { simulateTyping, simulateTypingMaxMs } = resolveFeatureFlags(this.configService);- if (!simulateTyping) return;- try {- await engine.sendChatState(chatId, 'typing');- const maxMs = simulateTypingMaxMs;- const planned = Math.min(maxMs, 500 + text.length * 45);- const jittered = Math.round(planned * (0.85 + Math.random() * 0.3)); // ±15% so it isn't metronomic- await new Promise(resolve => setTimeout(resolve, jittered));- } catch (error) {- this.logger.warn(`simulateTyping skipped: ${error instanceof Error ? error.message : String(error)}`);- }- }-- /**- * Map a blocked outbound media fetch (SSRF guard) to an HTTP 400 so a- * caller-supplied internal/unsafe URL returns a client error instead of a 500.- * The raw guard message names the resolved internal IP (a recon/DNS-rebind oracle), so return a- * generic message to the client and keep the detail in the server log only. Others pass through.- */- private toClientFacingError(error: unknown): unknown {- if (error instanceof SsrfBlockedError) {- this.logger.warn(`Outbound media fetch blocked by SSRF guard: ${error.message}`);- return new BadRequestException(SSRF_BLOCKED_CLIENT_MESSAGE);- }- return error;- }-- private buildMediaInput(dto: SendMediaMessageDto): MediaInput {- const base64 = stripBase64DataUri(dto.base64);- if (!dto.url && !base64) {- throw new BadRequestException('Either url or base64 must be provided');- }-- if (base64 && !dto.mimetype) {- throw new BadRequestException('mimetype is required when using base64 data');- }-- // Bound an outbound base64 payload to the same byte cap as URL/inbound media, before it is- // persisted or handed to the engine. URL media is already capped while streaming.- assertBase64WithinMediaCap(base64);-- return {- mimetype: dto.mimetype || 'application/octet-stream',- // base64 wins over url when both are present: it is the explicit local payload, and a stale- // `url` (e.g. a Swagger/example default left in the body) must not be fetched in its place.- // Aligns the send selection with the base64-first persisted metadata and the url field's- // `@ValidateIf((o) => !o.base64)` (which skips @IsUrl when base64 is present) — #670.- data: base64 || dto.url!,- filename: dto.filename,- caption: dto.caption,- mentions: dto.mentions,- quotedMessageId: dto.quotedMessageId,- };- }}diff --git a/src/modules/message/send-pacing.service.spec.ts b/src/modules/message/send-pacing.service.spec.tsindex 2c97928b1..4d2957307 100644--- a/src/modules/message/send-pacing.service.spec.ts+++ b/src/modules/message/send-pacing.service.spec.ts@@ -15,7 +15,7 @@ import { MessageDirection, type Message } from './entities/message.entity';import type { Session } from '../session/entities/session.entity';import type { Repository } from 'typeorm';import type { ConfigService } from '@nestjs/config';-import { MessageService } from './message.service';+import { MessageSendService } from './message-send.service';import { BulkMessageService } from './bulk-message.service';import { StatusService } from '../status/status.service';import { CatalogService } from '../catalog/catalog.service';@@ -299,18 +299,16 @@ describe('send paths consult the governor', () => {assertSendAllowed: jest.fn().mockRejectedValue(new HttpException({ code: SEND_PACING_LIMITED }, 429)),});- it('MessageService refuses before the plugin gate runs and before the engine is asked', async () => {+ it('MessageSendService refuses before the plugin gate runs and before the engine is asked', async () => {const hookManager = { execute: jest.fn() };const engine = { sendTextMessage: jest.fn() };const pacing = refusing();- const service = new MessageService(+ const service = new MessageSendService({ save: jest.fn() } as never,{ isActive: () => true } as never,{ get: () => engine, require: () => engine } as never,- {} as never,hookManager as never,{} as never,- {} as never,pacing as never,);