diff --git a/dist/exports/admin.d.ts b/dist/exports/admin.d.ts index 7fbb2ff..58eeac4 100644 --- a/dist/exports/admin.d.ts +++ b/dist/exports/admin.d.ts @@ -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'; diff --git a/dist/exports/admin.js b/dist/exports/admin.js index fb36e5a..16945eb 100644 --- a/dist/exports/admin.js +++ b/dist/exports/admin.js @@ -6,5 +6,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 { IntegrationAlerts } from '../modules/integrations/IntegrationAlerts.js'; //# sourceMappingURL=admin.js.map \ No newline at end of file diff --git a/dist/exports/admin.js.map b/dist/exports/admin.js.map index 85c27cf..d62c221 100644 --- a/dist/exports/admin.js.map +++ b/dist/exports/admin.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../src/exports/admin.ts"],"sourcesContent":["export { RowLabel } from '../modules/admin-ui/RowLabelComponent.js'\n/**\n * Entry point: @intecion/ipal-kit/admin\n *\n * Admin-panel UI components (white-label branding, array row labels). Separate export so Payload's\n * importMap can resolve them by a stable path when ipalKit injects\n * admin.components.graphics.Logo/Icon.\n */\nexport { AdminIcon, AdminLogo, IntecionCredit } from '../modules/branding/index.js'\n"],"names":["RowLabel","AdminIcon","AdminLogo","IntecionCredit"],"mappings":"AAAA,SAASA,QAAQ,QAAQ,2CAA0C;AACnE;;;;;;CAMC,GACD,SAASC,SAAS,EAAEC,SAAS,EAAEC,cAAc,QAAQ,+BAA8B"} \ No newline at end of file +{"version":3,"sources":["../../src/exports/admin.ts"],"sourcesContent":["export { RowLabel } from '../modules/admin-ui/RowLabelComponent.js'\n/**\n * Entry point: @intecion/ipal-kit/admin\n *\n * Admin-panel UI components (white-label branding, array row labels). Separate export so Payload's\n * importMap can resolve them by a stable path when ipalKit injects\n * admin.components.graphics.Logo/Icon.\n */\nexport { AdminIcon, AdminLogo, IntecionCredit } from '../modules/branding/index.js'\nexport { IntegrationAlerts } from '../modules/integrations/IntegrationAlerts.js'\n"],"names":["RowLabel","AdminIcon","AdminLogo","IntecionCredit","IntegrationAlerts"],"mappings":"AAAA,SAASA,QAAQ,QAAQ,2CAA0C;AACnE;;;;;;CAMC,GACD,SAASC,SAAS,EAAEC,SAAS,EAAEC,cAAc,QAAQ,+BAA8B;AACnF,SAASC,iBAAiB,QAAQ,+CAA8C"} \ No newline at end of file diff --git a/dist/exports/client.d.ts b/dist/exports/client.d.ts index 3d166fe..78e344b 100644 --- a/dist/exports/client.d.ts +++ b/dist/exports/client.d.ts @@ -28,6 +28,7 @@ export { buildLocalizedPath, getLocaleCodes, getLocalizedSlugs, switchLocalePath export type { I18nConfig, LocalizedSlugs } from '../modules/i18n/index.js'; export { AlternateLinksProvider, AlternateLinksUpdater, LanguageSwitcher, useAlternateLinks, 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'; diff --git a/dist/exports/client.js b/dist/exports/client.js index 3f87346..caa37b8 100644 --- a/dist/exports/client.js +++ b/dist/exports/client.js @@ -21,6 +21,7 @@ export { buildValidator, checked, custom, email, isEmail, maxLength, minLength, // components (e.g. a LanguageSwitcher that computes locale URLs on the client). export { buildLocalizedPath, getLocaleCodes, getLocalizedSlugs, switchLocalePath } from '../modules/i18n/index.js'; export { AlternateLinksProvider, AlternateLinksUpdater, LanguageSwitcher, useAlternateLinks, useSetAlternateLinks } 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'; diff --git a/dist/exports/client.js.map b/dist/exports/client.js.map index 3107578..f3bea12 100644 --- a/dist/exports/client.js.map +++ b/dist/exports/client.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../src/exports/client.ts"],"sourcesContent":["'use client'\nexport { MaskedField } from '../globals/SiteIntegrations/components/MaskedField.js'\nexport { TestEmailButton } from '../globals/SiteIntegrations/components/TestEmailButton.js'\nexport { AccessibilityProvider, AccessibilityWidget, useAccessibility } from '../modules/accessibility/client.js'\nexport type { A11yClassNames, A11yState, A11yTexts } from '../modules/accessibility/client.js'\nexport { Analytics } from '../modules/analytics/client.js'\nexport type { AnalyticsProps } from '../modules/analytics/client.js'\n\nexport { pushDataLayer } from '../modules/analytics/client.js'\nexport { loadClarity, loadLinkedIn, loadMetaPixel, loadTikTok } from '../modules/analytics/client.js'\n/**\n * Entry point: ipal-kit/client\n *\n * Client-side ('use client') exports — React hooks, providers, and UI\n * components. Kept separate from the main entry so server bundles don't pull in\n * client-only code.\n */\nexport {\n ConsentProvider,\n ConsentScript,\n CookieBanner,\n CookieButton,\n useConsent,\n useConsentContext,\n} from '../modules/consent/client.js'\nexport type { CookieBannerClassNames } from '../modules/consent/client.js'\nexport { formAnalyticsOnSuccess } from '../modules/forms/formAnalytics.js'\nexport type { FormAnalyticsConfig } from '../modules/forms/formAnalytics.js'\nexport { HONEYPOT_FIELD, honeypotInputProps, isHoneypotTripped } from '../modules/forms/honeypot.js'\nexport { useContactForm } from '../modules/forms/useContactForm.js'\nexport type { ContactFormErrors, ContactFormValues, SubmitAction } from '../modules/forms/useContactForm.js'\nexport { useForm } from '../modules/forms/useForm.js'\nexport type { FormErrors, FormSubmitAction, Validator } from '../modules/forms/useForm.js'\nexport {\n buildValidator,\n checked,\n custom,\n email,\n isEmail,\n maxLength,\n minLength,\n pattern,\n required,\n} from '../modules/forms/validators.js'\nexport type { Rule } from '../modules/forms/validators.js'\n// Pure i18n path helpers — no server/RSC deps, safe to import in client\n// components (e.g. a LanguageSwitcher that computes locale URLs on the client).\nexport {\n buildLocalizedPath,\n getLocaleCodes,\n getLocalizedSlugs,\n switchLocalePath,\n} from '../modules/i18n/index.js'\nexport type { I18nConfig, LocalizedSlugs } from '../modules/i18n/index.js'\nexport {\n AlternateLinksProvider,\n AlternateLinksUpdater,\n LanguageSwitcher,\n useAlternateLinks,\n useSetAlternateLinks,\n} from '../modules/i18n/index.js'\nexport type { AlternateLinks, LanguageSwitcherClassNames } from '../modules/i18n/index.js'\nexport { LocaleView } from '../modules/pages/LocaleView.js'\nexport { Turnstile } from '../modules/turnstile/client.js'\nexport { TurnstileProvider, useTurnstile } from '../modules/turnstile/client.js'\nexport type { TurnstileProps } from '../modules/turnstile/client.js'\n"],"names":["MaskedField","TestEmailButton","AccessibilityProvider","AccessibilityWidget","useAccessibility","Analytics","pushDataLayer","loadClarity","loadLinkedIn","loadMetaPixel","loadTikTok","ConsentProvider","ConsentScript","CookieBanner","CookieButton","useConsent","useConsentContext","formAnalyticsOnSuccess","HONEYPOT_FIELD","honeypotInputProps","isHoneypotTripped","useContactForm","useForm","buildValidator","checked","custom","email","isEmail","maxLength","minLength","pattern","required","buildLocalizedPath","getLocaleCodes","getLocalizedSlugs","switchLocalePath","AlternateLinksProvider","AlternateLinksUpdater","LanguageSwitcher","useAlternateLinks","useSetAlternateLinks","LocaleView","Turnstile","TurnstileProvider","useTurnstile"],"mappings":"AAAA;AACA,SAASA,WAAW,QAAQ,wDAAuD;AACnF,SAASC,eAAe,QAAQ,4DAA2D;AAC3F,SAASC,qBAAqB,EAAEC,mBAAmB,EAAEC,gBAAgB,QAAQ,qCAAoC;AAEjH,SAASC,SAAS,QAAQ,iCAAgC;AAG1D,SAASC,aAAa,QAAQ,iCAAgC;AAC9D,SAASC,WAAW,EAAEC,YAAY,EAAEC,aAAa,EAAEC,UAAU,QAAQ,iCAAgC;AACrG;;;;;;CAMC,GACD,SACEC,eAAe,EACfC,aAAa,EACbC,YAAY,EACZC,YAAY,EACZC,UAAU,EACVC,iBAAiB,QACZ,+BAA8B;AAErC,SAASC,sBAAsB,QAAQ,oCAAmC;AAE1E,SAASC,cAAc,EAAEC,kBAAkB,EAAEC,iBAAiB,QAAQ,+BAA8B;AACpG,SAASC,cAAc,QAAQ,qCAAoC;AAEnE,SAASC,OAAO,QAAQ,8BAA6B;AAErD,SACEC,cAAc,EACdC,OAAO,EACPC,MAAM,EACNC,KAAK,EACLC,OAAO,EACPC,SAAS,EACTC,SAAS,EACTC,OAAO,EACPC,QAAQ,QACH,iCAAgC;AAEvC,wEAAwE;AACxE,gFAAgF;AAChF,SACEC,kBAAkB,EAClBC,cAAc,EACdC,iBAAiB,EACjBC,gBAAgB,QACX,2BAA0B;AAEjC,SACEC,sBAAsB,EACtBC,qBAAqB,EACrBC,gBAAgB,EAChBC,iBAAiB,EACjBC,oBAAoB,QACf,2BAA0B;AAEjC,SAASC,UAAU,QAAQ,iCAAgC;AAC3D,SAASC,SAAS,QAAQ,iCAAgC;AAC1D,SAASC,iBAAiB,EAAEC,YAAY,QAAQ,iCAAgC"} \ No newline at end of file +{"version":3,"sources":["../../src/exports/client.ts"],"sourcesContent":["'use client'\nexport { MaskedField } from '../globals/SiteIntegrations/components/MaskedField.js'\nexport { TestEmailButton } from '../globals/SiteIntegrations/components/TestEmailButton.js'\nexport { AccessibilityProvider, AccessibilityWidget, useAccessibility } from '../modules/accessibility/client.js'\nexport type { A11yClassNames, A11yState, A11yTexts } from '../modules/accessibility/client.js'\nexport { Analytics } from '../modules/analytics/client.js'\nexport type { AnalyticsProps } from '../modules/analytics/client.js'\n\nexport { pushDataLayer } from '../modules/analytics/client.js'\nexport { loadClarity, loadLinkedIn, loadMetaPixel, loadTikTok } from '../modules/analytics/client.js'\n/**\n * Entry point: ipal-kit/client\n *\n * Client-side ('use client') exports — React hooks, providers, and UI\n * components. Kept separate from the main entry so server bundles don't pull in\n * client-only code.\n */\nexport {\n ConsentProvider,\n ConsentScript,\n CookieBanner,\n CookieButton,\n useConsent,\n useConsentContext,\n} from '../modules/consent/client.js'\nexport type { CookieBannerClassNames } from '../modules/consent/client.js'\nexport { formAnalyticsOnSuccess } from '../modules/forms/formAnalytics.js'\nexport type { FormAnalyticsConfig } from '../modules/forms/formAnalytics.js'\nexport { HONEYPOT_FIELD, honeypotInputProps, isHoneypotTripped } from '../modules/forms/honeypot.js'\nexport { useContactForm } from '../modules/forms/useContactForm.js'\nexport type { ContactFormErrors, ContactFormValues, SubmitAction } from '../modules/forms/useContactForm.js'\nexport { useForm } from '../modules/forms/useForm.js'\nexport type { FormErrors, FormSubmitAction, Validator } from '../modules/forms/useForm.js'\nexport {\n buildValidator,\n checked,\n custom,\n email,\n isEmail,\n maxLength,\n minLength,\n pattern,\n required,\n} from '../modules/forms/validators.js'\nexport type { Rule } from '../modules/forms/validators.js'\n// Pure i18n path helpers — no server/RSC deps, safe to import in client\n// components (e.g. a LanguageSwitcher that computes locale URLs on the client).\nexport {\n buildLocalizedPath,\n getLocaleCodes,\n getLocalizedSlugs,\n switchLocalePath,\n} from '../modules/i18n/index.js'\nexport type { I18nConfig, LocalizedSlugs } from '../modules/i18n/index.js'\nexport {\n AlternateLinksProvider,\n AlternateLinksUpdater,\n LanguageSwitcher,\n useAlternateLinks,\n useSetAlternateLinks,\n} from '../modules/i18n/index.js'\nexport type { AlternateLinks, LanguageSwitcherClassNames } from '../modules/i18n/index.js'\nexport { IntegrationStatusBanner } from '../modules/integrations/IntegrationStatusBanner.js'\nexport { LocaleView } from '../modules/pages/LocaleView.js'\nexport { Turnstile } from '../modules/turnstile/client.js'\nexport { TurnstileProvider, useTurnstile } from '../modules/turnstile/client.js'\nexport type { TurnstileProps } from '../modules/turnstile/client.js'\n"],"names":["MaskedField","TestEmailButton","AccessibilityProvider","AccessibilityWidget","useAccessibility","Analytics","pushDataLayer","loadClarity","loadLinkedIn","loadMetaPixel","loadTikTok","ConsentProvider","ConsentScript","CookieBanner","CookieButton","useConsent","useConsentContext","formAnalyticsOnSuccess","HONEYPOT_FIELD","honeypotInputProps","isHoneypotTripped","useContactForm","useForm","buildValidator","checked","custom","email","isEmail","maxLength","minLength","pattern","required","buildLocalizedPath","getLocaleCodes","getLocalizedSlugs","switchLocalePath","AlternateLinksProvider","AlternateLinksUpdater","LanguageSwitcher","useAlternateLinks","useSetAlternateLinks","IntegrationStatusBanner","LocaleView","Turnstile","TurnstileProvider","useTurnstile"],"mappings":"AAAA;AACA,SAASA,WAAW,QAAQ,wDAAuD;AACnF,SAASC,eAAe,QAAQ,4DAA2D;AAC3F,SAASC,qBAAqB,EAAEC,mBAAmB,EAAEC,gBAAgB,QAAQ,qCAAoC;AAEjH,SAASC,SAAS,QAAQ,iCAAgC;AAG1D,SAASC,aAAa,QAAQ,iCAAgC;AAC9D,SAASC,WAAW,EAAEC,YAAY,EAAEC,aAAa,EAAEC,UAAU,QAAQ,iCAAgC;AACrG;;;;;;CAMC,GACD,SACEC,eAAe,EACfC,aAAa,EACbC,YAAY,EACZC,YAAY,EACZC,UAAU,EACVC,iBAAiB,QACZ,+BAA8B;AAErC,SAASC,sBAAsB,QAAQ,oCAAmC;AAE1E,SAASC,cAAc,EAAEC,kBAAkB,EAAEC,iBAAiB,QAAQ,+BAA8B;AACpG,SAASC,cAAc,QAAQ,qCAAoC;AAEnE,SAASC,OAAO,QAAQ,8BAA6B;AAErD,SACEC,cAAc,EACdC,OAAO,EACPC,MAAM,EACNC,KAAK,EACLC,OAAO,EACPC,SAAS,EACTC,SAAS,EACTC,OAAO,EACPC,QAAQ,QACH,iCAAgC;AAEvC,wEAAwE;AACxE,gFAAgF;AAChF,SACEC,kBAAkB,EAClBC,cAAc,EACdC,iBAAiB,EACjBC,gBAAgB,QACX,2BAA0B;AAEjC,SACEC,sBAAsB,EACtBC,qBAAqB,EACrBC,gBAAgB,EAChBC,iBAAiB,EACjBC,oBAAoB,QACf,2BAA0B;AAEjC,SAASC,uBAAuB,QAAQ,qDAAoD;AAC5F,SAASC,UAAU,QAAQ,iCAAgC;AAC3D,SAASC,SAAS,QAAQ,iCAAgC;AAC1D,SAASC,iBAAiB,EAAEC,YAAY,QAAQ,iCAAgC"} \ No newline at end of file diff --git a/dist/exports/server.d.ts b/dist/exports/server.d.ts index 2d85acf..e3306d8 100644 --- a/dist/exports/server.d.ts +++ b/dist/exports/server.d.ts @@ -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'; diff --git a/dist/exports/server.js b/dist/exports/server.js index 8b9d79d..c673da8 100644 --- a/dist/exports/server.js +++ b/dist/exports/server.js @@ -1,3 +1,5 @@ +export { sendEmail } from '../modules/email/index.js'; +export { submitForm } from '../modules/forms/index.js'; /** * Entry point: ipal-kit/server * @@ -9,8 +11,6 @@ * * 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 { submitForm } from '../modules/forms/index.js'; + */ export { checkTurnstile, verifyTurnstile } from '../modules/turnstile/index.js'; //# sourceMappingURL=server.js.map \ No newline at end of file diff --git a/dist/exports/server.js.map b/dist/exports/server.js.map index 8e406f9..7fad1a5 100644 --- a/dist/exports/server.js.map +++ b/dist/exports/server.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../src/exports/server.ts"],"sourcesContent":["/**\n * Entry point: ipal-kit/server\n *\n * Server-only runtime functions — these import 'server-only' (Turnstile secret,\n * SMTP password, nodemailer). Kept OUT of the main entry so that loading the\n * Payload config or running `payload generate:importmap` (both Node scripts,\n * no bundler) never pulls in 'server-only', which throws outside a bundled\n * server context.\n *\n * Import these only from Server Actions, route handlers, or server components —\n * never from the Payload config or client code.\n */\nexport { verifyTurnstile } from '../modules/turnstile/index.js'\nexport { sendEmail } from '../modules/email/index.js'\nexport type { SendEmailArgs, SendEmailResult } from '../modules/email/index.js'\nexport { submitForm } from '../modules/forms/index.js'\nexport type { SubmitFormArgs, SubmitFormResult } from '../modules/forms/index.js'\n"],"names":["verifyTurnstile","sendEmail","submitForm"],"mappings":"AAAA;;;;;;;;;;;CAWC,GACD,SAASA,eAAe,QAAQ,gCAA+B;AAC/D,SAASC,SAAS,QAAQ,4BAA2B;AAErD,SAASC,UAAU,QAAQ,4BAA2B"} \ No newline at end of file +{"version":3,"sources":["../../src/exports/server.ts"],"sourcesContent":["export { sendEmail } from '../modules/email/index.js'\nexport type { SendEmailArgs, SendEmailResult } from '../modules/email/index.js'\nexport { submitForm } from '../modules/forms/index.js'\nexport type { SubmitFormArgs, SubmitFormResult } from '../modules/forms/index.js'\n/**\n * Entry point: ipal-kit/server\n *\n * Server-only runtime functions — these import 'server-only' (Turnstile secret,\n * SMTP password, nodemailer). Kept OUT of the main entry so that loading the\n * Payload config or running `payload generate:importmap` (both Node scripts,\n * no bundler) never pulls in 'server-only', which throws outside a bundled\n * server context.\n *\n * Import these only from Server Actions, route handlers, or server components —\n * never from the Payload config or client code.\n */\nexport { checkTurnstile, verifyTurnstile } from '../modules/turnstile/index.js'\nexport type { TurnstileCheck, TurnstileOutcome } from '../modules/turnstile/index.js'\n"],"names":["sendEmail","submitForm","checkTurnstile","verifyTurnstile"],"mappings":"AAAA,SAASA,SAAS,QAAQ,4BAA2B;AAErD,SAASC,UAAU,QAAQ,4BAA2B;AAEtD;;;;;;;;;;;CAWC,GACD,SAASC,cAAc,EAAEC,eAAe,QAAQ,gCAA+B"} \ No newline at end of file diff --git a/dist/globals/SiteIntegrations/fields/turnstile.js b/dist/globals/SiteIntegrations/fields/turnstile.js index 80a43f9..598a5b6 100644 --- a/dist/globals/SiteIntegrations/fields/turnstile.js +++ b/dist/globals/SiteIntegrations/fields/turnstile.js @@ -1,3 +1,4 @@ +import { buildIntegrationStatusBanner, buildIntegrationStatusField } from '../../../modules/integrations/status.js'; /** * Cloudflare Turnstile credentials. * @@ -6,6 +7,8 @@ * (SiteIntegrations requires an authenticated user) rather than per-field, * so they remain editable in the admin panel. */ export const turnstileFields = [ + // Status written by the server when it verifies a form (checkTurnstile) — banner on this tab. + buildIntegrationStatusBanner('turnstileStatus', 'Turnstile'), { name: 'turnstileSiteKey', type: 'text', @@ -23,7 +26,8 @@ Field: '@intecion/ipal-kit/client#MaskedField' } } - } + }, + buildIntegrationStatusField('turnstileStatus') ]; //# sourceMappingURL=turnstile.js.map \ No newline at end of file diff --git a/dist/globals/SiteIntegrations/fields/turnstile.js.map b/dist/globals/SiteIntegrations/fields/turnstile.js.map index e4a1288..98622c6 100644 --- a/dist/globals/SiteIntegrations/fields/turnstile.js.map +++ b/dist/globals/SiteIntegrations/fields/turnstile.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../../../src/globals/SiteIntegrations/fields/turnstile.ts"],"sourcesContent":["import type { Field } from 'payload'\n\n/**\n * Cloudflare Turnstile credentials.\n *\n * siteKey is public (rendered in the widget); secretKey is used for\n * server-side verification. Both are protected at the global level\n * (SiteIntegrations requires an authenticated user) rather than per-field,\n * so they remain editable in the admin panel.\n */\nexport const turnstileFields: Field[] = [\n {\n name: 'turnstileSiteKey',\n type: 'text',\n admin: {\n description: 'Public site key rendered in the Turnstile widget.',\n },\n },\n {\n name: 'turnstileSecretKey',\n type: 'text',\n admin: {\n description: 'Secret key used for server-side verification.',\n // Masked in the UI (••••) — stored plaintext, readable for verification.\n components: {\n Field: '@intecion/ipal-kit/client#MaskedField',\n },\n },\n },\n]\n"],"names":["turnstileFields","name","type","admin","description","components","Field"],"mappings":"AAEA;;;;;;;CAOC,GACD,OAAO,MAAMA,kBAA2B;IACtC;QACEC,MAAM;QACNC,MAAM;QACNC,OAAO;YACLC,aAAa;QACf;IACF;IACA;QACEH,MAAM;QACNC,MAAM;QACNC,OAAO;YACLC,aAAa;YACb,yEAAyE;YACzEC,YAAY;gBACVC,OAAO;YACT;QACF;IACF;CACD,CAAA"} \ No newline at end of file +{"version":3,"sources":["../../../../src/globals/SiteIntegrations/fields/turnstile.ts"],"sourcesContent":["import type { Field } from 'payload'\n\nimport { buildIntegrationStatusBanner, buildIntegrationStatusField } from '../../../modules/integrations/status.js'\n\n/**\n * Cloudflare Turnstile credentials.\n *\n * siteKey is public (rendered in the widget); secretKey is used for\n * server-side verification. Both are protected at the global level\n * (SiteIntegrations requires an authenticated user) rather than per-field,\n * so they remain editable in the admin panel.\n */\nexport const turnstileFields: Field[] = [\n // Status written by the server when it verifies a form (checkTurnstile) — banner on this tab.\n buildIntegrationStatusBanner('turnstileStatus', 'Turnstile'),\n {\n name: 'turnstileSiteKey',\n type: 'text',\n admin: {\n description: 'Public site key rendered in the Turnstile widget.',\n },\n },\n {\n name: 'turnstileSecretKey',\n type: 'text',\n admin: {\n description: 'Secret key used for server-side verification.',\n // Masked in the UI (••••) — stored plaintext, readable for verification.\n components: {\n Field: '@intecion/ipal-kit/client#MaskedField',\n },\n },\n },\n buildIntegrationStatusField('turnstileStatus'),\n]\n"],"names":["buildIntegrationStatusBanner","buildIntegrationStatusField","turnstileFields","name","type","admin","description","components","Field"],"mappings":"AAEA,SAASA,4BAA4B,EAAEC,2BAA2B,QAAQ,0CAAyC;AAEnH;;;;;;;CAOC,GACD,OAAO,MAAMC,kBAA2B;IACtC,8FAA8F;IAC9FF,6BAA6B,mBAAmB;IAChD;QACEG,MAAM;QACNC,MAAM;QACNC,OAAO;YACLC,aAAa;QACf;IACF;IACA;QACEH,MAAM;QACNC,MAAM;QACNC,OAAO;YACLC,aAAa;YACb,yEAAyE;YACzEC,YAAY;gBACVC,OAAO;YACT;QACF;IACF;IACAP,4BAA4B;CAC7B,CAAA"} \ No newline at end of file diff --git a/dist/globals/SiteIntegrations/index.d.ts b/dist/globals/SiteIntegrations/index.d.ts index 7b757fe..52e35d7 100644 --- a/dist/globals/SiteIntegrations/index.d.ts +++ b/dist/globals/SiteIntegrations/index.d.ts @@ -14,10 +14,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 declare function buildSiteIntegrations({ additionalFields, }?: BuildSiteIntegrationsArgs): GlobalConfig; export {}; diff --git a/dist/globals/SiteIntegrations/index.js b/dist/globals/SiteIntegrations/index.js index 32e6a7a..f87ef33 100644 --- a/dist/globals/SiteIntegrations/index.js +++ b/dist/globals/SiteIntegrations/index.js @@ -13,10 +13,6 @@ import { turnstileFields } from './fields/turnstile.js'; * 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 } = {}) { return { slug: 'site-integrations', @@ -54,6 +50,28 @@ import { turnstileFields } from './fields/turnstile.js'; ] } ], + 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)=>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' }; } diff --git a/dist/globals/SiteIntegrations/index.js.map b/dist/globals/SiteIntegrations/index.js.map index 743ddd6..a2f5010 100644 --- a/dist/globals/SiteIntegrations/index.js.map +++ b/dist/globals/SiteIntegrations/index.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../../src/globals/SiteIntegrations/index.ts"],"sourcesContent":["import type { Field, GlobalConfig } from 'payload'\n\nimport { isAdmin } from '../../modules/access/index.js'\nimport { analyticsFields } from './fields/analytics.js'\nimport { smtpFields } from './fields/smtp.js'\nimport { turnstileFields } from './fields/turnstile.js'\n\ntype BuildSiteIntegrationsArgs = {\n /** Extra fields injected by the client project */\n additionalFields?: Field[]\n}\n\n/**\n * Builds the SiteIntegrations global.\n *\n * Holds third-party service credentials. Access is enforced at the global\n * level — the whole global requires an authenticated user — so secrets stay\n * out of anonymous API responses while remaining editable in the admin panel\n * and readable via the server-side Local API. (Field-level read:false was\n * avoided because it also hides fields from the admin UI, making them\n * impossible to enter.)\n *\n * Unnamed tabs keep data flat (siteIntegrations.ga4MeasurementId).\n *\n * Note: R2 storage credentials are NOT here — storage is infrastructure and\n * binds at boot, so its config lives in .env (R2_BUCKET, R2_ENDPOINT, ...),\n * consumed by buildR2Storage. See docs/storage.md.\n */\nexport function buildSiteIntegrations({\n additionalFields,\n}: BuildSiteIntegrationsArgs = {}): GlobalConfig {\n return {\n slug: 'site-integrations',\n access: {\n // Admin-only — secrets live here. Anonymous and non-admin users get\n // nothing through the API; admins read/edit in the panel and via Local API.\n read: ({ req: { user } }) => isAdmin(user),\n update: ({ req: { user } }) => isAdmin(user),\n },\n admin: {\n group: 'Settings',\n },\n fields: [\n {\n type: 'tabs',\n tabs: [\n { fields: analyticsFields, label: 'Analytics' },\n { fields: turnstileFields, label: 'Turnstile' },\n { fields: smtpFields, label: 'SMTP' },\n ...(additionalFields?.length ? [{ fields: additionalFields, label: 'Custom' }] : []),\n ],\n },\n ],\n label: 'Site Integrations',\n }\n}\n"],"names":["isAdmin","analyticsFields","smtpFields","turnstileFields","buildSiteIntegrations","additionalFields","slug","access","read","req","user","update","admin","group","fields","type","tabs","label","length"],"mappings":"AAEA,SAASA,OAAO,QAAQ,gCAA+B;AACvD,SAASC,eAAe,QAAQ,wBAAuB;AACvD,SAASC,UAAU,QAAQ,mBAAkB;AAC7C,SAASC,eAAe,QAAQ,wBAAuB;AAOvD;;;;;;;;;;;;;;;CAeC,GACD,OAAO,SAASC,sBAAsB,EACpCC,gBAAgB,EACU,GAAG,CAAC,CAAC;IAC/B,OAAO;QACLC,MAAM;QACNC,QAAQ;YACN,oEAAoE;YACpE,4EAA4E;YAC5EC,MAAM,CAAC,EAAEC,KAAK,EAAEC,IAAI,EAAE,EAAE,GAAKV,QAAQU;YACrCC,QAAQ,CAAC,EAAEF,KAAK,EAAEC,IAAI,EAAE,EAAE,GAAKV,QAAQU;QACzC;QACAE,OAAO;YACLC,OAAO;QACT;QACAC,QAAQ;YACN;gBACEC,MAAM;gBACNC,MAAM;oBACJ;wBAAEF,QAAQb;wBAAiBgB,OAAO;oBAAY;oBAC9C;wBAAEH,QAAQX;wBAAiBc,OAAO;oBAAY;oBAC9C;wBAAEH,QAAQZ;wBAAYe,OAAO;oBAAO;uBAChCZ,kBAAkBa,SAAS;wBAAC;4BAAEJ,QAAQT;4BAAkBY,OAAO;wBAAS;qBAAE,GAAG,EAAE;iBACpF;YACH;SACD;QACDA,OAAO;IACT;AACF"} \ No newline at end of file +{"version":3,"sources":["../../../src/globals/SiteIntegrations/index.ts"],"sourcesContent":["import type { Field, GlobalConfig } from 'payload'\n\nimport { isAdmin } from '../../modules/access/index.js'\nimport { analyticsFields } from './fields/analytics.js'\nimport { smtpFields } from './fields/smtp.js'\nimport { turnstileFields } from './fields/turnstile.js'\n\ntype BuildSiteIntegrationsArgs = {\n /** Extra fields injected by the client project */\n additionalFields?: Field[]\n}\n\n/**\n * Builds the SiteIntegrations global.\n *\n * Holds third-party service credentials. Access is enforced at the global\n * level — the whole global requires an authenticated user — so secrets stay\n * out of anonymous API responses while remaining editable in the admin panel\n * and readable via the server-side Local API. (Field-level read:false was\n * avoided because it also hides fields from the admin UI, making them\n * impossible to enter.)\n *\n * Unnamed tabs keep data flat (siteIntegrations.ga4MeasurementId).\n */\nexport function buildSiteIntegrations({\n additionalFields,\n}: BuildSiteIntegrationsArgs = {}): GlobalConfig {\n return {\n slug: 'site-integrations',\n access: {\n // Admin-only — secrets live here. Anonymous and non-admin users get\n // nothing through the API; admins read/edit in the panel and via Local API.\n read: ({ req: { user } }) => isAdmin(user),\n update: ({ req: { user } }) => isAdmin(user),\n },\n admin: {\n group: 'Settings',\n },\n fields: [\n {\n type: 'tabs',\n tabs: [\n { fields: analyticsFields, label: 'Analytics' },\n { fields: turnstileFields, label: 'Turnstile' },\n { fields: smtpFields, label: 'SMTP' },\n ...(additionalFields?.length\n ? [{ fields: additionalFields, label: 'Custom' }]\n : []),\n ],\n },\n ],\n hooks: {\n beforeChange: [\n // Keys edited in the panel → clear the old Turnstile status, so a stale\n // \"not working\" banner doesn't linger until the next form submission.\n ({ context, data, originalDoc }) => {\n if (context?.ipalIntegrationStatus || !data) {return data}\n const changed = (k: string) => k in data && data[k] !== originalDoc?.[k]\n if (changed('turnstileSecretKey') || changed('turnstileSiteKey')) {\n data.turnstileStatus = { checkedAt: null, code: null, message: null, since: null, state: null }\n }\n return data\n },\n ],\n },\n label: 'Site Integrations',\n }\n}\n"],"names":["isAdmin","analyticsFields","smtpFields","turnstileFields","buildSiteIntegrations","additionalFields","slug","access","read","req","user","update","admin","group","fields","type","tabs","label","length","hooks","beforeChange","context","data","originalDoc","ipalIntegrationStatus","changed","k","turnstileStatus","checkedAt","code","message","since","state"],"mappings":"AAEA,SAASA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AACF"} \ No newline at end of file diff --git a/dist/index.d.ts b/dist/index.d.ts index a64ff3d..824ae01 100644 --- a/dist/index.d.ts +++ b/dist/index.d.ts @@ -1,74 +1,76 @@ -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, adminOnlyField, adminOrEditor, adminOrEditorField, adminOrSelf, authenticated, hasMinimumRole, isAdmin, isEditor, requireRole, requireRoleField, ROLE_HIERARCHY, } from './modules/access/index.js'; -export type { GlobalQueryOptions } from './modules/payload/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'; -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, buildArchivePath, buildEntryPath, parsePageParam, } from './modules/content/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 { 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 { archiveFieldName, 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'; -export { lexicalToMarkdown } from './modules/richtext/index.js'; -export type { AutoFillMapping, SitemapEntry, RobotsRules, RobotsOptions } from './modules/seo/index.js'; -export { buildAutoFillMetaHook, injectAutoFillMeta, createMetadataGenerator, createPageMetadata, buildSitemapEntries, buildRobots, AI_ASSISTANT_BOTS, AI_TRAINING_BOTS, } 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'; +export { panelSmtpAdapter } from './modules/email/panelSmtpAdapter.js'; +export type { PanelSmtpAdapterArgs } from './modules/email/panelSmtpAdapter.js'; +export { assertEnv, ipalEnvRules } from './modules/env/index.js'; +export type { AssertEnvOptions, EnvKind, EnvRule, IpalEnvFeatures } from './modules/env/index.js'; +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'; +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'; +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, DEFAULT_MIDDLEWARE_MATCHER, } 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'; -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 { FormsOption, FormsCollectionOverrides, FormsFieldsOverride, } from './modules/forms/types.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 type { FormErrors, FormSubmitAction, Validator } from './modules/forms/useForm.js'; -export { HONEYPOT_FIELD, honeypotInputProps, isHoneypotTripped } from './modules/forms/honeypot.js'; -export { buildFormAnalyticsFields } from './modules/forms/formAnalyticsFields.js'; -export { createHealthRoute } from './modules/health/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 type { BuildLinkFieldOptions, BuildLinksFieldOptions, LinkAppearance, LinkValue, ResolveLinkHrefOptions, } from './modules/links/index.js'; export { createMcpRoute } from './modules/mcp/index.js'; -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 { getNotificationTexts, resolveFormMessage, NOTIFICATION_FALLBACK } from './modules/notifications/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 { 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'; +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 { buildLocalBusinessJsonLd, buildFaqJsonLd, buildServiceJsonLd } from './modules/seo/index.js'; +export { buildBreadcrumbJsonLd, buildSiteNavigationJsonLd, buildWebSiteJsonLd } 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'; diff --git a/dist/index.js b/dist/index.js index 1e2ca64..d8824b8 100644 --- a/dist/index.js +++ b/dist/index.js @@ -1,59 +1,60 @@ -export { ipalKit } from './plugin.js'; -export { buildLocalizedPath, getDefaultLocale, getLocaleCodes, getLocaleDefinition, getLocalizedSlugs, isValidLocale, LOCALE_COOKIE_NAME, matchAcceptLanguage, negotiateLocale, switchLocalePath } from './modules/i18n/index.js'; -export { ALL_SYSTEM_PAGE_ROLES, getSystemPagePath } from './modules/pages/index.js'; export { adminOnly, adminOnlyField, adminOrEditor, adminOrEditorField, adminOrSelf, authenticated, hasMinimumRole, isAdmin, isEditor, requireRole, requireRoleField, ROLE_HIERARCHY } from './modules/access/index.js'; -export { getGlobal, getSiteSettings, getSiteIntegrations, SITE_SETTINGS_SLUG, SITE_INTEGRATIONS_SLUG } from './modules/payload/index.js'; -export { composeTitle, buildHreflangAlternates, buildMetadata, readSiteMetaConfig, slugsAcrossLocales } from './modules/seo/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, parsePageParam } from './modules/content/index.js'; -// Lexical → Markdown (pure, no React) — for AI-readable output. -export { lexicalToMarkdown } from './modules/richtext/index.js'; -export { buildAutoFillMetaHook, injectAutoFillMeta, createMetadataGenerator, createPageMetadata, buildSitemapEntries, buildRobots, AI_ASSISTANT_BOTS, AI_TRAINING_BOTS } from './modules/seo/index.js'; -export { createLocaleMiddleware, DEFAULT_MIDDLEWARE_MATCHER } 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 { A11Y_COOKIE, A11Y_DEFAULT, a11yAttributes, parseA11y, serializeA11y } from './modules/accessibility/index.js'; +export { rowLabel } from './modules/admin-ui/index.js'; +export { getAnalyticsConfig } from './modules/analytics/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 { archiveFieldName, blocksToMarkdown, buildArchivePath, buildEntryPath, createMarkdownRenderer, createSearchRoute, getArchiveEntries, MARKDOWN_PREFIX, markdownHref, markdownResponse, parsePageParam, prefersMarkdown, resolveNotFoundPage, resolveRedirect, resolveRoute, searchContent } from './modules/content/index.js'; +export { graphAdapter } from './modules/email/graphAdapter.js'; +export { mailAdapter } 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 { graphAdapter } from './modules/email/graphAdapter.js'; -export { mailAdapter } from './modules/email/mailAdapter.js'; +// Boot-time environment validation (fail fast on misconfigured deploys). +export { assertEnv, ipalEnvRules } 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'; // 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 { HONEYPOT_FIELD, honeypotInputProps, isHoneypotTripped } from './modules/forms/honeypot.js'; -// Panel-managed form analytics (config-time field builder). -export { buildFormAnalyticsFields } from './modules/forms/formAnalyticsFields.js'; +export { buildValidator, checked, custom, email, isEmail, maxLength, minLength, pattern, required } 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 { buildLocalizedPath, getDefaultLocale, getLocaleCodes, getLocaleDefinition, getLocalizedSlugs, isValidLocale, LOCALE_COOKIE_NAME, matchAcceptLanguage, negotiateLocale, switchLocalePath } from './modules/i18n/index.js'; +export { createLocaleMiddleware, DEFAULT_MIDDLEWARE_MATCHER } 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 { buildLinkField, buildLinksField, resolveLinkHref } 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 { getAnalyticsConfig } from './modules/analytics/index.js'; -export { buildSlugField, toSlug } from './modules/slug/index.js'; -export { createLlmsTxtRoute, createSitemapRouteHandler, createManifestHandler } from './modules/seo/index.js'; -export { getNotificationTexts, resolveFormMessage, NOTIFICATION_FALLBACK } from './modules/notifications/index.js'; +export { buildOptimizeUploadField, buildOptimizeUploadHook, normalizeFilename, normalizeFilenameHook } from './modules/media/index.js'; +export { getNotificationTexts, NOTIFICATION_FALLBACK, resolveFormMessage } from './modules/notifications/index.js'; +export { ALL_SYSTEM_PAGE_ROLES, getSystemPagePath } from './modules/pages/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 { buildHreflangAlternates, buildMetadata, composeTitle, readSiteMetaConfig, slugsAcrossLocales } 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 { buildLinkField, buildLinksField, resolveLinkHref } 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 { 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 { 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 { ipalKit } from './plugin.js'; //# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/dist/index.js.map b/dist/index.js.map index dfed5b7..1f1b9f3 100644 --- a/dist/index.js.map +++ b/dist/index.js.map @@ -1 +1 @@ -{"version":3,"sources":["../src/index.ts"],"sourcesContent":["export { ipalKit } from './plugin.js'\nexport type { IpalOptions } from './types.js'\nexport type { I18nConfig, LocaleDefinition, LocalizedSlugs } from './modules/i18n/index.js'\nexport {\n buildLocalizedPath,\n getDefaultLocale,\n getLocaleCodes,\n getLocaleDefinition,\n getLocalizedSlugs,\n isValidLocale,\n LOCALE_COOKIE_NAME,\n matchAcceptLanguage,\n negotiateLocale,\n switchLocalePath,\n} from './modules/i18n/index.js'\nexport type { PagesOption, SystemPageRole } from './modules/pages/index.js'\nexport { ALL_SYSTEM_PAGE_ROLES, getSystemPagePath } from './modules/pages/index.js'\nexport type { AccessOption, Role } from './modules/access/index.js'\nexport {\n adminOnly,\n adminOnlyField,\n adminOrEditor,\n adminOrEditorField,\n adminOrSelf,\n authenticated,\n hasMinimumRole,\n isAdmin,\n isEditor,\n requireRole,\n requireRoleField,\n ROLE_HIERARCHY,\n} from './modules/access/index.js'\nexport type { GlobalQueryOptions } from './modules/payload/index.js'\nexport {\n getGlobal,\n getSiteSettings,\n getSiteIntegrations,\n SITE_SETTINGS_SLUG,\n SITE_INTEGRATIONS_SLUG,\n} from './modules/payload/index.js'\nexport type { SeoOption, SeoMeta, PageMetadata } from './modules/seo/index.js'\nexport {\n composeTitle,\n buildHreflangAlternates,\n buildMetadata,\n readSiteMetaConfig,\n slugsAcrossLocales,\n} from './modules/seo/index.js'\nexport type { SiteMetaConfig } from './modules/seo/index.js'\nexport type { ContentOption, ContentCollectionOption, ResolvedRoute } from './modules/content/index.js'\nexport { createContentHelpers } from './modules/frontend/index.js'\nexport {\n resolveRoute,\n resolveRedirect,\n resolveNotFoundPage,\n blocksToMarkdown,\n createMarkdownRenderer,\n markdownResponse,\n prefersMarkdown,\n markdownHref,\n MARKDOWN_PREFIX,\n searchContent,\n createSearchRoute,\n archiveFieldName,\n getArchiveEntries,\n buildArchivePath,\n buildEntryPath,\n parsePageParam,\n} from './modules/content/index.js'\nexport type { ArchiveEntries } from './modules/content/index.js'\nexport type { SearchResult } from './modules/content/index.js'\n// Lexical → Markdown (pure, no React) — for AI-readable output.\nexport { lexicalToMarkdown } from './modules/richtext/index.js'\nexport type { AutoFillMapping, SitemapEntry, RobotsRules, RobotsOptions } from './modules/seo/index.js'\nexport {\n buildAutoFillMetaHook,\n injectAutoFillMeta,\n createMetadataGenerator,\n createPageMetadata,\n buildSitemapEntries,\n buildRobots,\n AI_ASSISTANT_BOTS,\n AI_TRAINING_BOTS,\n} from './modules/seo/index.js'\nexport type { LocaleMiddlewareResult } from './modules/i18n/index.js'\nexport {\n createLocaleMiddleware,\n DEFAULT_MIDDLEWARE_MATCHER,\n} from './modules/i18n/index.js'\nexport { createProxy, DEFAULT_PROXY_MATCHER } from './modules/i18n/index.js'\nexport { resolveLocalized } from './modules/i18n/index.js'\nexport {\n CONSENT_CATEGORIES,\n DEFAULT_CONSENT,\n ACCEPT_ALL_CONSENT,\n REJECT_ALL_CONSENT,\n CONSENT_COOKIE,\n CONSENT_VERSION,\n CONSENT_MAX_AGE,\n serializeConsent,\n parseConsent,\n setDefaultConsent,\n updateConsent,\n getConsentTexts,\n} from './modules/consent/index.js'\nexport type { ConsentCategory, ConsentState, ConsentTexts } from './modules/consent/index.js'\n// Imported straight from the file, NOT from ./modules/email/index.js — that\n// barrel re-exports sendEmail, which imports 'server-only' and would crash when\n// Payload loads the config (or runs generate:importmap) as a plain Node script.\nexport { panelSmtpAdapter } from './modules/email/panelSmtpAdapter.js'\nexport { graphAdapter } from './modules/email/graphAdapter.js'\nexport { mailAdapter } from './modules/email/mailAdapter.js'\nexport type { MailAdapterArgs } from './modules/email/mailAdapter.js'\nexport type { GraphAdapterArgs } from './modules/email/graphAdapter.js'\nexport type { PanelSmtpAdapterArgs } from './modules/email/panelSmtpAdapter.js'\nexport { buildFormsPlugin } from './modules/forms/formsPluginConfig.js'\nexport type {\n FormsOption,\n FormsCollectionOverrides,\n FormsFieldsOverride,\n} from './modules/forms/types.js'\n// Validation rules are pure — exported server-side too, for re-validating a\n// submission inside a server action. (useForm/useContactForm are client-only →\n// '@intecion/ipal-kit/client'.)\nexport {\n buildValidator,\n isEmail,\n required,\n email,\n minLength,\n maxLength,\n checked,\n pattern,\n custom,\n} from './modules/forms/validators.js'\nexport type { Rule } from './modules/forms/validators.js'\nexport type { FormErrors, FormSubmitAction, Validator } from './modules/forms/useForm.js'\nexport { HONEYPOT_FIELD, honeypotInputProps, isHoneypotTripped } from './modules/forms/honeypot.js'\n// Panel-managed form analytics (config-time field builder).\nexport { buildFormAnalyticsFields } from './modules/forms/formAnalyticsFields.js'\n// Healthcheck route (Coolify/Docker liveness with a real DB round-trip).\nexport { createHealthRoute } from './modules/health/index.js'\n// Read-only MCP server (Claude/agents connect to the site and query it).\nexport { createMcpRoute } from './modules/mcp/index.js'\n// Boot-time environment validation (fail fast on misconfigured deploys).\nexport { assertEnv, ipalEnvRules } from './modules/env/index.js'\nexport type { EnvRule, EnvKind, AssertEnvOptions, IpalEnvFeatures } from './modules/env/index.js'\nexport type { AnalyticsConfig } from './modules/analytics/index.js'\nexport { getAnalyticsConfig } from './modules/analytics/index.js'\nexport { buildSlugField, toSlug } from './modules/slug/index.js'\nexport { createLlmsTxtRoute, createSitemapRouteHandler, createManifestHandler } from './modules/seo/index.js'\n\nexport { getNotificationTexts, resolveFormMessage, NOTIFICATION_FALLBACK } from './modules/notifications/index.js'\nexport { buildSecurityHeaders } from './modules/security/index.js'\nexport { buildCsp } from './modules/security/index.js'\nexport type { BuildCspArgs } from './modules/security/index.js'\nexport { buildIconsMetadata, buildOrganizationJsonLd, validateFaviconField } from './modules/seo/index.js'\nexport { buildNoindexField } from './modules/seo/index.js'\nexport { rowLabel } from './modules/admin-ui/index.js'\nexport type { RowLabelProps } from './modules/admin-ui/index.js'\nexport { buildLinkField, buildLinksField, resolveLinkHref } from './modules/links/index.js'\nexport type {\n LinkAppearance,\n LinkValue,\n BuildLinkFieldOptions,\n BuildLinksFieldOptions,\n ResolveLinkHrefOptions,\n} from './modules/links/index.js'\nexport { buildSpeakableJsonLd } from './modules/seo/index.js'\nexport { buildSummaryField } from './modules/seo/index.js'\nexport { buildWebSiteJsonLd, buildBreadcrumbJsonLd, buildSiteNavigationJsonLd } from './modules/seo/index.js'\n// Local SEO structured data — LocalBusiness (map pack), Service (offering), FAQPage.\nexport { buildLocalBusinessJsonLd, buildFaqJsonLd, buildServiceJsonLd } from './modules/seo/index.js'\nexport { buildArticleJsonLd } from './modules/seo/index.js'\nexport { buildLlmsTxt } from './modules/seo/index.js'\nexport { buildSitemapXml, buildSitemapCss, SITEMAP_STYLE_PARAM, DEFAULT_SITEMAP_CREDIT } from './modules/seo/index.js'\nexport type { SitemapRouteOptions, SitemapStyleOptions } from './modules/seo/index.js'\nexport { buildR2Storage } from './modules/storage/index.js'\nexport { normalizeFilename, normalizeFilenameHook, buildOptimizeUploadHook, buildOptimizeUploadField } from './modules/media/index.js'\nexport type { OptimizeUploadOptions } from './modules/media/index.js'\nexport { buildRevalidateHook, setPublishedAtHook, buildPreventDeleteSystemPage, buildValidateUniqueRole, trackSlugHistoryHook, buildCrossLocaleFieldSync } from './modules/hooks/index.js'\nexport { A11Y_COOKIE, A11Y_DEFAULT, a11yAttributes, parseA11y, serializeA11y } from './modules/accessibility/index.js'\nexport type { A11yState } from './modules/accessibility/index.js'\nexport type { SecurityHeader, BuildSecurityHeadersArgs } from './modules/security/index.js'\nexport type { NotificationTexts, FormNotificationTexts } from './modules/notifications/index.js'\n"],"names":["ipalKit","buildLocalizedPath","getDefaultLocale","getLocaleCodes","getLocaleDefinition","getLocalizedSlugs","isValidLocale","LOCALE_COOKIE_NAME","matchAcceptLanguage","negotiateLocale","switchLocalePath","ALL_SYSTEM_PAGE_ROLES","getSystemPagePath","adminOnly","adminOnlyField","adminOrEditor","adminOrEditorField","adminOrSelf","authenticated","hasMinimumRole","isAdmin","isEditor","requireRole","requireRoleField","ROLE_HIERARCHY","getGlobal","getSiteSettings","getSiteIntegrations","SITE_SETTINGS_SLUG","SITE_INTEGRATIONS_SLUG","composeTitle","buildHreflangAlternates","buildMetadata","readSiteMetaConfig","slugsAcrossLocales","createContentHelpers","resolveRoute","resolveRedirect","resolveNotFoundPage","blocksToMarkdown","createMarkdownRenderer","markdownResponse","prefersMarkdown","markdownHref","MARKDOWN_PREFIX","searchContent","createSearchRoute","archiveFieldName","getArchiveEntries","buildArchivePath","buildEntryPath","parsePageParam","lexicalToMarkdown","buildAutoFillMetaHook","injectAutoFillMeta","createMetadataGenerator","createPageMetadata","buildSitemapEntries","buildRobots","AI_ASSISTANT_BOTS","AI_TRAINING_BOTS","createLocaleMiddleware","DEFAULT_MIDDLEWARE_MATCHER","createProxy","DEFAULT_PROXY_MATCHER","resolveLocalized","CONSENT_CATEGORIES","DEFAULT_CONSENT","ACCEPT_ALL_CONSENT","REJECT_ALL_CONSENT","CONSENT_COOKIE","CONSENT_VERSION","CONSENT_MAX_AGE","serializeConsent","parseConsent","setDefaultConsent","updateConsent","getConsentTexts","panelSmtpAdapter","graphAdapter","mailAdapter","buildFormsPlugin","buildValidator","isEmail","required","email","minLength","maxLength","checked","pattern","custom","HONEYPOT_FIELD","honeypotInputProps","isHoneypotTripped","buildFormAnalyticsFields","createHealthRoute","createMcpRoute","assertEnv","ipalEnvRules","getAnalyticsConfig","buildSlugField","toSlug","createLlmsTxtRoute","createSitemapRouteHandler","createManifestHandler","getNotificationTexts","resolveFormMessage","NOTIFICATION_FALLBACK","buildSecurityHeaders","buildCsp","buildIconsMetadata","buildOrganizationJsonLd","validateFaviconField","buildNoindexField","rowLabel","buildLinkField","buildLinksField","resolveLinkHref","buildSpeakableJsonLd","buildSummaryField","buildWebSiteJsonLd","buildBreadcrumbJsonLd","buildSiteNavigationJsonLd","buildLocalBusinessJsonLd","buildFaqJsonLd","buildServiceJsonLd","buildArticleJsonLd","buildLlmsTxt","buildSitemapXml","buildSitemapCss","SITEMAP_STYLE_PARAM","DEFAULT_SITEMAP_CREDIT","buildR2Storage","normalizeFilename","normalizeFilenameHook","buildOptimizeUploadHook","buildOptimizeUploadField","buildRevalidateHook","setPublishedAtHook","buildPreventDeleteSystemPage","buildValidateUniqueRole","trackSlugHistoryHook","buildCrossLocaleFieldSync","A11Y_COOKIE","A11Y_DEFAULT","a11yAttributes","parseA11y","serializeA11y"],"mappings":"AAAA,SAASA,OAAO,QAAQ,cAAa;AAGrC,SACEC,kBAAkB,EAClBC,gBAAgB,EAChBC,cAAc,EACdC,mBAAmB,EACnBC,iBAAiB,EACjBC,aAAa,EACbC,kBAAkB,EAClBC,mBAAmB,EACnBC,eAAe,EACfC,gBAAgB,QACX,0BAAyB;AAEhC,SAASC,qBAAqB,EAAEC,iBAAiB,QAAQ,2BAA0B;AAEnF,SACEC,SAAS,EACTC,cAAc,EACdC,aAAa,EACbC,kBAAkB,EAClBC,WAAW,EACXC,aAAa,EACbC,cAAc,EACdC,OAAO,EACPC,QAAQ,EACRC,WAAW,EACXC,gBAAgB,EAChBC,cAAc,QACT,4BAA2B;AAElC,SACEC,SAAS,EACTC,eAAe,EACfC,mBAAmB,EACnBC,kBAAkB,EAClBC,sBAAsB,QACjB,6BAA4B;AAEnC,SACEC,YAAY,EACZC,uBAAuB,EACvBC,aAAa,EACbC,kBAAkB,EAClBC,kBAAkB,QACb,yBAAwB;AAG/B,SAASC,oBAAoB,QAAQ,8BAA6B;AAClE,SACEC,YAAY,EACZC,eAAe,EACfC,mBAAmB,EACnBC,gBAAgB,EAChBC,sBAAsB,EACtBC,gBAAgB,EAChBC,eAAe,EACfC,YAAY,EACZC,eAAe,EACfC,aAAa,EACbC,iBAAiB,EACjBC,gBAAgB,EAChBC,iBAAiB,EACjBC,g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index.js'\nexport {\n adminOnly,\n adminOnlyField,\n adminOrEditor,\n adminOrEditorField,\n adminOrSelf,\n authenticated,\n hasMinimumRole,\n isAdmin,\n isEditor,\n requireRole,\n requireRoleField,\n ROLE_HIERARCHY,\n} from './modules/access/index.js'\nexport { A11Y_COOKIE, A11Y_DEFAULT, a11yAttributes, parseA11y, serializeA11y } from './modules/accessibility/index.js'\nexport type { A11yState } from './modules/accessibility/index.js'\nexport { rowLabel } from './modules/admin-ui/index.js'\nexport type { RowLabelProps } from './modules/admin-ui/index.js'\nexport type { AnalyticsConfig } from './modules/analytics/index.js'\nexport { getAnalyticsConfig } from './modules/analytics/index.js'\nexport {\n ACCEPT_ALL_CONSENT,\n CONSENT_CATEGORIES,\n CONSENT_COOKIE,\n CONSENT_MAX_AGE,\n CONSENT_VERSION,\n DEFAULT_CONSENT,\n getConsentTexts,\n parseConsent,\n REJECT_ALL_CONSENT,\n serializeConsent,\n setDefaultConsent,\n updateConsent,\n} from './modules/consent/index.js'\nexport type { ConsentCategory, ConsentState, ConsentTexts } from './modules/consent/index.js'\nexport type { ContentCollectionOption, ContentOption, ResolvedRoute } from './modules/content/index.js'\nexport {\n archiveFieldName,\n blocksToMarkdown,\n buildArchivePath,\n buildEntryPath,\n createMarkdownRenderer,\n createSearchRoute,\n getArchiveEntries,\n MARKDOWN_PREFIX,\n markdownHref,\n markdownResponse,\n parsePageParam,\n prefersMarkdown,\n resolveNotFoundPage,\n resolveRedirect,\n resolveRoute,\n searchContent,\n} from './modules/content/index.js'\nexport type { ArchiveEntries } from './modules/content/index.js'\nexport type { SearchResult } from './modules/content/index.js'\nexport { graphAdapter } from './modules/email/graphAdapter.js'\nexport type { GraphAdapterArgs } from './modules/email/graphAdapter.js'\nexport { mailAdapter } from './modules/email/mailAdapter.js'\nexport type { MailAdapterArgs } from './modules/email/mailAdapter.js'\n// Imported straight from the file, NOT from ./modules/email/index.js — that\n// barrel re-exports sendEmail, which imports 'server-only' and would crash when\n// Payload loads the config (or runs generate:importmap) as a plain Node script.\nexport { panelSmtpAdapter } from './modules/email/panelSmtpAdapter.js'\nexport type { PanelSmtpAdapterArgs } from './modules/email/panelSmtpAdapter.js'\n// Boot-time environment validation (fail fast on misconfigured deploys).\nexport { assertEnv, ipalEnvRules } from './modules/env/index.js'\nexport type { AssertEnvOptions, EnvKind, EnvRule, IpalEnvFeatures } from './modules/env/index.js'\n// Panel-managed form analytics (config-time field builder).\nexport { buildFormAnalyticsFields } from './modules/forms/formAnalyticsFields.js'\nexport { buildFormsPlugin } from './modules/forms/formsPluginConfig.js'\nexport { HONEYPOT_FIELD, honeypotInputProps, isHoneypotTripped } from './modules/forms/honeypot.js'\nexport type {\n FormsCollectionOverrides,\n FormsFieldsOverride,\n FormsOption,\n} from './modules/forms/types.js'\nexport type { FormErrors, FormSubmitAction, Validator } from './modules/forms/useForm.js'\n// Validation rules are pure — exported server-side too, for re-validating a\n// submission inside a server action. (useForm/useContactForm are client-only →\n// '@intecion/ipal-kit/client'.)\nexport {\n buildValidator,\n checked,\n custom,\n email,\n isEmail,\n maxLength,\n minLength,\n pattern,\n required,\n} from './modules/forms/validators.js'\nexport type { Rule } from './modules/forms/validators.js'\nexport { createContentHelpers } from './modules/frontend/index.js'\n// Healthcheck route (Coolify/Docker liveness with a real DB round-trip).\nexport { createHealthRoute } from './modules/health/index.js'\nexport { buildCrossLocaleFieldSync, buildPreventDeleteSystemPage, buildRevalidateHook, buildValidateUniqueRole, setPublishedAtHook, trackSlugHistoryHook } from './modules/hooks/index.js'\nexport type { I18nConfig, LocaleDefinition, LocalizedSlugs } from './modules/i18n/index.js'\nexport {\n buildLocalizedPath,\n getDefaultLocale,\n getLocaleCodes,\n getLocaleDefinition,\n getLocalizedSlugs,\n isValidLocale,\n LOCALE_COOKIE_NAME,\n matchAcceptLanguage,\n negotiateLocale,\n switchLocalePath,\n} from './modules/i18n/index.js'\nexport type { LocaleMiddlewareResult } from './modules/i18n/index.js'\nexport {\n createLocaleMiddleware,\n DEFAULT_MIDDLEWARE_MATCHER,\n} from './modules/i18n/index.js'\nexport { createProxy, DEFAULT_PROXY_MATCHER } from './modules/i18n/index.js'\nexport { resolveLocalized } from './modules/i18n/index.js'\nexport { buildIntegrationStatusBanner, buildIntegrationStatusField, recordIntegrationStatus } from './modules/integrations/index.js'\nexport type { IntegrationState, IntegrationStatus } from './modules/integrations/index.js'\nexport { buildLinkField, buildLinksField, resolveLinkHref } from './modules/links/index.js'\nexport type {\n BuildLinkFieldOptions,\n BuildLinksFieldOptions,\n LinkAppearance,\n LinkValue,\n ResolveLinkHrefOptions,\n} from './modules/links/index.js'\n// Read-only MCP server (Claude/agents connect to the site and query it).\nexport { createMcpRoute } from './modules/mcp/index.js'\nexport { buildOptimizeUploadField, buildOptimizeUploadHook, normalizeFilename, normalizeFilenameHook } from './modules/media/index.js'\nexport type { OptimizeUploadOptions } from './modules/media/index.js'\nexport { getNotificationTexts, NOTIFICATION_FALLBACK, resolveFormMessage } from './modules/notifications/index.js'\nexport type { FormNotificationTexts, NotificationTexts } from './modules/notifications/index.js'\nexport type { PagesOption, SystemPageRole } from './modules/pages/index.js'\n\nexport { ALL_SYSTEM_PAGE_ROLES, getSystemPagePath } from './modules/pages/index.js'\nexport type { GlobalQueryOptions } from './modules/payload/index.js'\nexport {\n getGlobal,\n getSiteIntegrations,\n getSiteSettings,\n SITE_INTEGRATIONS_SLUG,\n SITE_SETTINGS_SLUG,\n} from './modules/payload/index.js'\n// Lexical → Markdown (pure, no React) — for AI-readable output.\nexport { lexicalToMarkdown } from './modules/richtext/index.js'\nexport { buildSecurityHeaders } from './modules/security/index.js'\nexport { buildCsp } from './modules/security/index.js'\nexport type { BuildCspArgs } from './modules/security/index.js'\nexport type { BuildSecurityHeadersArgs, SecurityHeader } from './modules/security/index.js'\nexport type { PageMetadata, SeoMeta, SeoOption } from './modules/seo/index.js'\nexport {\n buildHreflangAlternates,\n buildMetadata,\n composeTitle,\n readSiteMetaConfig,\n slugsAcrossLocales,\n} from './modules/seo/index.js'\nexport type { SiteMetaConfig } from './modules/seo/index.js'\nexport type { AutoFillMapping, RobotsOptions, RobotsRules, SitemapEntry } from './modules/seo/index.js'\nexport {\n AI_ASSISTANT_BOTS,\n AI_TRAINING_BOTS,\n buildAutoFillMetaHook,\n buildRobots,\n buildSitemapEntries,\n createMetadataGenerator,\n createPageMetadata,\n injectAutoFillMeta,\n} from './modules/seo/index.js'\nexport { createLlmsTxtRoute, createManifestHandler, createSitemapRouteHandler } from './modules/seo/index.js'\nexport { buildIconsMetadata, buildOrganizationJsonLd, validateFaviconField } from './modules/seo/index.js'\nexport { buildNoindexField } from './modules/seo/index.js'\nexport { buildSpeakableJsonLd } from './modules/seo/index.js'\nexport { buildSummaryField } from './modules/seo/index.js'\nexport { buildBreadcrumbJsonLd, buildSiteNavigationJsonLd, buildWebSiteJsonLd } from './modules/seo/index.js'\n// Local SEO structured data — LocalBusiness (map pack), Service (offering), FAQPage.\nexport { buildFaqJsonLd, buildLocalBusinessJsonLd, buildServiceJsonLd } from './modules/seo/index.js'\nexport { buildArticleJsonLd } from './modules/seo/index.js'\nexport { buildLlmsTxt } from './modules/seo/index.js'\nexport { buildSitemapCss, buildSitemapXml, DEFAULT_SITEMAP_CREDIT, SITEMAP_STYLE_PARAM } from './modules/seo/index.js'\nexport type { SitemapRouteOptions, SitemapStyleOptions } from './modules/seo/index.js'\nexport { buildSlugField, toSlug } from './modules/slug/index.js'\nexport { buildR2Storage } from './modules/storage/index.js'\nexport { ipalKit } from './plugin.js'\nexport type { IpalOptions } from './types.js'\n"],"names":["adminOnly","adminOnlyField","adminOrEditor","adminOrEditorField","adminOrSelf","authenticated","hasMinimumRole","isAdmin","isEditor","requireRole","requireRoleField","ROLE_HIERARCHY","A11Y_COOKIE","A11Y_DEFAULT","a11yAttributes","parseA11y","serializeA11y","rowLabel","getAnalyticsConfig","ACCEPT_ALL_CONSENT","CONSENT_CATEGORIES","CONSENT_COOKIE","CONSENT_MAX_AGE","CONSENT_VERSION","DEFAULT_CONSENT","getConsentTexts","parseConsent","REJECT_ALL_CONSENT","serializeConsent","setDefaultConsent","updateConsent","archiveFieldName","blocksToMarkdown","buildArchivePath","buildEntryPath","createMarkdownRenderer","createSearchRoute","getArchiveEntries","MARKDOWN_PREFIX","markdownHref","markdownResponse","parsePageParam","prefersMarkdown","resolveNotFoundPage","resolveRedirect","resolveRoute","searchContent","graphAdapter","mailAdapter","panelSmtpAdapter","assertEnv","ipalEnvRules","buildFormAnalyticsFields","buildFormsPlugin","HONEYPOT_FIELD","honeypotInputProps","isHoneypotTripped","buildValidator","checked","custom","email","isEmail","maxLength","minLength","pattern","required","createContentHelpers","createHealthRoute","buildCrossLocaleFieldSync","buildPreventDeleteSystemPage","buildRevalidateHook","buildValidateUniqueRole","setPublishedAtHook","trackSlugHistoryHook","buildLocalizedPath","getDefaultLocale","getLocaleCodes","getLocaleDefinition","getLocalizedSlugs","isValidLocale","LOCALE_COOKIE_NAME","matchAcceptLanguage","negotiateLocale","switchLocalePath","createLocaleMiddleware","DEFAULT_MIDDLEWARE_MATCHER","createProxy","DEFAULT_PROXY_MATCHER","resolveLocalized","buildIntegrationStatusBanner","buildIntegrationStatusField","recordIntegrationStatus","buildLinkField","buildLinksField","resolveLinkHref","createMcpRoute","buildOptimizeUploadField","buildOptimizeUploadHook","normalizeFilename","normalizeFilenameHook","getNotificationTexts","NOTIFICATION_FALLBACK","resolveFormMessage","ALL_SYSTEM_PAGE_ROLES","getSystemPagePath","getGlobal","getSiteIntegrations","getSiteSettings","SITE_INTEGRATIONS_SLUG","SITE_SETTINGS_SLUG","lexicalToMarkdown","buildSecurityHeaders","buildCsp","buildHreflangAlternates","buildMetadata","composeTitle","readSiteMetaConfig","slugsAcrossLocales","AI_ASSISTANT_BOTS","AI_TRAINING_BOTS","buildAutoFillMetaHook","buildRobots","buildSitemapEntries","createMetadataGenerator","createPageMetadata","injectAutoFillMeta","createLlmsTxtRoute","createManifestHandler","createSitemapRouteHandler","buildIconsMetadata","buildOrganizationJsonLd","validateFaviconField","buildNoindexField","buildSpeakableJsonLd","buildSummaryField","buildBreadcrumbJsonLd","buildSiteNavigationJsonLd","buildWebSiteJsonLd","buildFaqJsonLd","buildLocalBusinessJsonLd","buildServiceJsonLd","buildArticleJsonLd","buildLlmsTxt","buildSitemapCss","buildSitemapXml","DEFAULT_SITEMAP_CREDIT","SITEMAP_STYLE_PARAM","buildSlugField","toSlug","buildR2Storage","ipalKit"],"mappings":"AACA,SACEA,SAAS,EACTC,cAAc,EACdC,aAAa,EACbC,kBAAkB,EAClBC,WAAW,EACXC,aAAa,EACbC,cAAc,EACdC,OAAO,EACPC,QAAQ,EACRC,WAAW,EACXC,gBAAgB,EAChBC,cAAc,QACT,4BAA2B;AAClC,SAASC,WAAW,EAAEC,YAAY,EAAEC,cAAc,EAAEC,SAAS,EAAEC,aAAa,QAAQ,mCAAkC;AAEtH,SAASC,QAAQ,QAAQ,8BAA6B;AAGtD,SAASC,kBAAkB,QAAQ,+BAA8B;AACjE,SACEC,kBAAkB,EAClBC,kBAAkB,EAClBC,cAAc,EACdC,eAAe,EACfC,eAAe,EACfC,eAAe,EACfC,eAAe,EACfC,YAAY,EACZC,kBAAkB,EAClBC,gBAAgB,EAChBC,iBAAiB,EACjBC,aAAa,QACR,6BAA4B;AAGnC,SACEC,gBAAgB,EAChBC,gBAAgB,EAChBC,gBAAgB,EAChBC,cAAc,EACdC,sBAAsB,EACtBC,iBAAiB,EACjBC,iBAAiB,EACjBC,eAAe,EACfC,YAAY,EACZC,gBAAgB,EAChBC,cAAc,EACdC,eAAe,EACfC,mBAAmB,EACnBC,eAAe,EACfC,YAAY,EACZC,aAAa,QACR,6BAA4B;AAGnC,SAASC,YAAY,QAAQ,kCAAiC;AAE9D,SAASC,WAAW,QAAQ,iCAAgC;AAE5D,4EAA4E;AAC5E,gFAAgF;AAChF,gFAAgF;AAChF,SAASC,gBAAgB,QAAQ,sCAAqC;AAEtE,yEAAyE;AACzE,SAASC,SAAS,EAAEC,YAAY,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A0B;AAEnF,SACEC,SAAS,EACTC,mBAAmB,EACnBC,eAAe,EACfC,sBAAsB,EACtBC,kBAAkB,QACb,6BAA4B;AACnC,gEAAgE;AAChE,SAASC,iBAAiB,QAAQ,8BAA6B;AAC/D,SAASC,oBAAoB,QAAQ,8BAA6B;AAClE,SAASC,QAAQ,QAAQ,8BAA6B;AAItD,SACEC,uBAAuB,EACvBC,aAAa,EACbC,YAAY,EACZC,kBAAkB,EAClBC,kBAAkB,QACb,yBAAwB;AAG/B,SACEC,iBAAiB,EACjBC,gBAAgB,EAChBC,qBAAqB,EACrBC,WAAW,EACXC,mBAAmB,EACnBC,uBAAuB,EACvBC,kBAAkB,EAClBC,kBAAkB,QACb,yBAAwB;AAC/B,SAASC,kBAAkB,EAAEC,qBAAqB,EAAEC,yBAAyB,QAAQ,yBAAwB;AAC7G,SAASC,kBAAkB,EAAEC,uBAAuB,EAAEC,oBAAoB,QAAQ,yBAAwB;AAC1G,SAASC,iBAAiB,QAAQ,yBAAwB;AAC1D,SAASC,oBAAoB,QAAQ,yBAAwB;AAC7D,SAASC,iBAAiB,QAAQ,yBAAwB;AAC1D,SAASC,qBAAqB,EAAEC,yBAAyB,EAAEC,kBAAkB,QAAQ,yBAAwB;AAC7G,qFAAqF;AACrF,SAASC,cAAc,EAAEC,wBAAwB,EAAEC,kBAAkB,QAAQ,yBAAwB;AACrG,SAASC,kBAAkB,QAAQ,yBAAwB;AAC3D,SAASC,YAAY,QAAQ,yBAAwB;AACrD,SAASC,eAAe,EAAEC,eAAe,EAAEC,sBAAsB,EAAEC,mBAAmB,QAAQ,yBAAwB;AAEtH,SAASC,cAAc,EAAEC,MAAM,QAAQ,0BAAyB;AAChE,SAASC,cAAc,QAAQ,6BAA4B;AAC3D,SAASC,OAAO,QAAQ,cAAa"} \ No newline at end of file diff --git a/dist/modules/forms/submitForm.d.ts b/dist/modules/forms/submitForm.d.ts index 8a7c99b..c50135c 100644 --- a/dist/modules/forms/submitForm.d.ts +++ b/dist/modules/forms/submitForm.d.ts @@ -18,6 +18,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; }; @@ -80,4 +86,4 @@ export type SubmitFormResult = { * * server-only: touches the Turnstile secret. */ -export declare function submitForm({ consentFieldName, data, formId, ip, maxPerMinute, payload, turnstileToken, }: SubmitFormArgs): Promise; +export declare function submitForm({ consentFieldName, data, formId, ip, maxPerMinute, payload, turnstileOnConfigError, turnstileToken, }: SubmitFormArgs): Promise; diff --git a/dist/modules/forms/submitForm.js b/dist/modules/forms/submitForm.js index d39f2ed..3157a35 100644 --- a/dist/modules/forms/submitForm.js +++ b/dist/modules/forms/submitForm.js @@ -14,7 +14,7 @@ import { validateSubmission } from './validateSubmission.js'; * which goes out over the configured email adapter (mailAdapter). Storing the submission is enough. * * server-only: touches the Turnstile secret. - */ export async function submitForm({ consentFieldName, data, formId, ip, maxPerMinute = 5, payload, turnstileToken }) { + */ export async function submitForm({ consentFieldName, data, formId, ip, maxPerMinute = 5, payload, turnstileOnConfigError = 'allow', turnstileToken }) { // 1. Rate limit — cheapest gate, drops a flood before any real work. if (maxPerMinute > 0 && ip) { if (!checkRateLimit({ @@ -31,6 +31,7 @@ import { validateSubmission } from './validateSubmission.js'; if (turnstileToken !== undefined) { const ok = await verifyTurnstile({ ip, + onConfigError: turnstileOnConfigError, payload, token: turnstileToken }); diff --git a/dist/modules/forms/submitForm.js.map b/dist/modules/forms/submitForm.js.map index 198c712..637acad 100644 --- a/dist/modules/forms/submitForm.js.map +++ b/dist/modules/forms/submitForm.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../../src/modules/forms/submitForm.ts"],"sourcesContent":["import 'server-only'\n\nimport type { BasePayload } from 'payload'\n\nimport { verifyTurnstile } from '../turnstile/index.js'\nimport { checkRateLimit } from './rateLimit.js'\nimport { validateSubmission } from './validateSubmission.js'\n\nexport type SubmitFormArgs = {\n /**\n * Name of the GDPR consent checkbox. A field with this name must be checked\n * for the submission to succeed (enforced server-side). Defaults to 'consent'.\n */\n consentFieldName?: string\n /** Submitted field data — shape matches the form's fields. */\n data: Record\n /** Form-builder form ID this submission belongs to. */\n formId: string\n /** Client IP — used for Turnstile and rate limiting. */\n ip?: string\n /**\n * Rate limit: max submissions per IP per minute. Defaults to 5.\n * Set to 0 to disable (e.g. when a real limiter sits in front).\n */\n maxPerMinute?: number\n payload: BasePayload\n /** Turnstile token; when present it is verified, when absent it is skipped. */\n turnstileToken?: string\n}\n\n/**\n * Why a submission failed — a code, never a user-facing string.\n *\n * The plugin knows what went wrong; it deliberately doesn't decide how to say\n * it. The frontend maps these to its own copy, in its own language, and renders\n * whatever component fits — a field error, a toast, a full message. The plugin\n * has no business choosing the wording or the locale.\n *\n * - `rate_limited` — too many submissions from this IP\n * - `turnstile` — bot check failed\n * - `validation` — a field is missing/too long, or unknown keys were sent;\n * `field` and `kind` narrow it down when a specific field is\n * at fault (absent for whole-payload problems like unknown keys)\n * - `not_found` — no form with this id\n * - `consent` — a required GDPR consent checkbox was left unchecked\n * - `error` — persistence failed unexpectedly\n */\nexport type SubmitFailure =\n | {\n /** The offending field's name, when one field is at fault. */\n field?: string\n /** What was wrong with it. */\n kind?: 'required' | 'too_long' | 'unknown_fields'\n reason: 'validation'\n success: false\n }\n | {\n field?: string\n /** A GDPR consent field existed on the form but wasn't checked. */\n reason: 'consent'\n success: false\n }\n | { reason: 'error'; success: false }\n | { reason: 'not_found'; success: false }\n | { reason: 'rate_limited'; success: false }\n | { reason: 'turnstile'; success: false }\n\nexport type SubmitFormResult = { submissionId: number | string; success: true } | SubmitFailure\n\n/**\n * Handles a form submission end to end: rate limit, verify Turnstile, validate\n * against the form's own schema, then store.\n *\n * The order is cost-ascending on purpose — the cheapest checks reject first, so\n * a flood never reaches Turnstile's network call or the database.\n *\n * Emails aren't sent here. The form-builder sends whatever an editor configured\n * under the form's \"Emails\" tab (form-submissions hook → payload.sendEmail),\n * which goes out over the configured email adapter (mailAdapter). Storing the submission is enough.\n *\n * server-only: touches the Turnstile secret.\n */\nexport async function submitForm({\n consentFieldName,\n data,\n formId,\n ip,\n maxPerMinute = 5,\n payload,\n turnstileToken,\n}: SubmitFormArgs): Promise {\n // 1. Rate limit — cheapest gate, drops a flood before any real work.\n if (maxPerMinute > 0 && ip) {\n if (!checkRateLimit({ key: ip, max: maxPerMinute })) {\n return { reason: 'rate_limited', success: false }\n }\n }\n\n // 2. Turnstile — verify when a token is supplied; reject on failure.\n if (turnstileToken !== undefined) {\n const ok = await verifyTurnstile({ ip, payload, token: turnstileToken })\n if (!ok) {\n return { reason: 'turnstile', success: false }\n }\n }\n\n // 3. Validate against the form's schema. A public endpoint can't trust the\n // shape of `data` — drop unknown keys, enforce required, cap length.\n const validation = await validateSubmission(payload, formId, data, consentFieldName)\n if (!validation.ok) {\n if (validation.reason === 'not_found') {\n return { reason: 'not_found', success: false }\n }\n if (validation.reason === 'consent') {\n return { field: validation.field, reason: 'consent', success: false }\n }\n return {\n reason: 'validation',\n success: false,\n ...(validation.field ? { field: validation.field } : {}),\n ...(validation.kind ? { kind: validation.kind } : {}),\n }\n }\n\n // 4. Persist (form-builder shape: submissionData array). Triggers the email\n // hook. Only validated, known fields are stored.\n try {\n const submission = await payload.create({\n collection: 'form-submissions',\n data: {\n form: formId,\n submissionData: Object.entries(validation.cleaned).map(([field, value]) => ({\n field,\n value: value == null ? '' : String(value),\n })),\n } as never,\n })\n return { submissionId: submission.id, success: true }\n } catch (err) {\n payload.logger.error(`[ipal] Form submission failed: ${(err as Error).message}`)\n return { reason: 'error', success: false }\n }\n}\n"],"names":["verifyTurnstile","checkRateLimit","validateSubmission","submitForm","consentFieldName","data","formId","ip","maxPerMinute","payload","turnstileToken","key","max","reason","success","undefined","ok","token","validation","field","kind","submission","create","collection","form","submissionData","Object","entries","cleaned","map","value","String","submissionId","id","err","logger","error","message"],"mappings":"AAAA,OAAO,cAAa;AAIpB,SAASA,eAAe,QAAQ,wBAAuB;AACvD,SAASC,cAAc,QAAQ,iBAAgB;AAC/C,SAASC,kBAAkB,QAAQ,0BAAyB;AA+D5D;;;;;;;;;;;;CAYC,GACD,OAAO,eAAeC,WAAW,EAC/BC,gBAAgB,EAChBC,IAAI,EACJC,MAAM,EACNC,EAAE,EACFC,eAAe,CAAC,EAChBC,OAAO,EACPC,cAAc,EACC;IACf,qEAAqE;IACrE,IAAIF,eAAe,KAAKD,IAAI;QAC1B,IAAI,CAACN,eAAe;YAAEU,KAAKJ;YAAIK,KAAKJ;QAAa,IAAI;YACnD,OAAO;gBAAEK,QAAQ;gBAAgBC,SAAS;YAAM;QAClD;IACF;IAEA,qEAAqE;IACrE,IAAIJ,mBAAmBK,WAAW;QAChC,MAAMC,KAAK,MAAMhB,gBAAgB;YAAEO;YAAIE;YAASQ,OAAOP;QAAe;QACtE,IAAI,CAACM,IAAI;YACP,OAAO;gBAAEH,QAAQ;gBAAaC,SAAS;YAAM;QAC/C;IACF;IAEA,2EAA2E;IAC3E,wEAAwE;IACxE,MAAMI,aAAa,MAAMhB,mBAAmBO,SAASH,QAAQD,MAAMD;IACnE,IAAI,CAACc,WAAWF,EAAE,EAAE;QAClB,IAAIE,WAAWL,MAAM,KAAK,aAAa;YACrC,OAAO;gBAAEA,QAAQ;gBAAaC,SAAS;YAAM;QAC/C;QACA,IAAII,WAAWL,MAAM,KAAK,WAAW;YACnC,OAAO;gBAAEM,OAAOD,WAAWC,KAAK;gBAAEN,QAAQ;gBAAWC,SAAS;YAAM;QACtE;QACA,OAAO;YACLD,QAAQ;YACRC,SAAS;YACT,GAAII,WAAWC,KAAK,GAAG;gBAAEA,OAAOD,WAAWC,KAAK;YAAC,IAAI,CAAC,CAAC;YACvD,GAAID,WAAWE,IAAI,GAAG;gBAAEA,MAAMF,WAAWE,IAAI;YAAC,IAAI,CAAC,CAAC;QACtD;IACF;IAEA,4EAA4E;IAC5E,oDAAoD;IACpD,IAAI;QACF,MAAMC,aAAa,MAAMZ,QAAQa,MAAM,CAAC;YACtCC,YAAY;YACZlB,MAAM;gBACJmB,MAAMlB;gBACNmB,gBAAgBC,OAAOC,OAAO,CAACT,WAAWU,OAAO,EAAEC,GAAG,CAAC,CAAC,CAACV,OAAOW,MAAM,GAAM,CAAA;wBAC1EX;wBACAW,OAAOA,SAAS,OAAO,KAAKC,OAAOD;oBACrC,CAAA;YACF;QACF;QACA,OAAO;YAAEE,cAAcX,WAAWY,EAAE;YAAEnB,SAAS;QAAK;IACtD,EAAE,OAAOoB,KAAK;QACZzB,QAAQ0B,MAAM,CAACC,KAAK,CAAC,CAAC,+BAA+B,EAAE,AAACF,IAAcG,OAAO,EAAE;QAC/E,OAAO;YAAExB,QAAQ;YAASC,SAAS;QAAM;IAC3C;AACF"} \ No newline at end of file +{"version":3,"sources":["../../../src/modules/forms/submitForm.ts"],"sourcesContent":["import 'server-only'\n\nimport type { BasePayload } from 'payload'\n\nimport { verifyTurnstile } from '../turnstile/index.js'\nimport { checkRateLimit } from './rateLimit.js'\nimport { validateSubmission } from './validateSubmission.js'\n\nexport type SubmitFormArgs = {\n /**\n * Name of the GDPR consent checkbox. A field with this name must be checked\n * for the submission to succeed (enforced server-side). Defaults to 'consent'.\n */\n consentFieldName?: string\n /** Submitted field data — shape matches the form's fields. */\n data: Record\n /** Form-builder form ID this submission belongs to. */\n formId: string\n /** Client IP — used for Turnstile and rate limiting. */\n ip?: string\n /**\n * Rate limit: max submissions per IP per minute. Defaults to 5.\n * Set to 0 to disable (e.g. when a real limiter sits in front).\n */\n maxPerMinute?: number\n payload: BasePayload\n /**\n * Turnstile can't be verified because of OUR side (missing/wrong secret,\n * Cloudflare unreachable): 'allow' (default) accepts the submission and shows\n * the problem in the panel; 'reject' refuses it.\n */\n turnstileOnConfigError?: 'allow' | 'reject'\n /** Turnstile token; when present it is verified, when absent it is skipped. */\n turnstileToken?: string\n}\n\n/**\n * Why a submission failed — a code, never a user-facing string.\n *\n * The plugin knows what went wrong; it deliberately doesn't decide how to say\n * it. The frontend maps these to its own copy, in its own language, and renders\n * whatever component fits — a field error, a toast, a full message. The plugin\n * has no business choosing the wording or the locale.\n *\n * - `rate_limited` — too many submissions from this IP\n * - `turnstile` — bot check failed\n * - `validation` — a field is missing/too long, or unknown keys were sent;\n * `field` and `kind` narrow it down when a specific field is\n * at fault (absent for whole-payload problems like unknown keys)\n * - `not_found` — no form with this id\n * - `consent` — a required GDPR consent checkbox was left unchecked\n * - `error` — persistence failed unexpectedly\n */\nexport type SubmitFailure =\n | {\n /** The offending field's name, when one field is at fault. */\n field?: string\n /** What was wrong with it. */\n kind?: 'required' | 'too_long' | 'unknown_fields'\n reason: 'validation'\n success: false\n }\n | {\n field?: string\n /** A GDPR consent field existed on the form but wasn't checked. */\n reason: 'consent'\n success: false\n }\n | { reason: 'error'; success: false }\n | { reason: 'not_found'; success: false }\n | { reason: 'rate_limited'; success: false }\n | { reason: 'turnstile'; success: false }\n\nexport type SubmitFormResult = { submissionId: number | string; success: true } | SubmitFailure\n\n/**\n * Handles a form submission end to end: rate limit, verify Turnstile, validate\n * against the form's own schema, then store.\n *\n * The order is cost-ascending on purpose — the cheapest checks reject first, so\n * a flood never reaches Turnstile's network call or the database.\n *\n * Emails aren't sent here. The form-builder sends whatever an editor configured\n * under the form's \"Emails\" tab (form-submissions hook → payload.sendEmail),\n * which goes out over the configured email adapter (mailAdapter). Storing the submission is enough.\n *\n * server-only: touches the Turnstile secret.\n */\nexport async function submitForm({\n consentFieldName,\n data,\n formId,\n ip,\n maxPerMinute = 5,\n payload,\n turnstileOnConfigError = 'allow',\n turnstileToken,\n}: SubmitFormArgs): Promise {\n // 1. Rate limit — cheapest gate, drops a flood before any real work.\n if (maxPerMinute > 0 && ip) {\n if (!checkRateLimit({ key: ip, max: maxPerMinute })) {\n return { reason: 'rate_limited', success: false }\n }\n }\n\n // 2. Turnstile — verify when a token is supplied; reject on failure.\n if (turnstileToken !== undefined) {\n const ok = await verifyTurnstile({ ip, onConfigError: turnstileOnConfigError, payload, token: turnstileToken })\n if (!ok) {\n return { reason: 'turnstile', success: false }\n }\n }\n\n // 3. Validate against the form's schema. A public endpoint can't trust the\n // shape of `data` — drop unknown keys, enforce required, cap length.\n const validation = await validateSubmission(payload, formId, data, consentFieldName)\n if (!validation.ok) {\n if (validation.reason === 'not_found') {\n return { reason: 'not_found', success: false }\n }\n if (validation.reason === 'consent') {\n return { field: validation.field, reason: 'consent', success: false }\n }\n return {\n reason: 'validation',\n success: false,\n ...(validation.field ? { field: validation.field } : {}),\n ...(validation.kind ? { kind: validation.kind } : {}),\n }\n }\n\n // 4. Persist (form-builder shape: submissionData array). Triggers the email\n // hook. Only validated, known fields are stored.\n try {\n const submission = await payload.create({\n collection: 'form-submissions',\n data: {\n form: formId,\n submissionData: Object.entries(validation.cleaned).map(([field, value]) => ({\n field,\n value: value == null ? '' : String(value),\n })),\n } as never,\n })\n return { submissionId: submission.id, success: true }\n } catch (err) {\n payload.logger.error(`[ipal] Form submission failed: ${(err as Error).message}`)\n return { reason: 'error', success: false }\n }\n}\n"],"names":["verifyTurnstile","checkRateLimit","validateSubmission","submitForm","consentFieldName","data","formId","ip","maxPerMinute","payload","turnstileOnConfigError","turnstileToken","key","max","reason","success","undefined","ok","onConfigError","token","validation","field","kind","submission","create","collection","form","submissionData","Object","entries","cleaned","map","value","String","submissionId","id","err","logger","error","message"],"mappings":"AAAA,OAAO,cAAa;AAIpB,SAASA,eAAe,QAAQ,wBAAuB;AACvD,SAASC,cAAc,QAAQ,iBAAgB;AAC/C,SAASC,kBAAkB,QAAQ,0BAAyB;AAqE5D;;;;;;;;;;;;CAYC,GACD,OAAO,eAAeC,WAAW,EAC/BC,gBAAgB,EAChBC,IAAI,EACJC,MAAM,EACNC,EAAE,EACFC,eAAe,CAAC,EAChBC,OAAO,EACPC,yBAA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AAS,OAAO,KAAKC,OAAOD;oBACrC,CAAA;YACF;QACF;QACA,OAAO;YAAEE,cAAcX,WAAWY,EAAE;YAAEpB,SAAS;QAAK;IACtD,EAAE,OAAOqB,KAAK;QACZ3B,QAAQ4B,MAAM,CAACC,KAAK,CAAC,CAAC,+BAA+B,EAAE,AAACF,IAAcG,OAAO,EAAE;QAC/E,OAAO;YAAEzB,QAAQ;YAASC,SAAS;QAAM;IAC3C;AACF"} \ No newline at end of file diff --git a/dist/modules/integrations/IntegrationAlerts.d.ts b/dist/modules/integrations/IntegrationAlerts.d.ts new file mode 100644 index 0000000..19ddc64 --- /dev/null +++ b/dist/modules/integrations/IntegrationAlerts.d.ts @@ -0,0 +1,16 @@ +import type { Payload } from 'payload'; +type Props = { + /** Admin route, for the link. Default '/admin'. */ + adminRoute?: string; + /** Status groups to check: field name → label. */ + checks?: Record; + /** 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 declare function IntegrationAlerts({ adminRoute, checks, payload }: Props): Promise; +export default IntegrationAlerts; diff --git a/dist/modules/integrations/IntegrationAlerts.js b/dist/modules/integrations/IntegrationAlerts.js new file mode 100644 index 0000000..c9aaa5a --- /dev/null +++ b/dist/modules/integrations/IntegrationAlerts.js @@ -0,0 +1,72 @@ +import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime"; +/** + * 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 }) { + if (!payload) { + return null; + } + let doc; + try { + doc = await payload.findGlobal({ + slug: 'site-integrations', + depth: 0 + }); + } catch { + return null; + } + const failing = Object.entries(checks).map(([field, label])=>({ + label, + status: doc?.[field] + })).filter((x)=>x.status?.state === 'degraded'); + if (!failing.length) { + return null; + } + return /*#__PURE__*/ _jsxs("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' + }, + children: [ + /*#__PURE__*/ _jsx("strong", { + children: "Integration problem — the site still works, but a safeguard is off." + }), + /*#__PURE__*/ _jsx("ul", { + style: { + margin: '0.5rem 0 0', + paddingLeft: '1.2rem' + }, + children: failing.map(({ label, status })=>/*#__PURE__*/ _jsxs("li", { + children: [ + /*#__PURE__*/ _jsxs("strong", { + children: [ + label, + ":" + ] + }), + " ", + status?.message ?? status?.code ?? 'error' + ] + }, label)) + }), + /*#__PURE__*/ _jsx("a", { + href: `${adminRoute.replace(/\/$/, '')}/globals/site-integrations`, + style: { + display: 'inline-block', + marginTop: '0.5rem' + }, + children: "Open Site Integrations →" + }) + ] + }); +} +export default IntegrationAlerts; + +//# sourceMappingURL=IntegrationAlerts.js.map \ No newline at end of file diff --git a/dist/modules/integrations/IntegrationAlerts.js.map b/dist/modules/integrations/IntegrationAlerts.js.map new file mode 100644 index 0000000..17d95fd --- /dev/null +++ b/dist/modules/integrations/IntegrationAlerts.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/modules/integrations/IntegrationAlerts.tsx"],"sourcesContent":["import type { Payload } from 'payload'\n\nimport type { IntegrationStatus } from './status.js'\n\ntype Props = {\n /** Admin route, for the link. Default '/admin'. */\n adminRoute?: string\n /** Status groups to check: field name → label. */\n checks?: Record\n /** Injected by Payload into admin server components. */\n payload?: Payload\n}\n\n/**\n * Dashboard alert (admin.components.beforeDashboard): lists integrations that\n * are currently failing, with a link to Site Integrations. Renders nothing when\n * everything is fine — and never throws (DB not ready → nothing).\n */\nexport async function IntegrationAlerts({ adminRoute = '/admin', checks = { turnstileStatus: 'Turnstile' }, payload }: Props) {\n if (!payload) {return null}\n let doc: Record\n try {\n doc = (await payload.findGlobal({ slug: 'site-integrations' as never, depth: 0 })) as Record\n } catch {\n return null\n }\n const failing = Object.entries(checks)\n .map(([field, label]) => ({ label, status: doc?.[field] as IntegrationStatus | undefined }))\n .filter((x) => x.status?.state === 'degraded')\n if (!failing.length) {return null}\n\n return (\n \n Integration problem — the site still works, but a safeguard is off.\n
    \n {failing.map(({ label, status }) => (\n
  • \n {label}: {status?.message ?? status?.code ?? 'error'}\n
  • \n ))}\n
\n \n Open Site Integrations →\n \n \n )\n}\n\nexport default IntegrationAlerts\n"],"names":["IntegrationAlerts","adminRoute","checks","turnstileStatus","payload","doc","findGlobal","slug","depth","failing","Object","entries","map","field","label","status","filter","x","state","length","div","role","style","background","border","borderRadius","marginBottom","padding","strong","ul","margin","paddingLeft","li","message","code","a","href","replace","display","marginTop"],"mappings":";AAaA;;;;CAIC,GACD,OAAO,eAAeA,kBAAkB,EAAEC,aAAa,QAAQ,EAAEC,SAAS;IAAEC,iBAAiB;AAAY,CAAC,EAAEC,OAAO,EAAS;IAC1H,IAAI,CAACA,SAAS;QAAC,OAAO;IAAI;IAC1B,IAAIC;IACJ,IAAI;QACFA,MAAO,MAAMD,QAAQE,UAAU,CAAC;YAAEC,MAAM;YAA8BC,OAAO;QAAE;IACjF,EAAE,OAAM;QACN,OAAO;IACT;IACA,MAAMC,UAAUC,OAAOC,OAAO,CAACT,QAC5BU,GAAG,CAAC,CAAC,CAACC,OAAOC,MAAM,GAAM,CAAA;YAAEA;YAAOC,QAAQV,KAAK,CAACQ,MAAM;QAAkC,CAAA,GACxFG,MAAM,CAAC,CAACC,IAAMA,EAAEF,MAAM,EAAEG,UAAU;IACrC,IAAI,CAACT,QAAQU,MAAM,EAAE;QAAC,OAAO;IAAI;IAEjC,qBACE,MAACC;QACCC,MAAK;QACLC,OAAO;YACLC,YAAY;YACZC,QAAQ;YACRC,cAAc;YACdC,cAAc;YACdC,SAAS;QACX;;0BAEA,KAACC;0BAAO;;0BACR,KAACC;gBAAGP,OAAO;oBAAEQ,QAAQ;oBAAcC,aAAa;gBAAS;0BACtDtB,QAAQG,GAAG,CAAC,CAAC,EAAEE,KAAK,EAAEC,MAAM,EAAE,iBAC7B,MAACiB;;0CACC,MAACJ;;oCAAQd;oCAAM;;;4BAAU;4BAAEC,QAAQkB,WAAWlB,QAAQmB,QAAQ;;uBADvDpB;;0BAKb,KAACqB;gBAAEC,MAAM,GAAGnC,WAAWoC,OAAO,CAAC,OAAO,IAAI,0BAA0B,CAAC;gBAAEf,OAAO;oBAAEgB,SAAS;oBAAgBC,WAAW;gBAAS;0BAAG;;;;AAKtI;AAEA,eAAevC,kBAAiB"} \ No newline at end of file diff --git a/dist/modules/integrations/IntegrationStatusBanner.d.ts b/dist/modules/integrations/IntegrationStatusBanner.d.ts new file mode 100644 index 0000000..cbc9144 --- /dev/null +++ b/dist/modules/integrations/IntegrationStatusBanner.d.ts @@ -0,0 +1,13 @@ +type Props = { + /** Integration name shown in the banner, e.g. 'Turnstile'. */ + label: string; + /** Name of the hidden status group (buildIntegrationStatusField). */ + statusField: string; +}; +/** + * 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 declare function IntegrationStatusBanner({ label, statusField }: Props): import("react/jsx-runtime").JSX.Element | null; +export default IntegrationStatusBanner; diff --git a/dist/modules/integrations/IntegrationStatusBanner.js b/dist/modules/integrations/IntegrationStatusBanner.js new file mode 100644 index 0000000..45fc7ba --- /dev/null +++ b/dist/modules/integrations/IntegrationStatusBanner.js @@ -0,0 +1,87 @@ +'use client'; +import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime"; +import { useFormFields } from '@payloadcms/ui'; +const fmt = (iso)=>{ + 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 }) { + const state = useFormFields(([f])=>f[`${statusField}.state`]?.value); + const message = useFormFields(([f])=>f[`${statusField}.message`]?.value); + const code = useFormFields(([f])=>f[`${statusField}.code`]?.value); + const since = useFormFields(([f])=>f[`${statusField}.since`]?.value); + const checkedAt = useFormFields(([f])=>f[`${statusField}.checkedAt`]?.value); + if (!state) { + return null; + } + if (state === 'ok') { + return /*#__PURE__*/ _jsxs("div", { + style: { + fontSize: '0.85rem', + marginBottom: '1.5rem', + opacity: 0.75 + }, + children: [ + "✓ ", + label, + " working", + since ? ` since ${fmt(since)}` : '', + "." + ] + }); + } + return /*#__PURE__*/ _jsxs("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' + }, + children: [ + /*#__PURE__*/ _jsxs("strong", { + children: [ + label, + " is not working — forms are accepted without this check." + ] + }), + message ? /*#__PURE__*/ _jsx("div", { + style: { + marginTop: '0.35rem' + }, + children: message + }) : null, + /*#__PURE__*/ _jsxs("div", { + style: { + fontSize: '0.8rem', + marginTop: '0.35rem', + opacity: 0.75 + }, + children: [ + code ? `Code: ${code}. ` : '', + since ? `Since ${fmt(since)}. ` : '', + checkedAt ? `Last seen ${fmt(checkedAt)}.` : '' + ] + }), + /*#__PURE__*/ _jsx("div", { + style: { + fontSize: '0.8rem', + marginTop: '0.35rem', + opacity: 0.75 + }, + children: "Fix the keys below and save — the status is checked again on the next form submission." + }) + ] + }); +} +export default IntegrationStatusBanner; + +//# sourceMappingURL=IntegrationStatusBanner.js.map \ No newline at end of file diff --git a/dist/modules/integrations/IntegrationStatusBanner.js.map b/dist/modules/integrations/IntegrationStatusBanner.js.map new file mode 100644 index 0000000..19c1bc3 --- /dev/null +++ b/dist/modules/integrations/IntegrationStatusBanner.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/modules/integrations/IntegrationStatusBanner.tsx"],"sourcesContent":["'use client'\nimport { useFormFields } from '@payloadcms/ui'\n\ntype Props = {\n /** Integration name shown in the banner, e.g. 'Turnstile'. */\n label: string\n /** Name of the hidden status group (buildIntegrationStatusField). */\n statusField: string\n}\n\nconst fmt = (iso: unknown) => {\n if (typeof iso !== 'string' || !iso) {return ''}\n const d = new Date(iso)\n return Number.isNaN(d.getTime()) ? '' : d.toLocaleString()\n}\n\n/**\n * Status banner on an integration's tab (Site Integrations). Shows nothing until\n * the integration has been used once; a red box while it's failing; a short\n * green line once it works again.\n */\nexport function IntegrationStatusBanner({ label, statusField }: Props) {\n const state = useFormFields(([f]) => f[`${statusField}.state`]?.value) as string | undefined\n const message = useFormFields(([f]) => f[`${statusField}.message`]?.value) as string | undefined\n const code = useFormFields(([f]) => f[`${statusField}.code`]?.value) as string | undefined\n const since = useFormFields(([f]) => f[`${statusField}.since`]?.value)\n const checkedAt = useFormFields(([f]) => f[`${statusField}.checkedAt`]?.value)\n\n if (!state) {return null}\n\n if (state === 'ok') {\n return (\n
\n ✓ {label} working{since ? ` since ${fmt(since)}` : ''}.\n
\n )\n }\n\n return (\n \n {label} is not working — forms are accepted without this check.\n {message ?
{message}
: null}\n
\n {code ? `Code: ${code}. ` : ''}\n {since ? `Since ${fmt(since)}. ` : ''}\n {checkedAt ? `Last seen ${fmt(checkedAt)}.` : ''}\n
\n
\n Fix the keys below and save — the status is checked again on the next form submission.\n
\n \n )\n}\n\nexport default IntegrationStatusBanner\n"],"names":["useFormFields","fmt","iso","d","Date","Number","isNaN","getTime","toLocaleString","IntegrationStatusBanner","label","statusField","state","f","value","message","code","since","checkedAt","div","style","fontSize","marginBottom","opacity","role","background","border","borderRadius","padding","strong","marginTop"],"mappings":"AAAA;;AACA,SAASA,aAAa,QAAQ,iBAAgB;AAS9C,MAAMC,MAAM,CAACC;IACX,IAAI,OAAOA,QAAQ,YAAY,CAACA,KAAK;QAAC,OAAO;IAAE;IAC/C,MAAMC,IAAI,IAAIC,KAAK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AC,MAAM,EAAEA,KAAK,EAAE,CAAC,GAAG;oBAC3BC,QAAQ,CAAC,MAAM,EAAEhB,IAAIgB,OAAO,EAAE,CAAC,GAAG;oBAClCC,YAAY,CAAC,UAAU,EAAEjB,IAAIiB,WAAW,CAAC,CAAC,GAAG;;;0BAEhD,KAACC;gBAAIC,OAAO;oBAAEC,UAAU;oBAAUS,WAAW;oBAAWP,SAAS;gBAAK;0BAAG;;;;AAK/E;AAEA,eAAed,wBAAuB"} \ No newline at end of file diff --git a/dist/modules/integrations/index.d.ts b/dist/modules/integrations/index.d.ts new file mode 100644 index 0000000..f8f4940 --- /dev/null +++ b/dist/modules/integrations/index.d.ts @@ -0,0 +1,2 @@ +export { buildIntegrationStatusBanner, buildIntegrationStatusField, recordIntegrationStatus, } from './status.js'; +export type { IntegrationState, IntegrationStatus } from './status.js'; diff --git a/dist/modules/integrations/index.js b/dist/modules/integrations/index.js new file mode 100644 index 0000000..afcbff2 --- /dev/null +++ b/dist/modules/integrations/index.js @@ -0,0 +1,3 @@ +export { buildIntegrationStatusBanner, buildIntegrationStatusField, recordIntegrationStatus } from './status.js'; + +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/dist/modules/integrations/index.js.map b/dist/modules/integrations/index.js.map new file mode 100644 index 0000000..d82e20a --- /dev/null +++ b/dist/modules/integrations/index.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/modules/integrations/index.ts"],"sourcesContent":["export {\n buildIntegrationStatusBanner,\n buildIntegrationStatusField,\n recordIntegrationStatus,\n} from './status.js'\nexport type { IntegrationState, IntegrationStatus } from './status.js'\n"],"names":["buildIntegrationStatusBanner","buildIntegrationStatusField","recordIntegrationStatus"],"mappings":"AAAA,SACEA,4BAA4B,EAC5BC,2BAA2B,EAC3BC,uBAAuB,QAClB,cAAa"} \ No newline at end of file diff --git a/dist/modules/integrations/status.d.ts b/dist/modules/integrations/status.d.ts new file mode 100644 index 0000000..58a12d2 --- /dev/null +++ b/dist/modules/integrations/status.d.ts @@ -0,0 +1,37 @@ +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; +}; +/** Hidden group field holding the status — add next to the integration's fields. */ +export declare function buildIntegrationStatusField(name: string): Field; +/** Read-only banner (UI field) — shows the status group `statusField` on the tab. */ +export declare function buildIntegrationStatusBanner(statusField: string, label: string): Field; +/** + * Persist a status change. Never throws — a status write must not break the + * request that triggered it. + */ +export declare function recordIntegrationStatus(payload: BasePayload, field: string, previous: IntegrationStatus | null | undefined, next: { + code?: string; + message?: string; + state: IntegrationState; +}): Promise; diff --git a/dist/modules/integrations/status.js b/dist/modules/integrations/status.js new file mode 100644 index 0000000..414487a --- /dev/null +++ b/dist/modules/integrations/status.js @@ -0,0 +1,92 @@ +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) { + 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, label) { + 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, field, previous, next) { + 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 = { + 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, + context: { + ipalIntegrationStatus: true + }, + data: { + [field]: status + }, + depth: 0 + }); + } catch (err) { + console.warn(`[ipal] could not record ${field}:`, err instanceof Error ? err.message : err); + } +} + +//# sourceMappingURL=status.js.map \ No newline at end of file diff --git a/dist/modules/integrations/status.js.map b/dist/modules/integrations/status.js.map new file mode 100644 index 0000000..74874a0 --- /dev/null +++ b/dist/modules/integrations/status.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../src/modules/integrations/status.ts"],"sourcesContent":["import type { BasePayload, Field } from 'payload'\n\n/**\n * Health of a third-party integration (Turnstile today, SMTP/Graph later),\n * stored on the SiteIntegrations global so the panel can show it:\n * - a banner on the integration's tab (IntegrationStatusBanner),\n * - an alert on the admin dashboard (IntegrationAlerts).\n *\n * Written by the server when it USES the integration (e.g. verifying a form\n * token) — no polling, no cron. Writes are throttled: only on a state change, or\n * at most every REFRESH_MS while an error persists, so a broken integration on a\n * busy form doesn't turn every submission into a DB write.\n */\n\nexport type IntegrationState = 'degraded' | 'ok'\n\nexport type IntegrationStatus = {\n /** Last time the integration was used (refreshed at most every REFRESH_MS). */\n checkedAt?: null | string\n /** Machine code from the provider or the plugin, e.g. 'invalid-input-secret', 'missing-secret'. */\n code?: null | string\n /** Human explanation shown in the panel (English — panel language). */\n message?: null | string\n /** When the current state started. */\n since?: null | string\n state?: IntegrationState | null\n}\n\nconst REFRESH_MS = 10 * 60_000\nconst SITE_INTEGRATIONS = 'site-integrations'\n\n/** Hidden group field holding the status — add next to the integration's fields. */\nexport function buildIntegrationStatusField(name: string): Field {\n return {\n name,\n type: 'group',\n admin: { hidden: true },\n fields: [\n { name: 'state', type: 'select', options: ['ok', 'degraded'] },\n { name: 'code', type: 'text' },\n { name: 'message', type: 'text' },\n { name: 'since', type: 'date' },\n { name: 'checkedAt', type: 'date' },\n ],\n }\n}\n\n/** Read-only banner (UI field) — shows the status group `statusField` on the tab. */\nexport function buildIntegrationStatusBanner(statusField: string, label: string): Field {\n return {\n name: `${statusField}Banner`,\n type: 'ui',\n admin: {\n components: {\n Field: {\n clientProps: { label, statusField },\n path: '@intecion/ipal-kit/client#IntegrationStatusBanner',\n },\n },\n },\n }\n}\n\n/**\n * Persist a status change. Never throws — a status write must not break the\n * request that triggered it.\n */\nexport async function recordIntegrationStatus(\n payload: BasePayload,\n field: string,\n previous: IntegrationStatus | null | undefined,\n next: { code?: string; message?: string; state: IntegrationState },\n): Promise {\n const now = new Date()\n const changed = previous?.state !== next.state || (next.state === 'degraded' && previous?.code !== next.code)\n const stale =\n next.state === 'degraded' &&\n (!previous?.checkedAt || now.getTime() - new Date(previous.checkedAt).getTime() > REFRESH_MS)\n\n // Healthy and already recorded as healthy (or never recorded) → nothing to do.\n if (!changed && !stale) {return}\n if (next.state === 'ok' && !previous?.state) {return}\n\n const status: IntegrationStatus = {\n checkedAt: now.toISOString(),\n code: next.code ?? null,\n message: next.message ?? null,\n since: changed ? now.toISOString() : (previous?.since ?? now.toISOString()),\n state: next.state,\n }\n try {\n await payload.updateGlobal({\n slug: SITE_INTEGRATIONS as never,\n context: { ipalIntegrationStatus: true },\n data: { [field]: status } as never,\n depth: 0,\n })\n } catch (err) {\n console.warn(`[ipal] could not record ${field}:`, err instanceof Error ? err.message : err)\n }\n}\n"],"names":["REFRESH_MS","SITE_INTEGRATIONS","buildIntegrationStatusField","name","type","admin","hidden","fields","options","buildIntegrationStatusBanner","statusField","label","components","Field","clientProps","path","recordIntegrationStatus","payload","field","previous","next","now","Date","changed","state","code","stale","checkedAt","getTime","status","toISOString","message","since","updateGlobal","slug","context","ipalIntegrationStatus","data","depth","err","console","warn","Error"],"mappings":"AA4BA,MAAMA,aAAa,KAAK;AACxB,MAAMC,oBAAoB;AAE1B,kFAAkF,GAClF,OAAO,SAASC,4BAA4BC,IAAY;IACtD,OAAO;QACLA;QACAC,MAAM;QACNC,OAAO;YAAEC,QAAQ;QAAK;QACtBC,QAAQ;YACN;gBAAEJ,MAAM;gBAASC,MAAM;gBAAUI,SAAS;oBAAC;oBAAM;iBAAW;YAAC;YAC7D;gBAAEL,MAAM;gBAAQC,MAAM;YAAO;YAC7B;gBAAED,MAAM;gBAAWC,MAAM;YAAO;YAChC;gBAAED,MAAM;gBAASC,MAAM;YAAO;YAC9B;gBAAED,MAAM;gBAAaC,MAAM;YAAO;SACnC;IACH;AACF;AAEA,mFAAmF,GACnF,OAAO,SAASK,6BAA6BC,WAAmB,EAAEC,KAAa;IAC7E,OAAO;QACLR,MAAM,GAAGO,YAAY,MAAM,CAAC;QAC5BN,MAAM;QACNC,OAAO;YACLO,YAAY;gBACVC,OAAO;oBACLC,aAAa;wBAAEH;wBAAOD;oBAAY;oBAClCK,MAAM;gBACR;YACF;QACF;IACF;AACF;AAEA;;;CAGC,GACD,OAAO,eAAeC,wBACpBC,OAAoB,EACpBC,KAAa,EACbC,QAA8C,EAC9CC,IAAkE;IAElE,MAAMC,MAAM,IAAIC;IAChB,MAAMC,UAAUJ,UAAUK,UAAUJ,KAAKI,KAAK,IAAKJ,KAAKI,KAAK,KAAK,cAAcL,UAAUM,SAASL,KAAKK,IAAI;IAC5G,MAAMC,QACJN,KAAKI,KAAK,KAAK,cACd,CAAA,CAACL,UAAUQ,aAAaN,IAAIO,OAAO,KAAK,IAAIN,KAAKH,SAASQ,SAAS,EAAEC,OAAO,KAAK5B,UAAS;IAE7F,+EAA+E;IAC/E,IAAI,CAACuB,WAAW,CAACG,OAAO;QAAC;IAAM;IAC/B,IAAIN,KAAKI,KAAK,KAAK,QAAQ,CAACL,UAAUK,OAAO;QAAC;IAAM;IAEpD,MAAMK,SAA4B;QAChCF,WAAWN,IAAIS,WAAW;QAC1BL,MAAML,KAAKK,IAAI,IAAI;QACnBM,SAASX,KAAKW,OAAO,IAAI;QACzBC,OAAOT,UAAUF,IAAIS,WAAW,KAAMX,UAAUa,SAASX,IAAIS,WAAW;QACxEN,OAAOJ,KAAKI,KAAK;IACnB;IACA,IAAI;QACF,MAAMP,QAAQgB,YAAY,CAAC;YACzBC,MAAMjC;YACNkC,SAAS;gBAAEC,uBAAuB;YAAK;YACvCC,MAAM;gBAAE,CAACnB,MAAM,EAAEW;YAAO;YACxBS,OAAO;QACT;IACF,EAAE,OAAOC,KAAK;QACZC,QAAQC,IAAI,CAAC,CAAC,wBAAwB,EAAEvB,MAAM,CAAC,CAAC,EAAEqB,eAAeG,QAAQH,IAAIR,OAAO,GAAGQ;IACzF;AACF"} \ No newline at end of file diff --git a/dist/modules/turnstile/index.d.ts b/dist/modules/turnstile/index.d.ts index 35e57cb..b9378ae 100644 --- a/dist/modules/turnstile/index.d.ts +++ b/dist/modules/turnstile/index.d.ts @@ -1,2 +1,3 @@ export { TurnstileProvider, useTurnstile } from './TurnstileProvider.js'; -export { verifyTurnstile } from './verify.js'; +export { checkTurnstile, verifyTurnstile } from './verify.js'; +export type { TurnstileCheck, TurnstileOutcome } from './verify.js'; diff --git a/dist/modules/turnstile/index.js b/dist/modules/turnstile/index.js index 90302d3..0ef8648 100644 --- a/dist/modules/turnstile/index.js +++ b/dist/modules/turnstile/index.js @@ -1,6 +1,6 @@ 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'; //# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/dist/modules/turnstile/index.js.map b/dist/modules/turnstile/index.js.map index 48ee066..523164d 100644 --- a/dist/modules/turnstile/index.js.map +++ b/dist/modules/turnstile/index.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../../src/modules/turnstile/index.ts"],"sourcesContent":["export { TurnstileProvider, useTurnstile } from './TurnstileProvider.js'\n// Server-only exports. verify.ts imports 'server-only', so this must never be\n// imported from a client component — use ./client for the widget instead.\nexport { verifyTurnstile } from './verify.js'\n"],"names":["TurnstileProvider","useTurnstile","verifyTurnstile"],"mappings":"AAAA,SAASA,iBAAiB,EAAEC,YAAY,QAAQ,yBAAwB;AACxE,8EAA8E;AAC9E,0EAA0E;AAC1E,SAASC,eAAe,QAAQ,cAAa"} \ No newline at end of file +{"version":3,"sources":["../../../src/modules/turnstile/index.ts"],"sourcesContent":["export { TurnstileProvider, useTurnstile } from './TurnstileProvider.js'\n// Server-only exports. verify.ts imports 'server-only', so this must never be\n// imported from a client component — use ./client for the widget instead.\nexport { checkTurnstile, verifyTurnstile } from './verify.js'\nexport type { TurnstileCheck, TurnstileOutcome } from './verify.js'\n"],"names":["TurnstileProvider","useTurnstile","checkTurnstile","verifyTurnstile"],"mappings":"AAAA,SAASA,iBAAiB,EAAEC,YAAY,QAAQ,yBAAwB;AACxE,8EAA8E;AAC9E,0EAA0E;AAC1E,SAASC,cAAc,EAAEC,eAAe,QAAQ,cAAa"} \ No newline at end of file diff --git a/dist/modules/turnstile/verify.d.ts b/dist/modules/turnstile/verify.d.ts index 36d2dfb..45690b5 100644 --- a/dist/modules/turnstile/verify.d.ts +++ b/dist/modules/turnstile/verify.d.ts @@ -1,23 +1,50 @@ import 'server-only'; import type { BasePayload } from 'payload'; 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; }; /** - * 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 declare function verifyTurnstile({ ip, payload, token, }: VerifyTurnstileArgs): Promise; +export type TurnstileOutcome = 'degraded' | 'pass' | 'reject'; +export type TurnstileCheck = { + code?: string; + outcome: TurnstileOutcome; +}; +/** + * 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 declare function checkTurnstile({ ip, payload, sendRemoteIp, token, }: Omit): Promise; +/** + * 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 declare function verifyTurnstile({ onConfigError, ...args }: VerifyTurnstileArgs): Promise; export {}; diff --git a/dist/modules/turnstile/verify.js b/dist/modules/turnstile/verify.js index 250d69c..bd99ffa 100644 --- a/dist/modules/turnstile/verify.js +++ b/dist/modules/turnstile/verify.js @@ -1,41 +1,102 @@ import 'server-only'; +import { recordIntegrationStatus } from '../integrations/status.js'; import { getSiteIntegrations } from '../payload/index.js'; +/** Env fallback for the secret — same name ipalEnvRules({ turnstile: true }) requires. */ const ENV_SECRET = 'TURNSTILE_SECRET_KEY'; +const STATUS_FIELD = 'turnstileStatus'; +/** Cloudflare error codes caused by our configuration / Cloudflare itself — not by the visitor. */ const CONFIG_ERRORS = { + '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 = { + '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, server-side only. + * Verifies a Turnstile token with Cloudflare and classifies the result (server-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". - */ export async function verifyTurnstile({ ip, payload, token }) { + * 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 }) { if (!token) { - return false; + return { + code: 'missing-input-response', + outcome: 'reject' + }; } const integrations = await getSiteIntegrations(payload); - const secret = integrations.turnstileSecretKey; + const previous = integrations[STATUS_FIELD]; + const secret = integrations.turnstileSecretKey?.trim() || process.env[ENV_SECRET]?.trim(); + const degraded = async (code)=>{ + 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 false; + return degraded('missing-secret'); } const body = new URLSearchParams({ response: token, secret }); - if (ip) { + if (sendRemoteIp && ip) { body.append('remoteip', ip); } + let data; try { const res = await fetch('https://challenges.cloudflare.com/turnstile/v0/siteverify', { body, - method: 'POST' + method: 'POST', + signal: AbortSignal.timeout(8000) }); - const data = await res.json(); - return data.success; - } catch { - return false; + if (res.status >= 500) { + return degraded('internal-error'); + } + data = await res.json(); + } 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 }) { + const { outcome } = await checkTurnstile(args); + return outcome === 'pass' || outcome === 'degraded' && onConfigError === 'allow'; } //# sourceMappingURL=verify.js.map \ No newline at end of file diff --git a/dist/modules/turnstile/verify.js.map b/dist/modules/turnstile/verify.js.map index 91d58b7..54f1dc3 100644 --- a/dist/modules/turnstile/verify.js.map +++ b/dist/modules/turnstile/verify.js.map @@ -1 +1 @@ -{"version":3,"sources":["../../../src/modules/turnstile/verify.ts"],"sourcesContent":["import 'server-only'\n\nimport type { BasePayload } from 'payload'\n\nimport { getSiteIntegrations } from '../payload/index.js'\n\ntype SiteverifyResponse = {\n challenge_ts?: string\n 'error-codes'?: string[]\n hostname?: string\n success: boolean\n}\n\ntype IntegrationsWithTurnstile = {\n turnstileSecretKey?: null | string\n}\n\ntype VerifyTurnstileArgs = {\n /** Optional client IP for stricter verification. */\n ip?: string\n /** Payload instance — used to read the secret from SiteIntegrations. */\n payload: BasePayload\n /** Token produced by the client-side widget. */\n token: string\n}\n\n/**\n * Verifies a Turnstile token with Cloudflare, server-side only.\n *\n * The secret comes from the SiteIntegrations global (editor-managed, per the\n * plugin's \"secrets in the panel\" model), read via the Local API which bypasses\n * access control. `server-only` guarantees this never reaches the browser\n * bundle, keeping the secret off the client.\n *\n * Returns false on any failure (missing secret/token, network error, rejected\n * challenge) — callers treat false as \"do not trust this submission\".\n */\nexport async function verifyTurnstile({\n ip,\n payload,\n token,\n}: VerifyTurnstileArgs): Promise {\n if (!token) {return false}\n\n const integrations = await getSiteIntegrations(payload)\n const secret = integrations.turnstileSecretKey\n if (!secret) {return false}\n\n const body = new URLSearchParams({ response: token, secret })\n if (ip) {body.append('remoteip', ip)}\n\n try {\n const res = await fetch('https://challenges.cloudflare.com/turnstile/v0/siteverify', {\n body,\n method: 'POST',\n })\n const data = (await res.json()) as SiteverifyResponse\n return data.success\n } catch {\n return false\n }\n}\n"],"names":["getSiteIntegrations","verifyTurnstile","ip","payload","token","integrations","secret","turnstileSecretKey","body","URLSearchParams","response","append","res","fetch","method","data","json","success"],"mappings":"AAAA,OAAO,cAAa;AAIpB,SAASA,mBAAmB,QAAQ,sBAAqB;AAsBzD;;;;;;;;;;CAUC,GACD,OAAO,eAAeC,gBAAgB,EACpCC,EAAE,EACFC,OAAO,EACPC,KAAK,EACe;IACpB,IAAI,CAACA,OAAO;QAAC,OAAO;IAAK;IAEzB,MAAMC,eAAe,MAAML,oBAA+CG;IAC1E,MAAMG,SAASD,aAAaE,kBAAkB;IAC9C,IAAI,CAACD,QAAQ;QAAC,OAAO;IAAK;IAE1B,MAAME,OAAO,IAAIC,gBAAgB;QAAEC,UAAUN;QAAOE;IAAO;IAC3D,IAAIJ,IAAI;QAACM,KAAKG,MAAM,CAAC,YAAYT;IAAG;IAEpC,IAAI;QACF,MAAMU,MAAM,MAAMC,MAAM,6DAA6D;YACnFL;YACAM,QAAQ;QACV;QACA,MAAMC,OAAQ,MAAMH,IAAII,IAAI;QAC5B,OAAOD,KAAKE,OAAO;IACrB,EAAE,OAAM;QACN,OAAO;IACT;AACF"} \ No newline at end of file +{"version":3,"sources":["../../../src/modules/turnstile/verify.ts"],"sourcesContent":["import 'server-only'\n\nimport type { BasePayload } from 'payload'\n\nimport { type IntegrationStatus, recordIntegrationStatus } from '../integrations/status.js'\nimport { getSiteIntegrations } from '../payload/index.js'\n\ntype SiteverifyResponse = {\n challenge_ts?: string\n 'error-codes'?: string[]\n hostname?: string\n success: boolean\n}\n\ntype IntegrationsWithTurnstile = {\n turnstileSecretKey?: null | string\n turnstileStatus?: IntegrationStatus | null\n}\n\ntype VerifyTurnstileArgs = {\n /** Client IP. Sent to Cloudflare only with `sendRemoteIp: true`. */\n ip?: string\n /**\n * What to do when verification can't run because of OUR side (missing/wrong\n * secret, Cloudflare unreachable). 'allow' (default): accept the submission —\n * rate limit, honeypot and validation still apply — and show the problem in\n * the panel. 'reject': refuse (fail closed).\n */\n onConfigError?: 'allow' | 'reject'\n /** Payload instance — used to read the secret from SiteIntegrations. */\n payload: BasePayload\n /**\n * Send `remoteip` to Cloudflare. Default false: behind Cloudflare / Traefik /\n * Docker the IP the app sees can differ from the one that solved the challenge\n * (IPv6 on mobile vs IPv4 at the proxy), and Cloudflare's check doesn't need it.\n */\n sendRemoteIp?: boolean\n /** Token produced by the client-side widget. */\n token: string\n}\n\n/** Env fallback for the secret — same name ipalEnvRules({ turnstile: true }) requires. */\nconst ENV_SECRET = 'TURNSTILE_SECRET_KEY'\nconst STATUS_FIELD = 'turnstileStatus'\n\n/**\n * - `pass` — token valid.\n * - `reject` — the VISITOR's token is bad (forged, reused, expired, malformed) → refuse.\n * - `degraded` — OUR side is broken (no/wrong secret, Cloudflare unreachable or\n * erroring) → the visitor can't fix it; by default the submission\n * is accepted and the panel shows the problem.\n */\nexport type TurnstileOutcome = 'degraded' | 'pass' | 'reject'\nexport type TurnstileCheck = { code?: string; outcome: TurnstileOutcome }\n\n/** Cloudflare error codes caused by our configuration / Cloudflare itself — not by the visitor. */\nconst CONFIG_ERRORS: Record = {\n 'internal-error': 'Cloudflare reported an internal error while verifying.',\n 'invalid-input-secret':\n 'Cloudflare rejected the secret key — check Site Integrations → Turnstile (secret and site key must come from the same widget).',\n 'missing-input-secret': 'The secret key is missing in the request.',\n}\nconst PLUGIN_ERRORS: Record = {\n 'bad-response': 'Cloudflare returned an unexpected response.',\n 'missing-secret': `No secret key — fill in Site Integrations → Turnstile (or the ${ENV_SECRET} environment variable).`,\n 'network-error': 'The server could not reach Cloudflare (challenges.cloudflare.com).',\n}\n\n/**\n * Verifies a Turnstile token with Cloudflare and classifies the result (server-only).\n *\n * Secret: SiteIntegrations → Turnstile (panel) first, then TURNSTILE_SECRET_KEY.\n * Every result is logged when not `pass`, and the integration status on\n * SiteIntegrations is updated (throttled) so the panel shows failures.\n */\nexport async function checkTurnstile({\n ip,\n payload,\n sendRemoteIp = false,\n token,\n}: Omit): Promise {\n if (!token) {return { code: 'missing-input-response', outcome: 'reject' }}\n\n const integrations = await getSiteIntegrations(payload)\n const previous = integrations[STATUS_FIELD]\n const secret = integrations.turnstileSecretKey?.trim() || process.env[ENV_SECRET]?.trim()\n\n const degraded = async (code: string): Promise => {\n const message = PLUGIN_ERRORS[code] ?? CONFIG_ERRORS[code] ?? `Cloudflare error: ${code}`\n console.warn(`[ipal] Turnstile degraded (${code}): ${message}`)\n await recordIntegrationStatus(payload, STATUS_FIELD, previous, { code, message, state: 'degraded' })\n return { code, outcome: 'degraded' }\n }\n\n if (!secret) {return degraded('missing-secret')}\n\n const body = new URLSearchParams({ response: token, secret })\n if (sendRemoteIp && ip) {body.append('remoteip', ip)}\n\n let data: SiteverifyResponse\n try {\n const res = await fetch('https://challenges.cloudflare.com/turnstile/v0/siteverify', {\n body,\n method: 'POST',\n signal: AbortSignal.timeout(8000),\n })\n if (res.status >= 500) {return degraded('internal-error')}\n data = (await res.json()) as SiteverifyResponse\n } catch (err) {\n console.warn('[ipal] Turnstile: siteverify request failed:', err instanceof Error ? err.message : err)\n return degraded('network-error')\n }\n if (typeof data?.success !== 'boolean') {return degraded('bad-response')}\n\n if (data.success) {\n await recordIntegrationStatus(payload, STATUS_FIELD, previous, { state: 'ok' })\n return { outcome: 'pass' }\n }\n\n const codes = data['error-codes'] ?? []\n const configCode = codes.find((c) => c in CONFIG_ERRORS)\n if (configCode) {return degraded(configCode)}\n\n // Visitor-side: invalid-input-response, timeout-or-duplicate, missing-input-response, bad-request.\n console.warn(`[ipal] Turnstile rejected: ${codes.join(', ') || 'unknown'}${data.hostname ? ` (hostname ${data.hostname})` : ''}`)\n return { code: codes[0] ?? 'unknown', outcome: 'reject' }\n}\n\n/**\n * Boolean wrapper used by submitForm. `onConfigError` decides what a `degraded`\n * result means: 'allow' (default) keeps the site's forms working while the\n * panel shows the problem; 'reject' fails closed.\n */\nexport async function verifyTurnstile({ onConfigError = 'allow', ...args }: VerifyTurnstileArgs): Promise {\n const { outcome } = await checkTurnstile(args)\n return outcome === 'pass' || (outcome === 'degraded' && onConfigError === 'allow')\n}\n"],"names":["recordIntegrationStatus","getSiteIntegrations","ENV_SECRET","STATUS_FIELD","CONFIG_ERRORS","PLUGIN_ERRORS","checkTurnstile","ip","payload","sendRemoteIp","token","code","outcome","integrations","previous","secret","turnstileSecretKey","trim","process","env","degraded","message","console","warn","state","body","URLSearchParams","response","append","data","res","fetch","method","signal","AbortSignal","timeout","status","json","err","Error","success","codes","configCode","find","c","join","hostname","verifyTurnstile","onConfigError","args"],"mappings":"AAAA,OAAO,cAAa;AAIpB,SAAiCA,uBAAuB,QAAQ,4BAA2B;AAC3F,SAASC,mBAAmB,QAAQ,sBAAqB;AAoCzD,wFAAwF,GACxF,MAAMC,aAAa;AACnB,MAAMC,eAAe;AAYrB,iGAAiG,GACjG,MAAMC,gBAAwC;IAC5C,kBAAkB;IAClB,wBACE;IACF,wBAAwB;AAC1B;AACA,MAAMC,gBAAwC;IAC5C,gBAAgB;IAChB,kBAAkB,CAAC,8DAA8D,EAAEH,WAAW,uBAAuB,CAAC;IACtH,iBAAiB;AACnB;AAEA;;;;;;CAMC,GACD,OAAO,eAAeI,eAAe,EACnCC,EAAE,EACFC,OAAO,EACPC,eAAe,KAAK,EACpBC,KAAK,EACsC;IAC3C,IAAI,CAACA,OAAO;QAAC,OAAO;YAAEC,MAAM;YAA0BC,SAAS;QAAS;IAAC;IAEzE,MAAMC,eAAe,MAAMZ,oBAA+CO;IAC1E,MAAMM,WAAWD,YAAY,CAACV,aAAa;IAC3C,MAAMY,SAASF,aAAaG,kBAAkB,EAAEC,UAAUC,QAAQC,GAAG,CAACjB,WAAW,EAAEe;IAEnF,MAAMG,WAAW,OAAOT;QACtB,MAAMU,UAAUhB,aAAa,CAACM,KAAK,IAAIP,aAAa,CAACO,KAAK,IAAI,CAAC,kBAAkB,EAAEA,MAAM;QACzFW,QAAQC,IAAI,CAAC,CAAC,2BAA2B,EAAEZ,KAAK,GAAG,EAAEU,SAAS;QAC9D,MAAMrB,wBAAwBQ,SAASL,cAAcW,UAAU;YAAEH;YAAMU;YAASG,OAAO;QAAW;QAClG,OAAO;YAAEb;YAAMC,SAAS;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,gBAAgB,OAAO,EAAE,GAAGC,MAA2B;IAC7F,MAAM,EAAErC,OAAO,EAAE,GAAG,MAAMN,eAAe2C;IACzC,OAAOrC,YAAY,UAAWA,YAAY,cAAcoC,kBAAkB;AAC5E"} \ No newline at end of file diff --git a/dist/plugin.js b/dist/plugin.js index 0639700..447cea6 100644 --- a/dist/plugin.js +++ b/dist/plugin.js @@ -225,6 +225,23 @@ import { buildSeoPlugin, injectAutoFillMeta, injectSeoTabs } from './modules/seo ...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)=>{ diff --git a/dist/plugin.js.map b/dist/plugin.js.map index b878643..d744034 100644 --- a/dist/plugin.js.map +++ b/dist/plugin.js.map @@ -1 +1 @@ -{"version":3,"sources":["../src/plugin.ts"],"sourcesContent":["import type { Config, Plugin } from 'payload'\n\nimport type { IpalOptions, TotpPluginFactory } from './types.js'\n\nimport { buildCookieSettings } from './globals/CookieSettings/index.js'\nimport { buildNotifications } from './globals/Notifications/index.js'\nimport { buildSiteIntegrations } from './globals/SiteIntegrations/index.js'\nimport { buildSiteSettings } from './globals/SiteSettings/index.js'\nimport { injectRoles } from './modules/access/index.js'\nimport { buildArchiveFields } from './modules/content/index.js'\nimport { testEmailEndpoint } from './modules/email/test/testEmailEndpoint.js'\nimport { buildFormsPlugin } from './modules/forms/formsPluginConfig.js'\nimport { buildLocalizationConfig, validateI18nConfig } from './modules/i18n/index.js'\nimport { buildSystemPagesFields } from './modules/pages/index.js'\nimport { buildSeoPlugin, injectAutoFillMeta, injectSeoTabs } from './modules/seo/index.js'\n\n/**\n * IPAL (Intecion Payload Advanced Library) plugin for Payload CMS 3.\n *\n * @example\n * ```ts\n * import { ipalKit } from 'ipal-kit'\n *\n * export default buildConfig({\n * plugins: [\n * ipalKit({\n * i18n: {\n * locales: [\n * { code: 'pl', label: 'Polski' },\n * { code: 'en', label: 'English' },\n * ],\n * defaultLocale: 'pl',\n * },\n * access: { authCollection: 'users' },\n * }),\n * ],\n * })\n * ```\n */\nexport const ipalKit = (options: IpalOptions): Plugin => {\n // Validate eagerly — fail fast before Payload boots\n validateI18nConfig(options.i18n)\n\n return async (incomingConfig: Config): Promise => {\n // Early return when disabled — schema stays, behavior off\n if (options.enabled === false) {\n return incomingConfig\n }\n\n let config = { ...incomingConfig }\n\n // --- custom admin route (e.g. '/its' instead of '/admin') ---\n // Sets config.routes.admin; the project must move its app/(payload)//\n // folder to match (plugin can't create files in the project's app/).\n if (options.adminRoute) {\n config.routes = { ...(config.routes ?? {}), admin: options.adminRoute }\n }\n\n // --- enforced 2FA (TOTP) via @clocklimited/payload-2fa ---\n // Enforced by default (forceSetup) unless twoFactor is explicitly false. The\n // plugin is a PEER dependency imported dynamically — ipal-kit doesn't bundle\n // it, so projects that opt out (twoFactor: false) needn't install it, and the\n // import never runs under generate:importmap when 2FA is off. Wrapping access\n // control (not just admin UI) means TOTP gates data access — no API bypass.\n if (options.twoFactor !== false) {\n const tf = options.twoFactor\n if (!tf?.issuer) {\n throw new Error(\n '[ipal] twoFactor.issuer is required (name shown in the authenticator ' +\n 'app). Pass twoFactor: { issuer: \"Your Site\" }, or twoFactor: false to ' +\n 'opt out (discouraged).',\n )\n }\n // Prefer the INJECTED plugin factory (recommended): the project imports\n // payloadTotp from @clocklimited/payload-2fa and passes it in. Then the\n // plugin never imports the optional peer itself — no dynamic import, so\n // Next can't fail to bundle it (the cause of \"Cannot find module\n // '@clocklimited/payload-2fa'\" crashing even public frontend pages).\n let totp: TotpPluginFactory | undefined = tf.plugin\n\n if (!totp) {\n // Fallback: dynamic import. Variable specifier dodges the plugin's own\n // TS2307, but Next may NOT trace it into the server bundle — projects\n // using this path MUST add '@clocklimited/payload-2fa' to\n // serverExternalPackages in next.config (see docs/security.md).\n try {\n const pkg = '@clocklimited/payload-2fa'\n const mod = (await import(pkg)) as {\n payloadTotp?: TotpPluginFactory\n totpPlugin?: TotpPluginFactory\n }\n totp = mod.payloadTotp ?? mod.totpPlugin\n } catch (err) {\n throw new Error(\n '[ipal] 2FA is enforced but @clocklimited/payload-2fa could not be loaded. ' +\n 'Best fix — inject it: `import { payloadTotp } from \"@clocklimited/payload-2fa\"` ' +\n 'then `twoFactor: { issuer, plugin: payloadTotp }`. Or install it AND add ' +\n \"'@clocklimited/payload-2fa' to serverExternalPackages in next.config. Or set \" +\n `twoFactor: false to opt out (discouraged). Original error: ${String(err)}`,\n )\n }\n }\n\n if (typeof totp !== 'function') {\n throw new Error(\n '[ipal] 2FA: expected payloadTotp (or totpPlugin) to be a function — check the ' +\n 'injected `plugin` or the installed @clocklimited/payload-2fa version.',\n )\n }\n\n config = await totp({\n collection: tf.collectionSlug ?? 'users',\n forceSetup: true, // ENFORCED — every user must set up TOTP; no opt-out\n totp: { issuer: tf.issuer },\n })(config)\n }\n\n // --- white-label admin branding ---\n // Inject admin.components.graphics.Logo/Icon pointing at the plugin's\n // /admin export. The components read SiteSettings at render, so each client\n // sees their own brand from the panel (no brand in code). Project must run\n // `pnpm generate:importmap` so Payload resolves the component paths.\n if (options.whiteLabel) {\n const wl = options.whiteLabel === true ? {} : options.whiteLabel\n const serverProps: Record = {}\n if (wl.settingsSlug) {serverProps.settingsSlug = wl.settingsSlug}\n if (wl.nameField) {serverProps.nameField = wl.nameField}\n const logoProps = { ...serverProps, ...(wl.logoField ? { imageField: wl.logoField } : {}) }\n const iconProps = { ...serverProps, ...(wl.iconField ? { imageField: wl.iconField } : {}) }\n\n // Vendor credit (\"Technology by Intecion.com\") under the nav — on by\n // default, hidden with credit:false, text/url overridable.\n const creditOn = wl.credit !== false\n const creditProps =\n wl.credit && typeof wl.credit === 'object'\n ? {\n ...(wl.credit.text ? { text: wl.credit.text } : {}),\n ...(wl.credit.url ? { url: wl.credit.url } : {}),\n }\n : {}\n\n config.admin = {\n ...(config.admin ?? {}),\n components: {\n ...(config.admin?.components ?? {}),\n graphics: {\n ...(config.admin?.components?.graphics ?? {}),\n Icon: { path: '@intecion/ipal-kit/admin#AdminIcon', serverProps: iconProps },\n Logo: { path: '@intecion/ipal-kit/admin#AdminLogo', serverProps: logoProps },\n },\n ...(creditOn\n ? {\n afterLogin: [\n ...(config.admin?.components?.afterLogin ?? []),\n {\n path: '@intecion/ipal-kit/admin#IntecionCredit',\n serverProps: { ...creditProps, variant: 'login' },\n },\n ],\n afterNavLinks: [\n ...(config.admin?.components?.afterNavLinks ?? []),\n {\n path: '@intecion/ipal-kit/admin#IntecionCredit',\n serverProps: { ...creditProps, variant: 'nav' },\n },\n ],\n }\n : {}),\n },\n ...(wl.titleSuffix\n ? { meta: { ...(config.admin?.meta ?? {}), titleSuffix: wl.titleSuffix } }\n : {}),\n }\n }\n\n // --- i18n ---\n config.localization = buildLocalizationConfig(options.i18n)\n\n // --- access: inject roles into the client's auth collection ---\n if (options.access) {\n config = injectRoles(config, options.access)\n }\n\n // --- seo: apply @payloadcms/plugin-seo directly ---\n // NOTE: apply the plugin function to the config immediately rather than\n // pushing it onto config.plugins. Payload has already iterated the plugins\n // array by the time IPAL runs, so nested plugins added to that list are\n // never executed. Calling the plugin as (config) => config applies its\n // transform now.\n if (options.seo) {\n config = await buildSeoPlugin({ seo: options.seo })(config)\n // Auto-fill empty meta from document content on save\n config = injectAutoFillMeta(config, options.seo)\n // Wrap fields into Content + SEO tabs (replaces plugin-seo's tabbedUI,\n // which breaks when other fields already exist in the collection)\n config = injectSeoTabs(config, options.seo)\n }\n\n // --- forms: apply @payloadcms/plugin-form-builder directly ---\n if (options.forms) {\n config = await buildFormsPlugin(options.forms)(config)\n }\n\n // --- globals ---\n // The System Pages tab collects every \"which page plays this role\"\n // assignment. Composing it here keeps SiteSettings unaware of which modules\n // are enabled — it just renders the fields it's given.\n const systemPageFields = [\n ...(options.pages ? buildSystemPagesFields(options.pages) : []),\n ...(options.content && options.pages\n ? buildArchiveFields(options.content, options.pages.slug)\n : []),\n ]\n\n config.globals = [\n ...(config.globals ?? []),\n buildSiteSettings({\n additionalFields: options.siteSettingsFields,\n systemPageFields,\n }),\n buildSiteIntegrations({ additionalFields: options.integrationsFields }),\n buildCookieSettings(),\n buildNotifications(),\n ]\n\n config.endpoints = [...(config.endpoints ?? []), testEmailEndpoint]\n\n // --- hooks: onInit ---\n const incomingOnInit = config.onInit\n config.onInit = async (payload) => {\n if (incomingOnInit) {await incomingOnInit(payload)}\n payload.logger.info('[ipal] Plugin initialized.')\n }\n\n return config\n }\n}\n"],"names":["buildCookieSettings","buildNotifications","buildSiteIntegrations","buildSiteSettings","injectRoles","buildArchiveFields","testEmailEndpoint","buildFormsPlugin","buildLocalizationConfig","validateI18nConfig","buildSystemPagesFields","buildSeoPlugin","injectAutoFillMeta","injectSeoTabs","ipalKit","options","i18n","incomingConfig","enabled","config","adminRoute","routes","admin","twoFactor","tf","issuer","Error","totp","plugin","pkg","mod","payloadTotp","totpPlugin","err","String","collection","collectionSlug","forceSetup","whiteLabel","wl","serverProps","settingsSlug","nameField","logoProps","logoField","imageField","iconProps","iconField","creditOn","credit","creditProps","text","url","components","graphics","Icon","path","Logo","afterLogin","variant","afterNavLinks","titleSuffix","meta","localization","access","seo","forms","systemPageFields","pages","content","slug","globals","additionalFields","siteSettingsFields","integrationsFields","endpoints","incomingOnInit","onInit","payload","logger","info"],"mappings":"AAIA,SAASA,mBAAmB,QAAQ,oCAAmC;AACvE,SAASC,kBAAkB,QAAQ,mCAAkC;AACrE,SAASC,qBAAqB,QAAQ,sCAAqC;AAC3E,SAASC,iBAAiB,QAAQ,kCAAiC;AACnE,SAASC,WAAW,QAAQ,4BAA2B;AACvD,SAASC,kBAAkB,QAAQ,6BAA4B;AAC/D,SAAS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iB;QACjB,IAAIjD,QAAQkD,GAAG,EAAE;YACf9C,SAAS,MAAMR,eAAe;gBAAEsD,KAAKlD,QAAQkD,GAAG;YAAC,GAAG9C;YACpD,qDAAqD;YACrDA,SAASP,mBAAmBO,QAAQJ,QAAQkD,GAAG;YAC/C,uEAAuE;YACvE,kEAAkE;YAClE9C,SAASN,cAAcM,QAAQJ,QAAQkD,GAAG;QAC5C;QAEA,gEAAgE;QAChE,IAAIlD,QAAQmD,KAAK,EAAE;YACjB/C,SAAS,MAAMZ,iBAAiBQ,QAAQmD,KAAK,EAAE/C;QACjD;QAEA,kBAAkB;QAClB,mEAAmE;QACnE,4EAA4E;QAC5E,uDAAuD;QACvD,MAAMgD,mBAAmB;eACnBpD,QAAQqD,KAAK,GAAG1D,uBAAuBK,QAAQqD,KAAK,IAAI,EAAE;eAC1DrD,QAAQsD,OAAO,IAAItD,QAAQqD,KAAK,GAChC/D,mBAAmBU,QAAQsD,OAAO,EAAEtD,QAAQqD,KAAK,CAACE,IAAI,IACtD,EAAE;SACP;QAEDnD,OAAOoD,OAAO,GAAG;eACXpD,OAAOoD,OAAO,IAAI,EAAE;YACxBpE,kBAAkB;gBAChBqE,kBAAkBzD,QAAQ0D,kBAAkB;gBAC5CN;YACF;YACAjE,sBAAsB;gBAAEsE,kBAAkBzD,QAAQ2D,kBAAkB;YAAC;YACrE1E;YACAC;SACD;QAEDkB,OAAOwD,SAAS,GAAG;eAAKxD,OAAOwD,SAAS,IAAI,EAAE;YAAGrE;SAAkB;QAEnE,wBAAwB;QACxB,MAAMsE,iBAAiBzD,OAAO0D,MAAM;QACpC1D,OAAO0D,MAAM,GAAG,OAAOC;YACrB,IAAIF,gBAAgB;gBAAC,MAAMA,eAAeE;YAAQ;YAClDA,QAAQC,MAAM,CAACC,IAAI,CAAC;QACtB;QAEA,OAAO7D;IACT;AACF,EAAC"} \ No newline at end of file +{"version":3,"sources":["../src/plugin.ts"],"sourcesContent":["import type { Config, Plugin } from 'payload'\n\nimport type { IpalOptions, TotpPluginFactory } from './types.js'\n\nimport { buildCookieSettings } from './globals/CookieSettings/index.js'\nimport { buildNotifications } from './globals/Notifications/index.js'\nimport { buildSiteIntegrations } from './globals/SiteIntegrations/index.js'\nimport { buildSiteSettings } from './globals/SiteSettings/index.js'\nimport { injectRoles } from './modules/access/index.js'\nimport { buildArchiveFields } from './modules/content/index.js'\nimport { testEmailEndpoint } from './modules/email/test/testEmailEndpoint.js'\nimport { buildFormsPlugin } from './modules/forms/formsPluginConfig.js'\nimport { buildLocalizationConfig, validateI18nConfig } from './modules/i18n/index.js'\nimport { buildSystemPagesFields } from './modules/pages/index.js'\nimport { buildSeoPlugin, injectAutoFillMeta, injectSeoTabs } from './modules/seo/index.js'\n\n/**\n * IPAL (Intecion Payload Advanced Library) plugin for Payload CMS 3.\n *\n * @example\n * ```ts\n * import { ipalKit } from 'ipal-kit'\n *\n * export default buildConfig({\n * plugins: [\n * ipalKit({\n * i18n: {\n * locales: [\n * { code: 'pl', label: 'Polski' },\n * { code: 'en', label: 'English' },\n * ],\n * defaultLocale: 'pl',\n * },\n * access: { authCollection: 'users' },\n * }),\n * ],\n * })\n * ```\n */\nexport const ipalKit = (options: IpalOptions): Plugin => {\n // Validate eagerly — fail fast before Payload boots\n validateI18nConfig(options.i18n)\n\n return async (incomingConfig: Config): Promise => {\n // Early return when disabled — schema stays, behavior off\n if (options.enabled === false) {\n return incomingConfig\n }\n\n let config = { ...incomingConfig }\n\n // --- custom admin route (e.g. '/its' instead of '/admin') ---\n // Sets config.routes.admin; the project must move its app/(payload)//\n // folder to match (plugin can't create files in the project's app/).\n if (options.adminRoute) {\n config.routes = { ...(config.routes ?? {}), admin: options.adminRoute }\n }\n\n // --- enforced 2FA (TOTP) via @clocklimited/payload-2fa ---\n // Enforced by default (forceSetup) unless twoFactor is explicitly false. The\n // plugin is a PEER dependency imported dynamically — ipal-kit doesn't bundle\n // it, so projects that opt out (twoFactor: false) needn't install it, and the\n // import never runs under generate:importmap when 2FA is off. Wrapping access\n // control (not just admin UI) means TOTP gates data access — no API bypass.\n if (options.twoFactor !== false) {\n const tf = options.twoFactor\n if (!tf?.issuer) {\n throw new Error(\n '[ipal] twoFactor.issuer is required (name shown in the authenticator ' +\n 'app). Pass twoFactor: { issuer: \"Your Site\" }, or twoFactor: false to ' +\n 'opt out (discouraged).',\n )\n }\n // Prefer the INJECTED plugin factory (recommended): the project imports\n // payloadTotp from @clocklimited/payload-2fa and passes it in. Then the\n // plugin never imports the optional peer itself — no dynamic import, so\n // Next can't fail to bundle it (the cause of \"Cannot find module\n // '@clocklimited/payload-2fa'\" crashing even public frontend pages).\n let totp: TotpPluginFactory | undefined = tf.plugin\n\n if (!totp) {\n // Fallback: dynamic import. Variable specifier dodges the plugin's own\n // TS2307, but Next may NOT trace it into the server bundle — projects\n // using this path MUST add '@clocklimited/payload-2fa' to\n // serverExternalPackages in next.config (see docs/security.md).\n try {\n const pkg = '@clocklimited/payload-2fa'\n const mod = (await import(pkg)) as {\n payloadTotp?: TotpPluginFactory\n totpPlugin?: TotpPluginFactory\n }\n totp = mod.payloadTotp ?? mod.totpPlugin\n } catch (err) {\n throw new Error(\n '[ipal] 2FA is enforced but @clocklimited/payload-2fa could not be loaded. ' +\n 'Best fix — inject it: `import { payloadTotp } from \"@clocklimited/payload-2fa\"` ' +\n 'then `twoFactor: { issuer, plugin: payloadTotp }`. Or install it AND add ' +\n \"'@clocklimited/payload-2fa' to serverExternalPackages in next.config. Or set \" +\n `twoFactor: false to opt out (discouraged). Original error: ${String(err)}`,\n )\n }\n }\n\n if (typeof totp !== 'function') {\n throw new Error(\n '[ipal] 2FA: expected payloadTotp (or totpPlugin) to be a function — check the ' +\n 'injected `plugin` or the installed @clocklimited/payload-2fa version.',\n )\n }\n\n config = await totp({\n collection: tf.collectionSlug ?? 'users',\n forceSetup: true, // ENFORCED — every user must set up TOTP; no opt-out\n totp: { issuer: tf.issuer },\n })(config)\n }\n\n // --- white-label admin branding ---\n // Inject admin.components.graphics.Logo/Icon pointing at the plugin's\n // /admin export. The components read SiteSettings at render, so each client\n // sees their own brand from the panel (no brand in code). Project must run\n // `pnpm generate:importmap` so Payload resolves the component paths.\n if (options.whiteLabel) {\n const wl = options.whiteLabel === true ? {} : options.whiteLabel\n const serverProps: Record = {}\n if (wl.settingsSlug) {serverProps.settingsSlug = wl.settingsSlug}\n if (wl.nameField) {serverProps.nameField = wl.nameField}\n const logoProps = { ...serverProps, ...(wl.logoField ? { imageField: wl.logoField } : {}) }\n const iconProps = { ...serverProps, ...(wl.iconField ? { imageField: wl.iconField } : {}) }\n\n // Vendor credit (\"Technology by Intecion.com\") under the nav — on by\n // default, hidden with credit:false, text/url overridable.\n const creditOn = wl.credit !== false\n const creditProps =\n wl.credit && typeof wl.credit === 'object'\n ? {\n ...(wl.credit.text ? { text: wl.credit.text } : {}),\n ...(wl.credit.url ? { url: wl.credit.url } : {}),\n }\n : {}\n\n config.admin = {\n ...(config.admin ?? {}),\n components: {\n ...(config.admin?.components ?? {}),\n graphics: {\n ...(config.admin?.components?.graphics ?? {}),\n Icon: { path: '@intecion/ipal-kit/admin#AdminIcon', serverProps: iconProps },\n Logo: { path: '@intecion/ipal-kit/admin#AdminLogo', serverProps: logoProps },\n },\n ...(creditOn\n ? {\n afterLogin: [\n ...(config.admin?.components?.afterLogin ?? []),\n {\n path: '@intecion/ipal-kit/admin#IntecionCredit',\n serverProps: { ...creditProps, variant: 'login' },\n },\n ],\n afterNavLinks: [\n ...(config.admin?.components?.afterNavLinks ?? []),\n {\n path: '@intecion/ipal-kit/admin#IntecionCredit',\n serverProps: { ...creditProps, variant: 'nav' },\n },\n ],\n }\n : {}),\n },\n ...(wl.titleSuffix\n ? { meta: { ...(config.admin?.meta ?? {}), titleSuffix: wl.titleSuffix } }\n : {}),\n }\n }\n\n // --- i18n ---\n config.localization = buildLocalizationConfig(options.i18n)\n\n // --- access: inject roles into the client's auth collection ---\n if (options.access) {\n config = injectRoles(config, options.access)\n }\n\n // --- seo: apply @payloadcms/plugin-seo directly ---\n // NOTE: apply the plugin function to the config immediately rather than\n // pushing it onto config.plugins. Payload has already iterated the plugins\n // array by the time IPAL runs, so nested plugins added to that list are\n // never executed. Calling the plugin as (config) => config applies its\n // transform now.\n if (options.seo) {\n config = await buildSeoPlugin({ seo: options.seo })(config)\n // Auto-fill empty meta from document content on save\n config = injectAutoFillMeta(config, options.seo)\n // Wrap fields into Content + SEO tabs (replaces plugin-seo's tabbedUI,\n // which breaks when other fields already exist in the collection)\n config = injectSeoTabs(config, options.seo)\n }\n\n // --- forms: apply @payloadcms/plugin-form-builder directly ---\n if (options.forms) {\n config = await buildFormsPlugin(options.forms)(config)\n }\n\n // --- globals ---\n // The System Pages tab collects every \"which page plays this role\"\n // assignment. Composing it here keeps SiteSettings unaware of which modules\n // are enabled — it just renders the fields it's given.\n const systemPageFields = [\n ...(options.pages ? buildSystemPagesFields(options.pages) : []),\n ...(options.content && options.pages\n ? buildArchiveFields(options.content, options.pages.slug)\n : []),\n ]\n\n config.globals = [\n ...(config.globals ?? []),\n buildSiteSettings({\n additionalFields: options.siteSettingsFields,\n systemPageFields,\n }),\n buildSiteIntegrations({ additionalFields: options.integrationsFields }),\n buildCookieSettings(),\n buildNotifications(),\n ]\n\n config.endpoints = [...(config.endpoints ?? []), testEmailEndpoint]\n\n // --- integration alerts on the dashboard (Turnstile status, …) ---\n // Renders nothing while everything works; never throws.\n config.admin = {\n ...(config.admin ?? {}),\n components: {\n ...(config.admin?.components ?? {}),\n beforeDashboard: [\n ...(config.admin?.components?.beforeDashboard ?? []),\n {\n path: '@intecion/ipal-kit/admin#IntegrationAlerts',\n serverProps: { adminRoute: options.adminRoute ?? '/admin' },\n },\n ],\n },\n }\n\n // --- hooks: onInit ---\n const incomingOnInit = config.onInit\n config.onInit = async (payload) => {\n if (incomingOnInit) {await incomingOnInit(payload)}\n payload.logger.info('[ipal] Plugin initialized.')\n }\n\n return config\n }\n}\n"],"names":["buildCookieSettings","buildNotifications","buildSiteIntegrations","buildSiteSettings","injectRoles","buildArchiveFields","testEmailEndpoint","buildFormsPlugin","buildLocalizationConfig","validateI18nConfig","buildSystemPagesFields","buildSeoPlugin","injectAutoFillMeta","injectSeoTabs","ipalKit","options","i18n","incomingConfig","enabled","config","adminRoute","routes","admin","twoFactor","tf","issuer","Error","totp","plugin","pkg","mod","payloadTotp","totpPlugin","err","String","collection","collectionSlug","forceSetup","whiteLabel","wl","serverProps","settingsSlug","nameField","logoProps","logoField","imageField","iconProps","iconField","creditOn","credit","creditProps","text","url","components","graphics","Icon","path","Logo","afterLogin","variant","afterNavLinks","titleSuffix","meta","localization","access","seo","forms","systemPageFields","pages","content","slug","globals","additionalFields","siteSettingsFields","integrationsFields","endpoints","beforeDashboard","incomingOnInit","onInit","payload","logger","info"],"mappings":"AAIA,SAASA,mBAAmB,QAAQ,oCAAmC;AACvE,SAASC,kBAAkB,QAAQ,mCAAkC;AACrE,SAASC,qBAAqB,QAAQ,sCAAqC;AAC3E,SAASC,iBAAiB,QAAQ,kCAAiC;AACnE,SAASC,WAAW,QAAQ,4BAA2B;AACvD,SAASC,kBAAkB,QAAQ,6BAA4B;AAC/D,SAASC,iBAAiB,QAAQ,4CAA2C;AAC7E,SAASC,gBAAgB,QAAQ,uCAAsC;AACvE,SAASC,uBAAuB,EAAEC,kBAAkB,QAAQ,0BAAyB;AACrF,SAASC,sBAAsB,QAAQ,2BAA0B;AACjE,SAASC,cAAc,EAAEC,kBAAkB,EAAEC,aAAa,QAAQ,yBAAwB;AAE1F;;;;;;;;;;;;;;;;;;;;;;CAsBC,GACD,OAAO,MAAMC,UAAU,CAACC;IACtB,oDAAoD;IACpDN,mBAAmBM,QAAQC,IAAI;IAE/B,OAAO,OAAOC;QACZ,0DAA0D;QAC1D,IAAIF,QAAQG,OAAO,KAAK,OAAO;YAC7B,OAAOD;QACT;QAEA,IAAIE,SAAS;YAAE,GAAGF,cAAc;QAAC;QAEjC,+DAA+D;QAC/D,6EAA6E;QAC7E,qEAAqE;QACrE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1DrD,QAAQsD,OAAO,IAAItD,QAAQqD,KAAK,GAChC/D,mBAAmBU,QAAQsD,OAAO,EAAEtD,QAAQqD,KAAK,CAACE,IAAI,IACtD,EAAE;SACP;QAEDnD,OAAOoD,OAAO,GAAG;eACXpD,OAAOoD,OAAO,IAAI,EAAE;YACxBpE,kBAAkB;gBAChBqE,kBAAkBzD,QAAQ0D,kBAAkB;gBAC5CN;YACF;YACAjE,sBAAsB;gBAAEsE,kBAAkBzD,QAAQ2D,kBAAkB;YAAC;YACrE1E;YACAC;SACD;QAEDkB,OAAOwD,SAAS,GAAG;eAAKxD,OAAOwD,SAAS,IAAI,EAAE;YAAGrE;SAAkB;QAEnE,oEAAoE;QACpE,wDAAwD;QACxDa,OAAOG,KAAK,GAAG;YACb,GAAIH,OAAOG,KAAK,IAAI,CAAC,CAAC;YACtB+B,YAAY;gBACV,GAAIlC,OAAOG,KAAK,EAAE+B,cAAc,CAAC,CAAC;gBAClCuB,iBAAiB;uBACXzD,OAAOG,KAAK,EAAE+B,YAAYuB,mBAAmB,EAAE;oBACnD;wBACEpB,MAAM;wBACNhB,aAAa;4BAAEpB,YAAYL,QAAQK,UAAU,IAAI;wBAAS;oBAC5D;iBACD;YACH;QACF;QAEA,wBAAwB;QACxB,MAAMyD,iBAAiB1D,OAAO2D,MAAM;QACpC3D,OAAO2D,MAAM,GAAG,OAAOC;YACrB,IAAIF,gBAAgB;gBAAC,MAAMA,eAAeE;YAAQ;YAClDA,QAAQC,MAAM,CAACC,IAAI,CAAC;QACtB;QAEA,OAAO9D;IACT;AACF,EAAC"} \ No newline at end of file diff --git a/docs/agent/skills/ipal-debug/SKILL.md b/docs/agent/skills/ipal-debug/SKILL.md index fbcd8c0..ffd3a71 100644 --- a/docs/agent/skills/ipal-debug/SKILL.md +++ b/docs/agent/skills/ipal-debug/SKILL.md @@ -78,7 +78,7 @@ tej procedury. Pytasz tylko, gdy brakuje czegoś, czego nie możesz uzyskać sam | maile nie wychodzą | brak `email: mailAdapter()` / pusty transport / pusta zakładka Emails | email.md; Send test w panelu | | nadawca maila stary | cache klienta poczty | sprawdź surowe nagłówki | | formularz: `unknown_fields` | pole spoza definicji (honeypot nieusunięty) | `ipal-form` → actions.ts | -| Turnstile zawsze odrzuca | token użyty drugi raz / zła domena w Cloudflare | reset tokenu po każdej próbie; domena w CF | +| Turnstile zawsze odrzuca | log `[ipal] Turnstile …` mówi dlaczego: brak sekretu, `invalid-input-secret`, `timeout-or-duplicate` | turnstile.md → tabela; sekret w panelu albo `TURNSTILE_SECRET_KEY`; **nie** zapisuj sekretu kodem | ### Środowisko | Objaw | Przyczyna | Naprawa | diff --git a/docs/agent/skills/ipal-form/SKILL.md b/docs/agent/skills/ipal-form/SKILL.md index 4d15ee5..882c7c5 100644 --- a/docs/agent/skills/ipal-form/SKILL.md +++ b/docs/agent/skills/ipal-form/SKILL.md @@ -82,7 +82,7 @@ Zapytanie strony: `depth` ≥ 1 (relacja `form` jako obiekt). Rejestr bloków: (Send test w panelu działa = transport OK; brak maila mimo to → zakładka Emails formularza); - [ ] niezaznaczona zgoda → komunikat z Notifications (nie angielski fallback); - [ ] 6 szybkich wysyłek → `rate_limited`; -- [ ] Turnstile z kluczami → widget widoczny, wysyłka bez tokenu odrzucona; +- [ ] Turnstile z kluczami → widget widoczny; zły sekret → formularz przechodzi, a w panelu (dashboard + Site Integrations → Turnstile) jest czerwony alert; - [ ] drugi język → etykiety i komunikaty w tym języku; - [ ] GTM Preview → zdarzenie z nazwą z panelu po sukcesie; - [ ] `ipal-audit --quick` → zero hardkodów w FormRenderer/FormBlock; diff --git a/docs/dev/PROGRAMISTA.md b/docs/dev/PROGRAMISTA.md index 7d5c660..241f0ac 100644 --- a/docs/dev/PROGRAMISTA.md +++ b/docs/dev/PROGRAMISTA.md @@ -490,6 +490,9 @@ Rób po jednej pozycji, buduj, sprawdzaj. Kolejność wg wagi: | 15g | `instrumentation.ts` importuje z roota (crash Edge/Turbopack: `fileTypeFromFile`) | `import { assertEnv, ipalEnvRules } from '@intecion/ipal-kit/env'` + `if (process.env.NEXT_RUNTIME !== 'nodejs') return`; usuń dynamiczny `await import` | env.md | | 15h | `` w panelu = XSS) | seo.md | | 15i | własne formuły `clamp()` w `styles.css` | `@import "@intecion/ipal-kit/fluid.css"` + mapowanie w `@theme` (§2.5) | — | +| 15j | front formularza wysyła `fetch('/api/form-submissions')` (od tej wersji REST zwraca 403 dla anonimów) | przepisz na server action + `submitForm` (skill `ipal-form`) | forms.md | +| 15k | sekret Turnstile zapisywany kodem (`updateGlobal` w `onInit` / akcji) albo własny `verify` bez `remoteip` | usuń obejście: sekret w panelu albo env `TURNSTILE_SECRET_KEY`; plugin nie wysyła `remoteip` i loguje przyczynę odrzucenia | turnstile.md | +| 15l | awaria Turnstile blokowała formularze | nic w projekcie: plugin przy błędzie po naszej stronie przyjmuje zgłoszenie i pokazuje alert w panelu; `generate:importmap`, Postgres: `migrate:create` | turnstile.md | | 16 | 404 na sztywno | rola 404 w System Pages + `getNotFoundPage` | pages.md | | 16a | `privacyPolicy: { label: 'Polityka prywatności', … }` w layoucie | usuń cały parametr; tekst wpisz w Cookie Settings → Privacy link label | consent.md | | 17 | Opcjonalnie — AI/GEO | Markdown per strona, llms-full, boty AI w robots, MCP, wyszukiwarka, speakable, aiSummary | content.md, seo.md, mcp.md | diff --git a/docs/turnstile.md b/docs/turnstile.md index abac87e..5e1230c 100644 --- a/docs/turnstile.md +++ b/docs/turnstile.md @@ -52,9 +52,51 @@ if (!ok) { } ``` -`verifyTurnstile` czyta secret z SiteIntegrations (Local API), woła Cloudflare. -Zwraca `false` na każdy problem (brak klucza, sieć, odrzucenie) — traktuj -`false` jako „nie ufaj temu zgłoszeniu". `server-only` gwarantuje, że nie +`verifyTurnstile` czyta secret z SiteIntegrations (Local API), a gdy pole jest +puste — ze zmiennej **`TURNSTILE_SECRET_KEY`** (ta sama, której wymaga +`ipalEnvRules({ turnstile: true })`). Zwraca `false` na każdy problem i **loguje +przyczynę** w logach serwera: + +| Log | Przyczyna | +|---|---| +| `[ipal] Turnstile: no secret key …` | brak sekretu w panelu i w env (log raz na proces) | +| `Turnstile rejected: invalid-input-secret` | zły sekret albo para site key / secret z różnych widgetów | +| `Turnstile rejected: timeout-or-duplicate` | token użyty drugi raz albo starszy niż 300 s — `reset()` po każdej próbie | +| `Turnstile rejected: invalid-input-response` | uszkodzony / pusty token z frontu | +| `siteverify request failed` | brak wyjścia do `challenges.cloudflare.com` z kontenera | + +### Awaria po naszej stronie ≠ odrzucenie formularza + +`checkTurnstile` (z `/server`) klasyfikuje wynik: + +| Wynik | Kiedy | `submitForm` (domyślnie) | +|---|---|---| +| `pass` | token poprawny | przyjmuje | +| `reject` | zły token **odwiedzającego**: `invalid-input-response`, `timeout-or-duplicate`, brak tokenu | **odrzuca** (`reason: 'turnstile'`) | +| `degraded` | błąd **po naszej stronie**: brak sekretu, `invalid-input-secret`, Cloudflare nieosiągalny / `internal-error` | **przyjmuje** — limit, honeypot i walidacja dalej działają | + +Przy `degraded` panel pokazuje problem: +- **Dashboard** — czerwony alert „Integration problem…” z linkiem do Site Integrations + (`admin.components.beforeDashboard`, wpinany przez plugin automatycznie), +- **Site Integrations → Turnstile** — baner z przyczyną, kodem i czasem. + +Status zapisuje serwer przy weryfikacji formularza (bez crona), najwyżej raz na 10 min +przy trwającym błędzie i od razu przy zmianie stanu. Zapis nowych kluczy w panelu +czyści status; po następnym wysłaniu formularza pojawi się aktualny. +Twardo (fail closed): `submitForm({ …, turnstileOnConfigError: 'reject' })`. + +Po aktualizacji pluginu: `pnpm payload generate:importmap` (nowe komponenty panelu); +Postgres: `pnpm payload migrate:create` (pole `turnstileStatus` w SiteIntegrations). + +`remoteip` **nie jest** wysyłany domyślnie — za Cloudflare/Traefikiem/Dockerem IP +widziane przez aplikację bywa inne niż to, z którego rozwiązano wyzwanie (IPv6 na +telefonie vs IPv4 proxy). Włączenie: `verifyTurnstile({ …, sendRemoteIp: true })`. + +**Diagnoza „formularz zawsze odrzuca Turnstile”:** najpierw logi serwera (tabela +wyżej), potem czy sekret jest w bazie: +`docker exec mongosh --eval 'db["site-integrations"].findOne({}, {turnstileSecretKey:1})'`. +Nie zapisuj sekretu kodem (`updateGlobal` w `onInit` / akcji) — nadpisuje panel przy +każdym starcie; jeśli wolisz env, ustaw `TURNSTILE_SECRET_KEY` i zostaw pole puste. `server-only` gwarantuje, że nie trafi do bundla przeglądarki. > W formularzach zwykle nie wołasz `verifyTurnstile` wprost — robi to diff --git a/src/exports/admin.ts b/src/exports/admin.ts index a00d6ea..c04efe3 100644 --- a/src/exports/admin.ts +++ b/src/exports/admin.ts @@ -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' diff --git a/src/exports/client.ts b/src/exports/client.ts index a36e4de..9c7cb8c 100644 --- a/src/exports/client.ts +++ b/src/exports/client.ts @@ -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' diff --git a/src/exports/server.ts b/src/exports/server.ts index 261bf93..1964906 100644 --- a/src/exports/server.ts +++ b/src/exports/server.ts @@ -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' diff --git a/src/globals/SiteIntegrations/fields/turnstile.ts b/src/globals/SiteIntegrations/fields/turnstile.ts index 49d4d84..0fd084f 100644 --- a/src/globals/SiteIntegrations/fields/turnstile.ts +++ b/src/globals/SiteIntegrations/fields/turnstile.ts @@ -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'), ] diff --git a/src/globals/SiteIntegrations/index.ts b/src/globals/SiteIntegrations/index.ts index cd886f0..c63e31c 100644 --- a/src/globals/SiteIntegrations/index.ts +++ b/src/globals/SiteIntegrations/index.ts @@ -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', } } diff --git a/src/index.ts b/src/index.ts index 2ca3d3b..64c33d1 100644 --- a/src/index.ts +++ b/src/index.ts @@ -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' diff --git a/src/modules/forms/submitForm.ts b/src/modules/forms/submitForm.ts index 455c16d..561497e 100644 --- a/src/modules/forms/submitForm.ts +++ b/src/modules/forms/submitForm.ts @@ -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 { // 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 } } diff --git a/src/modules/integrations/IntegrationAlerts.tsx b/src/modules/integrations/IntegrationAlerts.tsx new file mode 100644 index 0000000..c2243aa --- /dev/null +++ b/src/modules/integrations/IntegrationAlerts.tsx @@ -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 + /** 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 + try { + doc = (await payload.findGlobal({ slug: 'site-integrations' as never, depth: 0 })) as Record + } 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 ( +
+ Integration problem — the site still works, but a safeguard is off. +
    + {failing.map(({ label, status }) => ( +
  • + {label}: {status?.message ?? status?.code ?? 'error'} +
  • + ))} +
+ + Open Site Integrations → + +
+ ) +} + +export default IntegrationAlerts diff --git a/src/modules/integrations/IntegrationStatusBanner.tsx b/src/modules/integrations/IntegrationStatusBanner.tsx new file mode 100644 index 0000000..9e0ff18 --- /dev/null +++ b/src/modules/integrations/IntegrationStatusBanner.tsx @@ -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 ( +
+ ✓ {label} working{since ? ` since ${fmt(since)}` : ''}. +
+ ) + } + + return ( +
+ {label} is not working — forms are accepted without this check. + {message ?
{message}
: null} +
+ {code ? `Code: ${code}. ` : ''} + {since ? `Since ${fmt(since)}. ` : ''} + {checkedAt ? `Last seen ${fmt(checkedAt)}.` : ''} +
+
+ Fix the keys below and save — the status is checked again on the next form submission. +
+
+ ) +} + +export default IntegrationStatusBanner diff --git a/src/modules/integrations/index.ts b/src/modules/integrations/index.ts new file mode 100644 index 0000000..b84f1b0 --- /dev/null +++ b/src/modules/integrations/index.ts @@ -0,0 +1,6 @@ +export { + buildIntegrationStatusBanner, + buildIntegrationStatusField, + recordIntegrationStatus, +} from './status.js' +export type { IntegrationState, IntegrationStatus } from './status.js' diff --git a/src/modules/integrations/status.ts b/src/modules/integrations/status.ts new file mode 100644 index 0000000..601c90d --- /dev/null +++ b/src/modules/integrations/status.ts @@ -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 { + 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) + } +} diff --git a/src/modules/turnstile/index.ts b/src/modules/turnstile/index.ts index 98b88e4..6ec7812 100644 --- a/src/modules/turnstile/index.ts +++ b/src/modules/turnstile/index.ts @@ -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' diff --git a/src/modules/turnstile/verify.ts b/src/modules/turnstile/verify.ts index 209b6a5..15532a8 100644 --- a/src/modules/turnstile/verify.ts +++ b/src/modules/turnstile/verify.ts @@ -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 = { + '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 = { + '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 { - if (!token) {return false} +}: Omit): Promise { + if (!token) {return { code: 'missing-input-response', outcome: 'reject' }} const integrations = await getSiteIntegrations(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 => { + 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 { + const { outcome } = await checkTurnstile(args) + return outcome === 'pass' || (outcome === 'degraded' && onConfigError === 'allow') } diff --git a/src/plugin.ts b/src/plugin.ts index e3e3721..88d7795 100644 --- a/src/plugin.ts +++ b/src/plugin.ts @@ -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) => {