Files
ipal-kit/test/emailTransports.test.ts
T
2026-11-13 16:24:27 +01:00

206 lines
8.0 KiB
TypeScript

import type { BasePayload, PayloadEmailAdapter } from 'payload'
import { createServer, type Server } from 'node:net'
import { afterAll, afterEach, beforeAll, describe, expect, test, vi } from 'vitest'
import { clearGraphTokenCache } from '../src/modules/email/graphAdapter.js'
import { mailAdapter } from '../src/modules/email/mailAdapter.js'
import { panelSmtpAdapter } from '../src/modules/email/panelSmtpAdapter.js'
import { sendEmail } from '../src/modules/email/sendEmail.js'
import { fakePayload } from './helpers.js'
vi.mock('server-only', () => ({}))
type Received = { auth: string[]; data: string; from: string; to: string[] }
/**
* Minimal plain-text SMTP server: just enough of RFC 5321 for nodemailer to
* authenticate and deliver one message per connection. No STARTTLS is
* advertised, so the real nodemailer client talks to it in the clear.
*/
function startSmtpServer(received: Received[]): Promise<{ port: number; server: Server }> {
const server = createServer((socket) => {
const mail: Received = { auth: [], data: '', from: '', to: [] }
let inData = false
let buffer = ''
const reply = (line: string) => socket.write(`${line}\r\n`)
reply('220 localhost ESMTP test')
socket.on('data', (chunk) => {
buffer += chunk.toString('utf8')
let index: number
while ((index = buffer.indexOf('\r\n')) >= 0) {
const line = buffer.slice(0, index)
buffer = buffer.slice(index + 2)
if (inData) {
if (line === '.') {
inData = false
received.push(mail)
reply('250 2.0.0 Ok: queued as TEST1')
} else {
mail.data += `${line.startsWith('..') ? line.slice(1) : line}\n`
}
continue
}
const command = line.toUpperCase()
if (command.startsWith('EHLO')) {
socket.write('250-localhost\r\n250-AUTH PLAIN LOGIN\r\n250 8BITMIME\r\n')
} else if (command.startsWith('AUTH PLAIN')) {
mail.auth.push(Buffer.from(line.slice(11), 'base64').toString('utf8'))
reply('235 2.7.0 Authentication successful')
} else if (command.startsWith('MAIL FROM:')) {
mail.from = line.slice(10).trim()
reply('250 2.1.0 Ok')
} else if (command.startsWith('RCPT TO:')) {
mail.to.push(line.slice(8).trim())
reply('250 2.1.5 Ok')
} else if (command === 'DATA') {
inData = true
reply('354 End data with <CR><LF>.<CR><LF>')
} else if (command === 'QUIT') {
reply('221 2.0.0 Bye')
socket.end()
} else {
reply('502 5.5.2 Command not recognized')
}
}
})
})
return new Promise((resolve) => {
server.listen(0, '127.0.0.1', () => {
const address = server.address()
resolve({ port: typeof address === 'object' && address ? address.port : 0, server })
})
})
}
const buildAdapter = (adapter: PayloadEmailAdapter, payload: BasePayload) =>
adapter({ payload } as Parameters<PayloadEmailAdapter>[0])
describe('e-mail transports (nodemailer 10)', () => {
const received: Received[] = []
let port = 0
let server: Server
beforeAll(async () => {
;({ port, server } = await startSmtpServer(received))
})
afterAll(async () => {
await new Promise((resolve) => server.close(resolve))
})
afterEach(() => {
received.length = 0
clearGraphTokenCache()
vi.unstubAllEnvs()
vi.unstubAllGlobals()
})
const smtpSettings = () => ({
smtpFromAddress: '[email protected]',
smtpFromName: 'Example Office',
smtpHost: '127.0.0.1',
smtpPassword: 'test-password',
smtpPort: port,
smtpUser: 'mailer',
})
test('panelSmtpAdapter delivers over SMTP with the panel sender and a single-line subject', async () => {
const { payload } = fakePayload({ integrations: smtpSettings() })
const adapter = buildAdapter(panelSmtpAdapter(), payload)
const result = await adapter.sendEmail({
html: '<p>Hello</p>',
subject: 'New lead\r\nBcc: [email protected]',
to: '[email protected]',
})
expect(result).toMatchObject({ sent: true })
expect((result as { messageId: string }).messageId).toMatch(/^<[^@>]+@[^@>]+>$/)
expect(received).toHaveLength(1)
const [mail] = received
expect(mail.auth).toEqual(['\0mailer\0test-password'])
expect(mail.from).toBe('<[email protected]>')
expect(mail.to).toEqual(['<[email protected]>'])
expect(mail.data).toContain('From: Example Office <[email protected]>')
expect(mail.data).toContain('Subject: New lead Bcc: [email protected]')
expect(mail.data).not.toMatch(/^Bcc:/m)
expect(mail.data).toContain('<p>Hello</p>')
})
test('sendEmail helper delivers over SMTP and returns the message id', async () => {
const { payload } = fakePayload({ integrations: smtpSettings() })
const result = await sendEmail({
html: '<p>Hi</p>',
payload,
replyTo: '[email protected]',
subject: 'Contact',
text: 'Hi',
to: ['[email protected]', '[email protected]'],
})
expect(result).toMatchObject({ sent: true })
expect(received[0].to).toEqual(['<[email protected]>', '<[email protected]>'])
expect(received[0].data).toContain('Reply-To: [email protected]')
})
test('an unreachable SMTP server is reported, not thrown, and the status is recorded', async () => {
const { payload } = fakePayload({ integrations: { ...smtpSettings(), smtpPort: 1 } })
const adapter = buildAdapter(mailAdapter(), payload)
const result = await adapter.sendEmail({ html: '<p>x</p>', subject: 'x', to: '[email protected]' })
expect(result).toMatchObject({ error: 'The e-mail was not sent.', sent: false })
expect(payload.updateGlobal).toHaveBeenCalledWith(
expect.objectContaining({
data: expect.objectContaining({
emailStatus: expect.objectContaining({ code: 'smtp-error', state: 'degraded' }),
}),
}),
)
})
test('mailAdapter sends over Microsoft Graph when selected and configured', async () => {
vi.stubEnv('GRAPH_TENANT_ID', 'tenant')
vi.stubEnv('GRAPH_CLIENT_ID', 'client')
vi.stubEnv('GRAPH_CLIENT_SECRET', 'secret')
vi.stubEnv('GRAPH_SENDER', '[email protected]')
const fetchMock = vi.fn(async (url: string) =>
url.includes('login.microsoftonline.com')
? new Response(JSON.stringify({ access_token: 'token-1' }), { status: 200 })
: new Response(null, { status: 202 }),
)
vi.stubGlobal('fetch', fetchMock)
const { payload } = fakePayload({ integrations: { ...smtpSettings(), emailTransport: 'graph' } })
const adapter = buildAdapter(mailAdapter(), payload)
const result = await adapter.sendEmail({ html: '<p>Graph</p>', subject: 'Via Graph', to: '[email protected]' })
expect(result).toEqual({ sent: true })
expect(received).toHaveLength(0)
expect(fetchMock).toHaveBeenCalledTimes(2)
const [url, init] = fetchMock.mock.calls[1] as unknown as [string, RequestInit]
expect(url).toBe('https://graph.microsoft.com/v1.0/users/forms%40example.com/sendMail')
expect((init.headers as Record<string, string>).Authorization).toBe('Bearer token-1')
const body = JSON.parse(init.body as string) as { message: Record<string, unknown> }
expect(body.message).toMatchObject({
from: { emailAddress: { name: 'Example Office', address: '[email protected]' } },
replyTo: [{ emailAddress: { address: '[email protected]' } }],
subject: 'Via Graph',
toRecipients: [{ emailAddress: { address: '[email protected]' } }],
})
})
test('mailAdapter falls back to SMTP when Graph is selected but not configured', async () => {
const { payload } = fakePayload({ integrations: { ...smtpSettings(), emailTransport: 'graph' } })
const adapter = buildAdapter(mailAdapter(), payload)
const result = await adapter.sendEmail({ html: '<p>x</p>', subject: 'Fallback', to: '[email protected]' })
expect(result).toMatchObject({ sent: true })
expect(received).toHaveLength(1)
expect(payload.logger.warn).toHaveBeenCalled()
})
})