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:
co-authored by
Claude Fable 5.2
parent
68a2555277
commit
c6841a1674
@@ -11,6 +11,8 @@ type State = {
|
||||
accessKeyField?: boolean
|
||||
error?: string
|
||||
message?: string
|
||||
methodChosen?: boolean
|
||||
methodProblem?: 'graph-not-set-up' | 'smtp-incomplete'
|
||||
ok?: boolean
|
||||
refusalText?: string
|
||||
relay?: {
|
||||
@@ -104,6 +106,11 @@ export const MailRelayStatus = () => {
|
||||
: state.transport === 'graph' ? text('mailRelayTransportGraph')
|
||||
: text(relay ? 'mailRelayTransportNone' : 'mailRelayOff')}
|
||||
</p>
|
||||
{state.methodProblem ? (
|
||||
<p role="alert" style={warn}>{text(state.methodProblem === 'graph-not-set-up' ? 'mailMethodGraphNotSetUp' : 'mailMethodSmtpIncomplete')}</p>
|
||||
) : state.methodChosen === false && state.transport !== 'none' ? (
|
||||
<p style={{ ...line, fontSize: '0.85rem', opacity: 0.75 }}>{text('mailMethodNotChosen')}</p>
|
||||
) : null}
|
||||
{onRelay && relay ? (
|
||||
<>
|
||||
<p role={attention ? 'alert' : undefined} style={attention ? warn : line}>{relayState}</p>
|
||||
|
||||
@@ -1,29 +1,45 @@
|
||||
import type { Condition, Field } from 'payload'
|
||||
import type { BasePayload, Condition, Field } from 'payload'
|
||||
|
||||
import { graphAvailable, resolveMailMethod } from '../../../modules/email/mailAdapter.js'
|
||||
import { getMailMethod, type MailMethod } from '../../../modules/email/method.js'
|
||||
import { RELAY_SHORT_NAME as IWSN } from '../../../modules/email/relay/constants.js'
|
||||
import { buildIntegrationStatusBanner, buildIntegrationStatusField } from '../../../modules/integrations/status.js'
|
||||
|
||||
/**
|
||||
* E-mail sending settings. No field is needed for mail to work: a site with no SMTP server here
|
||||
* sends through the Intecion Notifications Webservice (modules/email/relay). The SMTP fields are
|
||||
* for a client who wants its own mail server; Microsoft Graph (set up on the server) is deprecated.
|
||||
* E-mail sending settings. "Sending method" names how e-mails leave: the built-in Intecion Notifications
|
||||
* Webservice (modules/email/relay; no other field is needed for it), the client's own SMTP server, or
|
||||
* Microsoft Graph (set up on the server; deprecated). What is chosen is what is used.
|
||||
*
|
||||
* Protected at the global level (SiteIntegrations requires an authenticated
|
||||
* user), so all fields — including the password — stay editable in the admin
|
||||
* panel while remaining inaccessible to anonymous API requests.
|
||||
*/
|
||||
|
||||
// SMTP fields only matter with the SMTP transport — hidden while Graph is selected.
|
||||
const usesSmtp: Condition = (_, siblingData) => siblingData?.emailTransport !== 'graph'
|
||||
// SMTP fields are shown only while "Own SMTP server" is the sending method.
|
||||
const usesSmtp: Condition = (_, siblingData) =>
|
||||
siblingData?.emailMethod ? siblingData.emailMethod === 'smtp' : siblingData?.emailTransport !== 'graph'
|
||||
|
||||
/**
|
||||
* What the "Sending method" field shows: the chosen method, or — while nobody has chosen — the method the
|
||||
* order of 1.17.0 picks for the present settings (so an upgraded site sees what it sends through today).
|
||||
*/
|
||||
export async function shownMailMethod(payload: Pick<BasePayload, 'kv'>, settings: Parameters<typeof resolveMailMethod>[0], relay: boolean): Promise<MailMethod> {
|
||||
const { method } = resolveMailMethod(settings, { chosen: await getMailMethod(payload), graphEnv: graphAvailable(), relay })
|
||||
// nothing usable at all (the service switched off, no SMTP, no Graph): SMTP is what is left to fill in
|
||||
return method === 'none' ? 'smtp' : method
|
||||
}
|
||||
|
||||
/**
|
||||
* The fields of the "E-mail sending" tab. `relay: false` (the project switched the Intecion mail
|
||||
* service off): no state block, and the wording of 1.16 — SMTP is then the way to send.
|
||||
* No stored field differs between the two: labels, descriptions and one client prop only.
|
||||
* service off): no state block, no "IWSN" option, and the wording of 1.16 — SMTP is then the way to send.
|
||||
*
|
||||
* "Sending method" (`emailMethod`) is a VIRTUAL field: it has no column, so no SQL schema changes. The
|
||||
* choice is kept in the key-value store (modules/email/method.ts) by the global's hooks. `emailTransport`
|
||||
* — the stored field of 1.6 to 1.17.0, values `smtp` / `graph` — stays as it was, hidden in the panel.
|
||||
*/
|
||||
export const buildSmtpFields = ({ relay = true }: { relay?: boolean } = {}): Field[] => [
|
||||
// Status written by mailAdapter on every send (throttled) — banner on this tab. With the mail service
|
||||
// enabled the same component shows, above it, which transport is in effect and the site's state with the
|
||||
// enabled the same component shows, above it, which method is in effect and the site's state with the
|
||||
// service (MailRelayStatus): no import-map entry of its own, so an upgrade needs no `generate:importmap`.
|
||||
buildIntegrationStatusBanner(
|
||||
'emailStatus',
|
||||
@@ -32,29 +48,36 @@ export const buildSmtpFields = ({ relay = true }: { relay?: boolean } = {}): Fie
|
||||
{ mailRelay: relay },
|
||||
),
|
||||
{
|
||||
name: 'emailTransport',
|
||||
name: 'emailMethod',
|
||||
type: 'select',
|
||||
admin: {
|
||||
description: relay
|
||||
? {
|
||||
en: `Automatic uses your SMTP server when it is filled in below, and ${IWSN} otherwise.`,
|
||||
pl: `Automatycznie: przez Twój serwer SMTP, jeśli jest uzupełniony poniżej, a w innym razie przez ${IWSN}.`,
|
||||
}
|
||||
: {
|
||||
en: 'Microsoft Graph works only when your administrator has set it up on the server.',
|
||||
pl: 'Microsoft Graph działa tylko wtedy, gdy administrator skonfiguruje go na serwerze.',
|
||||
},
|
||||
// The Graph option only makes sense when agency credentials exist in env.
|
||||
// We can't read process.env in the admin UI directly, so a client project
|
||||
// that hasn't set up Graph should filter this option via integrationsFields
|
||||
// override, or simply leave it on 'smtp'. The adapter enforces the real
|
||||
// availability at send time regardless of what's selected here.
|
||||
description: {
|
||||
en: 'E-mails are sent the way chosen here, and no other way.',
|
||||
pl: 'E-maile wychodzą wybranym tu sposobem i żadnym innym.',
|
||||
},
|
||||
},
|
||||
hooks: {
|
||||
afterRead: [({ req, siblingData }) => shownMailMethod(req.payload, siblingData ?? {}, relay)],
|
||||
},
|
||||
defaultValue: 'smtp',
|
||||
label: { en: 'Sending method', pl: 'Sposób wysyłki' },
|
||||
options: [
|
||||
// Labels only: the two stored values stay (a new value would change the Postgres enum).
|
||||
{ label: relay ? { en: 'Automatic', pl: 'Automatycznie' } : { en: 'SMTP server', pl: 'Serwer SMTP' }, value: 'smtp' },
|
||||
...(relay ? [{ label: { en: `${IWSN} (built-in)`, pl: `${IWSN} (wbudowany)` }, value: 'relay' }] : []),
|
||||
{ label: relay ? { en: 'Own SMTP server', pl: 'Własny serwer SMTP' } : { en: 'SMTP server', pl: 'Serwer SMTP' }, value: 'smtp' },
|
||||
// Works only when the administrator has set Graph up on the server (GRAPH_*); chosen without it, e-mails fail and say so.
|
||||
{ label: { en: 'Microsoft Graph (deprecated)', pl: 'Microsoft Graph (wycofywany)' }, value: 'graph' },
|
||||
],
|
||||
virtual: true,
|
||||
},
|
||||
{
|
||||
// The stored field of 1.6 – 1.17.0. Kept with its two values (a third would change the Postgres enum) and
|
||||
// kept in step with the choice where it can say it (`graph`, else `smtp`); the panel shows `emailMethod`.
|
||||
name: 'emailTransport',
|
||||
type: 'select',
|
||||
admin: { hidden: true },
|
||||
defaultValue: 'smtp',
|
||||
label: { en: 'Sending method (stored)', pl: 'Sposób wysyłki (zapis)' },
|
||||
options: [
|
||||
{ label: { en: 'SMTP server', pl: 'Serwer SMTP' }, value: 'smtp' },
|
||||
{ label: { en: 'Microsoft Graph (deprecated)', pl: 'Microsoft Graph (wycofywany)' }, value: 'graph' },
|
||||
],
|
||||
},
|
||||
@@ -106,18 +129,10 @@ export const buildSmtpFields = ({ relay = true }: { relay?: boolean } = {}): Fie
|
||||
name: 'smtpHost',
|
||||
type: 'text',
|
||||
admin: {
|
||||
...(relay
|
||||
? {
|
||||
description: {
|
||||
en: `Optional: fill in only to send through your own mail server instead of ${IWSN}.`,
|
||||
pl: `Opcjonalne: uzupełnij tylko, aby wysyłać przez własny serwer zamiast ${IWSN}.`,
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
placeholder: 'smtp.example.com',
|
||||
width: '70%',
|
||||
},
|
||||
label: relay ? { en: 'Own SMTP server', pl: 'Własny serwer SMTP' } : { en: 'Server', pl: 'Serwer' },
|
||||
label: { en: 'Server', pl: 'Serwer' },
|
||||
},
|
||||
{
|
||||
name: 'smtpPort',
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
import type { Field, GlobalConfig } from 'payload'
|
||||
|
||||
import { ValidationError } from 'payload'
|
||||
|
||||
import { userMeetsRole } from '../../modules/access/index.js'
|
||||
import { isMailMethod, setMailMethod } from '../../modules/email/method.js'
|
||||
import { INTEGRATION_SECRET_FIELDS, maskSecretsOnRestore, SMTP_PASSWORD_BOUND_TO, writeOnlySecrets } from '../../modules/secrets/writeOnly.js'
|
||||
import { indexNowFields } from '../../modules/seo/indexNow.js'
|
||||
import { analyticsFields } from './fields/analytics.js'
|
||||
import { buildSmtpFields } from './fields/smtp.js'
|
||||
import { buildSmtpFields, shownMailMethod } from './fields/smtp.js'
|
||||
import { turnstileFields } from './fields/turnstile.js'
|
||||
|
||||
type BuildSiteIntegrationsArgs = {
|
||||
@@ -87,13 +90,46 @@ export function buildSiteIntegrations({
|
||||
hooks: {
|
||||
// a restore answers with the version document: the secrets are masked there too
|
||||
...(writeOnly ? { afterRead: [maskSecretsOnRestore] } : {}),
|
||||
afterChange: [
|
||||
async ({ context, doc, req }) => {
|
||||
if (isMailMethod(context?.iaplMailMethod)) {
|
||||
await setMailMethod(req.payload, context.iaplMailMethod)
|
||||
// (the answer was read before this write: it must show what was just chosen)
|
||||
if (doc && typeof doc === 'object') {(doc as Record<string, unknown>).emailMethod = context.iaplMailMethod}
|
||||
} else if (context?.iaplMailMethod === null) {
|
||||
await setMailMethod(req.payload, null)
|
||||
}
|
||||
return doc
|
||||
},
|
||||
],
|
||||
// What the caller sent for the sending method, before Payload merges the stored document into the data.
|
||||
beforeChange: [
|
||||
// Keys edited in the panel → clear that integration's old status, so a stale
|
||||
// "not working" banner doesn't linger until the next form submission.
|
||||
({ context, data, originalDoc }) => {
|
||||
async ({ context, data, originalDoc, req }) => {
|
||||
if (context?.ipalIntegrationStatus || !data) {return data}
|
||||
const changed = (k: string) => k in data && data[k] !== originalDoc?.[k]
|
||||
const cleared = { checkedAt: null, code: null, message: null, since: null, state: null }
|
||||
// "Sending method" (the virtual field `emailMethod`): the choice is written to the key-value store
|
||||
// once the global is saved (afterChange). The stored `emailTransport` follows where it can say it.
|
||||
// (`data` is merged with the stored document by now; what the caller really sent was noted before the
|
||||
// merge — beforeOperation below. Without that note: a value that differs from the stored one was sent.)
|
||||
const noted = context?.iaplMailSent as { method?: unknown; transport?: boolean } | undefined
|
||||
const sent = noted ? noted.method : data.emailMethod !== originalDoc?.emailMethod ? data.emailMethod : undefined
|
||||
// (a virtual field's value is not checked against its options by Payload)
|
||||
if (sent !== undefined && sent !== null && !(isMailMethod(sent) && (sent !== 'relay' || mailRelay))) {
|
||||
throw new ValidationError({ errors: [{ message: 'This is not a sending method.', path: 'emailMethod' }], global: 'site-integrations' }, req.t)
|
||||
}
|
||||
if (isMailMethod(sent)) {
|
||||
data.emailMethod = sent
|
||||
const before = await shownMailMethod(req.payload, (originalDoc ?? {}) as never, mailRelay).catch(() => null)
|
||||
if (before !== data.emailMethod) {data.emailStatus = cleared}
|
||||
context.iaplMailMethod = data.emailMethod
|
||||
data.emailTransport = data.emailMethod === 'graph' ? 'graph' : 'smtp'
|
||||
} else if ((noted ? noted.transport : true) && changed('emailTransport')) {
|
||||
// written the old way (a script from before 1.17.1): it means what it meant — the order of 1.17.0
|
||||
context.iaplMailMethod = null
|
||||
}
|
||||
if (changed('turnstileSecretKey') || changed('turnstileSiteKey')) {data.turnstileStatus = cleared}
|
||||
if (Object.keys(data).some((k) => (k === 'emailTransport' || k.startsWith('smtp')) && changed(k))) {
|
||||
data.emailStatus = cleared
|
||||
@@ -101,6 +137,15 @@ export function buildSiteIntegrations({
|
||||
return data
|
||||
},
|
||||
],
|
||||
beforeOperation: [
|
||||
({ args, context, operation }) => {
|
||||
const data = (args as { data?: Record<string, unknown> } | undefined)?.data
|
||||
if (operation === 'update' && data && typeof data === 'object' && context) {
|
||||
context.iaplMailSent = { method: data.emailMethod ?? undefined, transport: 'emailTransport' in data }
|
||||
}
|
||||
return args
|
||||
},
|
||||
],
|
||||
},
|
||||
label: { en: 'Site integrations', pl: 'Integracje' },
|
||||
}
|
||||
|
||||
+5
-2
@@ -251,8 +251,11 @@ export { holdAccountMail, releaseAccountMail, sendAccountMailAfterCommit, withAc
|
||||
export { mailAttachmentLimit } from './modules/email/attachmentLimit.js'
|
||||
export { graphAdapter } from './modules/email/graphAdapter.js'
|
||||
export type { GraphAdapterArgs } from './modules/email/graphAdapter.js'
|
||||
export { GRAPH_DEPRECATION_NOTICE, mailAdapter, resolveMailTransport } from './modules/email/mailAdapter.js'
|
||||
export type { MailAdapterArgs, MailTransport } from './modules/email/mailAdapter.js'
|
||||
export { GRAPH_DEPRECATION_NOTICE, mailAdapter, resolveMailMethod, resolveMailTransport } from './modules/email/mailAdapter.js'
|
||||
export type { MailAdapterArgs, MailMethodProblem, MailTransport, ResolvedMailMethod } from './modules/email/mailAdapter.js'
|
||||
// "Sending method": the choice an admin saved (kept in payload-kv, so no SQL schema changes).
|
||||
export { getMailMethod, isMailMethod, MAIL_METHOD_KV_KEY, MAIL_METHODS, setMailMethod } from './modules/email/method.js'
|
||||
export type { MailMethod } from './modules/email/method.js'
|
||||
// Imported straight from the file, NOT from ./modules/email/index.js — that
|
||||
// barrel re-exports sendEmail, which imports 'server-only' and would crash when
|
||||
// Payload loads the config (or runs generate:importmap) as a plain Node script.
|
||||
|
||||
@@ -11,6 +11,9 @@ 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.',
|
||||
mailMethodNotChosen: 'Nobody has chosen the sending method yet, so the site picked this one. Save this page to keep it.',
|
||||
mailMethodSmtpIncomplete: 'Your SMTP server is chosen, but its settings are incomplete. E-mails are not sent. Fill in server, user name and password.',
|
||||
mailRelayCheck: 'Check now',
|
||||
mailRelayConnect: 'Connect again',
|
||||
mailRelayConnected: `The site is connected to ${IWSN}.`,
|
||||
@@ -84,6 +87,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 +124,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 +137,9 @@ 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.',
|
||||
mailMethodNotChosen: 'Nikt jeszcze nie wybrał sposobu wysyłki, więc witryna dobrała ten. Zapisz tę stronę, aby go zachować.',
|
||||
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.',
|
||||
mailRelayCheck: 'Sprawdź teraz',
|
||||
mailRelayConnect: 'Połącz ponownie',
|
||||
mailRelayConnected: `Witryna jest połączona z ${IWSN}.`,
|
||||
@@ -201,6 +210,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 +246,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,27 @@ 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.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: 'open Site integrations → E-mail sending, check "Sending method" and save: from then on the site sends that way only', message: `nobody has chosen the sending method yet: the site picks one from what is filled in (now: ${mail.transport === 'relay' ? 'the built-in service' : mail.transport === 'smtp' ? 'the SMTP server' : 'Microsoft Graph'}), and would switch by itself if that changed`, 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,7 @@ 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,
|
||||
relay: state.relay
|
||||
? {
|
||||
connected: state.relay.connected,
|
||||
@@ -84,6 +85,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,10 @@ 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
|
||||
/** 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`. */
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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 })
|
||||
}
|
||||
@@ -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,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user