Merge claude/mail-transport-choice: "Sending method" is an explicit choice in the panel (IWSN, own SMTP, Graph); nothing changes until another option is picked
Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
@@ -11,6 +11,11 @@ export const integrationsTexts = defineTexts({
|
||||
alertsUnknownError: 'Unknown error.',
|
||||
|
||||
// Intecion mail service: the state block on the e-mail tab (MailRelayStatus) and its routes
|
||||
mailMethodGraphNotSetUp: 'Microsoft Graph is chosen, but it is not set up on this server. E-mails are not sent. Ask your administrator.',
|
||||
mailMethodGraphNotSetUpForm: 'Microsoft Graph is not set up on this server. If you save this, e-mails will not be sent.',
|
||||
mailMethodNotChosen: 'The site sends the way it did before. It changes only when you pick another sending method.',
|
||||
mailMethodSmtpIncomplete: 'Your SMTP server is chosen, but its settings are incomplete. E-mails are not sent. Fill in server, user name and password.',
|
||||
mailMethodSmtpIncompleteForm: 'Fill in server, user name and password below. If you save without them, e-mails will not be sent.',
|
||||
mailRelayCheck: 'Check now',
|
||||
mailRelayConnect: 'Connect again',
|
||||
mailRelayConnected: `The site is connected to ${IWSN}.`,
|
||||
@@ -84,6 +89,8 @@ export const integrationsTexts = defineTexts({
|
||||
'Microsoft Graph cannot send files of 3 MB and more here, so larger form files are limited or go over SMTP. Ask your administrator.',
|
||||
statusEmailGraphUnavailable:
|
||||
'Microsoft Graph is selected but not set up on the server, so e-mails go over SMTP. Ask your administrator.',
|
||||
statusEmailMethodGraphNotSetUp: 'Microsoft Graph is chosen, but it is not set up on this server. E-mails are not sent.',
|
||||
statusEmailMethodSmtpIncomplete: 'Your SMTP server is chosen, but its settings are incomplete. E-mails are not sent.',
|
||||
statusEmailRelayAttachmentRefused: `${IWSN} does not carry this type of file. The e-mail was not sent.`,
|
||||
statusEmailRelayDisconnected: `The site is disconnected from ${IWSN}, so e-mails are not sent. Connect again, or fill in an SMTP server.`,
|
||||
statusEmailRelayError: `${IWSN} refused the e-mail. Tell your administrator.`,
|
||||
@@ -119,6 +126,7 @@ export const integrationsTexts = defineTexts({
|
||||
testEmailSend: 'Send test e-mail',
|
||||
testEmailSending: 'Sending…',
|
||||
testEmailSent: 'Test e-mail sent to {{to}}.',
|
||||
testEmailSentGraph: 'Test e-mail sent to {{to}} through Microsoft Graph.',
|
||||
testEmailSentRelay: `Test e-mail sent to {{to}} through ${IWSN}, as "{{name}}".`,
|
||||
testEmailSentSmtp: 'Test e-mail sent to {{to}} through your SMTP server.',
|
||||
testEmailSubject: 'Test e-mail from {{site}}',
|
||||
@@ -131,6 +139,11 @@ export const integrationsTexts = defineTexts({
|
||||
alertsLink: 'Przejdź do integracji',
|
||||
alertsUnknownError: 'Nieznany błąd.',
|
||||
|
||||
mailMethodGraphNotSetUp: 'Wybrano Microsoft Graph, ale nie jest on skonfigurowany na tym serwerze. E-maile nie są wysyłane. Zapytaj administratora.',
|
||||
mailMethodGraphNotSetUpForm: 'Microsoft Graph nie jest skonfigurowany na tym serwerze. Jeśli to zapiszesz, e-maile nie będą wysyłane.',
|
||||
mailMethodNotChosen: 'Witryna wysyła tak jak dotąd. Zmieni to dopiero wybór innego sposobu wysyłki.',
|
||||
mailMethodSmtpIncomplete: 'Wybrano Twój serwer SMTP, ale jego ustawienia są niepełne. E-maile nie są wysyłane. Uzupełnij serwer, nazwę użytkownika i hasło.',
|
||||
mailMethodSmtpIncompleteForm: 'Uzupełnij poniżej serwer, nazwę użytkownika i hasło. Jeśli zapiszesz bez nich, e-maile nie będą wysyłane.',
|
||||
mailRelayCheck: 'Sprawdź teraz',
|
||||
mailRelayConnect: 'Połącz ponownie',
|
||||
mailRelayConnected: `Witryna jest połączona z ${IWSN}.`,
|
||||
@@ -201,6 +214,8 @@ export const integrationsTexts = defineTexts({
|
||||
'Microsoft Graph nie może tu wysyłać plików od 3 MB, więc większe pliki z formularzy są ograniczone lub idą przez SMTP. Zapytaj administratora.',
|
||||
statusEmailGraphUnavailable:
|
||||
'Wybrano Microsoft Graph, ale nie jest on skonfigurowany na serwerze, więc e-maile idą przez SMTP. Zapytaj administratora.',
|
||||
statusEmailMethodGraphNotSetUp: 'Wybrano Microsoft Graph, ale nie jest on skonfigurowany na tym serwerze. E-maile nie są wysyłane.',
|
||||
statusEmailMethodSmtpIncomplete: 'Wybrano Twój serwer SMTP, ale jego ustawienia są niepełne. E-maile nie są wysyłane.',
|
||||
statusEmailRelayAttachmentRefused: `${IWSN} nie przesyła plików tego typu. E-mail nie został wysłany.`,
|
||||
statusEmailRelayDisconnected: `Witryna jest rozłączona z ${IWSN}, więc e-maile nie są wysyłane. Połącz ją ponownie albo uzupełnij serwer SMTP.`,
|
||||
statusEmailRelayError: `${IWSN} odrzucił e-mail. Powiadom administratora.`,
|
||||
@@ -235,6 +250,7 @@ export const integrationsTexts = defineTexts({
|
||||
testEmailSend: 'Wyślij testowy e-mail',
|
||||
testEmailSending: 'Wysyłanie…',
|
||||
testEmailSent: 'Testowy e-mail wysłano na adres {{to}}.',
|
||||
testEmailSentGraph: 'Testowy e-mail wysłano na adres {{to}} przez Microsoft Graph.',
|
||||
testEmailSentRelay: `Testowy e-mail wysłano na adres {{to}} przez ${IWSN}, jako „{{name}}”.`,
|
||||
testEmailSentSmtp: 'Testowy e-mail wysłano na adres {{to}} przez Twój serwer SMTP.',
|
||||
testEmailSubject: 'Testowy e-mail z witryny {{site}}',
|
||||
|
||||
@@ -53,6 +53,30 @@ export const mailRules: DoctorRule[] = [
|
||||
group: 'mail',
|
||||
source: 'deep',
|
||||
},
|
||||
{
|
||||
// "Sending method": what is chosen is what is used. A choice that cannot be used sends nothing.
|
||||
id: 'mail-method',
|
||||
check: (ctx) => {
|
||||
const mail = ctx.deep?.mail
|
||||
if (!mail) {return []}
|
||||
if (mail.methodColumnMissing) {
|
||||
return [{ fix: 'create and apply the migration: `pnpm payload migrate:create`, commit it, and have it applied when the new container starts (docs/email.md "Which transport a send takes" → Postgres and SQLite)', message: 'the database has no column for "Sending method" (`emailMethod`, new in 1.17.1): e-mails still go the way they did before the upgrade, but the Site integrations page of the panel does not open and the method cannot be chosen', severity: 'error' }]
|
||||
}
|
||||
if (mail.methodProblem === 'smtp-incomplete') {
|
||||
return [{ fix: 'Site integrations → E-mail sending: fill in server, user name and password — or choose another sending method', message: '"Own SMTP server" is the chosen sending method, but its settings are incomplete: e-mails are not sent (nothing is sent another way)', severity: 'error' }]
|
||||
}
|
||||
if (mail.methodProblem === 'graph-not-set-up') {
|
||||
return [{ fix: 'set the four GRAPH_* variables on the server — or choose another sending method in Site integrations → E-mail sending (Microsoft Graph is deprecated and removed in 2.0)', message: '"Microsoft Graph" is the chosen sending method, but the GRAPH_* variables are missing on this server: e-mails are not sent (nothing is sent another way)', severity: 'error' }]
|
||||
}
|
||||
if (mail.methodChosen === false && mail.transport !== 'none') {
|
||||
return [{ fix: 'nothing to do while it sends the way it should; to fix the method, pick it in Site integrations → E-mail sending (another option, or setMailMethod)', message: `nobody has picked a sending method: the site sends the way it did before the upgrade (now: ${mail.transport === 'relay' ? 'the built-in service' : mail.transport === 'smtp' ? 'the SMTP server' : 'Microsoft Graph'}) and follows what is filled in, as before`, severity: 'info' }]
|
||||
}
|
||||
return []
|
||||
},
|
||||
docs: 'docs/email.md',
|
||||
group: 'mail',
|
||||
source: 'deep',
|
||||
},
|
||||
{
|
||||
// Which signal makes the site a non-public copy for the mail service — said plainly, because that signal
|
||||
// decides whether a copy of another site's data mails real people.
|
||||
|
||||
@@ -73,6 +73,8 @@ export async function collectDoctorStatus(payload: BasePayload): Promise<DoctorS
|
||||
graphEnv: graphAvailable(),
|
||||
...(state.nonPublic ? { nonPublic: true, ...(state.nonPublicBy ? { nonPublicBy: state.nonPublicBy } : {}), ...(state.nonPublicPattern ? { nonPublicPattern: state.nonPublicPattern } : {}) } : {}),
|
||||
...(state.otherHostEntries ? { otherHostEntries: true } : {}),
|
||||
methodChosen: state.methodChosen,
|
||||
...(state.methodColumnMissing ? { methodColumnMissing: true } : {}),
|
||||
relay: state.relay
|
||||
? {
|
||||
connected: state.relay.connected,
|
||||
@@ -84,6 +86,7 @@ export async function collectDoctorStatus(payload: BasePayload): Promise<DoctorS
|
||||
: null,
|
||||
replyAddress: Boolean(state.replyAddress),
|
||||
status: integrations.emailStatus?.state ? { code: integrations.emailStatus.code ?? null, since: integrations.emailStatus.since ?? null, state: integrations.emailStatus.state } : null,
|
||||
...(state.methodProblem ? { methodProblem: state.methodProblem } : {}),
|
||||
transport: state.transport,
|
||||
}
|
||||
} catch {
|
||||
|
||||
@@ -67,6 +67,12 @@ export type DoctorStatus = {
|
||||
mail?: {
|
||||
/** The four GRAPH_* variables are set (Microsoft Graph: deprecated). */
|
||||
graphEnv: boolean
|
||||
/** An admin chose the sending method ("Sending method" was saved); false = the order of 1.17.0 still decides. */
|
||||
methodChosen?: boolean
|
||||
/** Postgres / SQLite: the column of "Sending method" is missing — the 1.17.1 migration has not run. */
|
||||
methodColumnMissing?: boolean
|
||||
/** The chosen method cannot be used: e-mails are not sent. */
|
||||
methodProblem?: 'graph-not-set-up' | 'smtp-incomplete'
|
||||
/** The site says it is not public (`IAPL_NOINDEX`, or a development host): a copy of another site's data does not mail by itself. */
|
||||
nonPublic?: boolean
|
||||
/** Which signal makes it non-public: the host matches a development pattern (`nonPublicPattern`), or `IAPL_NOINDEX`. */
|
||||
|
||||
@@ -1,18 +1,20 @@
|
||||
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 { isMailMethod, type MailMethod, readMailSettings } 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'
|
||||
|
||||
type TransportIntegrations = {
|
||||
emailStatus?: IntegrationStatus | null
|
||||
/** 'smtp' | 'graph' — chosen by the editor in SiteIntegrations. */
|
||||
/** "Sending method" as stored: empty = nobody has chosen. */
|
||||
emailMethod?: null | string
|
||||
emailStatus?: IntegrationStatus | null
|
||||
emailTransport?: 'graph' | 'smtp' | null
|
||||
smtpFromAddress?: null | string
|
||||
smtpFromName?: null | string
|
||||
@@ -46,6 +48,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 (`emailMethod`, as stored): 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 +165,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 = (settings: TransportIntegrations) => resolveMailMethod(settings, { chosen: isMailMethod(settings.emailMethod) ? settings.emailMethod : null, graphEnv: graphAvailable(), relay: Boolean(relayOptions()) })
|
||||
|
||||
const attachmentLimit = async (): Promise<null | number> => {
|
||||
const settings = await getSiteIntegrations<TransportIntegrations>(payload)
|
||||
const transport = transportOf(settings)
|
||||
const settings = await readMailSettings<TransportIntegrations>(payload)
|
||||
const transport = 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}
|
||||
@@ -165,24 +193,33 @@ export const mailAdapter =
|
||||
}
|
||||
|
||||
async function send(message: SendEmailOptions): Promise<unknown> {
|
||||
const settings = await getSiteIntegrations<TransportIntegrations>(payload)
|
||||
const settings = await readMailSettings<TransportIntegrations>(payload)
|
||||
const choice = settings.emailTransport ?? 'smtp'
|
||||
const previous = settings[STATUS_FIELD]
|
||||
const chosen = transportOf(settings)
|
||||
const resolved = 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 +243,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)
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
import type { BasePayload } from 'payload'
|
||||
|
||||
import { findSiteIntegrations, MAIL_METHOD_FIELD, SITE_INTEGRATIONS_SLUG } from '../payload/getSiteIntegrations.js'
|
||||
|
||||
/**
|
||||
* 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).
|
||||
*
|
||||
* Stored in the global's field `emailMethod` (a select, new in 1.17.1; Postgres / SQLite: one migration).
|
||||
* Empty = 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 the panel's
|
||||
* form — or `setMailMethod()` — stores the choice; from then on what is chosen is what is used.
|
||||
*
|
||||
* Why a field of its own and not a third value in `emailTransport` (`smtp` / `graph`, stored since 1.6):
|
||||
* every site has `smtp` stored there from before there was a choice, so "SMTP was chosen" could not be told
|
||||
* from "nothing was chosen" — and an upgrade must keep a site with no SMTP server on the service.
|
||||
*/
|
||||
export type MailMethod = 'graph' | 'relay' | 'smtp'
|
||||
|
||||
export const MAIL_METHODS: readonly MailMethod[] = ['relay', 'smtp', 'graph']
|
||||
|
||||
/**
|
||||
* A read with this key in its `context` gets `emailMethod` as stored (empty when nobody chose) — not the
|
||||
* method the panel shows as selected.
|
||||
*/
|
||||
export const STORED_MAIL_METHOD_CONTEXT = 'iaplStoredMailMethod'
|
||||
|
||||
export const isMailMethod = (value: unknown): value is MailMethod => typeof value === 'string' && (MAIL_METHODS as readonly string[]).includes(value)
|
||||
|
||||
/** Site integrations with `emailMethod` as stored — what the mail adapter and the state block decide from. */
|
||||
export function readMailSettings<T = Record<string, unknown>>(payload: BasePayload): Promise<T> {
|
||||
return findSiteIntegrations<T>(payload, { context: { [STORED_MAIL_METHOD_CONTEXT]: true } })
|
||||
}
|
||||
|
||||
/** The chosen method, or null when nobody has chosen yet. Reads only. */
|
||||
export async function getMailMethod(payload: BasePayload): Promise<MailMethod | null> {
|
||||
const stored = (await readMailSettings<Record<string, unknown>>(payload))[MAIL_METHOD_FIELD]
|
||||
return isMailMethod(stored) ? stored : 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: BasePayload, method: MailMethod | null): Promise<void> {
|
||||
if (method !== null && !isMailMethod(method)) {throw new Error(`[iapl] setMailMethod: "${String(method)}" is not a sending method (relay, smtp, graph).`)}
|
||||
await payload.updateGlobal({ slug: SITE_INTEGRATIONS_SLUG as never, data: { [MAIL_METHOD_FIELD]: method } as never, overrideAccess: true })
|
||||
}
|
||||
@@ -5,8 +5,9 @@ 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 { mailMethodColumnMissing } from '../../payload/getSiteIntegrations.js'
|
||||
import { graphAvailable, type MailMethodProblem, type MailTransport, resolveMailMethod, smtpIncomplete } from '../mailAdapter.js'
|
||||
import { isMailMethod, readMailSettings } 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'
|
||||
@@ -15,6 +16,7 @@ import { disconnectRelay, enrolRelay, type EnrolResult, getRelayStatus, LOCAL_CO
|
||||
import { otherRelayHosts } from './store.js'
|
||||
|
||||
type Settings = {
|
||||
emailMethod?: null | string
|
||||
emailStatus?: IntegrationStatus | null
|
||||
emailTransport?: 'graph' | 'smtp' | null
|
||||
smtpFromAddress?: null | string
|
||||
@@ -29,6 +31,17 @@ export type MailPanelState = {
|
||||
accessKeyField?: boolean
|
||||
/** The address the service calls this site back at. */
|
||||
confirmUrl?: string
|
||||
/** The four `GRAPH_*` variables are set on this server (whether "Microsoft Graph" could send). */
|
||||
graphReady: boolean
|
||||
/**
|
||||
* 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
|
||||
/** Postgres / SQLite: the column of "Sending method" is missing (the 1.17.1 migration has not run); the order of 1.17.0 applies. */
|
||||
methodColumnMissing?: 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. */
|
||||
@@ -58,9 +71,10 @@ function refuse(req: PayloadRequest): null | Response {
|
||||
/** The transport in effect and the site's state with the service, for the panel and the doctor. */
|
||||
export async function mailPanelState(req: Pick<PayloadRequest, 'payload'>, own: false | RelayOptions | undefined, { refresh = false }: { refresh?: boolean } = {}): Promise<MailPanelState> {
|
||||
const { payload } = req
|
||||
const settings = await getSiteIntegrations<Settings>(payload)
|
||||
const settings = await readMailSettings<Settings>(payload)
|
||||
const options = resolveRelayOptions(payload, own)
|
||||
const transport = resolveMailTransport(settings, { graphEnv: graphAvailable(), relay: Boolean(options) })
|
||||
const method = resolveMailMethod(settings, { chosen: isMailMethod(settings.emailMethod) ? settings.emailMethod : null, 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 +102,16 @@ 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}` } : {}),
|
||||
graphReady: graphAvailable(),
|
||||
methodChosen: method.explicit,
|
||||
...(mailMethodColumnMissing() ? { methodColumnMissing: true } : {}),
|
||||
...(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,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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}`)
|
||||
|
||||
@@ -18,6 +18,7 @@ export function resolveLabel(label: IntegrationLabel | undefined, language: stri
|
||||
export const STATUS_CODE_TEXTS: Record<string, AdminTextKey> = {
|
||||
'bad-response': 'statusTurnstileBadResponse',
|
||||
'graph-large-files': 'statusEmailGraphLargeFiles',
|
||||
'graph-not-set-up': 'statusEmailMethodGraphNotSetUp',
|
||||
'graph-unavailable': 'statusEmailGraphUnavailable',
|
||||
'internal-error': 'statusTurnstileInternalError',
|
||||
'invalid-input-secret': 'statusTurnstileInvalidSecret',
|
||||
@@ -35,6 +36,7 @@ export const STATUS_CODE_TEXTS: Record<string, AdminTextKey> = {
|
||||
'relay-suspended': 'statusEmailRelaySuspended',
|
||||
'relay-too-large': 'statusEmailRelayTooLarge',
|
||||
'relay-unreachable': 'statusEmailRelayUnreachable',
|
||||
'smtp-incomplete': 'statusEmailMethodSmtpIncomplete',
|
||||
}
|
||||
|
||||
type I18nLike = { language?: string; t?: (key: never, vars?: Record<string, unknown>) => string } | undefined
|
||||
|
||||
@@ -2,11 +2,85 @@ import type { BasePayload } from 'payload'
|
||||
|
||||
import type { GlobalQueryOptions } from './getGlobal.js'
|
||||
|
||||
import { getGlobal } from './getGlobal.js'
|
||||
|
||||
/** Slug of the SiteIntegrations global defined by the plugin. */
|
||||
export const SITE_INTEGRATIONS_SLUG = 'site-integrations'
|
||||
|
||||
/** The stored field added in 1.17.1 ("Sending method"). On Postgres / SQLite it needs a migration (a column). */
|
||||
export const MAIL_METHOD_FIELD = 'emailMethod'
|
||||
|
||||
let methodColumnMissing = false
|
||||
let warned = false
|
||||
let probedAt = 0
|
||||
/** While the column is missing, the full read is tried again this often — the migration may have run meanwhile. */
|
||||
const PROBE_EVERY_MS = 60_000
|
||||
|
||||
/**
|
||||
* True once a read of Site integrations found that the database has no column for `emailMethod`: a Postgres /
|
||||
* SQLite project upgraded to 1.17.1 whose migration has not run. The site keeps working by reading the global
|
||||
* without that field (the sending method then follows the order of 1.17.0); the panel page of Site integrations
|
||||
* and writes to the global fail until the migration runs. `iapl-doctor --deep` reports it (`mail-method`).
|
||||
*/
|
||||
export const mailMethodColumnMissing = (): boolean => methodColumnMissing
|
||||
|
||||
/** For tests. */
|
||||
export function resetMailMethodColumnMissing(): void {
|
||||
methodColumnMissing = false
|
||||
warned = false
|
||||
probedAt = 0
|
||||
}
|
||||
|
||||
const chain = (err: unknown): string => {
|
||||
const parts: string[] = []
|
||||
for (let current: unknown = err, depth = 0; current && depth < 6; current = (current as { cause?: unknown }).cause, depth++) {
|
||||
const message = (current as { message?: unknown }).message
|
||||
if (typeof message === 'string') {parts.push(message)}
|
||||
}
|
||||
return parts.join(' — ')
|
||||
}
|
||||
/** The database says the column of `emailMethod` is not there (Postgres, SQLite; Drizzle keeps its words in `cause`). */
|
||||
const isMissingMethodColumn = (err: unknown): boolean => {
|
||||
const text = chain(err)
|
||||
return /email_method/i.test(text) && /does not exist|no such column|unknown column|has no column/i.test(text)
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads Site integrations (Local API, access control bypassed). `context` reaches the fields' hooks.
|
||||
* Without the column of `emailMethod` the read is repeated without that field, so that e-mail, Turnstile and
|
||||
* analytics keep working on a SQL project whose migration has not run yet; one loud line says what to do.
|
||||
*/
|
||||
export async function findSiteIntegrations<T = Record<string, unknown>>(
|
||||
payload: BasePayload,
|
||||
options: { context?: Record<string, unknown> } & GlobalQueryOptions = {},
|
||||
): Promise<T> {
|
||||
const args = {
|
||||
slug: SITE_INTEGRATIONS_SLUG,
|
||||
...(options.locale ? { locale: options.locale as never } : {}),
|
||||
...(typeof options.depth === 'number' ? { depth: options.depth } : {}),
|
||||
...(options.context ? { context: options.context } : {}),
|
||||
}
|
||||
if (!methodColumnMissing || Date.now() - probedAt > PROBE_EVERY_MS) {
|
||||
probedAt = Date.now()
|
||||
try {
|
||||
const found = (await payload.findGlobal(args as never)) as T
|
||||
methodColumnMissing = false
|
||||
return found
|
||||
} catch (err) {
|
||||
if (!isMissingMethodColumn(err)) {throw err}
|
||||
methodColumnMissing = true
|
||||
if (!warned) {
|
||||
warned = true
|
||||
payload.logger.error(
|
||||
`[iapl] Site integrations: the column for "${MAIL_METHOD_FIELD}" ("Sending method", new in 1.17.1) is missing in the database (${chain(err)}). ` +
|
||||
'The site keeps working — e-mails go the way they did before the upgrade — but the Site integrations page of the panel does not open and the sending method cannot be chosen ' +
|
||||
'until the migration that adds the column has run: `pnpm payload migrate:create`, commit the migration, and have it applied when the new container starts ' +
|
||||
'(docs/email.md "Which transport a send takes" → Postgres and SQLite; docs/deployment.md §4.3).',
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
return (await payload.findGlobal({ ...args, select: { [MAIL_METHOD_FIELD]: false } } as never)) as T
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetches the SiteIntegrations global.
|
||||
*
|
||||
@@ -27,5 +101,5 @@ export function getSiteIntegrations<T = Record<string, unknown>>(
|
||||
payload: BasePayload,
|
||||
options?: GlobalQueryOptions,
|
||||
): Promise<T> {
|
||||
return getGlobal<T>(payload, SITE_INTEGRATIONS_SLUG, options)
|
||||
return findSiteIntegrations<T>(payload, options)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user