Files
ipal-kit/src/globals/SiteIntegrations/index.ts
T
Radosław SmolińskiandClaude Fable 5.2 ee8ea42956 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]>
2026-11-26 22:39:03 +01:00

145 lines
7.4 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import type { Field, GlobalConfig } from 'payload'
import { ValidationError } from 'payload'
import { userMeetsRole } from '../../modules/access/index.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'
import { buildSmtpFields, shownMailMethod } from './fields/smtp.js'
import { turnstileFields } from './fields/turnstile.js'
type BuildSiteIntegrationsArgs = {
/** Extra fields injected by the client project */
additionalFields?: Field[]
/**
* The Intecion mail service is enabled in the project (`mail.relay` is not `false`): the e-mail
* tab shows its state block and says that SMTP is optional. Default true.
*/
mailRelay?: boolean
/**
* A save through access control that changes the SMTP server, port or user name must send the
* password again (or remove it), whatever the transport. Default true; needs write-only
* secrets. `false` = the stored password follows the new server, as before.
*/
reenterSecretOnChange?: boolean
/**
* The stored secrets (`smtpPassword`, `turnstileSecretKey`) are write-only: reads through
* access control get `SECRET_MASK`, never the value (modules/secrets/writeOnly.ts). Default
* true; `false` = the value is returned to whoever may read the global, as before.
*/
writeOnlySecrets?: boolean
}
/**
* Builds the SiteIntegrations global.
*
* Holds third-party service credentials. Access is enforced at the global
* level — the whole global requires an authenticated user — so secrets stay
* out of anonymous API responses while remaining editable in the admin panel
* and readable via the server-side Local API. (Field-level read:false was
* avoided because it also hides fields from the admin UI, making them
* impossible to enter.)
*
* Unnamed tabs keep data flat (siteIntegrations.ga4MeasurementId).
*/
export function buildSiteIntegrations({
additionalFields,
mailRelay = true,
reenterSecretOnChange = true,
writeOnlySecrets: writeOnly = true,
}: BuildSiteIntegrationsArgs = {}): GlobalConfig {
const secret = (fields: Field[]) =>
writeOnly ? writeOnlySecrets(fields, INTEGRATION_SECRET_FIELDS, reenterSecretOnChange ? { smtpPassword: { boundTo: SMTP_PASSWORD_BOUND_TO } } : {}) : fields
return {
slug: 'site-integrations',
access: {
// Admin-only — secrets live here. Anonymous and non-admin users get
// nothing through the API; admins read/edit in the panel and via Local API.
// Without roles (no `access` option) every logged-in account is admin.
read: ({ req }) => userMeetsRole(req, 'admin'),
// With versions on (globalOverrides), Payload lets every signed-in account list them unless told otherwise.
readVersions: ({ req }) => userMeetsRole(req, 'admin'),
update: ({ req }) => userMeetsRole(req, 'admin'),
},
admin: {
group: { en: 'Settings', pl: 'Ustawienia' },
},
fields: [
{
type: 'tabs',
tabs: [
{ fields: analyticsFields, label: { en: 'Analytics', pl: 'Analityka' } },
{
description: {
en: 'Cloudflare Turnstile checks that forms are sent by people, not bots.',
pl: 'Cloudflare Turnstile sprawdza, czy formularze wysyłają ludzie, a nie boty.',
},
fields: secret(turnstileFields),
label: { en: 'Spam protection', pl: 'Ochrona przed spamem' },
},
{ fields: secret(buildSmtpFields({ relay: mailRelay })), label: { en: 'E-mail sending', pl: 'Wysyłka e-mail' } },
{ fields: indexNowFields, label: { en: 'IndexNow', pl: 'IndexNow' } },
...(additionalFields?.length
? [{ fields: additionalFields, label: { en: 'More', pl: 'Więcej' } }]
: []),
],
},
],
hooks: {
// a restore answers with the version document: the secrets are masked there too
...(writeOnly ? { afterRead: [maskSecretsOnRestore] } : {}),
// 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, 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" (`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
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))) {
data.emailStatus = cleared
}
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 = { sent: 'emailMethod' in data, transport: 'emailTransport' in data }
}
return args
},
],
},
label: { en: 'Site integrations', pl: 'Integracje' },
}
}