Fixed turnstile

This commit is contained in:
2026-10-15 15:27:43 +02:00
parent 7ef7927e38
commit 3bab8a0697
58 changed files with 1182 additions and 322 deletions
+1
View File
@@ -7,3 +7,4 @@ export { RowLabel } from '../modules/admin-ui/RowLabelComponent.js'
* admin.components.graphics.Logo/Icon.
*/
export { AdminIcon, AdminLogo, IntecionCredit } from '../modules/branding/index.js'
export { IntegrationAlerts } from '../modules/integrations/IntegrationAlerts.js'
+1
View File
@@ -60,6 +60,7 @@ export {
useSetAlternateLinks,
} 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'
+6 -5
View File
@@ -1,3 +1,7 @@
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
*
@@ -10,8 +14,5 @@
* Import these only from Server Actions, route handlers, or server components —
* never from the Payload config or client code.
*/
export { verifyTurnstile } 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'
export { checkTurnstile, verifyTurnstile } from '../modules/turnstile/index.js'
export type { TurnstileCheck, TurnstileOutcome } from '../modules/turnstile/index.js'
@@ -1,5 +1,7 @@
import type { Field } from 'payload'
import { buildIntegrationStatusBanner, buildIntegrationStatusField } from '../../../modules/integrations/status.js'
/**
* Cloudflare Turnstile credentials.
*
@@ -9,6 +11,8 @@ import type { Field } from 'payload'
* so they remain editable in the admin panel.
*/
export const turnstileFields: Field[] = [
// Status written by the server when it verifies a form (checkTurnstile) — banner on this tab.
buildIntegrationStatusBanner('turnstileStatus', 'Turnstile'),
{
name: 'turnstileSiteKey',
type: 'text',
@@ -27,4 +31,5 @@ export const turnstileFields: Field[] = [
},
},
},
buildIntegrationStatusField('turnstileStatus'),
]
+17 -5
View File
@@ -21,10 +21,6 @@ type BuildSiteIntegrationsArgs = {
* impossible to enter.)
*
* Unnamed tabs keep data flat (siteIntegrations.ga4MeasurementId).
*
* Note: R2 storage credentials are NOT here — storage is infrastructure and
* binds at boot, so its config lives in .env (R2_BUCKET, R2_ENDPOINT, ...),
* consumed by buildR2Storage. See docs/storage.md.
*/
export function buildSiteIntegrations({
additionalFields,
@@ -47,10 +43,26 @@ export function buildSiteIntegrations({
{ fields: analyticsFields, label: 'Analytics' },
{ fields: turnstileFields, label: 'Turnstile' },
{ fields: smtpFields, label: 'SMTP' },
...(additionalFields?.length ? [{ fields: additionalFields, label: 'Custom' }] : []),
...(additionalFields?.length
? [{ fields: additionalFields, label: 'Custom' }]
: []),
],
},
],
hooks: {
beforeChange: [
// Keys edited in the panel → clear the old Turnstile 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 }
}
return data
},
],
},
label: 'Site Integrations',
}
}
+139 -137
View File
@@ -1,20 +1,3 @@
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,
@@ -30,58 +13,102 @@ export {
requireRoleField,
ROLE_HIERARCHY,
} from './modules/access/index.js'
export type { GlobalQueryOptions } from './modules/payload/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 {
getGlobal,
getSiteSettings,
getSiteIntegrations,
SITE_SETTINGS_SLUG,
SITE_INTEGRATIONS_SLUG,
} from './modules/payload/index.js'
export type { SeoOption, SeoMeta, PageMetadata } from './modules/seo/index.js'
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'
export {
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,
blocksToMarkdown,
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'
// 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 { 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'.)
export {
buildAutoFillMetaHook,
injectAutoFillMeta,
createMetadataGenerator,
createPageMetadata,
buildSitemapEntries,
buildRobots,
AI_ASSISTANT_BOTS,
AI_TRAINING_BOTS,
} from './modules/seo/index.js'
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'
export type { LocaleMiddlewareResult } from './modules/i18n/index.js'
export {
createLocaleMiddleware,
@@ -89,97 +116,72 @@ export {
} from './modules/i18n/index.js'
export { createProxy, DEFAULT_PROXY_MATCHER } from './modules/i18n/index.js'
export { resolveLocalized } from './modules/i18n/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 { 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 type {
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'
BuildLinkFieldOptions,
BuildLinksFieldOptions,
LinkAppearance,
LinkValue,
ResolveLinkHrefOptions,
} from './modules/links/index.js'
// Read-only MCP server (Claude/agents connect to the site and query it).
export { createMcpRoute } from './modules/mcp/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 { 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'
export { getNotificationTexts, resolveFormMessage, NOTIFICATION_FALLBACK } from './modules/notifications/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 { 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 { 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 { buildWebSiteJsonLd, buildBreadcrumbJsonLd, buildSiteNavigationJsonLd } from './modules/seo/index.js'
export { buildBreadcrumbJsonLd, buildSiteNavigationJsonLd, buildWebSiteJsonLd } from './modules/seo/index.js'
// Local SEO structured data — LocalBusiness (map pack), Service (offering), FAQPage.
export { buildLocalBusinessJsonLd, buildFaqJsonLd, buildServiceJsonLd } from './modules/seo/index.js'
export { buildFaqJsonLd, buildLocalBusinessJsonLd, buildServiceJsonLd } from './modules/seo/index.js'
export { buildArticleJsonLd } from './modules/seo/index.js'
export { buildLlmsTxt } from './modules/seo/index.js'
export { buildSitemapXml, buildSitemapCss, SITEMAP_STYLE_PARAM, DEFAULT_SITEMAP_CREDIT } from './modules/seo/index.js'
export { buildSitemapCss, buildSitemapXml, DEFAULT_SITEMAP_CREDIT, SITEMAP_STYLE_PARAM } 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 { 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'
export { ipalKit } from './plugin.js'
export type { IpalOptions } from './types.js'
+8 -1
View File
@@ -24,6 +24,12 @@ export type SubmitFormArgs = {
*/
maxPerMinute?: number
payload: BasePayload
/**
* 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
}
@@ -87,6 +93,7 @@ export async function submitForm({
ip,
maxPerMinute = 5,
payload,
turnstileOnConfigError = 'allow',
turnstileToken,
}: SubmitFormArgs): Promise<SubmitFormResult> {
// 1. Rate limit — cheapest gate, drops a flood before any real work.
@@ -98,7 +105,7 @@ export async function submitForm({
// 2. Turnstile — verify when a token is supplied; reject on failure.
if (turnstileToken !== undefined) {
const ok = await verifyTurnstile({ ip, payload, token: turnstileToken })
const ok = await verifyTurnstile({ ip, onConfigError: turnstileOnConfigError, payload, token: turnstileToken })
if (!ok) {
return { reason: 'turnstile', success: false }
}
@@ -0,0 +1,58 @@
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
}
/**
* Dashboard alert (admin.components.beforeDashboard): lists integrations that
* 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}
let doc: Record<string, unknown>
try {
doc = (await payload.findGlobal({ slug: 'site-integrations' as never, depth: 0 })) as Record<string, unknown>
} catch {
return null
}
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}
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',
}}
>
<strong>Integration problem — the site still works, but a safeguard is off.</strong>
<ul style={{ margin: '0.5rem 0 0', paddingLeft: '1.2rem' }}>
{failing.map(({ label, status }) => (
<li key={label}>
<strong>{label}:</strong> {status?.message ?? status?.code ?? 'error'}
</li>
))}
</ul>
<a href={`${adminRoute.replace(/\/$/, '')}/globals/site-integrations`} style={{ display: 'inline-block', marginTop: '0.5rem' }}>
Open Site Integrations →
</a>
</div>
)
}
export default IntegrationAlerts
@@ -0,0 +1,64 @@
'use client'
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
}
const fmt = (iso: unknown) => {
if (typeof iso !== 'string' || !iso) {return ''}
const d = new Date(iso)
return Number.isNaN(d.getTime()) ? '' : d.toLocaleString()
}
/**
* Status banner on an integration's tab (Site Integrations). Shows nothing until
* 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) {
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 === 'ok') {
return (
<div style={{ fontSize: '0.85rem', marginBottom: '1.5rem', opacity: 0.75 }}>
✓ {label} working{since ? ` since ${fmt(since)}` : ''}.
</div>
)
}
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: '0.9rem 1rem',
}}
>
<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 }}>
{code ? `Code: ${code}. ` : ''}
{since ? `Since ${fmt(since)}. ` : ''}
{checkedAt ? `Last seen ${fmt(checkedAt)}.` : ''}
</div>
<div style={{ fontSize: '0.8rem', marginTop: '0.35rem', opacity: 0.75 }}>
Fix the keys below and save — the status is checked again on the next form submission.
</div>
</div>
)
}
export default IntegrationStatusBanner
+6
View File
@@ -0,0 +1,6 @@
export {
buildIntegrationStatusBanner,
buildIntegrationStatusField,
recordIntegrationStatus,
} from './status.js'
export type { IntegrationState, IntegrationStatus } from './status.js'
+101
View File
@@ -0,0 +1,101 @@
import type { BasePayload, Field } from 'payload'
/**
* Health of a third-party integration (Turnstile today, SMTP/Graph later),
* stored on the SiteIntegrations global so the panel can show it:
* - a banner on the integration's tab (IntegrationStatusBanner),
* - an alert on the admin dashboard (IntegrationAlerts).
*
* Written by the server when it USES the integration (e.g. verifying a form
* token) — no polling, no cron. Writes are throttled: only on a state change, or
* at most every REFRESH_MS while an error persists, so a broken integration on a
* busy form doesn't turn every submission into a DB write.
*/
export type IntegrationState = 'degraded' | 'ok'
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
}
const REFRESH_MS = 10 * 60_000
const SITE_INTEGRATIONS = 'site-integrations'
/** Hidden group field holding the status — add next to the integration's fields. */
export function buildIntegrationStatusField(name: string): Field {
return {
name,
type: 'group',
admin: { hidden: true },
fields: [
{ name: 'state', type: 'select', options: ['ok', 'degraded'] },
{ name: 'code', type: 'text' },
{ name: 'message', type: 'text' },
{ name: 'since', type: 'date' },
{ name: 'checkedAt', type: 'date' },
],
}
}
/** Read-only banner (UI field) — shows the status group `statusField` on the tab. */
export function buildIntegrationStatusBanner(statusField: string, label: string): Field {
return {
name: `${statusField}Banner`,
type: 'ui',
admin: {
components: {
Field: {
clientProps: { label, statusField },
path: '@intecion/ipal-kit/client#IntegrationStatusBanner',
},
},
},
}
}
/**
* Persist a status change. Never throws — a status write must not break the
* request that triggered it.
*/
export async function recordIntegrationStatus(
payload: BasePayload,
field: string,
previous: IntegrationStatus | null | undefined,
next: { code?: string; message?: string; state: IntegrationState },
): Promise<void> {
const now = new Date()
const changed = previous?.state !== next.state || (next.state === 'degraded' && previous?.code !== next.code)
const stale =
next.state === 'degraded' &&
(!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}
const status: IntegrationStatus = {
checkedAt: now.toISOString(),
code: next.code ?? null,
message: next.message ?? null,
since: changed ? now.toISOString() : (previous?.since ?? now.toISOString()),
state: next.state,
}
try {
await payload.updateGlobal({
slug: SITE_INTEGRATIONS as never,
context: { ipalIntegrationStatus: true },
data: { [field]: status } as never,
depth: 0,
})
} catch (err) {
console.warn(`[ipal] could not record ${field}:`, err instanceof Error ? err.message : err)
}
}
+2 -1
View File
@@ -1,4 +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 { verifyTurnstile } from './verify.js'
export { checkTurnstile, verifyTurnstile } from './verify.js'
export type { TurnstileCheck, TurnstileOutcome } from './verify.js'
+95 -20
View File
@@ -2,6 +2,7 @@ import 'server-only'
import type { BasePayload } from 'payload'
import { type IntegrationStatus, recordIntegrationStatus } from '../integrations/status.js'
import { getSiteIntegrations } from '../payload/index.js'
type SiteverifyResponse = {
@@ -13,50 +14,124 @@ type SiteverifyResponse = {
type IntegrationsWithTurnstile = {
turnstileSecretKey?: null | string
turnstileStatus?: IntegrationStatus | null
}
type VerifyTurnstileArgs = {
/** Optional client IP for stricter verification. */
/** Client IP. Sent to Cloudflare only with `sendRemoteIp: true`. */
ip?: string
/**
* What to do when verification can't run because of OUR side (missing/wrong
* secret, Cloudflare unreachable). 'allow' (default): accept the submission —
* rate limit, honeypot and validation still apply — and show the problem in
* 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. */
const ENV_SECRET = 'TURNSTILE_SECRET_KEY'
const STATUS_FIELD = 'turnstileStatus'
/**
* Verifies a Turnstile token with Cloudflare, server-side only.
*
* The secret comes from the SiteIntegrations global (editor-managed, per the
* plugin's "secrets in the panel" model), read via the Local API which bypasses
* access control. `server-only` guarantees this never reaches the browser
* bundle, keeping the secret off the client.
*
* Returns false on any failure (missing secret/token, network error, rejected
* challenge) — callers treat false as "do not trust this submission".
* - `pass` — token valid.
* - `reject` — the VISITOR's token is bad (forged, reused, expired, malformed) → refuse.
* - `degraded` — OUR side is broken (no/wrong secret, Cloudflare unreachable or
* erroring) → the visitor can't fix it; by default the submission
* is accepted and the panel shows the problem.
*/
export async function verifyTurnstile({
export type TurnstileOutcome = 'degraded' | 'pass' | 'reject'
export type TurnstileCheck = { code?: string; outcome: TurnstileOutcome }
/** 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.',
'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.',
}
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).',
}
/**
* Verifies a Turnstile token with Cloudflare and classifies the result (server-only).
*
* Secret: SiteIntegrations → Turnstile (panel) first, then TURNSTILE_SECRET_KEY.
* Every result is logged when not `pass`, and the integration status on
* SiteIntegrations is updated (throttled) so the panel shows failures.
*/
export async function checkTurnstile({
ip,
payload,
sendRemoteIp = false,
token,
}: VerifyTurnstileArgs): Promise<boolean> {
if (!token) {return false}
}: Omit<VerifyTurnstileArgs, 'onConfigError'>): Promise<TurnstileCheck> {
if (!token) {return { code: 'missing-input-response', outcome: 'reject' }}
const integrations = await getSiteIntegrations<IntegrationsWithTurnstile>(payload)
const secret = integrations.turnstileSecretKey
if (!secret) {return false}
const previous = integrations[STATUS_FIELD]
const secret = integrations.turnstileSecretKey?.trim() || process.env[ENV_SECRET]?.trim()
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' }
}
if (!secret) {return degraded('missing-secret')}
const body = new URLSearchParams({ response: token, secret })
if (ip) {body.append('remoteip', ip)}
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',
signal: AbortSignal.timeout(8000),
})
const data = (await res.json()) as SiteverifyResponse
return data.success
} catch {
return false
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 (data.success) {
await recordIntegrationStatus(payload, STATUS_FIELD, previous, { state: 'ok' })
return { outcome: 'pass' }
}
const codes = data['error-codes'] ?? []
const configCode = codes.find((c) => c in CONFIG_ERRORS)
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' }
}
/**
* Boolean wrapper used by submitForm. `onConfigError` decides what a `degraded`
* result means: 'allow' (default) keeps the site's forms working while the
* panel shows the problem; 'reject' fails closed.
*/
export async function verifyTurnstile({ onConfigError = 'allow', ...args }: VerifyTurnstileArgs): Promise<boolean> {
const { outcome } = await checkTurnstile(args)
return outcome === 'pass' || (outcome === 'degraded' && onConfigError === 'allow')
}
+16
View File
@@ -225,6 +225,22 @@ export const ipalKit = (options: IpalOptions): Plugin => {
config.endpoints = [...(config.endpoints ?? []), testEmailEndpoint]
// --- integration alerts on the dashboard (Turnstile status, …) ---
// Renders nothing while everything works; never throws.
config.admin = {
...(config.admin ?? {}),
components: {
...(config.admin?.components ?? {}),
beforeDashboard: [
...(config.admin?.components?.beforeDashboard ?? []),
{
path: '@intecion/ipal-kit/admin#IntegrationAlerts',
serverProps: { adminRoute: options.adminRoute ?? '/admin' },
},
],
},
}
// --- hooks: onInit ---
const incomingOnInit = config.onInit
config.onInit = async (payload) => {