E-mail: "Sending method" is an explicit choice - IWSN (built-in), Own SMTP server, Microsoft Graph (deprecated)

What is chosen is what is used. The choice is the stored field `emailMethod` of Site integrations (empty until
somebody chooses); `emailTransport` of 1.6 - 1.17.0 stays, hidden.

- no silent switch: a chosen method that cannot be used (SMTP incomplete, Graph without GRAPH_*) fails loudly
  - status smtp-incomplete / graph-not-set-up, state block, doctor mail-method - and nothing is sent another way
- upgrade writes nothing and loses no mail: until somebody chooses, the order of 1.17.0 applies and the field
  shows its result as selected; the first save of the panel's form stores the choice
- only the chosen method's fields are shown; the test e-mail names the method (Graph too)
- mail: { relay: false } does not offer "IWSN" (the stored values stay three: one SQL enum for every project)
- Postgres / SQLite: one migration (a column). Before it runs the plugin's readers read the global without the
  field, mail goes the old way, one loud log line and the doctor say what to do
- getMailMethod, setMailMethod, resolveMailMethod, readMailSettings, mailMethodColumnMissing exported
- tests on SQLite, Postgres and MongoDB, with and without the migration; docs, AGENT.md, skills, changelog

Co-Authored-By: Claude Fable 5.2 <[email protected]>
This commit is contained in:
Radosław Smoliński
2026-11-26 22:39:03 +01:00
co-authored by Claude Fable 5.2
parent c6841a1674
commit ee8ea42956
26 changed files with 376 additions and 138 deletions
+23 -10
View File
@@ -1,7 +1,7 @@
import type { BasePayload, Condition, Field } from 'payload'
import type { Condition, Field, SelectField } from 'payload'
import { graphAvailable, resolveMailMethod } from '../../../modules/email/mailAdapter.js'
import { getMailMethod, type MailMethod } from '../../../modules/email/method.js'
import { isMailMethod, type MailMethod, STORED_MAIL_METHOD_CONTEXT } 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'
@@ -19,12 +19,15 @@ import { buildIntegrationStatusBanner, buildIntegrationStatusField } from '../..
const usesSmtp: Condition = (_, siblingData) =>
siblingData?.emailMethod ? siblingData.emailMethod === 'smtp' : siblingData?.emailTransport !== 'graph'
const withoutRelay: NonNullable<SelectField['filterOptions']> = ({ options }) =>
options.filter((option) => (typeof option === 'string' ? option : option.value) !== 'relay')
/**
* 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 })
export function shownMailMethod(settings: Parameters<typeof resolveMailMethod>[0], relay: boolean): MailMethod {
const { method } = resolveMailMethod(settings, { chosen: isMailMethod(settings.emailMethod) ? settings.emailMethod : null, 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
}
@@ -33,9 +36,10 @@ export async function shownMailMethod(payload: Pick<BasePayload, 'kv'>, settings
* The fields of the "E-mail sending" tab. `relay: false` (the project switched the Intecion mail
* 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.
* "Sending method" (`emailMethod`) is a stored select, new in 1.17.1 (Postgres / SQLite: one migration); empty
* while nobody has chosen. Its three values are the same in every project, so the SQL enum does not depend on
* `relay`; with the service switched off the option is only not offered. `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
@@ -56,17 +60,26 @@ export const buildSmtpFields = ({ relay = true }: { relay?: boolean } = {}): Fie
pl: 'E-maile wychodzą wybranym tu sposobem i żadnym innym.',
},
},
// with the service switched off the stored values stay three; "IWSN" is only not offered
...(relay ? {} : { filterOptions: withoutRelay }),
hooks: {
afterRead: [({ req, siblingData }) => shownMailMethod(req.payload, siblingData ?? {}, relay)],
afterRead: [({ context, siblingData, value }) => {
// what is stored, for the update that follows this read (the global's beforeChange) …
if (context) {context.iaplMailMethodStored = isMailMethod(value) ? value : null}
// … and for the readers that decide from it (the mail adapter, the state block)
if (context?.[STORED_MAIL_METHOD_CONTEXT]) {return isMailMethod(value) ? value : null}
// the panel and everybody else: the method in effect, shown as selected
return shownMailMethod({ ...(siblingData ?? {}), emailMethod: value as never }, relay)
}],
},
label: { en: 'Sending method', pl: 'Sposób wysyłki' },
options: [
...(relay ? [{ label: { en: `${IWSN} (built-in)`, pl: `${IWSN} (wbudowany)` }, value: 'relay' }] : []),
// (with the service switched off the value stays in the list — one SQL enum for every project — unnamed and not offered)
{ label: relay ? { en: `${IWSN} (built-in)`, pl: `${IWSN} (wbudowany)` } : { en: 'Built-in (off)', pl: 'Wbudowany (wyłączony)' }, 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
+23 -31
View File
@@ -3,7 +3,7 @@ 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 { isMailMethod } 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'
@@ -90,45 +90,37 @@ 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.
async ({ context, data, originalDoc, req }) => {
({ 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
// "Sending method" (`emailMethod`). `data` is merged with the document as it was READ by now, and that read
// shows the method in effect as selected — which must not be stored as a choice nobody made. So: what the
// caller really sent was noted before the merge (beforeOperation below; without that note, a value that
// differs from the one read was sent), and what is stored was noted by the field's own read.
const noted = context?.iaplMailSent as { method?: unknown; sent?: boolean; transport?: boolean } | undefined
const sent = noted ? noted.sent : data.emailMethod !== originalDoc?.emailMethod
const stored = isMailMethod(context?.iaplMailMethodStored) ? context.iaplMailMethodStored : null
if (sent && isMailMethod(data.emailMethod)) {
if (data.emailMethod === 'relay' && !mailRelay) {
throw new ValidationError({ errors: [{ message: 'This sending method is switched off for this site.', path: 'emailMethod' }], global: 'site-integrations' }, req.t)
}
if (shownMailMethod({ ...(originalDoc ?? {}), emailMethod: stored } as never, mailRelay) !== data.emailMethod) {data.emailStatus = cleared}
// the stored field of 1.6 – 1.17.0 follows where it can say it
data.emailTransport = data.emailMethod === 'graph' ? 'graph' : 'smtp'
} else if (sent && data.emailMethod !== null && data.emailMethod !== undefined) {
// not a method: left as it is — the field's own validation refuses it
} else if (sent) {
data.emailMethod = null // un-chosen on purpose (`setMailMethod(payload, null)`): the order of 1.17.0 again
} 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
data.emailMethod = null
} else {
data.emailMethod = stored
}
if (changed('turnstileSecretKey') || changed('turnstileSiteKey')) {data.turnstileStatus = cleared}
if (Object.keys(data).some((k) => (k === 'emailTransport' || k.startsWith('smtp')) && changed(k))) {
@@ -141,7 +133,7 @@ export function buildSiteIntegrations({
({ 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 }
context.iaplMailSent = { sent: 'emailMethod' in data, transport: 'emailTransport' in data }
}
return args
},
+3 -2
View File
@@ -253,8 +253,8 @@ export { graphAdapter } from './modules/email/graphAdapter.js'
export type { GraphAdapterArgs } from './modules/email/graphAdapter.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'
// "Sending method": the choice an admin saved (the stored field `emailMethod`, new in 1.17.1).
export { getMailMethod, isMailMethod, MAIL_METHODS, readMailSettings, setMailMethod, STORED_MAIL_METHOD_CONTEXT } 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
@@ -426,6 +426,7 @@ export { getNotificationTexts, NOTIFICATION_FALLBACK, NOTIFICATION_FALLBACK_PL,
export type { FormNotificationTexts, NotificationTexts } from './modules/notifications/index.js'
export type { PagesOption, SystemPageRole } from './modules/pages/index.js'
export { ALL_SYSTEM_PAGE_ROLES, getSystemPagePath, unlistedPageIds } from './modules/pages/index.js'
export { mailMethodColumnMissing } from './modules/payload/getSiteIntegrations.js'
export type { GlobalQueryOptions } from './modules/payload/index.js'
export {
getGlobal,
+3
View File
@@ -59,6 +59,9 @@ export const mailRules: DoctorRule[] = [
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' }]
}
+1
View File
@@ -74,6 +74,7 @@ export async function collectDoctorStatus(payload: BasePayload): Promise<DoctorS
...(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,
+2
View File
@@ -69,6 +69,8 @@ export type DoctorStatus = {
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. */
+10 -9
View File
@@ -1,19 +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 { getMailMethod, type MailMethod } from './method.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
@@ -59,7 +60,7 @@ export type ResolvedMailMethod = {
}
/**
* The sending method in effect. With a choice (`getMailMethod`): exactly that method — an SMTP choice with
* 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
@@ -164,11 +165,11 @@ export const mailAdapter =
* without SMTP settings the ceiling is GRAPH_INLINE_MAX_BYTES.
*/
const relayOptions = () => resolveRelayOptions(payload, args.relay)
const methodOf = async (settings: TransportIntegrations) => resolveMailMethod(settings, { chosen: await getMailMethod(payload), 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 = (await methodOf(settings)).method
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}
@@ -192,10 +193,10 @@ 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 resolved = await methodOf(settings)
const resolved = methodOf(settings)
const chosen = resolved.method
// No SMTP server in the panel and no Graph: the Intecion Notifications Webservice.
+24 -25
View File
@@ -1,49 +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).
*
* 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.
* 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.
*
* 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.
* 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']
export const MAIL_METHOD_KV_KEY = 'iapl:mail-method'
/**
* 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)
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 ?? {})
/** 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: 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
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: 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 })
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 })
}
+8 -4
View File
@@ -5,9 +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 { mailMethodColumnMissing } from '../../payload/getSiteIntegrations.js'
import { graphAvailable, type MailMethodProblem, type MailTransport, resolveMailMethod, smtpIncomplete } from '../mailAdapter.js'
import { getMailMethod } from '../method.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'
@@ -16,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
@@ -35,6 +36,8 @@ export type MailPanelState = {
* 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. */
@@ -66,9 +69,9 @@ 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 method = resolveMailMethod(settings, { chosen: await getMailMethod(payload), 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
@@ -98,6 +101,7 @@ export async function mailPanelState(req: Pick<PayloadRequest, 'payload'>, own:
...(options?.accessKeyField === true ? { accessKeyField: true } : {}),
...(status?.host ? { confirmUrl: `https://${status.host}${api}${RELAY_CONFIRM_PATH}` } : {}),
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,
+77 -3
View File
@@ -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)
}