WIP: sending method as an explicit choice, kept in payload-kv (superseded: the choice moves to a stored field)

Co-Authored-By: Claude Fable 5.2 <[email protected]>
This commit is contained in:
Radosław Smoliński
2026-11-26 22:30:03 +01:00
co-authored by Claude Fable 5.2
parent 68a2555277
commit c6841a1674
34 changed files with 740 additions and 96 deletions
+43 -6
View File
@@ -6,6 +6,7 @@ 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 { getMailMethod, type MailMethod } from './method.js'
import { panelSmtpAdapter, type PanelSmtpAdapterArgs } from './panelSmtpAdapter.js'
import { relayAttachmentLimit, sendRelayWithPanel } from './relay/adapter.js'
import { pluginMailOptions, type RelayOptions, resolveRelayOptions } from './relay/options.js'
@@ -46,6 +47,32 @@ export function resolveMailTransport(settings: TransportIntegrations, state: { g
return state.relay ? 'relay' : 'none'
}
/** Why the chosen method cannot be used. The mail is NOT sent another way. */
export type MailMethodProblem = 'graph-not-set-up' | 'smtp-incomplete'
export type ResolvedMailMethod = {
/** An admin chose it ("Sending method" was saved); false = nobody has chosen yet, the order of 1.17.0 decides. */
explicit: boolean
method: MailTransport
/** Set only for an explicit choice that cannot be used; sends fail and say so. */
problem?: MailMethodProblem
}
/**
* The sending method in effect. With a choice (`getMailMethod`): exactly that method — an SMTP choice with
* an incomplete server, or Graph without the `GRAPH_*` variables, is a problem and the mail fails loudly;
* nothing is sent another way. Without a choice: `resolveMailTransport`, the order of 1.17.0.
* A choice of the built-in service counts as no choice when the project switched the service off
* (`mail: { relay: false }` removes the option).
*/
export function resolveMailMethod(settings: TransportIntegrations, state: { chosen: MailMethod | null; graphEnv: boolean; relay: boolean }): ResolvedMailMethod {
const chosen = state.chosen === 'relay' && !state.relay ? null : state.chosen
if (!chosen) {return { explicit: false, method: resolveMailTransport(settings, state) }}
if (chosen === 'smtp') {return { explicit: true, method: 'smtp', ...(smtpConfigured(settings) ? {} : { problem: 'smtp-incomplete' as const }) }}
if (chosen === 'graph') {return { explicit: true, method: 'graph', ...(state.graphEnv ? {} : { problem: 'graph-not-set-up' as const }) }}
return { explicit: true, method: 'relay' }
}
/** 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'])
@@ -137,11 +164,11 @@ export const mailAdapter =
* 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 methodOf = async (settings: TransportIntegrations) => resolveMailMethod(settings, { chosen: await getMailMethod(payload), graphEnv: graphAvailable(), relay: Boolean(relayOptions()) })
const attachmentLimit = async (): Promise<null | number> => {
const settings = await getSiteIntegrations<TransportIntegrations>(payload)
const transport = transportOf(settings)
const transport = (await methodOf(settings)).method
// 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}
@@ -168,21 +195,30 @@ export const mailAdapter =
const settings = await getSiteIntegrations<TransportIntegrations>(payload)
const choice = settings.emailTransport ?? 'smtp'
const previous = settings[STATUS_FIELD]
const chosen = transportOf(settings)
const resolved = await methodOf(settings)
const chosen = resolved.method
// 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) {
if (!resolved.explicit && 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)
}
// Graph was chosen, but this server has no GRAPH_* variables: the mail fails, and says so. It does not
// leave another way — what is chosen is what is used.
if (resolved.problem === 'graph-not-set-up') {
const error = 'Microsoft Graph is chosen as the sending method, but it is not set up on this server (the GRAPH_* variables are missing). Nothing was sent.'
await recordIntegrationStatus(payload, STATUS_FIELD, previous, { code: 'graph-not-set-up', message: error, state: 'degraded' })
return { code: 'graph-not-set-up', error, sent: false }
}
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
const graphFallback = !resolved.explicit && choice === 'graph' && !useGraph
if (graphFallback) {
// Panel asked for Graph but the agency creds aren't configured for
@@ -206,7 +242,8 @@ export const mailAdapter =
const viaGraph = useGraph && !largeOverSmtp
const transport = viaGraph ? 'Microsoft Graph' : 'SMTP'
const code = viaGraph ? 'graph-error' : 'smtp-error'
// (SMTP was chosen and its settings are incomplete: its own code, so the panel can say what to fill in)
const code = viaGraph ? 'graph-error' : resolved.problem === 'smtp-incomplete' ? 'smtp-incomplete' : 'smtp-error'
let result: unknown
try {
result = await (viaGraph ? graph : smtp).sendEmail(message)
+49
View File
@@ -0,0 +1,49 @@
import type { BasePayload } from 'payload'
/**
* The sending method an admin chose in Site integrations → E-mail sending ("Sending method"):
* the built-in service (IWSN), the client's own SMTP server, or Microsoft Graph (deprecated).
*
* Where it is stored: in Payload's key-value store (`payload-kv`), under `MAIL_METHOD_KV_KEY` — not in
* a column of the global. The global's stored field `emailTransport` has two values since 1.6 (`smtp`,
* `graph`); a third would change the Postgres enum and ask every SQL project for a migration, and it
* still could not tell "SMTP was chosen" from the `smtp` that every site has stored since before the
* choice existed. So the panel's field (`emailMethod`) is virtual, and the choice lives here.
*
* No entry = nobody has chosen yet (a site upgraded from 1.17.0 or older, a new site): the method follows
* the order of 1.17.0 (`resolveMailTransport`) and the panel shows it as selected. The first save of Site
* integrations — or `setMailMethod()` — writes the choice; from then on what is chosen is what is used.
*/
export type MailMethod = 'graph' | 'relay' | 'smtp'
export const MAIL_METHODS: readonly MailMethod[] = ['relay', 'smtp', 'graph']
export const MAIL_METHOD_KV_KEY = 'iapl:mail-method'
export const isMailMethod = (value: unknown): value is MailMethod => typeof value === 'string' && (MAIL_METHODS as readonly string[]).includes(value)
type Kv = { delete?: (key: string) => Promise<unknown>; get?: (key: string) => Promise<unknown>; set?: (key: string, value: object) => Promise<unknown> }
const kvOf = (payload: Pick<BasePayload, 'kv'>): Kv => ((payload as { kv?: Kv }).kv ?? {})
/** The chosen method, or null when nobody has chosen yet. Reads only. */
export async function getMailMethod(payload: Pick<BasePayload, 'kv'>): Promise<MailMethod | null> {
const kv = kvOf(payload)
if (typeof kv.get !== 'function') {return null}
const stored = (await kv.get(MAIL_METHOD_KV_KEY)) as { method?: unknown } | null
return isMailMethod(stored?.method) ? stored.method : null
}
/**
* Chooses the method (a seed, a deploy script; the panel does it on save). `null` = nobody has chosen:
* the order of 1.17.0 applies again.
*/
export async function setMailMethod(payload: Pick<BasePayload, 'kv'>, method: MailMethod | null): Promise<void> {
const kv = kvOf(payload)
if (method === null) {
await kv.delete?.(MAIL_METHOD_KV_KEY)
return
}
if (!isMailMethod(method)) {throw new Error(`[iapl] setMailMethod: "${String(method)}" is not a sending method (relay, smtp, graph).`)}
if (typeof kv.set !== 'function') {throw new Error('[iapl] setMailMethod: this Payload has no key-value store (payload.kv).')}
await kv.set(MAIL_METHOD_KV_KEY, { at: new Date().toISOString(), method })
}
+15 -3
View File
@@ -6,7 +6,8 @@ import type { RelayOptions } from './options.js'
import { userMeetsRole } from '../../access/predicates.js'
import { serverText } from '../../integrations/texts.js'
import { getSiteIntegrations } from '../../payload/index.js'
import { graphAvailable, type MailTransport, resolveMailTransport, smtpIncomplete } from '../mailAdapter.js'
import { graphAvailable, type MailMethodProblem, type MailTransport, resolveMailMethod, smtpIncomplete } from '../mailAdapter.js'
import { getMailMethod } from '../method.js'
import { RELAY_SENDER_ADDRESS } from './adapter.js'
import { relayRequest } from './client.js'
import { RELAY_CONFIRM_PATH, RELAY_CONNECT_PATH, RELAY_DISCONNECT_PATH, RELAY_STATUS_PATH } from './constants.js'
@@ -29,6 +30,13 @@ export type MailPanelState = {
accessKeyField?: boolean
/** The address the service calls this site back at. */
confirmUrl?: string
/**
* An admin chose the method in effect ("Sending method" was saved). False: nobody has chosen yet, and the
* method follows the order of 1.17.0 until Site integrations is saved.
*/
methodChosen: boolean
/** The chosen method cannot be used; e-mails are NOT sent another way. */
methodProblem?: MailMethodProblem
/** The site is not public: its host is a development address (`developmentHosts`), or `IAPL_NOINDEX` is set. */
nonPublic?: boolean
/** Which signal says so; with `development-host`, `nonPublicPattern` is the pattern that matched. */
@@ -60,7 +68,8 @@ export async function mailPanelState(req: Pick<PayloadRequest, 'payload'>, own:
const { payload } = req
const settings = await getSiteIntegrations<Settings>(payload)
const options = resolveRelayOptions(payload, own)
const transport = resolveMailTransport(settings, { graphEnv: graphAvailable(), relay: Boolean(options) })
const method = resolveMailMethod(settings, { chosen: await getMailMethod(payload), graphEnv: graphAvailable(), relay: Boolean(options) })
const transport = method.method
let status = options ? await getRelayStatus(payload, options, { refresh: refresh && transport === 'relay' }) : null
// A site the service could never call back (it runs locally, or does not know its address) is refused by the
// plugin before any call: say so now, not only after the first failed e-mail.
@@ -88,11 +97,14 @@ export async function mailPanelState(req: Pick<PayloadRequest, 'payload'>, own:
return {
...(options?.accessKeyField === true ? { accessKeyField: true } : {}),
...(status?.host ? { confirmUrl: `https://${status.host}${api}${RELAY_CONFIRM_PATH}` } : {}),
methodChosen: method.explicit,
...(method.problem ? { methodProblem: method.problem } : {}),
relay: status ? { ...status, senderAddress: status.senderAddress ?? RELAY_SENDER_ADDRESS } : null,
replyAddress: typeof settings.smtpFromAddress === 'string' && settings.smtpFromAddress.trim() ? settings.smtpFromAddress.trim() : null,
...(signal ? { nonPublic: true, nonPublicBy: signal.by, ...(signal.by === 'development-host' ? { nonPublicPattern: signal.pattern } : {}) } : {}),
...(otherHostEntries ? { otherHostEntries: true } : {}),
...(smtpIncomplete(settings) ? { smtpIncomplete: true } : {}),
// (the hint of a site nobody chose a method for: its half-filled SMTP server is passed over)
...(!method.explicit && smtpIncomplete(settings) ? { smtpIncomplete: true } : {}),
transport,
}
}
+8 -3
View File
@@ -90,7 +90,9 @@ export const testEmailEndpoint: Endpoint = {
req.payload.logger.error(`[iapl] Test email not sent: ${failed?.detail ?? failed?.error ?? 'unknown reason'}`)
const relayText = failed?.code ? STATUS_CODE_TEXTS[failed.code] : undefined
const error =
failed?.code === 'not-configured'
failed?.code === 'graph-not-set-up'
? serverText(i18n, 'statusEmailMethodGraphNotSetUp')
: failed?.code === 'not-configured'
? serverText(i18n, 'testEmailNotConfigured')
: failed?.confirmed === false
? serverText(i18n, 'testEmailNotConfirmed')
@@ -104,12 +106,15 @@ export const testEmailEndpoint: Endpoint = {
// The answer names the transport that carried it: the mail service says so itself; SMTP is told by the
// settings (the dispatcher's results for SMTP and Graph are what they were before 1.17.0).
const sentBy = info as { senderName?: string; transport?: string } | null
const smtp = !sentBy?.transport && req.payload.email?.name === 'ipal-mail-dispatcher' && transportBefore === 'smtp'
const byDispatcher = !sentBy?.transport && req.payload.email?.name === 'ipal-mail-dispatcher'
const smtp = byDispatcher && transportBefore === 'smtp'
const graph = byDispatcher && transportBefore === 'graph'
const message =
sentBy?.transport === 'relay' ? serverText(i18n, 'testEmailSentRelay', { name: sentBy.senderName ?? '', to })
: smtp ? serverText(i18n, 'testEmailSentSmtp', { to })
: graph ? serverText(i18n, 'testEmailSentGraph', { to })
: serverText(i18n, 'testEmailSent', { to })
return Response.json({ message, ok: true, ...(sentBy?.transport === 'relay' ? { transport: 'relay' } : smtp ? { transport: 'smtp' } : {}) })
return Response.json({ message, ok: true, ...(sentBy?.transport === 'relay' ? { transport: 'relay' } : smtp ? { transport: 'smtp' } : graph ? { transport: 'graph' } : {}) })
} catch (err) {
const message = err instanceof Error ? err.message : String(err)
req.payload.logger.error(`[iapl] Test email failed: ${message}`)