/** * "Sending method" on a running Payload (SQLite by default; MongoDB and Postgres through * IPAL_TEST_MONGO_URI / IPAL_TEST_POSTGRES_URI — test/http/db.ts): the explicit choice of 1.17.1. * - upgrade: a site of 1.17.0 or 1.16.x, with nothing chosen, shows the method it sends through today and * 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; * - 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' import { lexicalEditor } from '@payloadcms/richtext-lexical' import os from 'os' import path from 'path' 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, 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' 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 PASSWORD = 'a-long-test-password-1' const HOST = 'example.com' const GRAPH_ENV = ['GRAPH_TENANT_ID', 'GRAPH_CLIENT_ID', 'GRAPH_CLIENT_SECRET', 'GRAPH_SENDER'] // a mail server nobody listens on: an SMTP attempt fails at once, and is told apart from "not attempted" const SMTP = { smtpHost: '127.0.0.1', smtpPassword: 'smtp-test-password', smtpPort: 9, smtpUser: 'mailer' } const NO_SMTP = { smtpHost: null, smtpPassword: SECRET_CLEAR, smtpPort: 587, smtpUser: null } const MESSAGE = { html: '

Hello.

', subject: 'New enquiry', to: 'office@example.org' } let server: TestServer let payload: Payload let admin: Record const fake = createFakeRelay({ allow: [HOST], callSite: async (url, init) => fetch(`${server.url}${new URL(url).pathname}`, { ...init, redirect: 'manual' }), }) const makeConfig = (mail?: Parameters[0]['mail'], name = 'mailmethod') => buildTestConfig({ admin: { user: 'users' }, collections: [{ slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), 'iapl-mail-method-media') } }], db: testDatabase(name), editor: lexicalEditor(), email: mailAdapter({ smtp: { connectionTimeout: 2000 } as never }), plugins: [iapl({ access: { authCollection: 'users' }, i18n: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] }, mail, twoFactor: false })], secret: 'integration-test-secret-0123456789', serverURL: `https://${HOST}`, telemetry: false, }) const api = (pathname: string, init: RequestInit = {}) => fetch(`${server.url}/api${pathname}`, { ...init, headers: { 'content-type': 'application/json', ...admin, ...(init.headers as Record) } }) /** The global as the panel reads it. */ const read = async () => (await (await api('/globals/site-integrations?depth=0')).json()) as Record /** A save the way the panel's form makes it: the whole document, with what the form shows. */ const saveForm = async (change: Record = {}) => { const { id: _i, createdAt: _c, emailStatus: _s, globalType: _g, smtpPassword: _p, turnstileStatus: _t, updatedAt: _u, ...form } = await read() return api('/globals/site-integrations', { body: JSON.stringify({ ...form, ...change }), method: 'POST' }) } /** A site as an older version left it: the stored fields only, nothing chosen. */ const asStored = async (data: Record) => { 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 }> const relayCalls = () => fake.requests.filter((r) => r.path === '/v1/send').length const status = async () => ((await payload.findGlobal({ slug: 'site-integrations' as never, depth: 0 })) as unknown as { emailStatus?: { code?: string; state?: string } }).emailStatus beforeAll(async () => { const config = makeConfig({ relay: { fetchImpl: fake.fetch, url: fake.url } }) payload = await getPayload({ config }) server = await startPayloadServer(config) await payload.create({ collection: 'users' as never, data: { email: 'admin@example.com', password: PASSWORD, roles: ['admin'] } as never }) const res = await fetch(`${server.url}/api/users/login`, { body: JSON.stringify({ email: 'admin@example.com', password: PASSWORD }), headers: { 'content-type': 'application/json' }, method: 'POST' }) admin = { authorization: `JWT ${((await res.json()) as { token: string }).token}` } }, 120_000) afterAll(async () => { await server?.close() await payload?.destroy?.() }) beforeEach(() => { for (const name of GRAPH_ENV) {vi.stubEnv(name, '')} }) afterEach(() => vi.unstubAllEnvs()) describe('upgrade, with no edit: the site shows the method it sends through today, and keeps sending', () => { test('a 1.17.0 site that sends through the service because SMTP is empty: "IWSN" is selected, mail leaves through it, reading writes nothing', async () => { await asStored({ smtpFromAddress: 'biuro@example.com', smtpFromName: 'Kancelaria Example' }) expect((await read()).emailMethod).toBe('relay') expect(await state()).toMatchObject({ methodChosen: false, transport: 'relay' }) const before = relayCalls() expect(await send()).toMatchObject({ transport: 'relay' }) expect(relayCalls()).toBe(before + 1) expect(fake.outbox.at(-1)).toMatchObject({ subject: 'New enquiry' }) // 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() }) test('a site with its SMTP server filled in: "Own SMTP server" is selected, the service is not contacted', async () => { await asStored(SMTP) expect((await read()).emailMethod).toBe('smtp') expect(await state()).toMatchObject({ methodChosen: false, transport: 'smtp' }) const before = fake.requests.length const sent = await send().catch((e: Error) => ({ code: 'threw', error: e.message, sent: false })) expect(sent.sent).not.toBe(true) // nobody listens on the port: SMTP was tried, and only SMTP expect(fake.requests).toHaveLength(before) expect((await status())?.code).toBe('smtp-error') }) test('a Graph site: "Microsoft Graph (deprecated)" is selected — with the choice stored as `graph`, or with only the GRAPH_* variables', async () => { for (const name of GRAPH_ENV) {vi.stubEnv(name, 'x')} await asStored({ emailTransport: 'graph' }) expect((await read()).emailMethod).toBe('graph') expect(await state()).toMatchObject({ methodChosen: false, transport: 'graph' }) await asStored({}) expect((await read()).emailMethod).toBe('graph') // and with SMTP filled in beside the variables: SMTP, as in 1.17.0 and 1.16 await asStored(SMTP) expect((await read()).emailMethod).toBe('smtp') }) test('1.16.x straight to 1.17.1: "Graph" stored without the variables and SMTP filled in → SMTP; half an SMTP set-up → the service, with the hint', async () => { await asStored({ emailTransport: 'graph', ...SMTP }) expect((await read()).emailMethod).toBe('smtp') expect(await state()).toMatchObject({ methodChosen: false, transport: 'smtp' }) await asStored({ smtpHost: 'smtp.example.com', smtpUser: 'mailer' }) expect((await read()).emailMethod).toBe('relay') expect(await state()).toMatchObject({ methodChosen: false, smtpIncomplete: true, transport: 'relay' }) const before = relayCalls() expect(await send()).toMatchObject({ transport: 'relay' }) expect(relayCalls()).toBe(before + 1) }) test('a new site (nothing ever saved): "IWSN" is selected', async () => { await asStored({}) expect((await read()).emailMethod).toBe('relay') }) }) describe('the choice: what is chosen is what is used', () => { test('the owner\'s rule: saving without picking another option stores nothing and changes nothing; picking another one stores it', async () => { // an upgraded site on the service: the form is saved as it is, twice — nothing is chosen, mail goes as before await asStored({}) for (const change of [{}, { smtpFromName: 'Kancelaria Example' }]) { const saved = await saveForm(change) expect(saved.status).toBe(200) expect(((await saved.json()) as { result: { emailMethod: string } }).result.emailMethod).toBe('relay') expect(await getMailMethod(payload)).toBeNull() } expect(await state()).toMatchObject({ methodChosen: false, transport: 'relay' }) // …and it still follows what is filled in, as before (the old order): an SMTP server is filled in → SMTP await payload.updateGlobal({ slug: 'site-integrations' as never, data: SMTP as never }) expect((await read()).emailMethod).toBe('smtp') expect(await getMailMethod(payload)).toBeNull() // a Graph site saved as it is stays a Graph site (the old order), with the variables for (const name of GRAPH_ENV) {vi.stubEnv(name, 'x')} await asStored({ emailTransport: 'graph' }) await saveForm({}) expect(await getMailMethod(payload)).toBeNull() expect(await read()).toMatchObject({ emailMethod: 'graph', emailTransport: 'graph' }) for (const name of GRAPH_ENV) {vi.stubEnv(name, '')} // picking ANOTHER option stores it, and the answer shows it; the stored field of 1.17.0 follows await asStored({}) const changed = await saveForm({ emailMethod: 'graph' }) expect(((await changed.json()) as { result: { emailMethod: string; emailTransport: string } }).result).toMatchObject({ emailMethod: 'graph', emailTransport: 'graph' }) expect(await getMailMethod(payload)).toBe('graph') // once chosen, a save that keeps it keeps it, and the method no longer follows what is filled in await saveForm({ emailMethod: 'relay' }) expect(await getMailMethod(payload)).toBe('relay') await saveForm({ smtpFromName: 'Kancelaria Example' }) expect(await getMailMethod(payload)).toBe('relay') await payload.updateGlobal({ slug: 'site-integrations' as never, data: SMTP as never }) expect(await state()).toMatchObject({ methodChosen: true, transport: 'relay' }) await saveForm({ emailMethod: 'smtp' }) expect(await read()).toMatchObject({ emailMethod: 'smtp', emailTransport: 'smtp' }) }) test('the state block is told whether Graph could send, for its warning before the save', async () => { await asStored({}) expect((await state()).graphReady).toBe(false) for (const name of GRAPH_ENV) {vi.stubEnv(name, 'x')} expect((await state()).graphReady).toBe(true) }) test('"IWSN" chosen: the service carries the mail although an SMTP server is filled in and the GRAPH_* variables are set', async () => { await asStored(SMTP) await saveForm({ emailMethod: 'relay' }) for (const name of GRAPH_ENV) {vi.stubEnv(name, 'x')} expect(await state()).toMatchObject({ methodChosen: true, transport: 'relay' }) const before = relayCalls() expect(await send()).toMatchObject({ transport: 'relay' }) expect(relayCalls()).toBe(before + 1) expect((await read()).emailMethod).toBe('relay') }) test('"Own SMTP server" chosen with nothing filled in: the mail fails and says so — nothing goes through the service', async () => { await asStored({}) expect((await saveForm({ emailMethod: 'smtp' })).status).toBe(200) expect(await state()).toMatchObject({ methodChosen: true, methodProblem: 'smtp-incomplete', transport: 'smtp' }) const before = fake.requests.length expect(await send()).toMatchObject({ code: 'not-configured', sent: false }) expect(fake.requests).toHaveLength(before) expect(await status()).toMatchObject({ code: 'smtp-incomplete', state: 'degraded' }) // the test e-mail says the same to the admin, and still nothing leaves another way const tested = await api('/ipal/test-email', { body: JSON.stringify({ to: 'anna@example.org' }), method: 'POST' }) expect(tested.status).toBe(502) expect(fake.requests).toHaveLength(before) // the form still shows what was chosen, not what would work expect((await read()).emailMethod).toBe('smtp') }) test('"Microsoft Graph" chosen on a server without GRAPH_*: fails loudly; neither SMTP (filled in) nor the service is tried', async () => { await asStored(SMTP) await saveForm({ emailMethod: 'graph' }) expect(await state()).toMatchObject({ methodChosen: true, methodProblem: 'graph-not-set-up', transport: 'graph' }) const before = fake.requests.length expect(await send()).toMatchObject({ code: 'graph-not-set-up', sent: false }) expect(fake.requests).toHaveLength(before) expect(await status()).toMatchObject({ code: 'graph-not-set-up', state: 'degraded' }) // not `smtp-error`: SMTP was not tried const tested = await api('/ipal/test-email', { body: JSON.stringify({ to: 'anna@example.org' }), method: 'POST' }) expect(tested.status).toBe(502) expect(((await tested.json()) as { code: string; error: string })).toMatchObject({ code: 'graph-not-set-up' }) // with the variables the problem is gone (no send here: that would call Microsoft) for (const name of GRAPH_ENV) {vi.stubEnv(name, 'x')} expect((await state()).methodProblem).toBeUndefined() }) test('the test e-mail names the method that carried it', async () => { await asStored({ smtpFromName: 'Kancelaria Example' }) await saveForm({ emailMethod: 'relay' }) const tested = await api('/ipal/test-email', { body: JSON.stringify({ to: 'anna@example.org' }), method: 'POST' }) expect(tested.status).toBe(200) expect(await tested.json()).toMatchObject({ ok: true, transport: 'relay' }) }) test('a save that names nothing about e-mail leaves the choice alone; the old field written alone means what it meant', async () => { await asStored({}) await setMailMethod(payload, 'smtp') expect((await api('/globals/site-integrations', { body: JSON.stringify({ ga4MeasurementId: 'G-TEST123' }), method: 'POST' })).status).toBe(200) expect(await getMailMethod(payload)).toBe('smtp') // a script from before 1.17.1 writes `emailTransport`: the order of 1.17.0 applies again expect((await api('/globals/site-integrations', { body: JSON.stringify({ emailTransport: 'graph' }), method: 'POST' })).status).toBe(200) expect(await getMailMethod(payload)).toBeNull() expect((await read()).emailMethod).toBe('relay') // Graph stored, no variables, no SMTP: the service, as in 1.17.0 // the Local API, and the building blocks await payload.updateGlobal({ slug: 'site-integrations' as never, data: { emailMethod: 'smtp' } as never }) expect(await getMailMethod(payload)).toBe('smtp') await setMailMethod(payload, null) expect(await getMailMethod(payload)).toBeNull() await expect(setMailMethod(payload, 'sendmail' as never)).rejects.toThrow('not a sending method') // a value that is not a method is refused by the field expect((await api('/globals/site-integrations', { body: JSON.stringify({ emailMethod: 'sendmail' }), method: 'POST' })).status).toBe(400) expect(await getMailMethod(payload)).toBeNull() }) 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) // 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') }) }) describe('review M-1, M-2', () => { test('M-1: the plugin\'s own status write never stores a choice — a failed send, then a send that works again', async () => { // an upgraded site with an SMTP server nobody listens on: nothing chosen, SMTP shown await asStored(SMTP) expect(await getMailMethod(payload)).toBeNull() await send().catch(() => undefined) expect((await status())?.state).toBe('degraded') // the status WAS written expect(await getMailMethod(payload)).toBeNull() // the admin empties the SMTP server later: the site goes back to the service, as the old order says await payload.updateGlobal({ slug: 'site-integrations' as never, data: NO_SMTP as never }) expect(await getMailMethod(payload)).toBeNull() // (emptying the server cleared the old status; a status written the plugin's way, then a send that works: degraded → ok) await payload.updateGlobal({ slug: 'site-integrations' as never, context: { ipalIntegrationStatus: true }, data: { emailStatus: { code: 'relay-error', state: 'degraded' } } as never }) expect(await getMailMethod(payload)).toBeNull() expect(await send()).toMatchObject({ transport: 'relay' }) expect((await status())?.state).toBe('ok') expect(await getMailMethod(payload)).toBeNull() expect((await read()).emailMethod).toBe('relay') // and a stored choice survives the same writes await setMailMethod(payload, 'smtp') await send() expect((await status())?.code).toBe('smtp-incomplete') expect(await getMailMethod(payload)).toBe('smtp') await setMailMethod(payload, 'relay') await send() expect(await getMailMethod(payload)).toBe('relay') }) test('M-2: anything but null or one of the three values is refused with 400, and nothing is stored', async () => { await asStored({}) for (const bad of [0, 1, true, ['relay'], { method: 'relay' }, 'sendmail', '', 'RELAY']) { const res = await api('/globals/site-integrations', { body: JSON.stringify({ emailMethod: bad }), method: 'POST' }) expect(res.status, JSON.stringify(bad)).toBe(400) await expect(payload.updateGlobal({ slug: 'site-integrations' as never, data: { emailMethod: bad } as never }), JSON.stringify(bad)).rejects.toThrow() } expect(await getMailMethod(payload)).toBeNull() expect((await api('/globals/site-integrations', { body: JSON.stringify({ emailMethod: null }), method: 'POST' })).status).toBe(200) expect((await api('/globals/site-integrations', { body: JSON.stringify({ emailMethod: 'smtp' }), method: 'POST' })).status).toBe(200) expect(await getMailMethod(payload)).toBe('smtp') }) }) describe('resolveMailMethod', () => { const full = { smtpHost: 'smtp.example.com', smtpPassword: 'x', smtpUser: 'u' } const half = { smtpHost: 'smtp.example.com' } const on = { graphEnv: true, relay: true } const off = { graphEnv: false, relay: true } test.each([ // chosen, settings, env → method, problem ['relay', full, on, 'relay', undefined], ['relay', {}, off, 'relay', undefined], ['smtp', full, on, 'smtp', undefined], ['smtp', half, on, 'smtp', 'smtp-incomplete'], ['smtp', {}, off, 'smtp', 'smtp-incomplete'], ['graph', full, on, 'graph', undefined], ['graph', full, off, 'graph', 'graph-not-set-up'], ['graph', {}, off, 'graph', 'graph-not-set-up'], ] as const)('chosen %s, %j, %j → %s (%s)', (chosen, settings, state, method, problem) => { expect(resolveMailMethod(settings, { ...state, chosen })).toEqual({ explicit: true, method, ...(problem ? { problem } : {}) }) }) test('nothing chosen: the order of 1.17.0, never a problem; "IWSN" chosen with the service switched off counts as nothing chosen', () => { for (const settings of [{}, half, full, { emailTransport: 'graph' as const }, { emailTransport: 'graph' as const, ...full }]) { for (const state of [on, off, { graphEnv: true, relay: false }, { graphEnv: false, relay: false }]) { expect(resolveMailMethod(settings, { ...state, chosen: null })).toEqual({ explicit: false, method: resolveMailTransport(settings, state) }) expect(resolveMailMethod(settings, { ...state, chosen: 'relay', relay: false })).toEqual({ explicit: false, method: resolveMailTransport(settings, { ...state, relay: false }) }) } } }) }) 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({}) const db = payload.db as unknown as { connection?: { collection: (n: string) => { findOne: (q: object) => Promise> } }; tables?: Record> } const raw = async (): Promise => { 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 () => { const methods = (config: Awaited>) => { const field = JSON.stringify(config.globals?.find((g) => g.slug === 'site-integrations')?.fields).match(/"name":"emailMethod".*?"options":\[(.*?)\]/)?.[1] ?? '' return [...field.matchAll(/"value":"(\w+)"/g)].map((m) => m[1]) } expect(methods(await makeConfig(undefined, 'methodson'))).toEqual(['relay', '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('') }) })