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
+5
View File
@@ -754,6 +754,11 @@ describe('e-mail: transport, the mail service, Graph, the confirm route', () =>
expect(open[0].message).toContain('the built-in service')
expect(open[0].fix).toContain('save')
expect(await find({ methodChosen: true })).toEqual([])
// Postgres / SQLite whose 1.17.1 migration has not run
const column = await find({ methodChosen: false, methodColumnMissing: true })
expect(column.map((f) => f.severity)).toEqual(['error'])
expect(column[0].message).toContain('no column for "Sending method"')
expect(column[0].fix).toContain('migrate:create')
expect(await find({ methodChosen: false, relay: null, transport: 'none' })).toEqual([]) // that is mail-transport's error
})
+98
View File
@@ -0,0 +1,98 @@
/**
* Postgres / SQLite upgraded to 1.17.1 WITHOUT the migration that adds the column of "Sending method"
* (`emailMethod`), against the real adapter: the site must keep working — e-mail the way it went before, the
* other integrations readable — say loudly what to do, and pick the choice up once the column exists.
* SQLite in memory by default; `IPAL_TEST_POSTGRES_URI` runs it on Postgres. Not for MongoDB (no columns).
*/
import type { Payload } from 'payload'
import { lexicalEditor } from '@payloadcms/richtext-lexical'
import os from 'os'
import path from 'path'
import { getPayload } from 'payload'
import { afterAll, beforeAll, expect, test, vi } from 'vitest'
import { mailAdapter } from '../src/modules/email/mailAdapter.js'
import { getMailMethod, setMailMethod } from '../src/modules/email/method.js'
import { createFakeRelay } from '../src/modules/email/relay/fake.js'
import { mailPanelState } from '../src/modules/email/relay/panel.js'
import { getSiteIntegrations, mailMethodColumnMissing, resetMailMethodColumnMissing } from '../src/modules/payload/getSiteIntegrations.js'
import { iapl } from '../src/plugin.js'
import { buildTestConfig } from './helpers.js'
import { testDatabase } from './http/db.js'
import { startPayloadServer, type TestServer } from './http/server.js'
vi.mock('server-only', () => ({}))
vi.mock('next/headers.js', async () => (await import('./http/server.js')).nextHeadersMock)
const sql = !process.env.IPAL_TEST_MONGO_URI
const HOST = 'example.com'
let payload: Payload
let server: TestServer
const fake = createFakeRelay({ allow: [HOST], callSite: async (url, init) => fetch(`${server.url}${new URL(url).pathname}`, { ...init, redirect: 'manual' }) })
beforeAll(async () => {
if (!sql) {return}
const config = buildTestConfig({
admin: { user: 'users' },
collections: [{ slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), 'iapl-method-column-media') } }],
db: testDatabase('methodcol'),
editor: lexicalEditor(),
email: mailAdapter(),
plugins: [iapl({ access: { authCollection: 'users' }, i18n: { defaultLocale: 'en', locales: [{ code: 'en', label: 'English' }] }, mail: { relay: { fetchImpl: fake.fetch, url: fake.url } }, twoFactor: false })],
secret: 'integration-test-secret-0123456789',
serverURL: `https://${HOST}`,
telemetry: false,
})
payload = await getPayload({ config })
server = await startPayloadServer(config)
}, 120_000)
afterAll(async () => {
await server?.close()
await payload?.destroy?.()
resetMailMethodColumnMissing()
})
test.skipIf(!sql)('without the column: one loud line, mail and the other settings keep working by the order of 1.17.0; with it: the choice works', async () => {
// the site as 1.17.0 left it: a row with settings, sending through the service
await payload.updateGlobal({ slug: 'site-integrations' as never, data: { ga4MeasurementId: 'G-BEFORE1', smtpFromName: 'Kancelaria Example' } as never })
const db = payload.db as unknown as { client?: { execute: (q: string) => Promise<unknown> }; pool?: { query: (q: string) => Promise<unknown> }; schemaName?: string }
const run = (statement: string) => (db.pool ? db.pool.query(statement) : db.client!.execute(statement))
const table = db.pool && db.schemaName ? `"${db.schemaName}"."site_integrations"` : '"site_integrations"'
await run(`ALTER TABLE ${table} DROP COLUMN "email_method"`)
resetMailMethodColumnMissing()
const error = vi.spyOn(payload.logger, 'error').mockImplementation(() => undefined as never)
// Payload's own read of the global fails — that is the panel page …
await expect(payload.findGlobal({ slug: 'site-integrations' as never })).rejects.toThrow()
// … the plugin's readers do not: analytics and Turnstile settings are there
expect(await getSiteIntegrations<{ ga4MeasurementId?: string }>(payload)).toMatchObject({ ga4MeasurementId: 'G-BEFORE1' })
expect(mailMethodColumnMissing()).toBe(true)
expect(error).toHaveBeenCalledTimes(1)
expect(String(error.mock.calls[0]?.[0])).toMatch(/the column for "emailMethod".*is missing.*keeps working.*migrate:create/s)
// e-mail leaves the way it did before the upgrade (no SMTP server: the service), and says nothing more
expect(await getMailMethod(payload)).toBeNull()
expect(await mailPanelState({ payload }, undefined)).toMatchObject({ methodChosen: false, methodColumnMissing: true, transport: 'relay' })
expect(await payload.sendEmail({ html: '<p>Hello.</p>', subject: 'Before the migration', to: '[email protected]' })).toMatchObject({ transport: 'relay' })
expect(fake.outbox.at(-1)).toMatchObject({ subject: 'Before the migration' })
await getSiteIntegrations(payload)
expect(error).toHaveBeenCalledTimes(1) // once, not on every read
// the method cannot be chosen yet
await expect(setMailMethod(payload, 'smtp')).rejects.toThrow()
// the migration: the column is there → reads are whole again, the choice is stored and used
await run(`ALTER TABLE ${table} ADD COLUMN "email_method" ${db.pool && db.schemaName ? `"${db.schemaName}"."enum_site_integrations_email_method"` : 'text'}`)
resetMailMethodColumnMissing() // (a running process looks again within a minute; a deploy restarts it anyway)
expect((await getSiteIntegrations<{ emailMethod?: string }>(payload)).emailMethod).toBe('relay') // shown as selected
expect(mailMethodColumnMissing()).toBe(false)
expect(await getMailMethod(payload)).toBeNull()
await setMailMethod(payload, 'smtp')
expect(await getMailMethod(payload)).toBe('smtp')
expect(await mailPanelState({ payload }, undefined)).toMatchObject({ methodChosen: true, methodProblem: 'smtp-incomplete', transport: 'smtp' })
expect((await mailPanelState({ payload }, undefined)).methodColumnMissing).toBeUndefined()
const before = fake.requests.length
expect(await payload.sendEmail({ html: '<p>Hello.</p>', subject: 'After', to: '[email protected]' })).toMatchObject({ code: 'not-configured', sent: false })
expect(fake.requests).toHaveLength(before)
error.mockRestore()
})
+26 -23
View File
@@ -5,7 +5,8 @@
* keeps sending; nothing is written by reading;
* - the first save of the panel's form stores the choice; from then on what is chosen is what is used —
* an unusable choice fails loudly and nothing leaves another way;
* - no stored field was added: the panel's field is virtual, the choice is in the key-value store.
* - the choice is the stored field `emailMethod`, empty until somebody chooses (Postgres / SQLite: a column —
* test/mailMethodColumnMissing.test.ts is the site whose migration has not run).
*/
import type { Payload } from 'payload'
@@ -16,7 +17,7 @@ import { getPayload } from 'payload'
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test, vi } from 'vitest'
import { mailAdapter, resolveMailMethod, resolveMailTransport } from '../src/modules/email/mailAdapter.js'
import { getMailMethod, MAIL_METHOD_KV_KEY, setMailMethod } from '../src/modules/email/method.js'
import { getMailMethod, setMailMethod } from '../src/modules/email/method.js'
import { createFakeRelay } from '../src/modules/email/relay/fake.js'
import { mailPanelState } from '../src/modules/email/relay/panel.js'
import { SECRET_CLEAR } from '../src/modules/secrets/writeOnly.js'
@@ -69,8 +70,7 @@ const saveForm = async (change: Record<string, unknown> = {}) => {
}
/** A site as an older version left it: the stored fields only, nothing chosen. */
const asStored = async (data: Record<string, unknown>) => {
await payload.updateGlobal({ slug: 'site-integrations' as never, data: { emailStatus: { checkedAt: null, code: null, message: null, since: null, state: null }, emailTransport: 'smtp', ...NO_SMTP, ...data } as never })
await payload.kv.delete(MAIL_METHOD_KV_KEY)
await payload.updateGlobal({ slug: 'site-integrations' as never, data: { emailMethod: null, emailStatus: { checkedAt: null, code: null, message: null, since: null, state: null }, emailTransport: 'smtp', ...NO_SMTP, ...data } as never })
}
const state = () => mailPanelState({ payload }, undefined)
const send = () => payload.sendEmail(MESSAGE) as Promise<{ code?: string; sent?: boolean; transport?: string }>
@@ -108,7 +108,6 @@ describe('upgrade, with no edit: the site shows the method it sends through toda
// the stored field is what it was, and nothing was chosen on the site's behalf
expect((await read()).emailTransport).toBe('smtp')
expect(await getMailMethod(payload)).toBeNull()
expect(await payload.kv.get(MAIL_METHOD_KV_KEY)).toBeNull()
})
test('a site with its SMTP server filled in: "Own SMTP server" is selected, the service is not contacted', async () => {
@@ -147,7 +146,6 @@ describe('upgrade, with no edit: the site shows the method it sends through toda
})
test('a new site (nothing ever saved): "IWSN" is selected', async () => {
await payload.kv.delete(MAIL_METHOD_KV_KEY)
await asStored({})
expect((await read()).emailMethod).toBe('relay')
})
@@ -241,9 +239,15 @@ describe('the choice: what is chosen is what is used', () => {
expect(await getMailMethod(payload)).toBeNull()
})
test('only an admin reaches the choice; it is not in the key-value store\'s REST', async () => {
test('only an admin reaches the choice; a save that only records the sending status does not store one', async () => {
await asStored({})
expect((await fetch(`${server.url}/api/globals/site-integrations`, { body: JSON.stringify({ emailMethod: 'smtp' }), headers: { 'content-type': 'application/json' }, method: 'POST' })).status).toBeGreaterThanOrEqual(401)
expect((await api('/payload-kv')).status).toBeGreaterThanOrEqual(400)
// the plugin's own writes (the status after a send) and a partial save carry the method the read SHOWED — it must not become a choice
await send()
await payload.updateGlobal({ slug: 'site-integrations' as never, data: { smtpFromName: 'Kancelaria Example' } as never })
expect((await api('/globals/site-integrations', { body: JSON.stringify({ ga4MeasurementId: 'G-TEST456' }), method: 'POST' })).status).toBe(200)
expect(await getMailMethod(payload)).toBeNull()
expect((await read()).emailMethod).toBe('relay')
})
})
@@ -277,23 +281,20 @@ describe('resolveMailMethod', () => {
})
})
describe('no stored field was added', () => {
test('`emailMethod` is virtual: the SQL table has no column for it; the document in the database does not hold it', async () => {
describe('where the choice is stored', () => {
test('in the global\'s own field: empty until somebody chooses, then the method; the three values are the same with the service on and off', async () => {
await asStored({})
await saveForm({ emailMethod: 'smtp' })
const db = payload.db as unknown as { collections?: unknown; connection?: { collection: (n: string) => { findOne: (q: object) => Promise<null | Record<string, unknown>> } }; name?: string; tables?: Record<string, Record<string, unknown>> }
if (db.tables) {
const table = db.tables.site_integrations
expect(table).toBeTruthy()
const columns = Object.keys(table).map((c) => c.toLowerCase())
expect(columns).toContain('emailtransport')
expect(columns.filter((c) => c.includes('method'))).toEqual([])
} else {
const raw = await db.connection!.collection('globals').findOne({ globalType: 'site-integrations' })
expect(raw).toMatchObject({ emailTransport: 'smtp' })
expect(raw).not.toHaveProperty('emailMethod')
const db = payload.db as unknown as { connection?: { collection: (n: string) => { findOne: (q: object) => Promise<null | Record<string, unknown>> } }; tables?: Record<string, Record<string, unknown>> }
const raw = async (): Promise<unknown> => {
if (db.tables) {return ((await payload.findGlobal({ slug: 'site-integrations' as never, context: { iaplStoredMailMethod: true }, depth: 0 })) as unknown as { emailMethod?: unknown }).emailMethod ?? null}
return (await db.connection!.collection('globals').findOne({ globalType: 'site-integrations' }))?.emailMethod ?? null
}
expect(await raw()).toBeNull()
await saveForm({ emailMethod: 'smtp' })
expect(await raw()).toBe('smtp')
if (db.tables) {expect(Object.keys(db.tables.site_integrations).map((c) => c.toLowerCase())).toEqual(expect.arrayContaining(['emailtransport', 'emailmethod']))}
await setMailMethod(payload, null)
expect(await raw()).toBeNull()
})
test('`mail: { relay: false }`: the option "IWSN" is not offered, and a stored choice of it counts as none', async () => {
@@ -302,6 +303,8 @@ describe('no stored field was added', () => {
return [...field.matchAll(/"value":"(\w+)"/g)].map((m) => m[1])
}
expect(methods(await makeConfig(undefined, 'methodson'))).toEqual(['relay', 'smtp', 'graph'])
expect(methods(await makeConfig({ relay: false }, 'methodsoff'))).toEqual(['smtp', 'graph'])
// the stored values are the same (one SQL enum for every project); the option is not offered and not accepted
expect(methods(await makeConfig({ relay: false }, 'methodsoff'))).toEqual(['relay', 'smtp', 'graph'])
expect(JSON.stringify((await makeConfig({ relay: false }, 'methodsoff2')).globals?.find((g) => g.slug === 'site-integrations')?.fields ?? '')).not.toBe('')
})
})
+3 -2
View File
@@ -313,8 +313,7 @@ describe('switched off, and what did not change', () => {
const endpoints = (config: SanitizedConfig) => (config.endpoints ?? []).map((e) => `${e.method} ${e.path}`)
const stored = (fields: Field[]): string[] =>
fields.flatMap((f) => {
// (a virtual field has no column and no stored value: "Sending method", whose choice is in the key-value store)
if (f.type === 'ui' || ('virtual' in f && f.virtual)) {return []}
if (f.type === 'ui') {return []}
if (f.type === 'tabs') {return f.tabs.flatMap((t) => stored(t.fields))}
const own = 'name' in f && f.name ? [`${f.name}:${f.type}${f.type === 'select' ? `(${(f.options as { value: string }[]).map((o) => (typeof o === 'string' ? o : o.value)).join('|')})` : ''}`] : []
return 'fields' in f && Array.isArray(f.fields) ? [...own, ...stored(f.fields).map((n) => ('name' in f && f.name ? `${f.name}.${n}` : n))] : own
@@ -341,6 +340,8 @@ describe('switched off, and what did not change', () => {
const on = names(await makeConfig(undefined, 'fieldson'))
expect(on).toEqual(names(await makeConfig({ relay: false }, 'fieldsoff')))
expect(on).toEqual([
// new in 1.17.1 (Postgres / SQLite: one migration); the same three values with the service on and off
'emailMethod:select(relay|smtp|graph)',
'emailTransport:select(smtp|graph)',
'smtpFromAddress:email',
'smtpFromName:text',