Dependency advisories: nodemailer 10, overrides for Payload's pinned deps
- nodemailer ^8.0.1 -> ^10.2.1 (advisories up to 10.1.3); drop @types/nodemailer, nodemailer 10 ships its own types. Node engines >=20.9.0 (nodemailer 10 needs 20+). - pnpm.overrides (repo only, not passed to projects) for packages in payload 3.90.2's tree: undici and dompurify are exact-pinned upstream; fast-uri, js-yaml, browserslist, source-map-js, fast-copy, baseline-browser-mapping raised to fixed minimums. pnpm audit --prod: 19 high / 35 moderate / 11 low -> 0. - Tests: SMTP over a local SMTP socket with real nodemailer (panelSmtpAdapter, sendEmail, unreachable server status), Microsoft Graph and Graph->SMTP fallback via mailAdapter; real payloadTotp through ipalKit, plus a check that payload-2fa resolves the project's payload. - Docs: email.md, AGENT.md §4 item 12, ipal-setup, ipal-upgrade, README. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
54fb57b7a9
commit
007a0a3ae6
@@ -0,0 +1,203 @@
|
||||
import type { BasePayload, PayloadEmailAdapter } from 'payload'
|
||||
|
||||
import { createServer, type Server } from 'node:net'
|
||||
import { afterAll, afterEach, beforeAll, describe, expect, test, vi } from 'vitest'
|
||||
|
||||
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
|
||||
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()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,45 @@
|
||||
import type { Config, TextField } from 'payload'
|
||||
|
||||
import { payloadTotp } from '@clocklimited/payload-2fa'
|
||||
import { realpathSync } from 'node:fs'
|
||||
import { createRequire } from 'node:module'
|
||||
import { describe, expect, test } from 'vitest'
|
||||
|
||||
import type { I18nConfig } from '../src/modules/i18n/types.js'
|
||||
|
||||
import { ipalKit } from '../src/plugin.js'
|
||||
|
||||
const i18n: I18nConfig = { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] }
|
||||
|
||||
const require = createRequire(import.meta.url)
|
||||
/** Real path of the `payload` entry that `fromFile` would load. */
|
||||
const payloadSeenFrom = (fromFile: string) => realpathSync(createRequire(fromFile).resolve('payload'))
|
||||
|
||||
describe('@clocklimited/payload-2fa with the real plugin', () => {
|
||||
test('uses the same payload as the project (peer dependency, no second copy)', () => {
|
||||
const twoFactorEntry = realpathSync(require.resolve('@clocklimited/payload-2fa'))
|
||||
expect(payloadSeenFrom(twoFactorEntry)).toBe(payloadSeenFrom(import.meta.url))
|
||||
})
|
||||
|
||||
test('ipalKit wraps the auth collection with TOTP: secret field, strategy and setup view', async () => {
|
||||
const config = await ipalKit({
|
||||
access: { authCollection: 'users' },
|
||||
i18n,
|
||||
twoFactor: { issuer: 'Example', plugin: payloadTotp },
|
||||
})({ collections: [], secret: 'x' } as unknown as Config)
|
||||
|
||||
const users = config.collections?.find((c) => c.slug === 'users')
|
||||
const secret = users?.fields.find(
|
||||
(f): f is TextField => 'name' in f && f.name === 'totpSecret' && f.type === 'text',
|
||||
)
|
||||
expect(secret).toBeDefined()
|
||||
expect(secret?.admin?.hidden).toBe(true)
|
||||
// The TOTP secret is never readable over the API.
|
||||
expect((secret?.access?.read as () => boolean)()).toBe(false)
|
||||
|
||||
const auth = users?.auth
|
||||
expect(typeof auth === 'object' && auth.strategies?.length).toBeGreaterThan(0)
|
||||
expect(config.admin?.components?.views?.SetupTOTP).toBeDefined()
|
||||
expect(config.admin?.components?.views?.VerifyTOTP).toBeDefined()
|
||||
})
|
||||
})
|
||||
Reference in New Issue
Block a user