- V-1: assertDevelopmentHosts - iapl({ developmentHosts }), mail.relay.developmentHosts and
mailAdapter({ relay }) refuse anything but an array of non-empty host patterns, and a pattern of `*` alone
(it would make the public site a development address). Nothing is ignored silently any more.
- V-2: one trailing dot of the host is stripped before matching; patterns are punycoded, so one written in
Unicode matches; a `*` inside a non-ASCII label is refused.
- V-3: the 30-second memory of other hosts is gone. A dump restored into a running development site stops
its very next e-mail.
- docs, AGENT.md, changelog draft, skills
Co-Authored-By: Claude Fable 5.2 <[email protected]>
258 lines
13 KiB
TypeScript
258 lines
13 KiB
TypeScript
import type { PayloadEmailAdapter, SendEmailOptions } from 'payload'
|
|
|
|
import { type IntegrationStatus, recordIntegrationStatus } from '../integrations/status.js'
|
|
import { getSiteIntegrations } from '../payload/index.js'
|
|
import { assertDevelopmentHosts } from '../shared/developmentHosts.js'
|
|
import { sendAccountMailAfterCommit } from './accountMailAfterCommit.js'
|
|
import { graphAdapter, type GraphAdapterArgs, graphLargeAttachmentSupport } from './graphAdapter.js'
|
|
import { attachmentBytes, GRAPH_INLINE_MAX_BYTES, toGraphAttachments } from './graphAttachments.js'
|
|
import { panelSmtpAdapter, type PanelSmtpAdapterArgs } from './panelSmtpAdapter.js'
|
|
import { relayAttachmentLimit, sendRelayWithPanel } from './relay/adapter.js'
|
|
import { pluginMailOptions, type RelayOptions, resolveRelayOptions } from './relay/options.js'
|
|
|
|
type TransportIntegrations = {
|
|
emailStatus?: IntegrationStatus | null
|
|
/** 'smtp' | 'graph' — chosen by the editor in SiteIntegrations. */
|
|
emailTransport?: 'graph' | 'smtp' | null
|
|
smtpFromAddress?: null | string
|
|
smtpFromName?: null | string
|
|
smtpHost?: null | string
|
|
smtpPassword?: null | string
|
|
smtpUser?: null | string
|
|
}
|
|
|
|
const smtpConfigured = (s: TransportIntegrations) => Boolean(s.smtpHost && s.smtpUser && s.smtpPassword)
|
|
/** Some of server, user name and password are filled in, but not all: the SMTP server cannot be used. */
|
|
export const smtpIncomplete = (s: TransportIntegrations) => !smtpConfigured(s) && Boolean(s.smtpHost || s.smtpUser || s.smtpPassword)
|
|
let warnedSmtpIncomplete = false
|
|
|
|
/** Which transport a send takes. `none`: nothing is set up and the relay is switched off. */
|
|
export type MailTransport = 'graph' | 'none' | 'relay' | 'smtp'
|
|
|
|
/**
|
|
* The transport in effect for the present settings, decided on every send (no stored value):
|
|
* 1. "Sending method" is Microsoft Graph and the GRAPH_* variables are complete → Graph, as before
|
|
* (deprecated; removed in 2.0);
|
|
* 2. the panel has an SMTP server (server, user name, password) → SMTP — on the client's request;
|
|
* 3. the GRAPH_* variables are complete → Graph (deprecated), until they are removed;
|
|
* 4. otherwise → the Intecion Notifications Webservice, unless it is switched off (`mail: { relay: false }`);
|
|
* 5. otherwise nothing is configured.
|
|
* A site with SMTP filled in never contacts the service.
|
|
*/
|
|
export function resolveMailTransport(settings: TransportIntegrations, state: { graphEnv: boolean; relay: boolean }): MailTransport {
|
|
if ((settings.emailTransport ?? 'smtp') === 'graph' && state.graphEnv) {return 'graph'}
|
|
if (smtpConfigured(settings)) {return 'smtp'}
|
|
if (state.graphEnv) {return 'graph'}
|
|
return state.relay ? 'relay' : 'none'
|
|
}
|
|
|
|
/** Graph result codes that mean "Graph cannot carry an attachment this large" — SMTP may. */
|
|
const GRAPH_TOO_LARGE = new Set(['graph-large-off', 'graph-permission'])
|
|
|
|
/** The one warning a site on Microsoft Graph gets per process (silence: `mail: { graphDeprecationWarning: false }`). */
|
|
export const GRAPH_DEPRECATION_NOTICE =
|
|
'[iapl] Microsoft Graph as the e-mail transport is deprecated and will be removed in 2.0. Remove the GRAPH_* variables to send through the Intecion Notifications Webservice, or fill in an SMTP server in Site integrations (docs/email.md, "Moving off Microsoft Graph").'
|
|
|
|
const STATUS_FIELD = 'emailStatus'
|
|
/** Error text for the panel: first line, no stack, capped — SMTP errors don't carry the password. */
|
|
const describe = (err: unknown) =>
|
|
(err instanceof Error ? err.message : String(err)).split('\n')[0].slice(0, 200)
|
|
|
|
export type MailAdapterArgs = {
|
|
fallbackFromAddress?: string
|
|
fallbackFromName?: string
|
|
/** @deprecated Microsoft Graph is deprecated since 1.17.0 and removed in 2.0 (docs/email.md, "Moving off Microsoft Graph"). */
|
|
graph?: GraphAdapterArgs
|
|
/**
|
|
* The Intecion Notifications Webservice — the transport of a site with no SMTP server in the panel.
|
|
* `false` switches it off for this adapter; an object overrides `iapl({ mail: { relay } })`.
|
|
*/
|
|
relay?: false | RelayOptions
|
|
smtp?: PanelSmtpAdapterArgs
|
|
}
|
|
|
|
let warnedGraphDeprecated = false
|
|
/** iapl() left its options in the config: it has already warned at start (plugin.ts, onInit). */
|
|
const pluginWarnsAtStart = (payload: { config?: { custom?: unknown } }) => Boolean((payload.config?.custom as { iapl?: { mail?: unknown } } | undefined)?.iapl?.mail)
|
|
|
|
/** For tests. */
|
|
export function resetGraphDeprecationWarning(): void {
|
|
warnedGraphDeprecated = false
|
|
}
|
|
|
|
/** True when the agency Graph credentials are present in the environment. */
|
|
export function graphAvailable(): boolean {
|
|
return Boolean(
|
|
process.env.GRAPH_TENANT_ID &&
|
|
process.env.GRAPH_CLIENT_ID &&
|
|
process.env.GRAPH_CLIENT_SECRET &&
|
|
process.env.GRAPH_SENDER,
|
|
)
|
|
}
|
|
|
|
/**
|
|
* Dispatcher email adapter: wired into the config ONCE, but picks the transport
|
|
* per send from Site integrations (resolveMailTransport): the panel's SMTP server
|
|
* when one is filled in, Microsoft Graph while its variables last (deprecated),
|
|
* otherwise the Intecion Notifications Webservice (relay/).
|
|
* This is what makes the choice switchable in the panel — Payload builds the
|
|
* email adapter at boot and can't swap it at runtime, so instead of choosing
|
|
* between two adapters at boot we install one that delegates on every send.
|
|
*
|
|
* Availability guard: Graph only runs if its agency credentials exist in env
|
|
* (this is *our* Exchange). If the panel says 'graph' but env isn't set up,
|
|
* we DON'T silently fail — we log clearly and fall back to SMTP, so a client
|
|
* flipping the switch without the backing config still gets mail out (over SMTP)
|
|
* rather than silent nothing. If neither is usable, the send reports an error.
|
|
*
|
|
* @example
|
|
* // payload.config.ts
|
|
* import { mailAdapter } from '@intecion/ipal-kit'
|
|
* email: mailAdapter()
|
|
*/
|
|
export const mailAdapter =
|
|
(args: MailAdapterArgs = {}): PayloadEmailAdapter =>
|
|
(deps) => {
|
|
// a malformed list must stop the start, not be found at the first e-mail of a copy
|
|
if (args.relay && args.relay.developmentHosts !== undefined) {assertDevelopmentHosts(args.relay.developmentHosts, 'mailAdapter({ relay: { developmentHosts } })')}
|
|
// Build both delegates once; each still resolves its own config per send.
|
|
const smtp = panelSmtpAdapter({
|
|
fallbackFromAddress: args.fallbackFromAddress,
|
|
fallbackFromName: args.fallbackFromName,
|
|
...args.smtp,
|
|
})(deps)
|
|
const graph = graphAdapter({
|
|
fallbackFromAddress: args.fallbackFromAddress,
|
|
fallbackFromName: args.fallbackFromName,
|
|
...args.graph,
|
|
})(deps)
|
|
|
|
const { payload } = deps
|
|
|
|
/**
|
|
* The largest total attachment size (bytes) the current transport can
|
|
* carry, or null when the plugin knows no ceiling (the mail server's own
|
|
* limit still applies). Read by the forms module, so a File field never
|
|
* promises more than can be sent: on Graph without the large-file path and
|
|
* without SMTP settings the ceiling is GRAPH_INLINE_MAX_BYTES.
|
|
*/
|
|
const relayOptions = () => resolveRelayOptions(payload, args.relay)
|
|
const transportOf = (settings: TransportIntegrations) => resolveMailTransport(settings, { graphEnv: graphAvailable(), relay: Boolean(relayOptions()) })
|
|
|
|
const attachmentLimit = async (): Promise<null | number> => {
|
|
const settings = await getSiteIntegrations<TransportIntegrations>(payload)
|
|
const transport = transportOf(settings)
|
|
// The service says what it carries for this site (10 MB unless Intecion set another number).
|
|
if (transport === 'relay') {return relayAttachmentLimit(payload, relayOptions()!).catch(() => null)}
|
|
if (transport !== 'graph') {return null}
|
|
const support = await graphLargeAttachmentSupport(args.graph)
|
|
if (support === 'ok' || support === 'unavailable' || smtpConfigured(settings)) {return null}
|
|
return GRAPH_INLINE_MAX_BYTES - 1
|
|
}
|
|
|
|
return {
|
|
name: 'ipal-mail-dispatcher',
|
|
attachmentLimit,
|
|
defaultFromAddress: smtp.defaultFromAddress,
|
|
defaultFromName: smtp.defaultFromName,
|
|
|
|
sendEmail: async (message: SendEmailOptions) => {
|
|
// Payload's "forgot password" / "verify your e-mail" inside a transaction: sent right after it commits
|
|
// (accountMailAfterCommit.ts), so a slow mail server holds no database connection.
|
|
if (sendAccountMailAfterCommit(message, () => send(message))) {return { deferred: true }}
|
|
return send(message)
|
|
},
|
|
}
|
|
|
|
async function send(message: SendEmailOptions): Promise<unknown> {
|
|
const settings = await getSiteIntegrations<TransportIntegrations>(payload)
|
|
const choice = settings.emailTransport ?? 'smtp'
|
|
const previous = settings[STATUS_FIELD]
|
|
const chosen = transportOf(settings)
|
|
|
|
// No SMTP server in the panel and no Graph: the Intecion Notifications Webservice.
|
|
if (chosen === 'relay') {
|
|
// Half an SMTP set-up was "not configured" before 1.17.0; now the mail leaves another way: say so once.
|
|
if (smtpIncomplete(settings) && !warnedSmtpIncomplete) {
|
|
warnedSmtpIncomplete = true
|
|
payload.logger.warn('[iapl] The SMTP settings in Site integrations are incomplete (server, user name and password are all needed), so e-mails go through the Intecion Notifications Webservice. Complete them to use the SMTP server, or empty them.')
|
|
}
|
|
return sendRelayWithPanel(payload, relayOptions()!, message, settings)
|
|
}
|
|
|
|
const useGraph = chosen === 'graph'
|
|
// "Graph" in the panel without its variables is reported only while SMTP carries the mail instead.
|
|
const graphFallback = choice === 'graph' && !useGraph
|
|
|
|
if (graphFallback) {
|
|
// Panel asked for Graph but the agency creds aren't configured for
|
|
// this project. Fall back to SMTP rather than silently dropping mail.
|
|
payload.logger.warn(
|
|
'[iapl] Transport set to Graph but GRAPH_* env vars are missing; falling back to SMTP.',
|
|
)
|
|
}
|
|
// A project that uses mailAdapter() without iapl()'s start warning still hears it once.
|
|
if (useGraph && !warnedGraphDeprecated && !pluginWarnsAtStart(payload) && pluginMailOptions(payload).graphDeprecationWarning !== false) {
|
|
warnedGraphDeprecated = true
|
|
payload.logger.warn(GRAPH_DEPRECATION_NOTICE)
|
|
}
|
|
|
|
// A large attachment Graph cannot carry (switched off, or the app lacks
|
|
// Mail.ReadWrite) goes over SMTP when the panel has SMTP settings.
|
|
const attachments = useGraph ? toGraphAttachments(message) : []
|
|
const large = Boolean(attachments?.length) && attachmentBytes(attachments ?? []) >= GRAPH_INLINE_MAX_BYTES
|
|
const support = large ? await graphLargeAttachmentSupport(args.graph) : 'ok'
|
|
const largeOverSmtp = large && support !== 'ok' && support !== 'unavailable' && smtpConfigured(settings)
|
|
const viaGraph = useGraph && !largeOverSmtp
|
|
|
|
const transport = viaGraph ? 'Microsoft Graph' : 'SMTP'
|
|
const code = viaGraph ? 'graph-error' : 'smtp-error'
|
|
let result: unknown
|
|
try {
|
|
result = await (viaGraph ? graph : smtp).sendEmail(message)
|
|
// Graph found out only while sending (a token it could not read): one try over SMTP. Graph sent nothing.
|
|
const refused = result as { code?: string; sent?: boolean } | null
|
|
if (viaGraph && refused?.sent === false && GRAPH_TOO_LARGE.has(refused.code ?? '') && smtpConfigured(settings)) {
|
|
result = await smtp.sendEmail(message)
|
|
}
|
|
} catch (err) {
|
|
await recordIntegrationStatus(payload, STATUS_FIELD, previous, {
|
|
code,
|
|
message: `${transport}: ${describe(err)}`,
|
|
state: 'degraded',
|
|
})
|
|
throw err // callers (form-builder, Send test) still see the failure
|
|
}
|
|
|
|
// The delegates report failure as { sent: false, error, detail? } instead
|
|
// of throwing (a broken mailbox must not crash a form submission).
|
|
const failed = result as { code?: string; detail?: string; error?: string; sent?: boolean } | null
|
|
if (failed && typeof failed === 'object' && failed.sent === false) {
|
|
await recordIntegrationStatus(payload, STATUS_FIELD, previous, {
|
|
code: GRAPH_TOO_LARGE.has(failed.code ?? '') ? 'graph-large-files' : code,
|
|
message: `${transport}: ${describe(failed.detail ?? failed.error ?? 'not sent')}`,
|
|
state: 'degraded',
|
|
})
|
|
return result
|
|
}
|
|
|
|
// Graph selected but unavailable is a configuration problem even if SMTP delivered.
|
|
await recordIntegrationStatus(
|
|
payload,
|
|
STATUS_FIELD,
|
|
previous,
|
|
large && support === 'no-permission'
|
|
? { code: 'graph-large-files', state: 'degraded' }
|
|
: graphFallback
|
|
? {
|
|
code: 'graph-unavailable',
|
|
message:
|
|
'Microsoft Graph is selected but not set up on the server, so e-mails go over SMTP. Ask your administrator.',
|
|
state: 'degraded',
|
|
}
|
|
: { state: 'ok' },
|
|
)
|
|
return result
|
|
}
|
|
}
|