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 } | 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' }, } }