Files
ipal-kit/src/modules/email/panelSmtpAdapter.ts
T
radoslaw.smolinskiandClaude Opus 5.5 ab854ef37a MCP site tools, Turnstile key alert, required 2FA injection, a11y, more tests
- MCP: new get_site_info and list_pages tools (public by design, published
  and indexable content only); search results collapse the homepage to root.
  New listContent() helper shared with searchContent.
- Dashboard alert when Turnstile is half-configured (it is silently off then).
- twoFactor.plugin is now required; the dynamic-import fallback (which never
  worked under Next and caused a Turbopack warning) is gone.
- a11y: cookie category checkboxes are labelled, buttons have type, test-email
  input is labelled; tab labels keep localized collection labels.
- IPAL_IP_HEADER: one-time production warning when unset, opt-in
  ipalEnvRules({ ipHeader: true }).
- Tests: SEO/robots/sitemap/hreflang, CSP, Markdown, consent, MCP, and a real
  Payload + SQLite integration test for forms and the roles guard (74 total).
- Drop unused mongodb-memory-server; dev .env.example for SQLite.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-16 01:15:19 +02:00

109 lines
4.2 KiB
TypeScript

import type { PayloadEmailAdapter, SendEmailOptions } from 'payload'
import { getSiteIntegrations } from '../payload/index.js'
/** SMTP fields the adapter reads from SiteIntegrations. */
type SmtpIntegrations = {
smtpFromAddress?: null | string
smtpFromName?: null | string
smtpHost?: null | string
smtpPassword?: null | string
smtpPort?: null | number
smtpUser?: null | string
}
export type PanelSmtpAdapterArgs = {
/**
* Used only until the panel is filled in — Payload requires a from-address
* synchronously at boot, before any global can be read. Once SiteIntegrations
* has an address, it wins.
*/
fallbackFromAddress?: string
fallbackFromName?: string
}
/**
* Payload email adapter backed by the SMTP settings in the SiteIntegrations
* global.
*
* Why this exists: Payload builds its email adapter once, at boot, from the
* config — which would normally mean SMTP credentials living in env vars and a
* redeploy to change them. This adapter instead resolves SMTP on every send, so
* an editor can change the mailbox in the admin panel and the next email uses
* it.
*
* Wiring it into the config means `payload.sendEmail` works everywhere — which
* includes the form-builder's own submission emails (the ones an editor
* configures per form under "Emails"). Those go out over the panel's SMTP with
* no extra code.
*
* Boot-time constraints shape two details:
* - `defaultFromAddress` / `defaultFromName` must be returned synchronously, so
* they're placeholders; the real from-address is applied per message below.
* - nodemailer is imported dynamically inside sendEmail, so merely loading the
* Payload config (or running `generate:importmap`) doesn't pull it in.
*/
export const panelSmtpAdapter =
(args: PanelSmtpAdapterArgs = {}): PayloadEmailAdapter =>
({ payload }) => ({
name: 'ipal-panel-smtp',
defaultFromAddress: args.fallbackFromAddress ?? 'noreply@localhost',
defaultFromName: args.fallbackFromName ?? 'Website',
sendEmail: async (message: SendEmailOptions) => {
const smtp = await getSiteIntegrations<SmtpIntegrations>(payload)
const host = smtp.smtpHost
const port = smtp.smtpPort ?? 587
const user = smtp.smtpUser
const pass = smtp.smtpPassword
if (!host || !user || !pass) {
payload.logger.error(
'[ipal] Email not sent: SMTP is not configured in Site Integrations.',
)
return { error: 'SMTP is not configured in Site Integrations.', sent: false }
}
// The panel is the source of truth for the sender; fall back to whatever
// the caller set (Payload fills in defaultFromAddress when unset).
const fromAddress = smtp.smtpFromAddress
const fromName = smtp.smtpFromName
const from = fromAddress
? fromName
? `${fromName} <${fromAddress}>`
: fromAddress
: message.from
// Defence in depth against header injection. Modern nodemailer already
// normalises CRLF in standard headers, but the form-builder interpolates
// user data into the subject via {{field}} placeholders, so strip any
// newlines from header-bound values before they reach the transport.
const stripCRLF = (v: string): string => v.replace(/[\r\n]+/g, ' ').trim()
const { default: nodemailer } = await import('nodemailer')
const transporter = nodemailer.createTransport({
auth: { pass, user },
host,
port,
secure: port === 465, // implicit TLS on 465, STARTTLS otherwise
})
try {
const info = await transporter.sendMail({
...message,
from,
...(message.subject ? { subject: stripCRLF(message.subject) } : {}),
})
return { messageId: info.messageId, sent: true }
} catch (err) {
// Never surface SMTP internals to the caller — a form submission
// shouldn't fail loudly because the mailbox is misconfigured.
payload.logger.error(`[ipal] Email send failed: ${(err as Error).message}`)
// `detail` is for the panel status (mailAdapter), not for end users.
return { detail: (err as Error).message, error: 'Failed to send email.', sent: false }
}
},
})