Fix turnstile

This commit is contained in:
2026-10-15 15:53:32 +02:00
parent 7dc93ac5ed
commit 70b676660d
80 changed files with 1136 additions and 902 deletions
+2 -2
View File
@@ -1,4 +1,3 @@
export { RowLabel } from '../modules/admin-ui/RowLabelComponent.js'
/**
* Entry point: @intecion/ipal-kit/admin
*
@@ -6,5 +5,6 @@ export { RowLabel } from '../modules/admin-ui/RowLabelComponent.js'
* importMap can resolve them by a stable path when ipalKit injects
* admin.components.graphics.Logo/Icon.
*/
export { AdminIcon, AdminLogo, IntecionCredit } from '../modules/branding/index.js'
export { AdminLogo, AdminIcon, IntecionCredit } from '../modules/branding/index.js'
export { RowLabel } from '../modules/admin-ui/RowLabelComponent.js'
export { IntegrationAlerts } from '../modules/integrations/IntegrationAlerts.js'
+42 -42
View File
@@ -1,13 +1,4 @@
'use client'
export { MaskedField } from '../globals/SiteIntegrations/components/MaskedField.js'
export { TestEmailButton } from '../globals/SiteIntegrations/components/TestEmailButton.js'
export { AccessibilityProvider, AccessibilityWidget, useAccessibility } from '../modules/accessibility/client.js'
export type { A11yClassNames, A11yState, A11yTexts } from '../modules/accessibility/client.js'
export { Analytics } from '../modules/analytics/client.js'
export type { AnalyticsProps } from '../modules/analytics/client.js'
export { pushDataLayer } from '../modules/analytics/client.js'
export { loadClarity, loadLinkedIn, loadMetaPixel, loadTikTok } from '../modules/analytics/client.js'
/**
* Entry point: ipal-kit/client
*
@@ -16,52 +7,61 @@ export { loadClarity, loadLinkedIn, loadMetaPixel, loadTikTok } from '../modules
* client-only code.
*/
export {
useConsent,
ConsentProvider,
ConsentScript,
useConsentContext,
CookieBanner,
CookieButton,
useConsent,
useConsentContext,
ConsentScript,
} from '../modules/consent/client.js'
export type { CookieBannerClassNames } from '../modules/consent/client.js'
export { formAnalyticsOnSuccess } from '../modules/forms/formAnalytics.js'
export type { FormAnalyticsConfig } from '../modules/forms/formAnalytics.js'
export { HONEYPOT_FIELD, honeypotInputProps, isHoneypotTripped } from '../modules/forms/honeypot.js'
export { useContactForm } from '../modules/forms/useContactForm.js'
export type { ContactFormErrors, ContactFormValues, SubmitAction } from '../modules/forms/useContactForm.js'
export { useForm } from '../modules/forms/useForm.js'
export type { FormErrors, FormSubmitAction, Validator } from '../modules/forms/useForm.js'
export {
buildValidator,
checked,
custom,
email,
isEmail,
maxLength,
minLength,
pattern,
required,
} from '../modules/forms/validators.js'
export type { Rule } from '../modules/forms/validators.js'
export { Turnstile } from '../modules/turnstile/client.js'
export { TurnstileProvider, useTurnstile } from '../modules/turnstile/client.js'
export { AccessibilityProvider, useAccessibility, AccessibilityWidget } from '../modules/accessibility/client.js'
export type { A11yState, A11yTexts, A11yClassNames } from '../modules/accessibility/client.js'
// Pure i18n path helpers — no server/RSC deps, safe to import in client
// components (e.g. a LanguageSwitcher that computes locale URLs on the client).
export {
buildLocalizedPath,
getLocaleCodes,
getLocalizedSlugs,
switchLocalePath,
buildLocalizedPath,
getLocalizedSlugs,
getLocaleCodes,
} from '../modules/i18n/index.js'
export type { I18nConfig, LocalizedSlugs } from '../modules/i18n/index.js'
export type { LocalizedSlugs, I18nConfig } from '../modules/i18n/index.js'
export type { TurnstileProps } from '../modules/turnstile/client.js'
export { LocaleView } from '../modules/pages/LocaleView.js'
export { Analytics } from '../modules/analytics/client.js'
export type { AnalyticsProps } from '../modules/analytics/client.js'
export { pushDataLayer } from '../modules/analytics/client.js'
export { loadMetaPixel, loadClarity, loadLinkedIn, loadTikTok } from '../modules/analytics/client.js'
export { MaskedField } from '../globals/SiteIntegrations/components/MaskedField.js'
export { IntegrationStatusBanner } from '../modules/integrations/IntegrationStatusBanner.js'
export { TestEmailButton } from '../globals/SiteIntegrations/components/TestEmailButton.js'
export {
AlternateLinksProvider,
AlternateLinksUpdater,
LanguageSwitcher,
useAlternateLinks,
useSetAlternateLinks,
AlternateLinksUpdater,
LanguageSwitcher,
} from '../modules/i18n/index.js'
export type { AlternateLinks, LanguageSwitcherClassNames } from '../modules/i18n/index.js'
export { IntegrationStatusBanner } from '../modules/integrations/IntegrationStatusBanner.js'
export { LocaleView } from '../modules/pages/LocaleView.js'
export { Turnstile } from '../modules/turnstile/client.js'
export { TurnstileProvider, useTurnstile } from '../modules/turnstile/client.js'
export type { TurnstileProps } from '../modules/turnstile/client.js'
export { useForm } from '../modules/forms/useForm.js'
export type { FormErrors, FormSubmitAction, Validator } from '../modules/forms/useForm.js'
export { useContactForm } from '../modules/forms/useContactForm.js'
export type { ContactFormValues, ContactFormErrors, SubmitAction } from '../modules/forms/useContactForm.js'
export {
buildValidator,
isEmail,
required,
email,
minLength,
maxLength,
checked,
pattern,
custom,
} from '../modules/forms/validators.js'
export type { Rule } from '../modules/forms/validators.js'
export { HONEYPOT_FIELD, honeypotInputProps, isHoneypotTripped } from '../modules/forms/honeypot.js'
export { formAnalyticsOnSuccess } from '../modules/forms/formAnalytics.js'
export type { FormAnalyticsConfig } from '../modules/forms/formAnalytics.js'
+5 -5
View File
@@ -1,7 +1,3 @@
export { sendEmail } from '../modules/email/index.js'
export type { SendEmailArgs, SendEmailResult } from '../modules/email/index.js'
export { submitForm } from '../modules/forms/index.js'
export type { SubmitFormArgs, SubmitFormResult } from '../modules/forms/index.js'
/**
* Entry point: ipal-kit/server
*
@@ -14,5 +10,9 @@ export type { SubmitFormArgs, SubmitFormResult } from '../modules/forms/index.js
* Import these only from Server Actions, route handlers, or server components —
* never from the Payload config or client code.
*/
export { checkTurnstile, verifyTurnstile } from '../modules/turnstile/index.js'
export { verifyTurnstile, checkTurnstile } from '../modules/turnstile/index.js'
export type { TurnstileCheck, TurnstileOutcome } from '../modules/turnstile/index.js'
export { sendEmail } from '../modules/email/index.js'
export type { SendEmailArgs, SendEmailResult } from '../modules/email/index.js'
export { submitForm } from '../modules/forms/index.js'
export type { SubmitFormArgs, SubmitFormResult } from '../modules/forms/index.js'
+2 -2
View File
@@ -1,5 +1,4 @@
import type { GlobalConfig } from 'payload'
import { notificationsFields } from './fields.js'
/**
@@ -10,10 +9,11 @@ import { notificationsFields } from './fields.js'
export function buildNotifications(): GlobalConfig {
return {
slug: 'notifications',
label: 'Notifications',
admin: { group: 'Settings' },
access: {
read: () => true, // texts are public-facing (shown to end users)
},
fields: notificationsFields,
label: 'Notifications',
}
}
@@ -1,41 +1,69 @@
'use client'
import type { TextFieldClientComponent } from 'payload'
import { useField, FieldLabel, FieldDescription } from '@payloadcms/ui'
import { useState } from 'react'
import type { TextFieldClientComponent } from 'payload'
export const MaskedField: TextFieldClientComponent = (props: any) => {
const { field, path, value: propValue, setValue: propSetValue, onChange: propOnChange } = props || {}
const [internalValue, setInternalValue] = useState(propValue ?? '')
/**
* Masked text input for sensitive values (SMTP password, R2 secret key,
* Turnstile secret key, etc.).
*
* Renders the value as a password field (••••) so secrets aren't shown in
* plaintext on screen — protecting against shoulder-surfing and accidental
* exposure when the panel is open. The value is still stored and returned
* normally (UI masking, NOT hashing or encryption), because the plugin must
* read it back to authenticate with SMTP/R2/Turnstile. A toggle reveals the
* value when an authorised editor genuinely needs to check it.
*
* Uses a raw <input> driven by useField rather than @payloadcms/ui's TextInput,
* because TextInput doesn't expose inputProps, so there's no way to switch its
* inner input to type="password".
*
* Assigned via a field's admin.components.Field. Works on any `text` field.
*/
export const MaskedField: TextFieldClientComponent = ({ field, path }) => {
const { value, setValue } = useField<string>({ path })
const [revealed, setRevealed] = useState(false)
const label = typeof field?.label === 'string' ? field.label : (field?.name ?? path)
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const newVal = e.target.value
setInternalValue(newVal)
if (typeof propSetValue === 'function') {
propSetValue(newVal)
}
if (typeof propOnChange === 'function') {
propOnChange(e)
}
}
const currentValue = propValue !== undefined ? propValue : internalValue
const label =
typeof field?.label === 'string' ? field.label : (field?.name ?? path)
const description = field?.admin?.description
return (
<div className="field-type text">
{label && <label className="field-label">{label}</label>}
<div style={{ display: 'flex', gap: '.5rem' }}>
<div className="field-type text masked-field">
<FieldLabel label={label} htmlFor={`field-${path}`} />
<div className="field-type__wrap" style={{ display: 'flex', gap: '.5rem', alignItems: 'center' }}>
<input
autoComplete="off"
onChange={handleChange}
style={{ flex: 1 }}
id={`field-${path}`}
type={revealed ? 'text' : 'password'}
value={currentValue ?? ''}
autoComplete="off"
className="field-type__input"
value={value ?? ''}
onChange={(e) => setValue(e.target.value)}
style={{ flex: 1 }}
/>
<button onClick={() => setRevealed((r) => !r)} type="button">
<button
type="button"
onClick={() => setRevealed((r) => !r)}
style={{
background: 'none',
border: 'none',
padding: '.25rem .5rem',
cursor: 'pointer',
font: 'inherit',
textDecoration: 'underline',
opacity: 0.75,
whiteSpace: 'nowrap',
}}
>
{revealed ? 'Hide' : 'Reveal'}
</button>
</div>
{description && typeof description === 'string' ? (
<FieldDescription path={path} description={description} />
) : null}
</div>
)
}
@@ -14,10 +14,7 @@ import { useState } from 'react'
export const TestEmailButton = () => {
const [to, setTo] = useState('')
const [status, setStatus] = useState<
| { kind: 'error'; msg: string }
| { kind: 'idle' }
| { kind: 'ok'; msg: string }
| { kind: 'sending' }
{ kind: 'idle' } | { kind: 'sending' } | { kind: 'ok'; msg: string } | { kind: 'error'; msg: string }
>({ kind: 'idle' })
const send = async () => {
@@ -28,10 +25,10 @@ export const TestEmailButton = () => {
setStatus({ kind: 'sending' })
try {
const res = await fetch('/api/ipal/test-email', {
body: JSON.stringify({ to: to.trim() }),
credentials: 'include',
headers: { 'Content-Type': 'application/json' },
method: 'POST',
headers: { 'Content-Type': 'application/json' },
credentials: 'include',
body: JSON.stringify({ to: to.trim() }),
})
const data = await res.json()
if (data.ok) {
@@ -47,23 +44,23 @@ export const TestEmailButton = () => {
return (
<div className="field-type" style={{ marginTop: '1rem' }}>
<label className="field-label">Send a test email</label>
<p style={{ fontSize: '.85rem', marginTop: 0, opacity: 0.7 }}>
<p style={{ opacity: 0.7, fontSize: '.85rem', marginTop: 0 }}>
Sends through the transport selected above. Save your changes first.
</p>
<div style={{ alignItems: 'center', display: 'flex', flexWrap: 'wrap', gap: '.5rem' }}>
<div style={{ display: 'flex', gap: '.5rem', alignItems: 'center', flexWrap: 'wrap' }}>
<input
onChange={(e) => setTo(e.target.value)}
placeholder="[email protected]"
style={{ flex: 1, minWidth: '220px' }}
type="email"
placeholder="[email protected]"
value={to}
onChange={(e) => setTo(e.target.value)}
style={{ flex: 1, minWidth: '220px' }}
/>
<button
className="btn btn--style-secondary"
disabled={status.kind === 'sending'}
onClick={send}
style={{ whiteSpace: 'nowrap' }}
type="button"
onClick={send}
disabled={status.kind === 'sending'}
className="btn btn--style-secondary"
style={{ whiteSpace: 'nowrap' }}
>
{status.kind === 'sending' ? 'Sending…' : 'Send test'}
</button>
@@ -1,5 +1,7 @@
import type { Field } from 'payload'
import { buildIntegrationStatusBanner, buildIntegrationStatusField } from '../../../modules/integrations/status.js'
/**
* SMTP transport settings for outbound email.
*
@@ -8,6 +10,8 @@ import type { Field } from 'payload'
* panel while remaining inaccessible to anonymous API requests.
*/
export const smtpFields: Field[] = [
// Status written by mailAdapter on every send (throttled) — banner on this tab.
buildIntegrationStatusBanner('emailStatus', 'Email'),
{
name: 'emailTransport',
type: 'select',
@@ -87,4 +91,5 @@ export const smtpFields: Field[] = [
},
},
},
buildIntegrationStatusField('emailStatus'),
]
+5 -3
View File
@@ -51,13 +51,15 @@ export function buildSiteIntegrations({
],
hooks: {
beforeChange: [
// Keys edited in the panel → clear the old Turnstile status, so a stale
// 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 }) => {
if (context?.ipalIntegrationStatus || !data) {return data}
const changed = (k: string) => k in data && data[k] !== originalDoc?.[k]
if (changed('turnstileSecretKey') || changed('turnstileSiteKey')) {
data.turnstileStatus = { checkedAt: null, code: null, message: null, since: null, state: null }
const cleared = { checkedAt: null, code: null, message: null, since: null, state: null }
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
},
+139 -139
View File
@@ -1,3 +1,20 @@
export { ipalKit } from './plugin.js'
export type { IpalOptions } from './types.js'
export type { I18nConfig, LocaleDefinition, LocalizedSlugs } from './modules/i18n/index.js'
export {
buildLocalizedPath,
getDefaultLocale,
getLocaleCodes,
getLocaleDefinition,
getLocalizedSlugs,
isValidLocale,
LOCALE_COOKIE_NAME,
matchAcceptLanguage,
negotiateLocale,
switchLocalePath,
} from './modules/i18n/index.js'
export type { PagesOption, SystemPageRole } from './modules/pages/index.js'
export { ALL_SYSTEM_PAGE_ROLES, getSystemPagePath } from './modules/pages/index.js'
export type { AccessOption, Role } from './modules/access/index.js'
export {
adminOnly,
@@ -13,102 +30,58 @@ export {
requireRoleField,
ROLE_HIERARCHY,
} from './modules/access/index.js'
export { A11Y_COOKIE, A11Y_DEFAULT, a11yAttributes, parseA11y, serializeA11y } from './modules/accessibility/index.js'
export type { A11yState } from './modules/accessibility/index.js'
export { rowLabel } from './modules/admin-ui/index.js'
export type { RowLabelProps } from './modules/admin-ui/index.js'
export type { AnalyticsConfig } from './modules/analytics/index.js'
export { getAnalyticsConfig } from './modules/analytics/index.js'
export type { GlobalQueryOptions } from './modules/payload/index.js'
export {
ACCEPT_ALL_CONSENT,
CONSENT_CATEGORIES,
CONSENT_COOKIE,
CONSENT_MAX_AGE,
CONSENT_VERSION,
DEFAULT_CONSENT,
getConsentTexts,
parseConsent,
REJECT_ALL_CONSENT,
serializeConsent,
setDefaultConsent,
updateConsent,
} from './modules/consent/index.js'
export type { ConsentCategory, ConsentState, ConsentTexts } from './modules/consent/index.js'
export type { ContentCollectionOption, ContentOption, ResolvedRoute } from './modules/content/index.js'
getGlobal,
getSiteSettings,
getSiteIntegrations,
SITE_SETTINGS_SLUG,
SITE_INTEGRATIONS_SLUG,
} from './modules/payload/index.js'
export type { SeoOption, SeoMeta, PageMetadata } from './modules/seo/index.js'
export {
archiveFieldName,
composeTitle,
buildHreflangAlternates,
buildMetadata,
readSiteMetaConfig,
slugsAcrossLocales,
} from './modules/seo/index.js'
export type { SiteMetaConfig } from './modules/seo/index.js'
export type { ContentOption, ContentCollectionOption, ResolvedRoute } from './modules/content/index.js'
export { createContentHelpers } from './modules/frontend/index.js'
export {
resolveRoute,
resolveRedirect,
resolveNotFoundPage,
blocksToMarkdown,
createMarkdownRenderer,
markdownResponse,
prefersMarkdown,
markdownHref,
MARKDOWN_PREFIX,
searchContent,
createSearchRoute,
archiveFieldName,
getArchiveEntries,
buildArchivePath,
buildEntryPath,
createMarkdownRenderer,
createSearchRoute,
getArchiveEntries,
MARKDOWN_PREFIX,
markdownHref,
markdownResponse,
parsePageParam,
prefersMarkdown,
resolveNotFoundPage,
resolveRedirect,
resolveRoute,
searchContent,
} from './modules/content/index.js'
export type { ArchiveEntries } from './modules/content/index.js'
export type { SearchResult } from './modules/content/index.js'
export { graphAdapter } from './modules/email/graphAdapter.js'
export type { GraphAdapterArgs } from './modules/email/graphAdapter.js'
export { mailAdapter } from './modules/email/mailAdapter.js'
export type { MailAdapterArgs } from './modules/email/mailAdapter.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
// Payload loads the config (or runs generate:importmap) as a plain Node script.
export { panelSmtpAdapter } from './modules/email/panelSmtpAdapter.js'
export type { PanelSmtpAdapterArgs } from './modules/email/panelSmtpAdapter.js'
// Boot-time environment validation (fail fast on misconfigured deploys).
export { assertEnv, ipalEnvRules } from './modules/env/index.js'
export type { AssertEnvOptions, EnvKind, EnvRule, IpalEnvFeatures } from './modules/env/index.js'
// Panel-managed form analytics (config-time field builder).
export { buildFormAnalyticsFields } from './modules/forms/formAnalyticsFields.js'
export { buildFormsPlugin } from './modules/forms/formsPluginConfig.js'
export { HONEYPOT_FIELD, honeypotInputProps, isHoneypotTripped } from './modules/forms/honeypot.js'
export type {
FormsCollectionOverrides,
FormsFieldsOverride,
FormsOption,
} from './modules/forms/types.js'
export type { FormErrors, FormSubmitAction, Validator } from './modules/forms/useForm.js'
// Validation rules are pure — exported server-side too, for re-validating a
// submission inside a server action. (useForm/useContactForm are client-only →
// '@intecion/ipal-kit/client'.)
// Lexical → Markdown (pure, no React) — for AI-readable output.
export { lexicalToMarkdown } from './modules/richtext/index.js'
export type { AutoFillMapping, SitemapEntry, RobotsRules, RobotsOptions } from './modules/seo/index.js'
export {
buildValidator,
checked,
custom,
email,
isEmail,
maxLength,
minLength,
pattern,
required,
} from './modules/forms/validators.js'
export type { Rule } from './modules/forms/validators.js'
export { createContentHelpers } from './modules/frontend/index.js'
// Healthcheck route (Coolify/Docker liveness with a real DB round-trip).
export { createHealthRoute } from './modules/health/index.js'
export { buildCrossLocaleFieldSync, buildPreventDeleteSystemPage, buildRevalidateHook, buildValidateUniqueRole, setPublishedAtHook, trackSlugHistoryHook } from './modules/hooks/index.js'
export type { I18nConfig, LocaleDefinition, LocalizedSlugs } from './modules/i18n/index.js'
export {
buildLocalizedPath,
getDefaultLocale,
getLocaleCodes,
getLocaleDefinition,
getLocalizedSlugs,
isValidLocale,
LOCALE_COOKIE_NAME,
matchAcceptLanguage,
negotiateLocale,
switchLocalePath,
} from './modules/i18n/index.js'
buildAutoFillMetaHook,
injectAutoFillMeta,
createMetadataGenerator,
createPageMetadata,
buildSitemapEntries,
buildRobots,
AI_ASSISTANT_BOTS,
AI_TRAINING_BOTS,
} from './modules/seo/index.js'
export type { LocaleMiddlewareResult } from './modules/i18n/index.js'
export {
createLocaleMiddleware,
@@ -116,72 +89,99 @@ export {
} from './modules/i18n/index.js'
export { createProxy, DEFAULT_PROXY_MATCHER } from './modules/i18n/index.js'
export { resolveLocalized } from './modules/i18n/index.js'
export { buildIntegrationStatusBanner, buildIntegrationStatusField, recordIntegrationStatus } from './modules/integrations/index.js'
export type { IntegrationState, IntegrationStatus } from './modules/integrations/index.js'
export { buildLinkField, buildLinksField, resolveLinkHref } from './modules/links/index.js'
export {
CONSENT_CATEGORIES,
DEFAULT_CONSENT,
ACCEPT_ALL_CONSENT,
REJECT_ALL_CONSENT,
CONSENT_COOKIE,
CONSENT_VERSION,
CONSENT_MAX_AGE,
serializeConsent,
parseConsent,
setDefaultConsent,
updateConsent,
getConsentTexts,
} from './modules/consent/index.js'
export type { ConsentCategory, ConsentState, ConsentTexts } from './modules/consent/index.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
// Payload loads the config (or runs generate:importmap) as a plain Node script.
export { panelSmtpAdapter } from './modules/email/panelSmtpAdapter.js'
export { graphAdapter } from './modules/email/graphAdapter.js'
export { mailAdapter } from './modules/email/mailAdapter.js'
export type { MailAdapterArgs } from './modules/email/mailAdapter.js'
export type { GraphAdapterArgs } from './modules/email/graphAdapter.js'
export type { PanelSmtpAdapterArgs } from './modules/email/panelSmtpAdapter.js'
export { buildFormsPlugin } from './modules/forms/formsPluginConfig.js'
export type {
BuildLinkFieldOptions,
BuildLinksFieldOptions,
LinkAppearance,
LinkValue,
ResolveLinkHrefOptions,
} from './modules/links/index.js'
FormsOption,
FormsCollectionOverrides,
FormsFieldsOverride,
} from './modules/forms/types.js'
// Validation rules are pure — exported server-side too, for re-validating a
// submission inside a server action. (useForm/useContactForm are client-only →
// '@intecion/ipal-kit/client'.)
export {
buildValidator,
isEmail,
required,
email,
minLength,
maxLength,
checked,
pattern,
custom,
} from './modules/forms/validators.js'
export type { Rule } from './modules/forms/validators.js'
export type { FormErrors, FormSubmitAction, Validator } from './modules/forms/useForm.js'
export { HONEYPOT_FIELD, honeypotInputProps, isHoneypotTripped } from './modules/forms/honeypot.js'
// Panel-managed form analytics (config-time field builder).
export { buildFormAnalyticsFields } from './modules/forms/formAnalyticsFields.js'
// Healthcheck route (Coolify/Docker liveness with a real DB round-trip).
export { createHealthRoute } from './modules/health/index.js'
// Read-only MCP server (Claude/agents connect to the site and query it).
export { createMcpRoute } from './modules/mcp/index.js'
export { buildOptimizeUploadField, buildOptimizeUploadHook, normalizeFilename, normalizeFilenameHook } from './modules/media/index.js'
export type { OptimizeUploadOptions } from './modules/media/index.js'
export { getNotificationTexts, NOTIFICATION_FALLBACK, resolveFormMessage } from './modules/notifications/index.js'
export type { FormNotificationTexts, NotificationTexts } from './modules/notifications/index.js'
export type { PagesOption, SystemPageRole } from './modules/pages/index.js'
// Boot-time environment validation (fail fast on misconfigured deploys).
export { assertEnv, ipalEnvRules } from './modules/env/index.js'
export type { EnvRule, EnvKind, AssertEnvOptions, IpalEnvFeatures } from './modules/env/index.js'
export type { AnalyticsConfig } from './modules/analytics/index.js'
export { getAnalyticsConfig } from './modules/analytics/index.js'
export { buildSlugField, toSlug } from './modules/slug/index.js'
export { createLlmsTxtRoute, createSitemapRouteHandler, createManifestHandler } from './modules/seo/index.js'
export { ALL_SYSTEM_PAGE_ROLES, getSystemPagePath } from './modules/pages/index.js'
export type { GlobalQueryOptions } from './modules/payload/index.js'
export {
getGlobal,
getSiteIntegrations,
getSiteSettings,
SITE_INTEGRATIONS_SLUG,
SITE_SETTINGS_SLUG,
} from './modules/payload/index.js'
// Lexical → Markdown (pure, no React) — for AI-readable output.
export { lexicalToMarkdown } from './modules/richtext/index.js'
export { getNotificationTexts, resolveFormMessage, NOTIFICATION_FALLBACK } from './modules/notifications/index.js'
export { buildSecurityHeaders } from './modules/security/index.js'
export { buildCsp } from './modules/security/index.js'
export type { BuildCspArgs } from './modules/security/index.js'
export type { BuildSecurityHeadersArgs, SecurityHeader } from './modules/security/index.js'
export type { PageMetadata, SeoMeta, SeoOption } from './modules/seo/index.js'
export {
buildHreflangAlternates,
buildMetadata,
composeTitle,
readSiteMetaConfig,
slugsAcrossLocales,
} from './modules/seo/index.js'
export type { SiteMetaConfig } from './modules/seo/index.js'
export type { AutoFillMapping, RobotsOptions, RobotsRules, SitemapEntry } from './modules/seo/index.js'
export {
AI_ASSISTANT_BOTS,
AI_TRAINING_BOTS,
buildAutoFillMetaHook,
buildRobots,
buildSitemapEntries,
createMetadataGenerator,
createPageMetadata,
injectAutoFillMeta,
} from './modules/seo/index.js'
export { createLlmsTxtRoute, createManifestHandler, createSitemapRouteHandler } from './modules/seo/index.js'
export { buildIconsMetadata, buildOrganizationJsonLd, validateFaviconField } from './modules/seo/index.js'
export { buildNoindexField } from './modules/seo/index.js'
export { recordIntegrationStatus, buildIntegrationStatusField, buildIntegrationStatusBanner } from './modules/integrations/index.js'
export type { IntegrationStatus, IntegrationState } from './modules/integrations/index.js'
export { rowLabel } from './modules/admin-ui/index.js'
export type { RowLabelProps } from './modules/admin-ui/index.js'
export { buildLinkField, buildLinksField, resolveLinkHref } from './modules/links/index.js'
export type {
LinkAppearance,
LinkValue,
BuildLinkFieldOptions,
BuildLinksFieldOptions,
ResolveLinkHrefOptions,
} from './modules/links/index.js'
export { buildSpeakableJsonLd } from './modules/seo/index.js'
export { buildSummaryField } from './modules/seo/index.js'
export { buildBreadcrumbJsonLd, buildSiteNavigationJsonLd, buildWebSiteJsonLd } from './modules/seo/index.js'
export { buildWebSiteJsonLd, buildBreadcrumbJsonLd, buildSiteNavigationJsonLd } from './modules/seo/index.js'
// Local SEO structured data — LocalBusiness (map pack), Service (offering), FAQPage.
export { buildFaqJsonLd, buildLocalBusinessJsonLd, buildServiceJsonLd } from './modules/seo/index.js'
export { buildLocalBusinessJsonLd, buildFaqJsonLd, buildServiceJsonLd } from './modules/seo/index.js'
export { buildArticleJsonLd } from './modules/seo/index.js'
export { buildLlmsTxt } from './modules/seo/index.js'
export { buildSitemapCss, buildSitemapXml, DEFAULT_SITEMAP_CREDIT, SITEMAP_STYLE_PARAM } from './modules/seo/index.js'
export { buildSitemapXml, buildSitemapCss, SITEMAP_STYLE_PARAM, DEFAULT_SITEMAP_CREDIT } from './modules/seo/index.js'
export type { SitemapRouteOptions, SitemapStyleOptions } from './modules/seo/index.js'
export { buildSlugField, toSlug } from './modules/slug/index.js'
export { buildR2Storage } from './modules/storage/index.js'
export { ipalKit } from './plugin.js'
export type { IpalOptions } from './types.js'
export { normalizeFilename, normalizeFilenameHook, buildOptimizeUploadHook, buildOptimizeUploadField } from './modules/media/index.js'
export type { OptimizeUploadOptions } from './modules/media/index.js'
export { buildRevalidateHook, setPublishedAtHook, buildPreventDeleteSystemPage, buildValidateUniqueRole, trackSlugHistoryHook, buildCrossLocaleFieldSync } from './modules/hooks/index.js'
export { A11Y_COOKIE, A11Y_DEFAULT, a11yAttributes, parseA11y, serializeA11y } from './modules/accessibility/index.js'
export type { A11yState } from './modules/accessibility/index.js'
export type { SecurityHeader, BuildSecurityHeadersArgs } from './modules/security/index.js'
export type { NotificationTexts, FormNotificationTexts } from './modules/notifications/index.js'
+58 -14
View File
@@ -1,28 +1,34 @@
import type { PayloadEmailAdapter, SendEmailOptions } from 'payload'
import { getSiteIntegrations } from '../payload/index.js'
import { graphAdapter, type GraphAdapterArgs } from './graphAdapter.js'
import { recordIntegrationStatus, type IntegrationStatus } from '../integrations/status.js'
import { panelSmtpAdapter, type PanelSmtpAdapterArgs } from './panelSmtpAdapter.js'
import { graphAdapter, type GraphAdapterArgs } from './graphAdapter.js'
type TransportIntegrations = {
/** 'smtp' | 'graph' — chosen by the editor in SiteIntegrations. */
emailTransport?: 'graph' | 'smtp' | null
emailTransport?: 'smtp' | 'graph' | null
emailStatus?: IntegrationStatus | null
}
const STATUS_FIELD = 'emailStatus'
/** Error text for the panel: first line, no stack, capped — SMTP errors don't carry the password. */
const describe = (err: unknown) =>
(err instanceof Error ? err.message : String(err)).split('\n')[0].slice(0, 200)
export type MailAdapterArgs = {
smtp?: PanelSmtpAdapterArgs
graph?: GraphAdapterArgs
fallbackFromAddress?: string
fallbackFromName?: string
graph?: GraphAdapterArgs
smtp?: PanelSmtpAdapterArgs
}
/** True when the agency Graph credentials are present in the environment. */
function graphAvailable(): boolean {
return Boolean(
process.env.GRAPH_TENANT_ID &&
process.env.GRAPH_CLIENT_ID &&
process.env.GRAPH_CLIENT_SECRET &&
process.env.GRAPH_SENDER,
process.env.GRAPH_CLIENT_ID &&
process.env.GRAPH_CLIENT_SECRET &&
process.env.GRAPH_SENDER,
)
}
@@ -69,20 +75,58 @@ export const mailAdapter =
sendEmail: async (message: SendEmailOptions) => {
const settings = await getSiteIntegrations<TransportIntegrations>(payload)
const choice = settings.emailTransport ?? 'smtp'
const previous = settings[STATUS_FIELD]
const useGraph = choice === 'graph' && graphAvailable()
const graphFallback = choice === 'graph' && !useGraph
if (choice === 'graph') {
if (graphAvailable()) {
return graph.sendEmail(message)
}
if (graphFallback) {
// Panel asked for Graph but the agency creds aren't configured for
// this project. Fall back to SMTP rather than silently dropping mail.
payload.logger.warn(
'[ipal] Transport set to Graph but GRAPH_* env vars are missing; falling back to SMTP.',
)
return smtp.sendEmail(message)
}
return smtp.sendEmail(message)
const transport = useGraph ? 'Microsoft Graph' : 'SMTP'
const code = useGraph ? 'graph-error' : 'smtp-error'
let result: unknown
try {
result = await (useGraph ? graph : smtp).sendEmail(message)
} catch (err) {
await recordIntegrationStatus(payload, STATUS_FIELD, previous, {
state: 'degraded',
code,
message: `${transport}: ${describe(err)}`,
})
throw err // callers (form-builder, Send test) still see the failure
}
// The delegates report failure as { sent: false, error, detail? } instead
// of throwing (a broken mailbox must not crash a form submission).
const failed = result as { sent?: boolean; error?: string; detail?: string } | null
if (failed && typeof failed === 'object' && failed.sent === false) {
await recordIntegrationStatus(payload, STATUS_FIELD, previous, {
state: 'degraded',
code,
message: `${transport}: ${describe(failed.detail ?? failed.error ?? 'not sent')}`,
})
return result
}
// Graph selected but unavailable is a configuration problem even if SMTP delivered.
await recordIntegrationStatus(
payload,
STATUS_FIELD,
previous,
graphFallback
? {
state: 'degraded',
code: 'graph-unavailable',
message: 'Microsoft Graph is selected but not configured on the server — e-mails are sent over SMTP.',
}
: { state: 'ok' },
)
return result
},
}
}
+15 -16
View File
@@ -1,15 +1,14 @@
import type { PayloadEmailAdapter, SendEmailOptions } from 'payload'
import { getSiteIntegrations } from '../payload/index.js'
/** SMTP fields the adapter reads from SiteIntegrations. */
type SmtpIntegrations = {
smtpFromAddress?: null | string
smtpFromName?: null | string
smtpHost?: null | string
smtpPassword?: null | string
smtpPort?: null | number
smtpUser?: null | string
smtpHost?: string | null
smtpPort?: number | null
smtpUser?: string | null
smtpPassword?: string | null
smtpFromAddress?: string | null
smtpFromName?: string | null
}
export type PanelSmtpAdapterArgs = {
@@ -59,8 +58,10 @@ export const panelSmtpAdapter =
const pass = smtp.smtpPassword
if (!host || !user || !pass) {
payload.logger.error('[ipal] Email not sent: SMTP is not configured in Site Integrations.')
return { error: 'SMTP is not configured in Site Integrations.', sent: false }
payload.logger.error(
'[ipal] Email not sent: SMTP is not configured in Site Integrations.',
)
return { sent: false, error: 'SMTP is not configured in Site Integrations.' }
}
// The panel is the source of truth for the sender; fall back to whatever
@@ -77,18 +78,15 @@ export const panelSmtpAdapter =
// normalises CRLF in standard headers, but the form-builder interpolates
// user data into the subject via {{field}} placeholders, so strip any
// newlines from header-bound values before they reach the transport.
const stripCRLF = (v: unknown): string =>
String(v ?? '')
.replace(/[\r\n]+/g, ' ')
.trim()
const stripCRLF = (v: unknown): string => String(v ?? '').replace(/[\r\n]+/g, ' ').trim()
const { default: nodemailer } = await import('nodemailer')
const transporter = nodemailer.createTransport({
auth: { pass, user },
host,
port,
secure: port === 465, // implicit TLS on 465, STARTTLS otherwise
auth: { user, pass },
})
try {
@@ -97,12 +95,13 @@ export const panelSmtpAdapter =
from,
...(message.subject ? { subject: stripCRLF(message.subject) } : {}),
})
return { messageId: info.messageId, sent: true }
return { sent: true, messageId: info.messageId }
} catch (err) {
// Never surface SMTP internals to the caller — a form submission
// shouldn't fail loudly because the mailbox is misconfigured.
payload.logger.error(`[ipal] Email send failed: ${(err as Error).message}`)
return { error: 'Failed to send email.', sent: false }
// `detail` is for the panel status (mailAdapter), not for end users.
return { sent: false, error: 'Failed to send email.', detail: (err as Error).message }
}
},
})
+41 -18
View File
@@ -1,37 +1,60 @@
import type { Plugin } from 'payload'
import { formBuilderPlugin } from '@payloadcms/plugin-form-builder'
import type { Plugin } from 'payload'
import type { FormsOption } from './types.js'
/** REST/GraphQL: only logged-in users. Local API (submitForm) is unaffected. */
const submissionsCreateAccess = ({ req }: { req: { user?: unknown } }) => Boolean(req.user)
/**
* Configures @payloadcms/plugin-form-builder from IPAL's FormsOption.
*
* Provides the form/form-submissions collections and field types. Email
* delivery is intentionally NOT handled here — the plugin's own SMTP-from-panel
* sender (submitForm) does that, so the form-builder's built-in email (which
* needs a Payload email adapter) is left unused.
* Provides the forms / form-submissions collections and field types. E-mails
* after a submission are the form-builder's own (Forms → Emails), sent through
* the project's email adapter (mailAdapter()).
*
* SECURITY: form-builder defaults form-submissions to `create: () => true`, i.e.
* anyone can POST /api/form-submissions and skip everything submitForm enforces
* (rate limit, Turnstile, GDPR consent, schema validation). Here REST/GraphQL
* creation is limited to logged-in users; the site submits through submitForm
* (server action → Local API, which bypasses access by design). A project that
* really needs public REST submissions can override `formSubmissionOverrides.access.create`.
*/
export function buildFormsPlugin(forms: FormsOption): Plugin {
const adminGroup = forms.adminGroup === undefined ? 'Forms' : forms.adminGroup
const group = adminGroup ? { group: adminGroup } : {}
return formBuilderPlugin({
fields: {
checkbox: true,
email: true,
message: true,
number: true,
payment: false,
select: true,
text: true,
textarea: true,
email: true,
number: true,
select: true,
checkbox: true,
message: true,
payment: false,
...forms.fields,
},
...(forms.redirectRelationships ? { redirectRelationships: forms.redirectRelationships } : {}),
...(forms.redirectRelationships
? { redirectRelationships: forms.redirectRelationships }
: {}),
// Client-supplied collection overrides (e.g. a per-form notification
// address). The plugin provides the hook, not the opinion about which
// extra fields a form should carry.
...(forms.formOverrides ? { formOverrides: forms.formOverrides } : {}),
...(forms.formSubmissionOverrides
? { formSubmissionOverrides: forms.formSubmissionOverrides }
: {}),
// Tidy panel by default: both collections under one sidebar group with plain
// labels — no per-project overrides needed just to sort the sidebar.
formOverrides: {
labels: { singular: 'Form', plural: 'Forms' },
...forms.formOverrides,
admin: { ...group, ...forms.formOverrides?.admin },
},
formSubmissionOverrides: {
labels: { singular: 'Submission', plural: 'Submissions' },
...forms.formSubmissionOverrides,
admin: { ...group, defaultColumns: ['form', 'createdAt'], ...forms.formSubmissionOverrides?.admin },
access: {
create: submissionsCreateAccess,
...forms.formSubmissionOverrides?.access,
},
},
})
}
+32 -34
View File
@@ -1,21 +1,17 @@
import 'server-only'
import type { BasePayload } from 'payload'
import { verifyTurnstile } from '../turnstile/index.js'
import { checkRateLimit } from './rateLimit.js'
import { validateSubmission } from './validateSubmission.js'
import { checkRateLimit } from './rateLimit.js'
export type SubmitFormArgs = {
/**
* Name of the GDPR consent checkbox. A field with this name must be checked
* for the submission to succeed (enforced server-side). Defaults to 'consent'.
*/
consentFieldName?: string
/** Submitted field data — shape matches the form's fields. */
data: Record<string, unknown>
payload: BasePayload
/** Form-builder form ID this submission belongs to. */
formId: string
/** Submitted field data — shape matches the form's fields. */
data: Record<string, unknown>
/** Turnstile token; when present it is verified, when absent it is skipped. */
turnstileToken?: string
/** Client IP — used for Turnstile and rate limiting. */
ip?: string
/**
@@ -23,15 +19,17 @@ export type SubmitFormArgs = {
* Set to 0 to disable (e.g. when a real limiter sits in front).
*/
maxPerMinute?: number
payload: BasePayload
/**
* Name of the GDPR consent checkbox. A field with this name must be checked
* for the submission to succeed (enforced server-side). Defaults to 'consent'.
*/
consentFieldName?: string
/**
* Turnstile can't be verified because of OUR side (missing/wrong secret,
* Cloudflare unreachable): 'allow' (default) accepts the submission and shows
* the problem in the panel; 'reject' refuses it.
*/
turnstileOnConfigError?: 'allow' | 'reject'
/** Turnstile token; when present it is verified, when absent it is skipped. */
turnstileToken?: string
}
/**
@@ -52,26 +50,26 @@ export type SubmitFormArgs = {
* - `error` — persistence failed unexpectedly
*/
export type SubmitFailure =
| { success: false; reason: 'rate_limited' }
| { success: false; reason: 'turnstile' }
| {
success: false
reason: 'validation'
/** The offending field's name, when one field is at fault. */
field?: string
/** What was wrong with it. */
kind?: 'required' | 'too_long' | 'unknown_fields'
reason: 'validation'
success: false
}
| { success: false; reason: 'not_found' }
| {
field?: string
success: false
/** A GDPR consent field existed on the form but wasn't checked. */
reason: 'consent'
success: false
field?: string
}
| { reason: 'error'; success: false }
| { reason: 'not_found'; success: false }
| { reason: 'rate_limited'; success: false }
| { reason: 'turnstile'; success: false }
| { success: false; reason: 'error' }
export type SubmitFormResult = { submissionId: number | string; success: true } | SubmitFailure
export type SubmitFormResult = SubmitFailure | { success: true; submissionId: string | number }
/**
* Handles a form submission end to end: rate limit, verify Turnstile, validate
@@ -87,27 +85,27 @@ export type SubmitFormResult = { submissionId: number | string; success: true }
* server-only: touches the Turnstile secret.
*/
export async function submitForm({
consentFieldName,
data,
payload,
formId,
data,
turnstileToken,
ip,
maxPerMinute = 5,
payload,
consentFieldName,
turnstileOnConfigError = 'allow',
turnstileToken,
}: SubmitFormArgs): Promise<SubmitFormResult> {
// 1. Rate limit — cheapest gate, drops a flood before any real work.
if (maxPerMinute > 0 && ip) {
if (!checkRateLimit({ key: ip, max: maxPerMinute })) {
return { reason: 'rate_limited', success: false }
return { success: false, reason: 'rate_limited' }
}
}
// 2. Turnstile — verify when a token is supplied; reject on failure.
if (turnstileToken !== undefined) {
const ok = await verifyTurnstile({ ip, onConfigError: turnstileOnConfigError, payload, token: turnstileToken })
const ok = await verifyTurnstile({ token: turnstileToken, payload, ip, onConfigError: turnstileOnConfigError })
if (!ok) {
return { reason: 'turnstile', success: false }
return { success: false, reason: 'turnstile' }
}
}
@@ -116,14 +114,14 @@ export async function submitForm({
const validation = await validateSubmission(payload, formId, data, consentFieldName)
if (!validation.ok) {
if (validation.reason === 'not_found') {
return { reason: 'not_found', success: false }
return { success: false, reason: 'not_found' }
}
if (validation.reason === 'consent') {
return { field: validation.field, reason: 'consent', success: false }
return { success: false, reason: 'consent', field: validation.field }
}
return {
reason: 'validation',
success: false,
reason: 'validation',
...(validation.field ? { field: validation.field } : {}),
...(validation.kind ? { kind: validation.kind } : {}),
}
@@ -142,9 +140,9 @@ export async function submitForm({
})),
} as never,
})
return { submissionId: submission.id, success: true }
return { success: true, submissionId: submission.id }
} catch (err) {
payload.logger.error(`[ipal] Form submission failed: ${(err as Error).message}`)
return { reason: 'error', success: false }
return { success: false, reason: 'error' }
}
}
+19 -13
View File
@@ -19,23 +19,25 @@ export type FormsCollectionOverrides = {
* form-builder plugin. Kept minimal; the plugin passes these through.
*/
export type FormsOption = {
/** Field types available in the form builder. Sensible defaults applied. */
fields?: {
text?: boolean
textarea?: boolean
email?: boolean
number?: boolean
select?: boolean
checkbox?: boolean
message?: boolean
payment?: boolean
}
/** Collections a form can redirect to (e.g. ['pages']). */
redirectRelationships?: string[]
/**
* Name of the checkbox field treated as a GDPR consent gate. A form field
* with this name must be checked for submission to succeed — enforced
* server-side in submitForm. Defaults to 'consent'.
*/
consentFieldName?: string
/** Field types available in the form builder. Sensible defaults applied. */
fields?: {
checkbox?: boolean
email?: boolean
message?: boolean
number?: boolean
payment?: boolean
select?: boolean
text?: boolean
textarea?: boolean
}
/**
* Override the forms collection. The plugin stays opinion-free about what a
* form needs beyond its fields — a client that wants, say, a per-form
@@ -51,6 +53,10 @@ export type FormsOption = {
formOverrides?: FormsCollectionOverrides
/** Override the form-submissions collection (same shape). */
formSubmissionOverrides?: FormsCollectionOverrides
/** Collections a form can redirect to (e.g. ['pages']). */
redirectRelationships?: string[]
/**
* Admin sidebar group for Forms + Form Submissions. Default 'Forms'.
* `false` = Payload default ("Collections"). An explicit `admin.group` in
* formOverrides / formSubmissionOverrides still wins.
*/
adminGroup?: string | false
}
+11 -12
View File
@@ -1,14 +1,13 @@
import type { Payload } from 'payload'
import type { IntegrationStatus } from './status.js'
type Props = {
/** Admin route, for the link. Default '/admin'. */
adminRoute?: string
/** Status groups to check: field name → label. */
checks?: Record<string, string>
/** Injected by Payload into admin server components. */
payload?: Payload
/** Status groups to check: field name → label. */
checks?: Record<string, string>
/** Admin route, for the link. Default '/admin'. */
adminRoute?: string
}
/**
@@ -16,8 +15,8 @@ type Props = {
* are currently failing, with a link to Site Integrations. Renders nothing when
* everything is fine — and never throws (DB not ready → nothing).
*/
export async function IntegrationAlerts({ adminRoute = '/admin', checks = { turnstileStatus: 'Turnstile' }, payload }: Props) {
if (!payload) {return null}
export async function IntegrationAlerts({ payload, checks = { turnstileStatus: 'Turnstile', emailStatus: 'Email' }, adminRoute = '/admin' }: Props) {
if (!payload) return null
let doc: Record<string, unknown>
try {
doc = (await payload.findGlobal({ slug: 'site-integrations' as never, depth: 0 })) as Record<string, unknown>
@@ -27,20 +26,20 @@ export async function IntegrationAlerts({ adminRoute = '/admin', checks = { turn
const failing = Object.entries(checks)
.map(([field, label]) => ({ label, status: doc?.[field] as IntegrationStatus | undefined }))
.filter((x) => x.status?.state === 'degraded')
if (!failing.length) {return null}
if (!failing.length) return null
return (
<div
role="alert"
style={{
background: 'var(--theme-error-50, rgba(229, 72, 77, 0.08))',
border: '1px solid var(--theme-error-400, #e5484d)',
borderRadius: 4,
marginBottom: '1.5rem',
padding: '1rem 1.25rem',
borderRadius: 4,
border: '1px solid var(--theme-error-400, #e5484d)',
background: 'var(--theme-error-50, rgba(229, 72, 77, 0.08))',
}}
>
<strong>Integration problem — the site still works, but a safeguard is off.</strong>
<strong>Integration problem — the site still works, but something needs attention.</strong>
<ul style={{ margin: '0.5rem 0 0', paddingLeft: '1.2rem' }}>
{failing.map(({ label, status }) => (
<li key={label}>
@@ -2,14 +2,14 @@
import { useFormFields } from '@payloadcms/ui'
type Props = {
/** Integration name shown in the banner, e.g. 'Turnstile'. */
label: string
/** Name of the hidden status group (buildIntegrationStatusField). */
statusField: string
/** Integration name shown in the banner, e.g. 'Turnstile'. */
label: string
}
const fmt = (iso: unknown) => {
if (typeof iso !== 'string' || !iso) {return ''}
if (typeof iso !== 'string' || !iso) return ''
const d = new Date(iso)
return Number.isNaN(d.getTime()) ? '' : d.toLocaleString()
}
@@ -19,18 +19,18 @@ const fmt = (iso: unknown) => {
* the integration has been used once; a red box while it's failing; a short
* green line once it works again.
*/
export function IntegrationStatusBanner({ label, statusField }: Props) {
export function IntegrationStatusBanner({ statusField, label }: Props) {
const state = useFormFields(([f]) => f[`${statusField}.state`]?.value) as string | undefined
const message = useFormFields(([f]) => f[`${statusField}.message`]?.value) as string | undefined
const code = useFormFields(([f]) => f[`${statusField}.code`]?.value) as string | undefined
const since = useFormFields(([f]) => f[`${statusField}.since`]?.value)
const checkedAt = useFormFields(([f]) => f[`${statusField}.checkedAt`]?.value)
if (!state) {return null}
if (!state) return null
if (state === 'ok') {
return (
<div style={{ fontSize: '0.85rem', marginBottom: '1.5rem', opacity: 0.75 }}>
<div style={{ marginBottom: '1.5rem', fontSize: '0.85rem', opacity: 0.75 }}>
✓ {label} working{since ? ` since ${fmt(since)}` : ''}.
</div>
)
@@ -40,21 +40,21 @@ export function IntegrationStatusBanner({ label, statusField }: Props) {
<div
role="alert"
style={{
background: 'var(--theme-error-50, rgba(229, 72, 77, 0.08))',
border: '1px solid var(--theme-error-400, #e5484d)',
borderRadius: 4,
marginBottom: '1.5rem',
padding: '0.9rem 1rem',
borderRadius: 4,
border: '1px solid var(--theme-error-400, #e5484d)',
background: 'var(--theme-error-50, rgba(229, 72, 77, 0.08))',
}}
>
<strong>{label} is not working — forms are accepted without this check.</strong>
{message ? <div style={{ marginTop: '0.35rem' }}>{message}</div> : null}
<div style={{ fontSize: '0.8rem', marginTop: '0.35rem', opacity: 0.75 }}>
<div style={{ marginTop: '0.35rem', fontSize: '0.8rem', opacity: 0.75 }}>
{code ? `Code: ${code}. ` : ''}
{since ? `Since ${fmt(since)}. ` : ''}
{checkedAt ? `Last seen ${fmt(checkedAt)}.` : ''}
</div>
<div style={{ fontSize: '0.8rem', marginTop: '0.35rem', opacity: 0.75 }}>
<div style={{ marginTop: '0.35rem', fontSize: '0.8rem', opacity: 0.75 }}>
Fix the keys below and save — the status is checked again on the next form submission.
</div>
</div>
+3 -3
View File
@@ -1,6 +1,6 @@
export {
buildIntegrationStatusBanner,
buildIntegrationStatusField,
recordIntegrationStatus,
buildIntegrationStatusField,
buildIntegrationStatusBanner,
} from './status.js'
export type { IntegrationState, IntegrationStatus } from './status.js'
export type { IntegrationStatus, IntegrationState } from './status.js'
+16 -16
View File
@@ -12,18 +12,18 @@ import type { BasePayload, Field } from 'payload'
* busy form doesn't turn every submission into a DB write.
*/
export type IntegrationState = 'degraded' | 'ok'
export type IntegrationState = 'ok' | 'degraded'
export type IntegrationStatus = {
/** Last time the integration was used (refreshed at most every REFRESH_MS). */
checkedAt?: null | string
/** Machine code from the provider or the plugin, e.g. 'invalid-input-secret', 'missing-secret'. */
code?: null | string
/** Human explanation shown in the panel (English — panel language). */
message?: null | string
/** When the current state started. */
since?: null | string
state?: IntegrationState | null
/** Machine code from the provider or the plugin, e.g. 'invalid-input-secret', 'missing-secret'. */
code?: string | null
/** Human explanation shown in the panel (English — panel language). */
message?: string | null
/** When the current state started. */
since?: string | null
/** Last time the integration was used (refreshed at most every REFRESH_MS). */
checkedAt?: string | null
}
const REFRESH_MS = 10 * 60_000
@@ -53,8 +53,8 @@ export function buildIntegrationStatusBanner(statusField: string, label: string)
admin: {
components: {
Field: {
clientProps: { label, statusField },
path: '@intecion/ipal-kit/client#IntegrationStatusBanner',
clientProps: { statusField, label },
},
},
},
@@ -69,7 +69,7 @@ export async function recordIntegrationStatus(
payload: BasePayload,
field: string,
previous: IntegrationStatus | null | undefined,
next: { code?: string; message?: string; state: IntegrationState },
next: { state: IntegrationState; code?: string; message?: string },
): Promise<void> {
const now = new Date()
const changed = previous?.state !== next.state || (next.state === 'degraded' && previous?.code !== next.code)
@@ -78,22 +78,22 @@ export async function recordIntegrationStatus(
(!previous?.checkedAt || now.getTime() - new Date(previous.checkedAt).getTime() > REFRESH_MS)
// Healthy and already recorded as healthy (or never recorded) → nothing to do.
if (!changed && !stale) {return}
if (next.state === 'ok' && !previous?.state) {return}
if (!changed && !stale) return
if (next.state === 'ok' && !previous?.state) return
const status: IntegrationStatus = {
checkedAt: now.toISOString(),
state: next.state,
code: next.code ?? null,
message: next.message ?? null,
since: changed ? now.toISOString() : (previous?.since ?? now.toISOString()),
state: next.state,
checkedAt: now.toISOString(),
}
try {
await payload.updateGlobal({
slug: SITE_INTEGRATIONS as never,
context: { ipalIntegrationStatus: true },
data: { [field]: status } as never,
depth: 0,
context: { ipalIntegrationStatus: true },
})
} catch (err) {
console.warn(`[ipal] could not record ${field}:`, err instanceof Error ? err.message : err)
+2 -2
View File
@@ -1,5 +1,5 @@
export { TurnstileProvider, useTurnstile } from './TurnstileProvider.js'
// Server-only exports. verify.ts imports 'server-only', so this must never be
// imported from a client component — use ./client for the widget instead.
export { checkTurnstile, verifyTurnstile } from './verify.js'
export { verifyTurnstile, checkTurnstile } from './verify.js'
export type { TurnstileCheck, TurnstileOutcome } from './verify.js'
export { TurnstileProvider, useTurnstile } from './TurnstileProvider.js'
+34 -36
View File
@@ -1,25 +1,33 @@
import 'server-only'
import type { BasePayload } from 'payload'
import { type IntegrationStatus, recordIntegrationStatus } from '../integrations/status.js'
import { getSiteIntegrations } from '../payload/index.js'
import { recordIntegrationStatus, type IntegrationStatus } from '../integrations/status.js'
type SiteverifyResponse = {
challenge_ts?: string
'error-codes'?: string[]
hostname?: string
success: boolean
'error-codes'?: string[]
challenge_ts?: string
hostname?: string
}
type IntegrationsWithTurnstile = {
turnstileSecretKey?: null | string
turnstileSecretKey?: string | null
turnstileStatus?: IntegrationStatus | null
}
type VerifyTurnstileArgs = {
/** Token produced by the client-side widget. */
token: string
/** Payload instance — used to read the secret from SiteIntegrations. */
payload: BasePayload
/** Client IP. Sent to Cloudflare only with `sendRemoteIp: true`. */
ip?: string
/**
* Send `remoteip` to Cloudflare. Default false: behind Cloudflare / Traefik /
* Docker the IP the app sees can differ from the one that solved the challenge
* (IPv6 on mobile vs IPv4 at the proxy), and Cloudflare's check doesn't need it.
*/
sendRemoteIp?: boolean
/**
* What to do when verification can't run because of OUR side (missing/wrong
* secret, Cloudflare unreachable). 'allow' (default): accept the submission —
@@ -27,16 +35,6 @@ type VerifyTurnstileArgs = {
* the panel. 'reject': refuse (fail closed).
*/
onConfigError?: 'allow' | 'reject'
/** Payload instance — used to read the secret from SiteIntegrations. */
payload: BasePayload
/**
* Send `remoteip` to Cloudflare. Default false: behind Cloudflare / Traefik /
* Docker the IP the app sees can differ from the one that solved the challenge
* (IPv6 on mobile vs IPv4 at the proxy), and Cloudflare's check doesn't need it.
*/
sendRemoteIp?: boolean
/** Token produced by the client-side widget. */
token: string
}
/** Env fallback for the secret — same name ipalEnvRules({ turnstile: true }) requires. */
@@ -50,20 +48,20 @@ const STATUS_FIELD = 'turnstileStatus'
* erroring) → the visitor can't fix it; by default the submission
* is accepted and the panel shows the problem.
*/
export type TurnstileOutcome = 'degraded' | 'pass' | 'reject'
export type TurnstileCheck = { code?: string; outcome: TurnstileOutcome }
export type TurnstileOutcome = 'pass' | 'reject' | 'degraded'
export type TurnstileCheck = { outcome: TurnstileOutcome; code?: string }
/** Cloudflare error codes caused by our configuration / Cloudflare itself — not by the visitor. */
const CONFIG_ERRORS: Record<string, string> = {
'internal-error': 'Cloudflare reported an internal error while verifying.',
'missing-input-secret': 'The secret key is missing in the request.',
'invalid-input-secret':
'Cloudflare rejected the secret key — check Site Integrations → Turnstile (secret and site key must come from the same widget).',
'missing-input-secret': 'The secret key is missing in the request.',
'internal-error': 'Cloudflare reported an internal error while verifying.',
}
const PLUGIN_ERRORS: Record<string, string> = {
'bad-response': 'Cloudflare returned an unexpected response.',
'missing-secret': `No secret key — fill in Site Integrations → Turnstile (or the ${ENV_SECRET} environment variable).`,
'network-error': 'The server could not reach Cloudflare (challenges.cloudflare.com).',
'bad-response': 'Cloudflare returned an unexpected response.',
}
/**
@@ -74,12 +72,12 @@ const PLUGIN_ERRORS: Record<string, string> = {
* SiteIntegrations is updated (throttled) so the panel shows failures.
*/
export async function checkTurnstile({
ip,
payload,
sendRemoteIp = false,
token,
payload,
ip,
sendRemoteIp = false,
}: Omit<VerifyTurnstileArgs, 'onConfigError'>): Promise<TurnstileCheck> {
if (!token) {return { code: 'missing-input-response', outcome: 'reject' }}
if (!token) return { outcome: 'reject', code: 'missing-input-response' }
const integrations = await getSiteIntegrations<IntegrationsWithTurnstile>(payload)
const previous = integrations[STATUS_FIELD]
@@ -88,29 +86,29 @@ export async function checkTurnstile({
const degraded = async (code: string): Promise<TurnstileCheck> => {
const message = PLUGIN_ERRORS[code] ?? CONFIG_ERRORS[code] ?? `Cloudflare error: ${code}`
console.warn(`[ipal] Turnstile degraded (${code}): ${message}`)
await recordIntegrationStatus(payload, STATUS_FIELD, previous, { code, message, state: 'degraded' })
return { code, outcome: 'degraded' }
await recordIntegrationStatus(payload, STATUS_FIELD, previous, { state: 'degraded', code, message })
return { outcome: 'degraded', code }
}
if (!secret) {return degraded('missing-secret')}
if (!secret) return degraded('missing-secret')
const body = new URLSearchParams({ response: token, secret })
if (sendRemoteIp && ip) {body.append('remoteip', ip)}
const body = new URLSearchParams({ secret, response: token })
if (sendRemoteIp && ip) body.append('remoteip', ip)
let data: SiteverifyResponse
try {
const res = await fetch('https://challenges.cloudflare.com/turnstile/v0/siteverify', {
body,
method: 'POST',
body,
signal: AbortSignal.timeout(8000),
})
if (res.status >= 500) {return degraded('internal-error')}
if (res.status >= 500) return degraded('internal-error')
data = (await res.json()) as SiteverifyResponse
} catch (err) {
console.warn('[ipal] Turnstile: siteverify request failed:', err instanceof Error ? err.message : err)
return degraded('network-error')
}
if (typeof data?.success !== 'boolean') {return degraded('bad-response')}
if (typeof data?.success !== 'boolean') return degraded('bad-response')
if (data.success) {
await recordIntegrationStatus(payload, STATUS_FIELD, previous, { state: 'ok' })
@@ -119,11 +117,11 @@ export async function checkTurnstile({
const codes = data['error-codes'] ?? []
const configCode = codes.find((c) => c in CONFIG_ERRORS)
if (configCode) {return degraded(configCode)}
if (configCode) return degraded(configCode)
// Visitor-side: invalid-input-response, timeout-or-duplicate, missing-input-response, bad-request.
console.warn(`[ipal] Turnstile rejected: ${codes.join(', ') || 'unknown'}${data.hostname ? ` (hostname ${data.hostname})` : ''}`)
return { code: codes[0] ?? 'unknown', outcome: 'reject' }
return { outcome: 'reject', code: codes[0] ?? 'unknown' }
}
/**
+20 -21
View File
@@ -1,18 +1,17 @@
import type { Config, Plugin } from 'payload'
import type { IpalOptions, TotpPluginFactory } from './types.js'
import { buildLocalizationConfig, validateI18nConfig } from './modules/i18n/index.js'
import { injectRoles } from './modules/access/index.js'
import { buildSeoPlugin, injectAutoFillMeta, injectSeoTabs } from './modules/seo/index.js'
import { buildFormsPlugin } from './modules/forms/formsPluginConfig.js'
import { buildSystemPagesFields } from './modules/pages/index.js'
import { buildArchiveFields } from './modules/content/index.js'
import { buildSiteSettings } from './globals/SiteSettings/index.js'
import { buildSiteIntegrations } from './globals/SiteIntegrations/index.js'
import { buildCookieSettings } from './globals/CookieSettings/index.js'
import { buildNotifications } from './globals/Notifications/index.js'
import { buildSiteIntegrations } from './globals/SiteIntegrations/index.js'
import { buildSiteSettings } from './globals/SiteSettings/index.js'
import { injectRoles } from './modules/access/index.js'
import { buildArchiveFields } from './modules/content/index.js'
import { testEmailEndpoint } from './modules/email/test/testEmailEndpoint.js'
import { buildFormsPlugin } from './modules/forms/formsPluginConfig.js'
import { buildLocalizationConfig, validateI18nConfig } from './modules/i18n/index.js'
import { buildSystemPagesFields } from './modules/pages/index.js'
import { buildSeoPlugin, injectAutoFillMeta, injectSeoTabs } from './modules/seo/index.js'
/**
* IPAL (Intecion Payload Advanced Library) plugin for Payload CMS 3.
@@ -123,8 +122,8 @@ export const ipalKit = (options: IpalOptions): Plugin => {
if (options.whiteLabel) {
const wl = options.whiteLabel === true ? {} : options.whiteLabel
const serverProps: Record<string, unknown> = {}
if (wl.settingsSlug) {serverProps.settingsSlug = wl.settingsSlug}
if (wl.nameField) {serverProps.nameField = wl.nameField}
if (wl.settingsSlug) serverProps.settingsSlug = wl.settingsSlug
if (wl.nameField) serverProps.nameField = wl.nameField
const logoProps = { ...serverProps, ...(wl.logoField ? { imageField: wl.logoField } : {}) }
const iconProps = { ...serverProps, ...(wl.iconField ? { imageField: wl.iconField } : {}) }
@@ -145,18 +144,11 @@ export const ipalKit = (options: IpalOptions): Plugin => {
...(config.admin?.components ?? {}),
graphics: {
...(config.admin?.components?.graphics ?? {}),
Icon: { path: '@intecion/ipal-kit/admin#AdminIcon', serverProps: iconProps },
Logo: { path: '@intecion/ipal-kit/admin#AdminLogo', serverProps: logoProps },
Icon: { path: '@intecion/ipal-kit/admin#AdminIcon', serverProps: iconProps },
},
...(creditOn
? {
afterLogin: [
...(config.admin?.components?.afterLogin ?? []),
{
path: '@intecion/ipal-kit/admin#IntecionCredit',
serverProps: { ...creditProps, variant: 'login' },
},
],
afterNavLinks: [
...(config.admin?.components?.afterNavLinks ?? []),
{
@@ -164,6 +156,13 @@ export const ipalKit = (options: IpalOptions): Plugin => {
serverProps: { ...creditProps, variant: 'nav' },
},
],
afterLogin: [
...(config.admin?.components?.afterLogin ?? []),
{
path: '@intecion/ipal-kit/admin#IntecionCredit',
serverProps: { ...creditProps, variant: 'login' },
},
],
}
: {}),
},
@@ -215,8 +214,8 @@ export const ipalKit = (options: IpalOptions): Plugin => {
config.globals = [
...(config.globals ?? []),
buildSiteSettings({
additionalFields: options.siteSettingsFields,
systemPageFields,
additionalFields: options.siteSettingsFields,
}),
buildSiteIntegrations({ additionalFields: options.integrationsFields }),
buildCookieSettings(),
@@ -244,7 +243,7 @@ export const ipalKit = (options: IpalOptions): Plugin => {
// --- hooks: onInit ---
const incomingOnInit = config.onInit
config.onInit = async (payload) => {
if (incomingOnInit) {await incomingOnInit(payload)}
if (incomingOnInit) await incomingOnInit(payload)
payload.logger.info('[ipal] Plugin initialized.')
}