import type { Context } from 'hono' import { beforeEach, describe, expect, it, vi } from 'vitest' const { connectMock, mailerSendMock, closeMock, env } = vi.hoisted(() => ({ connectMock: vi.fn(), mailerSendMock: vi.fn(async (_email: unknown) => {}), closeMock: vi.fn(async () => {}), env: {} as Record, })) vi.mock('worker-mailer', () => ({ WorkerMailer: { connect: connectMock } })) vi.mock('../supabase/functions/_backend/utils/logging.ts', async () => ({ ...await vi.importActual('../supabase/functions/_backend/utils/logging.ts'), cloudlog: vi.fn(), })) vi.mock('../supabase/functions/_backend/utils/utils.ts', async () => ({ ...await vi.importActual('../supabase/functions/_backend/utils/utils.ts'), getEnv: (_c: unknown, key: string) => env[key] ?? '', })) const { sendCloudflareEmail, isEmailDeliveryConfigured } = await import('../cloudflare_workers/api/email_templates/send.ts') const content = { subject: 'Confirm your Capgo.app email', html: '

Hi

', text: 'Hi' } function context(binding?: { send: ReturnType }) { return { env: binding ? { AUTH_EMAIL: binding } : {}, get: () => 'request-id' } as unknown as Context } function setEnv(values: Record) { for (const key of Object.keys(env)) delete env[key] Object.assign(env, values) } describe('email delivery: Cloudflare binding first, SMTP fallback', () => { beforeEach(() => { vi.clearAllMocks() setEnv({}) connectMock.mockResolvedValue({ send: mailerSendMock, close: closeMock }) }) it('uses the AUTH_EMAIL binding when it exists, even with SMTP configured', async () => { setEnv({ SMTP_HOST: 'smtp.example.com' }) const binding = { send: vi.fn(async () => ({ messageId: 'cf-id' })) } const messageId = await sendCloudflareEmail(context(binding), 'user@example.com', content, {}) expect(messageId).toBe('cf-id') expect(binding.send).toHaveBeenCalledWith({ to: 'user@example.com', from: 'noreply@capgo.app', ...content }) expect(connectMock).not.toHaveBeenCalled() }) it('sends over SMTP with TLS from the first byte when there is no binding', async () => { setEnv({ SMTP_HOST: ' smtp.example.com ', SMTP_USER: 'mailer', SMTP_PASS: 'secret' }) const messageId = await sendCloudflareEmail(context(), 'user@example.com', content, {}) expect(connectMock).toHaveBeenCalledWith(expect.objectContaining({ host: 'smtp.example.com', port: 465, secure: true, startTls: false, credentials: { username: 'mailer', password: 'secret' }, })) expect(messageId).toMatch(/^<[0-9a-f-]+@capgo\.app>$/) expect(mailerSendMock).toHaveBeenCalledWith(expect.objectContaining({ from: 'noreply@capgo.app', to: 'user@example.com', subject: content.subject, html: content.html, text: content.text, headers: { 'Message-ID': messageId }, })) expect(closeMock).toHaveBeenCalledOnce() }) it('never enables STARTTLS; SMTP_TLS=false means plain SMTP for local development', async () => { setEnv({ SMTP_HOST: '127.0.0.1', SMTP_PORT: '54325', SMTP_TLS: 'false' }) await sendCloudflareEmail(context(), 'user@example.com', content, {}) expect(connectMock).toHaveBeenCalledWith(expect.objectContaining({ port: 54325, secure: false, startTls: false, credentials: undefined })) }) it('uses EMAIL_FROM as the sender on both paths', async () => { setEnv({ SMTP_HOST: 'smtp.example.com', EMAIL_FROM: 'auth@self-host.example' }) const messageId = await sendCloudflareEmail(context(), 'user@example.com', content, {}) expect(mailerSendMock).toHaveBeenCalledWith(expect.objectContaining({ from: 'auth@self-host.example' })) expect(messageId).toMatch(/@self-host\.example>$/) const binding = { send: vi.fn(async () => ({ messageId: 'cf-id' })) } await sendCloudflareEmail(context(binding), 'user@example.com', content, {}) expect(binding.send).toHaveBeenCalledWith(expect.objectContaining({ from: 'auth@self-host.example' })) }) it('maps invoice attachments to the worker-mailer shape', async () => { setEnv({ SMTP_HOST: 'smtp.example.com' }) await sendCloudflareEmail(context(), 'billing@example.com', { ...content, attachments: [{ filename: 'invoice-EX-1.pdf', content: 'JVBERi0=', type: 'application/pdf', disposition: 'attachment' }], }, {}) expect(mailerSendMock).toHaveBeenCalledWith(expect.objectContaining({ attachments: [{ filename: 'invoice-EX-1.pdf', content: 'JVBERi0=', mimeType: 'application/pdf' }], })) }) it.each([ ['recipient', 'user@example.com\r\nRCPT TO:', content], ['subject', 'user@example.com', { ...content, subject: 'Hi\r\nBcc: other@example.com' }], ])('rejects a line break in the %s before connecting', async (_field, to, message) => { setEnv({ SMTP_HOST: 'smtp.example.com' }) await expect(sendCloudflareEmail(context(), to, message, {})).rejects.toThrow('line break') expect(connectMock).not.toHaveBeenCalled() }) it('rejects an invalid SMTP_PORT before connecting', async () => { setEnv({ SMTP_HOST: 'smtp.example.com', SMTP_PORT: '465abc' }) await expect(sendCloudflareEmail(context(), 'user@example.com', content, {})).rejects.toThrow('SMTP_PORT') expect(connectMock).not.toHaveBeenCalled() }) it('closes the connection and fails when the SMTP server rejects the email', async () => { setEnv({ SMTP_HOST: 'smtp.example.com' }) mailerSendMock.mockRejectedValueOnce(new Error('550 rejected')) await expect(sendCloudflareEmail(context(), 'user@example.com', content, {})).rejects.toThrow('550 rejected') expect(closeMock).toHaveBeenCalledOnce() }) it('fails with the existing error when neither the binding nor SMTP is configured', async () => { expect(isEmailDeliveryConfigured(context())).toBe(false) await expect(sendCloudflareEmail(context(), 'user@example.com', content, {})).rejects.toMatchObject({ status: 500 }) expect(connectMock).not.toHaveBeenCalled() }) it('reports delivery as configured with either the binding or SMTP_HOST', () => { expect(isEmailDeliveryConfigured(context({ send: vi.fn() }))).toBe(true) setEnv({ SMTP_HOST: 'smtp.example.com' }) expect(isEmailDeliveryConfigured(context())).toBe(true) }) })