Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
eb436528d4 | ||
|
|
70b676660d | ||
|
|
7dc93ac5ed | ||
|
|
3bab8a0697 | ||
|
|
7ef7927e38 | ||
|
|
a7846d9770 |
Vendored
+3
-2
@@ -1,4 +1,3 @@
|
||||
export { RowLabel } from '../modules/admin-ui/RowLabelComponent.js';
|
||||
/**
|
||||
* Entry point: @intecion/ipal-kit/admin
|
||||
*
|
||||
@@ -6,4 +5,6 @@ export { RowLabel } from '../modules/admin-ui/RowLabelComponent.js';
|
||||
* importMap can resolve them by a stable path when ipalKit injects
|
||||
* admin.components.graphics.Logo/Icon.
|
||||
*/
|
||||
export { AdminIcon, AdminLogo, IntecionCredit } from '../modules/branding/index.js';
|
||||
export { AdminLogo, AdminIcon, IntecionCredit } from '../modules/branding/index.js';
|
||||
export { RowLabel } from '../modules/admin-ui/RowLabelComponent.js';
|
||||
export { IntegrationAlerts } from '../modules/integrations/IntegrationAlerts.js';
|
||||
|
||||
Vendored
+3
-2
@@ -1,10 +1,11 @@
|
||||
export { RowLabel } from '../modules/admin-ui/RowLabelComponent.js';
|
||||
/**
|
||||
* Entry point: @intecion/ipal-kit/admin
|
||||
*
|
||||
* Admin-panel UI components (white-label branding, array row labels). Separate export so Payload's
|
||||
* importMap can resolve them by a stable path when ipalKit injects
|
||||
* admin.components.graphics.Logo/Icon.
|
||||
*/ export { AdminIcon, AdminLogo, IntecionCredit } from '../modules/branding/index.js';
|
||||
*/ export { AdminLogo, AdminIcon, IntecionCredit } from '../modules/branding/index.js';
|
||||
export { RowLabel } from '../modules/admin-ui/RowLabelComponent.js';
|
||||
export { IntegrationAlerts } from '../modules/integrations/IntegrationAlerts.js';
|
||||
|
||||
//# sourceMappingURL=admin.js.map
|
||||
Vendored
+1
-1
@@ -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"}
|
||||
{"version":3,"sources":["../../src/exports/admin.ts"],"sourcesContent":["/**\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 { AdminLogo, AdminIcon, IntecionCredit } from '../modules/branding/index.js'\nexport { RowLabel } from '../modules/admin-ui/RowLabelComponent.js'\nexport { IntegrationAlerts } from '../modules/integrations/IntegrationAlerts.js'\n"],"names":["AdminLogo","AdminIcon","IntecionCredit","RowLabel","IntegrationAlerts"],"mappings":"AAAA;;;;;;CAMC,GACD,SAASA,SAAS,EAAEC,SAAS,EAAEC,cAAc,QAAQ,+BAA8B;AACnF,SAASC,QAAQ,QAAQ,2CAA0C;AACnE,SAASC,iBAAiB,QAAQ,+CAA8C"}
|
||||
Vendored
+24
-23
@@ -1,11 +1,3 @@
|
||||
export { MaskedField } from '../globals/SiteIntegrations/components/MaskedField.js';
|
||||
export { TestEmailButton } from '../globals/SiteIntegrations/components/TestEmailButton.js';
|
||||
export { AccessibilityProvider, AccessibilityWidget, useAccessibility } from '../modules/accessibility/client.js';
|
||||
export type { A11yClassNames, A11yState, A11yTexts } from '../modules/accessibility/client.js';
|
||||
export { Analytics } from '../modules/analytics/client.js';
|
||||
export type { AnalyticsProps } from '../modules/analytics/client.js';
|
||||
export { pushDataLayer } from '../modules/analytics/client.js';
|
||||
export { loadClarity, loadLinkedIn, loadMetaPixel, loadTikTok } from '../modules/analytics/client.js';
|
||||
/**
|
||||
* Entry point: ipal-kit/client
|
||||
*
|
||||
@@ -13,22 +5,31 @@ export { loadClarity, loadLinkedIn, loadMetaPixel, loadTikTok } from '../modules
|
||||
* components. Kept separate from the main entry so server bundles don't pull in
|
||||
* client-only code.
|
||||
*/
|
||||
export { ConsentProvider, ConsentScript, CookieBanner, CookieButton, useConsent, useConsentContext, } from '../modules/consent/client.js';
|
||||
export { useConsent, ConsentProvider, useConsentContext, CookieBanner, CookieButton, ConsentScript, } from '../modules/consent/client.js';
|
||||
export type { CookieBannerClassNames } from '../modules/consent/client.js';
|
||||
export { formAnalyticsOnSuccess } from '../modules/forms/formAnalytics.js';
|
||||
export type { FormAnalyticsConfig } from '../modules/forms/formAnalytics.js';
|
||||
export { HONEYPOT_FIELD, honeypotInputProps, isHoneypotTripped } from '../modules/forms/honeypot.js';
|
||||
export { useContactForm } from '../modules/forms/useContactForm.js';
|
||||
export type { ContactFormErrors, ContactFormValues, SubmitAction } from '../modules/forms/useContactForm.js';
|
||||
export { useForm } from '../modules/forms/useForm.js';
|
||||
export type { FormErrors, FormSubmitAction, Validator } from '../modules/forms/useForm.js';
|
||||
export { buildValidator, checked, custom, email, isEmail, maxLength, minLength, pattern, required, } from '../modules/forms/validators.js';
|
||||
export type { Rule } from '../modules/forms/validators.js';
|
||||
export { buildLocalizedPath, getLocaleCodes, getLocalizedSlugs, switchLocalePath, } from '../modules/i18n/index.js';
|
||||
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 { LocaleView } from '../modules/pages/LocaleView.js';
|
||||
export { Turnstile } from '../modules/turnstile/client.js';
|
||||
export { TurnstileProvider, useTurnstile } from '../modules/turnstile/client.js';
|
||||
export { AccessibilityProvider, useAccessibility, AccessibilityWidget } from '../modules/accessibility/client.js';
|
||||
export type { A11yState, A11yTexts, A11yClassNames } from '../modules/accessibility/client.js';
|
||||
export { switchLocalePath, buildLocalizedPath, getLocalizedSlugs, getLocaleCodes, } from '../modules/i18n/index.js';
|
||||
export type { LocalizedSlugs, I18nConfig } from '../modules/i18n/index.js';
|
||||
export type { TurnstileProps } from '../modules/turnstile/client.js';
|
||||
export { LocaleView } from '../modules/pages/LocaleView.js';
|
||||
export { Analytics } from '../modules/analytics/client.js';
|
||||
export type { AnalyticsProps } from '../modules/analytics/client.js';
|
||||
export { pushDataLayer } from '../modules/analytics/client.js';
|
||||
export { loadMetaPixel, loadClarity, loadLinkedIn, loadTikTok } from '../modules/analytics/client.js';
|
||||
export { MaskedField } from '../globals/SiteIntegrations/components/MaskedField.js';
|
||||
export { IntegrationStatusBanner } from '../modules/integrations/IntegrationStatusBanner.js';
|
||||
export { TestEmailButton } from '../globals/SiteIntegrations/components/TestEmailButton.js';
|
||||
export { AlternateLinksProvider, useAlternateLinks, useSetAlternateLinks, AlternateLinksUpdater, LanguageSwitcher, } from '../modules/i18n/index.js';
|
||||
export type { AlternateLinks, LanguageSwitcherClassNames } from '../modules/i18n/index.js';
|
||||
export { useForm } from '../modules/forms/useForm.js';
|
||||
export type { FormErrors, FormSubmitAction, Validator } from '../modules/forms/useForm.js';
|
||||
export { useContactForm } from '../modules/forms/useContactForm.js';
|
||||
export type { ContactFormValues, ContactFormErrors, SubmitAction } from '../modules/forms/useContactForm.js';
|
||||
export { buildValidator, isEmail, required, email, minLength, maxLength, checked, pattern, custom, } from '../modules/forms/validators.js';
|
||||
export type { Rule } from '../modules/forms/validators.js';
|
||||
export { HONEYPOT_FIELD, honeypotInputProps, isHoneypotTripped } from '../modules/forms/honeypot.js';
|
||||
export { formAnalyticsOnSuccess } from '../modules/forms/formAnalytics.js';
|
||||
export type { FormAnalyticsConfig } from '../modules/forms/formAnalytics.js';
|
||||
|
||||
Vendored
+18
-17
@@ -1,28 +1,29 @@
|
||||
'use client';
|
||||
export { MaskedField } from '../globals/SiteIntegrations/components/MaskedField.js';
|
||||
export { TestEmailButton } from '../globals/SiteIntegrations/components/TestEmailButton.js';
|
||||
export { AccessibilityProvider, AccessibilityWidget, useAccessibility } from '../modules/accessibility/client.js';
|
||||
export { Analytics } from '../modules/analytics/client.js';
|
||||
export { pushDataLayer } from '../modules/analytics/client.js';
|
||||
export { loadClarity, loadLinkedIn, loadMetaPixel, loadTikTok } from '../modules/analytics/client.js';
|
||||
/**
|
||||
* Entry point: ipal-kit/client
|
||||
*
|
||||
* Client-side ('use client') exports — React hooks, providers, and UI
|
||||
* components. Kept separate from the main entry so server bundles don't pull in
|
||||
* client-only code.
|
||||
*/ export { ConsentProvider, ConsentScript, CookieBanner, CookieButton, useConsent, useConsentContext } from '../modules/consent/client.js';
|
||||
export { formAnalyticsOnSuccess } from '../modules/forms/formAnalytics.js';
|
||||
export { HONEYPOT_FIELD, honeypotInputProps, isHoneypotTripped } from '../modules/forms/honeypot.js';
|
||||
export { useContactForm } from '../modules/forms/useContactForm.js';
|
||||
export { useForm } from '../modules/forms/useForm.js';
|
||||
export { buildValidator, checked, custom, email, isEmail, maxLength, minLength, pattern, required } from '../modules/forms/validators.js';
|
||||
// Pure i18n path helpers — no server/RSC deps, safe to import in client
|
||||
// components (e.g. a LanguageSwitcher that computes locale URLs on the client).
|
||||
export { buildLocalizedPath, getLocaleCodes, getLocalizedSlugs, switchLocalePath } from '../modules/i18n/index.js';
|
||||
export { AlternateLinksProvider, AlternateLinksUpdater, LanguageSwitcher, useAlternateLinks, useSetAlternateLinks } from '../modules/i18n/index.js';
|
||||
export { LocaleView } from '../modules/pages/LocaleView.js';
|
||||
*/ export { useConsent, ConsentProvider, useConsentContext, CookieBanner, CookieButton, ConsentScript } from '../modules/consent/client.js';
|
||||
export { Turnstile } from '../modules/turnstile/client.js';
|
||||
export { TurnstileProvider, useTurnstile } from '../modules/turnstile/client.js';
|
||||
export { AccessibilityProvider, useAccessibility, AccessibilityWidget } from '../modules/accessibility/client.js';
|
||||
// Pure i18n path helpers — no server/RSC deps, safe to import in client
|
||||
// components (e.g. a LanguageSwitcher that computes locale URLs on the client).
|
||||
export { switchLocalePath, buildLocalizedPath, getLocalizedSlugs, getLocaleCodes } from '../modules/i18n/index.js';
|
||||
export { LocaleView } from '../modules/pages/LocaleView.js';
|
||||
export { Analytics } from '../modules/analytics/client.js';
|
||||
export { pushDataLayer } from '../modules/analytics/client.js';
|
||||
export { loadMetaPixel, loadClarity, loadLinkedIn, loadTikTok } from '../modules/analytics/client.js';
|
||||
export { MaskedField } from '../globals/SiteIntegrations/components/MaskedField.js';
|
||||
export { IntegrationStatusBanner } from '../modules/integrations/IntegrationStatusBanner.js';
|
||||
export { TestEmailButton } from '../globals/SiteIntegrations/components/TestEmailButton.js';
|
||||
export { AlternateLinksProvider, useAlternateLinks, useSetAlternateLinks, AlternateLinksUpdater, LanguageSwitcher } from '../modules/i18n/index.js';
|
||||
export { useForm } from '../modules/forms/useForm.js';
|
||||
export { useContactForm } from '../modules/forms/useContactForm.js';
|
||||
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';
|
||||
export { formAnalyticsOnSuccess } from '../modules/forms/formAnalytics.js';
|
||||
|
||||
//# sourceMappingURL=client.js.map
|
||||
Vendored
+1
-1
@@ -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"}
|
||||
{"version":3,"sources":["../../src/exports/client.ts"],"sourcesContent":["'use client'\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 useConsent,\n ConsentProvider,\n useConsentContext,\n CookieBanner,\n CookieButton,\n ConsentScript,\n} from '../modules/consent/client.js'\nexport type { CookieBannerClassNames } from '../modules/consent/client.js'\nexport { Turnstile } from '../modules/turnstile/client.js'\nexport { TurnstileProvider, useTurnstile } from '../modules/turnstile/client.js'\nexport { AccessibilityProvider, useAccessibility, AccessibilityWidget } from '../modules/accessibility/client.js'\nexport type { A11yState, A11yTexts, A11yClassNames } from '../modules/accessibility/client.js'\n\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 switchLocalePath,\n buildLocalizedPath,\n getLocalizedSlugs,\n getLocaleCodes,\n} from '../modules/i18n/index.js'\nexport type { LocalizedSlugs, I18nConfig } from '../modules/i18n/index.js'\nexport type { TurnstileProps } from '../modules/turnstile/client.js'\nexport { LocaleView } from '../modules/pages/LocaleView.js'\nexport { Analytics } from '../modules/analytics/client.js'\nexport type { AnalyticsProps } from '../modules/analytics/client.js'\nexport { pushDataLayer } from '../modules/analytics/client.js'\nexport { loadMetaPixel, loadClarity, loadLinkedIn, loadTikTok } from '../modules/analytics/client.js'\nexport { MaskedField } from '../globals/SiteIntegrations/components/MaskedField.js'\nexport { IntegrationStatusBanner } from '../modules/integrations/IntegrationStatusBanner.js'\nexport { TestEmailButton } from '../globals/SiteIntegrations/components/TestEmailButton.js'\nexport {\n AlternateLinksProvider,\n useAlternateLinks,\n useSetAlternateLinks,\n AlternateLinksUpdater,\n LanguageSwitcher,\n} from '../modules/i18n/index.js'\nexport type { AlternateLinks, LanguageSwitcherClassNames } from '../modules/i18n/index.js'\nexport { useForm } from '../modules/forms/useForm.js'\nexport type { FormErrors, FormSubmitAction, Validator } from '../modules/forms/useForm.js'\nexport { useContactForm } from '../modules/forms/useContactForm.js'\nexport type { ContactFormValues, ContactFormErrors, SubmitAction } from '../modules/forms/useContactForm.js'\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 { HONEYPOT_FIELD, honeypotInputProps, isHoneypotTripped } from '../modules/forms/honeypot.js'\nexport { formAnalyticsOnSuccess } from '../modules/forms/formAnalytics.js'\nexport type { FormAnalyticsConfig } from '../modules/forms/formAnalytics.js'\n"],"names":["useConsent","ConsentProvider","useConsentContext","CookieBanner","CookieButton","ConsentScript","Turnstile","TurnstileProvider","useTurnstile","AccessibilityProvider","useAccessibility","AccessibilityWidget","switchLocalePath","buildLocalizedPath","getLocalizedSlugs","getLocaleCodes","LocaleView","Analytics","pushDataLayer","loadMetaPixel","loadClarity","loadLinkedIn","loadTikTok","MaskedField","IntegrationStatusBanner","TestEmailButton","AlternateLinksProvider","useAlternateLinks","useSetAlternateLinks","AlternateLinksUpdater","LanguageSwitcher","useForm","useContactForm","buildValidator","isEmail","required","email","minLength","maxLength","checked","pattern","custom","HONEYPOT_FIELD","honeypotInputProps","isHoneypotTripped","formAnalyticsOnSuccess"],"mappings":"AAAA;AACA;;;;;;CAMC,GACD,SACEA,UAAU,EACVC,eAAe,EACfC,iBAAiB,EACjBC,YAAY,EACZC,YAAY,EACZC,aAAa,QACR,+BAA8B;AAErC,SAASC,SAAS,QAAQ,iCAAgC;AAC1D,SAASC,iBAAiB,EAAEC,YAAY,QAAQ,iCAAgC;AAChF,SAASC,qBAAqB,EAAEC,gBAAgB,EAAEC,mBAAmB,QAAQ,qCAAoC;AAGjH,wEAAwE;AACxE,gFAAgF;AAChF,SACEC,gBAAgB,EAChBC,kBAAkB,EAClBC,iBAAiB,EACjBC,cAAc,QACT,2BAA0B;AAGjC,SAASC,UAAU,QAAQ,iCAAgC;AAC3D,SAASC,SAAS,QAAQ,iCAAgC;AAE1D,SAASC,aAAa,QAAQ,iCAAgC;AAC9D,SAASC,aAAa,EAAEC,WAAW,EAAEC,YAAY,EAAEC,UAAU,QAAQ,iCAAgC;AACrG,SAASC,WAAW,QAAQ,wDAAuD;AACnF,SAASC,uBAAuB,QAAQ,qDAAoD;AAC5F,SAASC,eAAe,QAAQ,4DAA2D;AAC3F,SACEC,sBAAsB,EACtBC,iBAAiB,EACjBC,oBAAoB,EACpBC,qBAAqB,EACrBC,gBAAgB,QACX,2BAA0B;AAEjC,SAASC,OAAO,QAAQ,8BAA6B;AAErD,SAASC,cAAc,QAAQ,qCAAoC;AAEnE,SACEC,cAAc,EACdC,OAAO,EACPC,QAAQ,EACRC,KAAK,EACLC,SAAS,EACTC,SAAS,EACTC,OAAO,EACPC,OAAO,EACPC,MAAM,QACD,iCAAgC;AAEvC,SAASC,cAAc,EAAEC,kBAAkB,EAAEC,iBAAiB,QAAQ,+BAA8B;AACpG,SAASC,sBAAsB,QAAQ,oCAAmC"}
|
||||
Vendored
+2
-1
@@ -10,7 +10,8 @@
|
||||
* 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 { verifyTurnstile, checkTurnstile } from '../modules/turnstile/index.js';
|
||||
export type { TurnstileCheck, TurnstileOutcome } from '../modules/turnstile/index.js';
|
||||
export { sendEmail } from '../modules/email/index.js';
|
||||
export type { SendEmailArgs, SendEmailResult } from '../modules/email/index.js';
|
||||
export { submitForm } from '../modules/forms/index.js';
|
||||
|
||||
Vendored
+1
-1
@@ -9,7 +9,7 @@
|
||||
*
|
||||
* 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 { verifyTurnstile, checkTurnstile } from '../modules/turnstile/index.js';
|
||||
export { sendEmail } from '../modules/email/index.js';
|
||||
export { submitForm } from '../modules/forms/index.js';
|
||||
|
||||
|
||||
Vendored
+1
-1
@@ -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"}
|
||||
{"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, checkTurnstile } from '../modules/turnstile/index.js'\nexport type { TurnstileCheck, TurnstileOutcome } 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","checkTurnstile","sendEmail","submitForm"],"mappings":"AAAA;;;;;;;;;;;CAWC,GACD,SAASA,eAAe,EAAEC,cAAc,QAAQ,gCAA+B;AAE/E,SAASC,SAAS,QAAQ,4BAA2B;AAErD,SAASC,UAAU,QAAQ,4BAA2B"}
|
||||
Vendored
+5
-2
@@ -6,11 +6,14 @@ import { notificationsFields } from './fields.js';
|
||||
*/ export function buildNotifications() {
|
||||
return {
|
||||
slug: 'notifications',
|
||||
label: 'Notifications',
|
||||
admin: {
|
||||
group: 'Settings'
|
||||
},
|
||||
access: {
|
||||
read: ()=>true
|
||||
},
|
||||
fields: notificationsFields,
|
||||
label: 'Notifications'
|
||||
fields: notificationsFields
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -1 +1 @@
|
||||
{"version":3,"sources":["../../../src/globals/Notifications/index.ts"],"sourcesContent":["import type { GlobalConfig } from 'payload'\n\nimport { notificationsFields } from './fields.js'\n\n/**\n * Builds the Notifications global — localized action-result texts. Readable by\n * any authenticated panel user; server-side helpers read it with overrideAccess\n * so the frontend can resolve texts without a session.\n */\nexport function buildNotifications(): GlobalConfig {\n return {\n slug: 'notifications',\n access: {\n read: () => true, // texts are public-facing (shown to end users)\n },\n fields: notificationsFields,\n label: 'Notifications',\n }\n}\n"],"names":["notificationsFields","buildNotifications","slug","access","read","fields","label"],"mappings":"AAEA,SAASA,mBAAmB,QAAQ,cAAa;AAEjD;;;;CAIC,GACD,OAAO,SAASC;IACd,OAAO;QACLC,MAAM;QACNC,QAAQ;YACNC,MAAM,IAAM;QACd;QACAC,QAAQL;QACRM,OAAO;IACT;AACF"}
|
||||
{"version":3,"sources":["../../../src/globals/Notifications/index.ts"],"sourcesContent":["import type { GlobalConfig } from 'payload'\nimport { notificationsFields } from './fields.js'\n\n/**\n * Builds the Notifications global — localized action-result texts. Readable by\n * any authenticated panel user; server-side helpers read it with overrideAccess\n * so the frontend can resolve texts without a session.\n */\nexport function buildNotifications(): GlobalConfig {\n return {\n slug: 'notifications',\n label: 'Notifications',\n admin: { group: 'Settings' },\n access: {\n read: () => true, // texts are public-facing (shown to end users)\n },\n fields: notificationsFields,\n }\n}\n"],"names":["notificationsFields","buildNotifications","slug","label","admin","group","access","read","fields"],"mappings":"AACA,SAASA,mBAAmB,QAAQ,cAAa;AAEjD;;;;CAIC,GACD,OAAO,SAASC;IACd,OAAO;QACLC,MAAM;QACNC,OAAO;QACPC,OAAO;YAAEC,OAAO;QAAW;QAC3BC,QAAQ;YACNC,MAAM,IAAM;QACd;QACAC,QAAQR;IACV;AACF"}
|
||||
@@ -1,3 +1,20 @@
|
||||
import type { TextFieldClientComponent } from 'payload';
|
||||
/**
|
||||
* Masked text input for sensitive values (SMTP password, R2 secret key,
|
||||
* Turnstile secret key, etc.).
|
||||
*
|
||||
* Renders the value as a password field (••••) so secrets aren't shown in
|
||||
* plaintext on screen — protecting against shoulder-surfing and accidental
|
||||
* exposure when the panel is open. The value is still stored and returned
|
||||
* normally (UI masking, NOT hashing or encryption), because the plugin must
|
||||
* read it back to authenticate with SMTP/R2/Turnstile. A toggle reveals the
|
||||
* value when an authorised editor genuinely needs to check it.
|
||||
*
|
||||
* Uses a raw <input> driven by useField rather than @payloadcms/ui's TextInput,
|
||||
* because TextInput doesn't expose inputProps, so there's no way to switch its
|
||||
* inner input to type="password".
|
||||
*
|
||||
* Assigned via a field's admin.components.Field. Works on any `text` field.
|
||||
*/
|
||||
export declare const MaskedField: TextFieldClientComponent;
|
||||
export default MaskedField;
|
||||
|
||||
+51
-25
@@ -1,51 +1,77 @@
|
||||
'use client';
|
||||
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
||||
import { useField, FieldLabel, FieldDescription } from '@payloadcms/ui';
|
||||
import { useState } from 'react';
|
||||
export const MaskedField = (props)=>{
|
||||
const { field, path, value: propValue, setValue: propSetValue, onChange: propOnChange } = props || {};
|
||||
const [internalValue, setInternalValue] = useState(propValue ?? '');
|
||||
/**
|
||||
* Masked text input for sensitive values (SMTP password, R2 secret key,
|
||||
* Turnstile secret key, etc.).
|
||||
*
|
||||
* Renders the value as a password field (••••) so secrets aren't shown in
|
||||
* plaintext on screen — protecting against shoulder-surfing and accidental
|
||||
* exposure when the panel is open. The value is still stored and returned
|
||||
* normally (UI masking, NOT hashing or encryption), because the plugin must
|
||||
* read it back to authenticate with SMTP/R2/Turnstile. A toggle reveals the
|
||||
* value when an authorised editor genuinely needs to check it.
|
||||
*
|
||||
* Uses a raw <input> driven by useField rather than @payloadcms/ui's TextInput,
|
||||
* because TextInput doesn't expose inputProps, so there's no way to switch its
|
||||
* inner input to type="password".
|
||||
*
|
||||
* Assigned via a field's admin.components.Field. Works on any `text` field.
|
||||
*/ export const MaskedField = ({ field, path })=>{
|
||||
const { value, setValue } = useField({
|
||||
path
|
||||
});
|
||||
const [revealed, setRevealed] = useState(false);
|
||||
const label = typeof field?.label === 'string' ? field.label : field?.name ?? path;
|
||||
const handleChange = (e)=>{
|
||||
const newVal = e.target.value;
|
||||
setInternalValue(newVal);
|
||||
if (typeof propSetValue === 'function') {
|
||||
propSetValue(newVal);
|
||||
}
|
||||
if (typeof propOnChange === 'function') {
|
||||
propOnChange(e);
|
||||
}
|
||||
};
|
||||
const currentValue = propValue !== undefined ? propValue : internalValue;
|
||||
const description = field?.admin?.description;
|
||||
return /*#__PURE__*/ _jsxs("div", {
|
||||
className: "field-type text",
|
||||
className: "field-type text masked-field",
|
||||
children: [
|
||||
label && /*#__PURE__*/ _jsx("label", {
|
||||
className: "field-label",
|
||||
children: label
|
||||
/*#__PURE__*/ _jsx(FieldLabel, {
|
||||
label: label,
|
||||
htmlFor: `field-${path}`
|
||||
}),
|
||||
/*#__PURE__*/ _jsxs("div", {
|
||||
className: "field-type__wrap",
|
||||
style: {
|
||||
display: 'flex',
|
||||
gap: '.5rem'
|
||||
gap: '.5rem',
|
||||
alignItems: 'center'
|
||||
},
|
||||
children: [
|
||||
/*#__PURE__*/ _jsx("input", {
|
||||
id: `field-${path}`,
|
||||
type: revealed ? 'text' : 'password',
|
||||
autoComplete: "off",
|
||||
onChange: handleChange,
|
||||
className: "field-type__input",
|
||||
value: value ?? '',
|
||||
onChange: (e)=>setValue(e.target.value),
|
||||
style: {
|
||||
flex: 1
|
||||
},
|
||||
type: revealed ? 'text' : 'password',
|
||||
value: currentValue ?? ''
|
||||
}
|
||||
}),
|
||||
/*#__PURE__*/ _jsx("button", {
|
||||
onClick: ()=>setRevealed((r)=>!r),
|
||||
type: "button",
|
||||
onClick: ()=>setRevealed((r)=>!r),
|
||||
style: {
|
||||
background: 'none',
|
||||
border: 'none',
|
||||
padding: '.25rem .5rem',
|
||||
cursor: 'pointer',
|
||||
font: 'inherit',
|
||||
textDecoration: 'underline',
|
||||
opacity: 0.75,
|
||||
whiteSpace: 'nowrap'
|
||||
},
|
||||
children: revealed ? 'Hide' : 'Reveal'
|
||||
})
|
||||
]
|
||||
})
|
||||
}),
|
||||
description && typeof description === 'string' ? /*#__PURE__*/ _jsx(FieldDescription, {
|
||||
path: path,
|
||||
description: description
|
||||
}) : null
|
||||
]
|
||||
});
|
||||
};
|
||||
|
||||
@@ -1 +1 @@
|
||||
{"version":3,"sources":["../../../../src/globals/SiteIntegrations/components/MaskedField.tsx"],"sourcesContent":["'use client'\nimport type { TextFieldClientComponent } from 'payload'\nimport { useState } from 'react'\n\nexport const MaskedField: TextFieldClientComponent = (props: any) => {\n const { field, path, value: propValue, setValue: propSetValue, onChange: propOnChange } = props || {}\n const [internalValue, setInternalValue] = useState(propValue ?? '')\n const [revealed, setRevealed] = useState(false)\n const label = typeof field?.label === 'string' ? field.label : (field?.name ?? path)\n\n const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {\n const newVal = e.target.value\n setInternalValue(newVal)\n if (typeof propSetValue === 'function') {\n propSetValue(newVal)\n }\n if (typeof propOnChange === 'function') {\n propOnChange(e)\n }\n }\n\n const currentValue = propValue !== undefined ? propValue : internalValue\n\n return (\n <div className=\"field-type text\">\n {label && <label className=\"field-label\">{label}</label>}\n <div style={{ display: 'flex', gap: '.5rem' }}>\n <input\n autoComplete=\"off\"\n onChange={handleChange}\n style={{ flex: 1 }}\n type={revealed ? 'text' : 'password'}\n value={currentValue ?? ''}\n />\n <button onClick={() => setRevealed((r) => !r)} type=\"button\">\n {revealed ? 'Hide' : 'Reveal'}\n </button>\n </div>\n </div>\n )\n}\n\nexport default MaskedField\n"],"names":["useState","MaskedField","props","field","path","value","propValue","setValue","propSetValue","onChange","propOnChange","internalValue","setInternalValue","revealed","setRevealed","label","name","handleChange","e","newVal","target","currentValue","undefined","div","className","style","display","gap","input","autoComplete","flex","type","button","onClick","r"],"mappings":"AAAA;;AAEA,SAASA,QAAQ,QAAQ,QAAO;AAEhC,OAAO,MAAMC,cAAwC,CAACC;IACpD,MAAM,EAAEC,KAAK,EAAEC,IAAI,EAAEC,OAAOC,SAAS,EAAEC,UAAUC,YAAY,EAAEC,UAAUC,YAAY,EAAE,GAAGR,SAAS,CAAC;IACpG,MAAM,CAACS,eAAeC,iBAAiB,GAAGZ,SAASM,aAAa;IAChE,MAAM,CAACO,UAAUC,YAAY,GAAGd,SAAS;IACzC,MAAMe,QAAQ,OAAOZ,OAAOY,UAAU,WAAWZ,MAAMY,KAAK,GAAIZ,OAAOa,QAAQZ;IAE/E,MAAMa,eAAe,CAACC;QACpB,MAAMC,SAASD,EAAEE,MAAM,CAACf,KAAK;QAC7BO,iBAAiBO;QACjB,IAAI,OAAOX,iBAAiB,YAAY;YACtCA,aAAaW;QACf;QACA,IAAI,OAAOT,iBAAiB,YAAY;YACtCA,aAAaQ;QACf;IACF;IAEA,MAAMG,eAAef,cAAcgB,YAAYhB,YAAYK;IAE3D,qBACE,MAACY;QAAIC,WAAU;;YACZT,uBAAS,KAACA;gBAAMS,WAAU;0BAAeT;;0BAC1C,MAACQ;gBAAIE,OAAO;oBAAEC,SAAS;oBAAQC,KAAK;gBAAQ;;kCAC1C,KAACC;wBACCC,cAAa;wBACbpB,UAAUQ;wBACVQ,OAAO;4BAAEK,MAAM;wBAAE;wBACjBC,MAAMlB,WAAW,SAAS;wBAC1BR,OAAOgB,gBAAgB;;kCAEzB,KAACW;wBAAOC,SAAS,IAAMnB,YAAY,CAACoB,IAAM,CAACA;wBAAIH,MAAK;kCACjDlB,WAAW,SAAS;;;;;;AAK/B,EAAC;AAED,eAAeZ,YAAW"}
|
||||
{"version":3,"sources":["../../../../src/globals/SiteIntegrations/components/MaskedField.tsx"],"sourcesContent":["'use client'\n\nimport { useField, FieldLabel, FieldDescription } from '@payloadcms/ui'\nimport { useState } from 'react'\nimport type { TextFieldClientComponent } from 'payload'\n\n/**\n * Masked text input for sensitive values (SMTP password, R2 secret key,\n * Turnstile secret key, etc.).\n *\n * Renders the value as a password field (••••) so secrets aren't shown in\n * plaintext on screen — protecting against shoulder-surfing and accidental\n * exposure when the panel is open. The value is still stored and returned\n * normally (UI masking, NOT hashing or encryption), because the plugin must\n * read it back to authenticate with SMTP/R2/Turnstile. A toggle reveals the\n * value when an authorised editor genuinely needs to check it.\n *\n * Uses a raw <input> driven by useField rather than @payloadcms/ui's TextInput,\n * because TextInput doesn't expose inputProps, so there's no way to switch its\n * inner input to type=\"password\".\n *\n * Assigned via a field's admin.components.Field. Works on any `text` field.\n */\nexport const MaskedField: TextFieldClientComponent = ({ field, path }) => {\n const { value, setValue } = useField<string>({ path })\n const [revealed, setRevealed] = useState(false)\n\n const label =\n typeof field?.label === 'string' ? field.label : (field?.name ?? path)\n const description = field?.admin?.description\n\n return (\n <div className=\"field-type text masked-field\">\n <FieldLabel label={label} htmlFor={`field-${path}`} />\n\n <div className=\"field-type__wrap\" style={{ display: 'flex', gap: '.5rem', alignItems: 'center' }}>\n <input\n id={`field-${path}`}\n type={revealed ? 'text' : 'password'}\n autoComplete=\"off\"\n className=\"field-type__input\"\n value={value ?? ''}\n onChange={(e) => setValue(e.target.value)}\n style={{ flex: 1 }}\n />\n <button\n type=\"button\"\n onClick={() => setRevealed((r) => !r)}\n style={{\n background: 'none',\n border: 'none',\n padding: '.25rem .5rem',\n cursor: 'pointer',\n font: 'inherit',\n textDecoration: 'underline',\n opacity: 0.75,\n whiteSpace: 'nowrap',\n }}\n >\n {revealed ? 'Hide' : 'Reveal'}\n </button>\n </div>\n\n {description && typeof description === 'string' ? (\n <FieldDescription path={path} description={description} />\n ) : null}\n </div>\n )\n}\n\nexport default MaskedField\n"],"names":["useField","FieldLabel","FieldDescription","useState","MaskedField","field","path","value","setValue","revealed","setRevealed","label","name","description","admin","div","className","htmlFor","style","display","gap","alignItems","input","id","type","autoComplete","onChange","e","target","flex","button","onClick","r","background","border","padding","cursor","font","textDecoration","opacity","whiteSpace"],"mappings":"AAAA;;AAEA,SAASA,QAAQ,EAAEC,UAAU,EAAEC,gBAAgB,QAAQ,iBAAgB;AACvE,SAASC,QAAQ,QAAQ,QAAO;AAGhC;;;;;;;;;;;;;;;;CAgBC,GACD,OAAO,MAAMC,cAAwC,CAAC,EAAEC,KAAK,EAAEC,IAAI,EAAE;IACnE,MAAM,EAAEC,KAAK,EAAEC,QAAQ,EAAE,GAAGR,SAAiB;QAAEM;IAAK;IACpD,MAAM,CAACG,UAAUC,YAAY,GAAGP,SAAS;IAEzC,MAAMQ,QACJ,OAAON,OAAOM,UAAU,WAAWN,MAAMM,KAAK,GAAIN,OAAOO,QAAQN;IACnE,MAAMO,cAAcR,OAAOS,OAAOD;IAElC,qBACE,MAACE;QAAIC,WAAU;;0BACb,KAACf;gBAAWU,OAAOA;gBAAOM,SAAS,CAAC,MAAM,EAAEX,MAAM;;0BAElD,MAACS;gBAAIC,WAAU;gBAAmBE,OAAO;oBAAEC,SAAS;oBAAQC,KAAK;oBAASC,YAAY;gBAAS;;kCAC7F,KAACC;wBACCC,IAAI,CAAC,MAAM,EAAEjB,MAAM;wBACnBkB,MAAMf,WAAW,SAAS;wBAC1BgB,cAAa;wBACbT,WAAU;wBACVT,OAAOA,SAAS;wBAChBmB,UAAU,CAACC,IAAMnB,SAASmB,EAAEC,MAAM,CAACrB,KAAK;wBACxCW,OAAO;4BAAEW,MAAM;wBAAE;;kCAEnB,KAACC;wBACCN,MAAK;wBACLO,SAAS,IAAMrB,YAAY,CAACsB,IAAM,CAACA;wBACnCd,OAAO;4BACLe,YAAY;4BACZC,QAAQ;4BACRC,SAAS;4BACTC,QAAQ;4BACRC,MAAM;4BACNC,gBAAgB;4BAChBC,SAAS;4BACTC,YAAY;wBACd;kCAEC/B,WAAW,SAAS;;;;YAIxBI,eAAe,OAAOA,gBAAgB,yBACrC,KAACX;gBAAiBI,MAAMA;gBAAMO,aAAaA;iBACzC;;;AAGV,EAAC;AAED,eAAeT,YAAW"}
|
||||
+17
-17
@@ -27,14 +27,14 @@ import { useState } from 'react';
|
||||
});
|
||||
try {
|
||||
const res = await fetch('/api/ipal/test-email', {
|
||||
body: JSON.stringify({
|
||||
to: to.trim()
|
||||
}),
|
||||
credentials: 'include',
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
method: 'POST'
|
||||
credentials: 'include',
|
||||
body: JSON.stringify({
|
||||
to: to.trim()
|
||||
})
|
||||
});
|
||||
const data = await res.json();
|
||||
if (data.ok) {
|
||||
@@ -67,38 +67,38 @@ import { useState } from 'react';
|
||||
}),
|
||||
/*#__PURE__*/ _jsx("p", {
|
||||
style: {
|
||||
opacity: 0.7,
|
||||
fontSize: '.85rem',
|
||||
marginTop: 0,
|
||||
opacity: 0.7
|
||||
marginTop: 0
|
||||
},
|
||||
children: "Sends through the transport selected above. Save your changes first."
|
||||
}),
|
||||
/*#__PURE__*/ _jsxs("div", {
|
||||
style: {
|
||||
alignItems: 'center',
|
||||
display: 'flex',
|
||||
flexWrap: 'wrap',
|
||||
gap: '.5rem'
|
||||
gap: '.5rem',
|
||||
alignItems: 'center',
|
||||
flexWrap: 'wrap'
|
||||
},
|
||||
children: [
|
||||
/*#__PURE__*/ _jsx("input", {
|
||||
onChange: (e)=>setTo(e.target.value),
|
||||
type: "email",
|
||||
placeholder: "[email protected]",
|
||||
value: to,
|
||||
onChange: (e)=>setTo(e.target.value),
|
||||
style: {
|
||||
flex: 1,
|
||||
minWidth: '220px'
|
||||
},
|
||||
type: "email",
|
||||
value: to
|
||||
}
|
||||
}),
|
||||
/*#__PURE__*/ _jsx("button", {
|
||||
className: "btn btn--style-secondary",
|
||||
disabled: status.kind === 'sending',
|
||||
type: "button",
|
||||
onClick: send,
|
||||
disabled: status.kind === 'sending',
|
||||
className: "btn btn--style-secondary",
|
||||
style: {
|
||||
whiteSpace: 'nowrap'
|
||||
},
|
||||
type: "button",
|
||||
children: status.kind === 'sending' ? 'Sending…' : 'Send test'
|
||||
})
|
||||
]
|
||||
|
||||
@@ -1 +1 @@
|
||||
{"version":3,"sources":["../../../../src/globals/SiteIntegrations/components/TestEmailButton.tsx"],"sourcesContent":["'use client'\n\nimport { useState } from 'react'\n\n/**\n * Admin UI: a small \"send test email\" tool for the SiteIntegrations email tab.\n * Enter an address, click Send, and it POSTs to /api/ipal/test-email, which\n * sends through the currently-selected transport (SMTP or Graph). Shows the\n * result inline so you can confirm delivery — or read the exact error — without\n * leaving the panel.\n *\n * Assigned via a `ui` field's admin.components.Field.\n */\nexport const TestEmailButton = () => {\n const [to, setTo] = useState('')\n const [status, setStatus] = useState<\n | { kind: 'error'; msg: string }\n | { kind: 'idle' }\n | { kind: 'ok'; msg: string }\n | { kind: 'sending' }\n >({ kind: 'idle' })\n\n const send = async () => {\n if (!to.trim()) {\n setStatus({ kind: 'error', msg: 'Enter a recipient address.' })\n return\n }\n setStatus({ kind: 'sending' })\n try {\n const res = await fetch('/api/ipal/test-email', {\n body: JSON.stringify({ to: to.trim() }),\n credentials: 'include',\n headers: { 'Content-Type': 'application/json' },\n method: 'POST',\n })\n const data = await res.json()\n if (data.ok) {\n setStatus({ kind: 'ok', msg: data.message ?? 'Test email sent.' })\n } else {\n setStatus({ kind: 'error', msg: data.error ?? 'Send failed.' })\n }\n } catch {\n setStatus({ kind: 'error', msg: 'Request failed. Is the server running?' })\n }\n }\n\n return (\n <div className=\"field-type\" style={{ marginTop: '1rem' }}>\n <label className=\"field-label\">Send a test email</label>\n <p style={{ fontSize: '.85rem', marginTop: 0, opacity: 0.7 }}>\n Sends through the transport selected above. Save your changes first.\n </p>\n <div style={{ alignItems: 'center', display: 'flex', flexWrap: 'wrap', gap: '.5rem' }}>\n <input\n onChange={(e) => setTo(e.target.value)}\n placeholder=\"[email protected]\"\n style={{ flex: 1, minWidth: '220px' }}\n type=\"email\"\n value={to}\n />\n <button\n className=\"btn btn--style-secondary\"\n disabled={status.kind === 'sending'}\n onClick={send}\n style={{ whiteSpace: 'nowrap' }}\n type=\"button\"\n >\n {status.kind === 'sending' ? 'Sending…' : 'Send test'}\n </button>\n </div>\n {status.kind === 'ok' && (\n <p style={{ color: 'var(--theme-success-500, green)', marginTop: '.5rem' }}>\n ✓ {status.msg}\n </p>\n )}\n {status.kind === 'error' && (\n <p style={{ color: 'var(--theme-error-500, crimson)', marginTop: '.5rem' }}>\n ✗ {status.msg}\n </p>\n )}\n </div>\n )\n}\n\nexport default TestEmailButton\n"],"names":["useState","TestEmailButton","to","setTo","status","setStatus","kind","send","trim","msg","res","fetch","body","JSON","stringify","credentials","headers","method","data","json","ok","message","error","div","className","style","marginTop","label","p","fontSize","opacity","alignItems","display","flexWrap","gap","input","onChange","e","target","value","placeholder","flex","minWidth","type","button","disabled","onClick","whiteSpace","color"],"mappings":"AAAA;;AAEA,SAASA,QAAQ,QAAQ,QAAO;AAEhC;;;;;;;;CAQC,GACD,OAAO,MAAMC,kBAAkB;IAC7B,MAAM,CAACC,IAAIC,MAAM,GAAGH,SAAS;IAC7B,MAAM,CAACI,QAAQC,UAAU,GAAGL,SAK1B;QAAEM,MAAM;IAAO;IAEjB,MAAMC,OAAO;QACX,IAAI,CAACL,GAAGM,IAAI,IAAI;YACdH,UAAU;gBAAEC,MAAM;gBAASG,KAAK;YAA6B;YAC7D;QACF;QACAJ,UAAU;YAAEC,MAAM;QAAU;QAC5B,IAAI;YACF,MAAMI,MAAM,MAAMC,MAAM,wBAAwB;gBAC9CC,MAAMC,KAAKC,SAAS,CAAC;oBAAEZ,IAAIA,GAAGM,IAAI;gBAAG;gBACrCO,aAAa;gBACbC,SAAS;oBAAE,gBAAgB;gBAAmB;gBAC9CC,QAAQ;YACV;YACA,MAAMC,OAAO,MAAMR,IAAIS,IAAI;YAC3B,IAAID,KAAKE,EAAE,EAAE;gBACXf,UAAU;oBAAEC,MAAM;oBAAMG,KAAKS,KAAKG,OAAO,IAAI;gBAAmB;YAClE,OAAO;gBACLhB,UAAU;oBAAEC,MAAM;oBAASG,KAAKS,KAAKI,KAAK,IAAI;gBAAe;YAC/D;QACF,EAAE,OAAM;YACNjB,UAAU;gBAAEC,MAAM;gBAASG,KAAK;YAAyC;QAC3E;IACF;IAEA,qBACE,MAACc;QAAIC,WAAU;QAAaC,OAAO;YAAEC,WAAW;QAAO;;0BACrD,KAACC;gBAAMH,WAAU;0BAAc;;0BAC/B,KAACI;gBAAEH,OAAO;oBAAEI,UAAU;oBAAUH,WAAW;oBAAGI,SAAS;gBAAI;0BAAG;;0BAG9D,MAACP;gBAAIE,OAAO;oBAAEM,YAAY;oBAAUC,SAAS;oBAAQC,UAAU;oBAAQC,KAAK;gBAAQ;;kCAClF,KAACC;wBACCC,UAAU,CAACC,IAAMlC,MAAMkC,EAAEC,MAAM,CAACC,KAAK;wBACrCC,aAAY;wBACZf,OAAO;4BAAEgB,MAAM;4BAAGC,UAAU;wBAAQ;wBACpCC,MAAK;wBACLJ,OAAOrC;;kCAET,KAAC0C;wBACCpB,WAAU;wBACVqB,UAAUzC,OAAOE,IAAI,KAAK;wBAC1BwC,SAASvC;wBACTkB,OAAO;4BAAEsB,YAAY;wBAAS;wBAC9BJ,MAAK;kCAEJvC,OAAOE,IAAI,KAAK,YAAY,aAAa;;;;YAG7CF,OAAOE,IAAI,KAAK,sBACf,MAACsB;gBAAEH,OAAO;oBAAEuB,OAAO;oBAAmCtB,WAAW;gBAAQ;;oBAAG;oBACvEtB,OAAOK,GAAG;;;YAGhBL,OAAOE,IAAI,KAAK,yBACf,MAACsB;gBAAEH,OAAO;oBAAEuB,OAAO;oBAAmCtB,WAAW;gBAAQ;;oBAAG;oBACvEtB,OAAOK,GAAG;;;;;AAKvB,EAAC;AAED,eAAeR,gBAAe"}
|
||||
{"version":3,"sources":["../../../../src/globals/SiteIntegrations/components/TestEmailButton.tsx"],"sourcesContent":["'use client'\n\nimport { useState } from 'react'\n\n/**\n * Admin UI: a small \"send test email\" tool for the SiteIntegrations email tab.\n * Enter an address, click Send, and it POSTs to /api/ipal/test-email, which\n * sends through the currently-selected transport (SMTP or Graph). Shows the\n * result inline so you can confirm delivery — or read the exact error — without\n * leaving the panel.\n *\n * Assigned via a `ui` field's admin.components.Field.\n */\nexport const TestEmailButton = () => {\n const [to, setTo] = useState('')\n const [status, setStatus] = useState<\n { kind: 'idle' } | { kind: 'sending' } | { kind: 'ok'; msg: string } | { kind: 'error'; msg: string }\n >({ kind: 'idle' })\n\n const send = async () => {\n if (!to.trim()) {\n setStatus({ kind: 'error', msg: 'Enter a recipient address.' })\n return\n }\n setStatus({ kind: 'sending' })\n try {\n const res = await fetch('/api/ipal/test-email', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n credentials: 'include',\n body: JSON.stringify({ to: to.trim() }),\n })\n const data = await res.json()\n if (data.ok) {\n setStatus({ kind: 'ok', msg: data.message ?? 'Test email sent.' })\n } else {\n setStatus({ kind: 'error', msg: data.error ?? 'Send failed.' })\n }\n } catch {\n setStatus({ kind: 'error', msg: 'Request failed. Is the server running?' })\n }\n }\n\n return (\n <div className=\"field-type\" style={{ marginTop: '1rem' }}>\n <label className=\"field-label\">Send a test email</label>\n <p style={{ opacity: 0.7, fontSize: '.85rem', marginTop: 0 }}>\n Sends through the transport selected above. Save your changes first.\n </p>\n <div style={{ display: 'flex', gap: '.5rem', alignItems: 'center', flexWrap: 'wrap' }}>\n <input\n type=\"email\"\n placeholder=\"[email protected]\"\n value={to}\n onChange={(e) => setTo(e.target.value)}\n style={{ flex: 1, minWidth: '220px' }}\n />\n <button\n type=\"button\"\n onClick={send}\n disabled={status.kind === 'sending'}\n className=\"btn btn--style-secondary\"\n style={{ whiteSpace: 'nowrap' }}\n >\n {status.kind === 'sending' ? 'Sending…' : 'Send test'}\n </button>\n </div>\n {status.kind === 'ok' && (\n <p style={{ color: 'var(--theme-success-500, green)', marginTop: '.5rem' }}>\n ✓ {status.msg}\n </p>\n )}\n {status.kind === 'error' && (\n <p style={{ color: 'var(--theme-error-500, crimson)', marginTop: '.5rem' }}>\n ✗ {status.msg}\n </p>\n )}\n </div>\n )\n}\n\nexport default TestEmailButton\n"],"names":["useState","TestEmailButton","to","setTo","status","setStatus","kind","send","trim","msg","res","fetch","method","headers","credentials","body","JSON","stringify","data","json","ok","message","error","div","className","style","marginTop","label","p","opacity","fontSize","display","gap","alignItems","flexWrap","input","type","placeholder","value","onChange","e","target","flex","minWidth","button","onClick","disabled","whiteSpace","color"],"mappings":"AAAA;;AAEA,SAASA,QAAQ,QAAQ,QAAO;AAEhC;;;;;;;;CAQC,GACD,OAAO,MAAMC,kBAAkB;IAC7B,MAAM,CAACC,IAAIC,MAAM,GAAGH,SAAS;IAC7B,MAAM,CAACI,QAAQC,UAAU,GAAGL,SAE1B;QAAEM,MAAM;IAAO;IAEjB,MAAMC,OAAO;QACX,IAAI,CAACL,GAAGM,IAAI,IAAI;YACdH,UAAU;gBAAEC,MAAM;gBAASG,KAAK;YAA6B;YAC7D;QACF;QACAJ,UAAU;YAAEC,MAAM;QAAU;QAC5B,IAAI;YACF,MAAMI,MAAM,MAAMC,MAAM,wBAAwB;gBAC9CC,QAAQ;gBACRC,SAAS;oBAAE,gBAAgB;gBAAmB;gBAC9CC,aAAa;gBACbC,MAAMC,KAAKC,SAAS,CAAC;oBAAEf,IAAIA,GAAGM,IAAI;gBAAG;YACvC;YACA,MAAMU,OAAO,MAAMR,IAAIS,IAAI;YAC3B,IAAID,KAAKE,EAAE,EAAE;gBACXf,UAAU;oBAAEC,MAAM;oBAAMG,KAAKS,KAAKG,OAAO,IAAI;gBAAmB;YAClE,OAAO;gBACLhB,UAAU;oBAAEC,MAAM;oBAASG,KAAKS,KAAKI,KAAK,IAAI;gBAAe;YAC/D;QACF,EAAE,OAAM;YACNjB,UAAU;gBAAEC,MAAM;gBAASG,KAAK;YAAyC;QAC3E;IACF;IAEA,qBACE,MAACc;QAAIC,WAAU;QAAaC,OAAO;YAAEC,WAAW;QAAO;;0BACrD,KAACC;gBAAMH,WAAU;0BAAc;;0BAC/B,KAACI;gBAAEH,OAAO;oBAAEI,SAAS;oBAAKC,UAAU;oBAAUJ,WAAW;gBAAE;0BAAG;;0BAG9D,MAACH;gBAAIE,OAAO;oBAAEM,SAAS;oBAAQC,KAAK;oBAASC,YAAY;oBAAUC,UAAU;gBAAO;;kCAClF,KAACC;wBACCC,MAAK;wBACLC,aAAY;wBACZC,OAAOpC;wBACPqC,UAAU,CAACC,IAAMrC,MAAMqC,EAAEC,MAAM,CAACH,KAAK;wBACrCb,OAAO;4BAAEiB,MAAM;4BAAGC,UAAU;wBAAQ;;kCAEtC,KAACC;wBACCR,MAAK;wBACLS,SAAStC;wBACTuC,UAAU1C,OAAOE,IAAI,KAAK;wBAC1BkB,WAAU;wBACVC,OAAO;4BAAEsB,YAAY;wBAAS;kCAE7B3C,OAAOE,IAAI,KAAK,YAAY,aAAa;;;;YAG7CF,OAAOE,IAAI,KAAK,sBACf,MAACsB;gBAAEH,OAAO;oBAAEuB,OAAO;oBAAmCtB,WAAW;gBAAQ;;oBAAG;oBACvEtB,OAAOK,GAAG;;;YAGhBL,OAAOE,IAAI,KAAK,yBACf,MAACsB;gBAAEH,OAAO;oBAAEuB,OAAO;oBAAmCtB,WAAW;gBAAQ;;oBAAG;oBACvEtB,OAAOK,GAAG;;;;;AAKvB,EAAC;AAED,eAAeR,gBAAe"}
|
||||
+5
-1
@@ -1,3 +1,4 @@
|
||||
import { buildIntegrationStatusBanner, buildIntegrationStatusField } from '../../../modules/integrations/status.js';
|
||||
/**
|
||||
* SMTP transport settings for outbound email.
|
||||
*
|
||||
@@ -5,6 +6,8 @@
|
||||
* user), so all fields — including the password — stay editable in the admin
|
||||
* panel while remaining inaccessible to anonymous API requests.
|
||||
*/ export const smtpFields = [
|
||||
// Status written by mailAdapter on every send (throttled) — banner on this tab.
|
||||
buildIntegrationStatusBanner('emailStatus', 'Email'),
|
||||
{
|
||||
name: 'emailTransport',
|
||||
type: 'select',
|
||||
@@ -88,7 +91,8 @@
|
||||
Field: '@intecion/ipal-kit/client#TestEmailButton'
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
buildIntegrationStatusField('emailStatus')
|
||||
];
|
||||
|
||||
//# sourceMappingURL=smtp.js.map
|
||||
+1
-1
@@ -1 +1 @@
|
||||
{"version":3,"sources":["../../../../src/globals/SiteIntegrations/fields/smtp.ts"],"sourcesContent":["import type { Field } from 'payload'\n\n/**\n * SMTP transport settings for outbound email.\n *\n * Protected at the global level (SiteIntegrations requires an authenticated\n * user), so all fields — including the password — stay editable in the admin\n * panel while remaining inaccessible to anonymous API requests.\n */\nexport const smtpFields: Field[] = [\n {\n name: 'emailTransport',\n type: 'select',\n admin: {\n description:\n 'How outbound email is sent. \"Microsoft Graph\" is only available when configured by the administrator (Intecion).',\n // The Graph option only makes sense when agency credentials exist in env.\n // We can't read process.env in the admin UI directly, so a client project\n // that hasn't set up Graph should filter this option via integrationsFields\n // override, or simply leave it on 'smtp'. The adapter enforces the real\n // availability at send time regardless of what's selected here.\n },\n defaultValue: 'smtp',\n options: [\n { label: 'SMTP', value: 'smtp' },\n { label: 'Microsoft Graph (Exchange)', value: 'graph' },\n ],\n },\n {\n type: 'row',\n admin: {\n // Hide SMTP fields when Graph is selected — they're not used then.\n condition: (_, siblingData) => siblingData?.emailTransport !== 'graph',\n },\n fields: [\n {\n name: 'smtpHost',\n type: 'text',\n admin: { placeholder: 'smtp.example.com', width: '70%' },\n },\n {\n name: 'smtpPort',\n type: 'number',\n admin: { width: '30%' },\n defaultValue: 587,\n },\n ],\n },\n {\n name: 'smtpUser',\n type: 'text',\n admin: {\n description: 'SMTP account username.',\n },\n },\n {\n name: 'smtpPassword',\n type: 'text',\n admin: {\n description: 'SMTP account password.',\n // Masked in the UI (••••) — stored plaintext, readable for SMTP auth.\n components: {\n Field: '@intecion/ipal-kit/client#MaskedField',\n },\n },\n },\n {\n name: 'smtpFromAddress',\n type: 'email',\n admin: {\n description: 'Default \"from\" address for outgoing mail.',\n },\n },\n {\n name: 'smtpFromName',\n type: 'text',\n admin: {\n description: 'Default \"from\" display name.',\n },\n },\n {\n name: 'emailTest',\n type: 'ui',\n admin: {\n components: {\n Field: '@intecion/ipal-kit/client#TestEmailButton',\n },\n },\n },\n]\n"],"names":["smtpFields","name","type","admin","description","defaultValue","options","label","value","condition","_","siblingData","emailTransport","fields","placeholder","width","components","Field"],"mappings":"AAEA;;;;;;CAMC,GACD,OAAO,MAAMA,aAAsB;IACjC;QACEC,MAAM;QACNC,MAAM;QACNC,OAAO;YACLC,aACE;QAMJ;QACAC,cAAc;QACdC,SAAS;YACP;gBAAEC,OAAO;gBAAQC,OAAO;YAAO;YAC/B;gBAAED,OAAO;gBAA8BC,OAAO;YAAQ;SACvD;IACH;IACA;QACEN,MAAM;QACNC,OAAO;YACL,mEAAmE;YACnEM,WAAW,CAACC,GAAGC,cAAgBA,aAAaC,mBAAmB;QACjE;QACAC,QAAQ;YACN;gBACEZ,MAAM;gBACNC,MAAM;gBACNC,OAAO;oBAAEW,aAAa;oBAAoBC,OAAO;gBAAM;YACzD;YACA;gBACEd,MAAM;gBACNC,MAAM;gBACNC,OAAO;oBAAEY,OAAO;gBAAM;gBACtBV,cAAc;YAChB;SACD;IACH;IACA;QACEJ,MAAM;QACNC,MAAM;QACNC,OAAO;YACLC,aAAa;QACf;IACF;IACA;QACEH,MAAM;QACNC,MAAM;QACNC,OAAO;YACLC,aAAa;YACb,sEAAsE;YACtEY,YAAY;gBACVC,OAAO;YACT;QACF;IACF;IACA;QACEhB,MAAM;QACNC,MAAM;QACNC,OAAO;YACLC,aAAa;QACf;IACF;IACA;QACEH,MAAM;QACNC,MAAM;QACNC,OAAO;YACLC,aAAa;QACf;IACF;IACA;QACEH,MAAM;QACNC,MAAM;QACNC,OAAO;YACLa,YAAY;gBACVC,OAAO;YACT;QACF;IACF;CACD,CAAA"}
|
||||
{"version":3,"sources":["../../../../src/globals/SiteIntegrations/fields/smtp.ts"],"sourcesContent":["import type { Field } from 'payload'\n\nimport { buildIntegrationStatusBanner, buildIntegrationStatusField } from '../../../modules/integrations/status.js'\n\n/**\n * SMTP transport settings for outbound email.\n *\n * Protected at the global level (SiteIntegrations requires an authenticated\n * user), so all fields — including the password — stay editable in the admin\n * panel while remaining inaccessible to anonymous API requests.\n */\nexport const smtpFields: Field[] = [\n // Status written by mailAdapter on every send (throttled) — banner on this tab.\n buildIntegrationStatusBanner('emailStatus', 'Email'),\n {\n name: 'emailTransport',\n type: 'select',\n admin: {\n description:\n 'How outbound email is sent. \"Microsoft Graph\" is only available when configured by the administrator (Intecion).',\n // The Graph option only makes sense when agency credentials exist in env.\n // We can't read process.env in the admin UI directly, so a client project\n // that hasn't set up Graph should filter this option via integrationsFields\n // override, or simply leave it on 'smtp'. The adapter enforces the real\n // availability at send time regardless of what's selected here.\n },\n defaultValue: 'smtp',\n options: [\n { label: 'SMTP', value: 'smtp' },\n { label: 'Microsoft Graph (Exchange)', value: 'graph' },\n ],\n },\n {\n type: 'row',\n admin: {\n // Hide SMTP fields when Graph is selected — they're not used then.\n condition: (_, siblingData) => siblingData?.emailTransport !== 'graph',\n },\n fields: [\n {\n name: 'smtpHost',\n type: 'text',\n admin: { placeholder: 'smtp.example.com', width: '70%' },\n },\n {\n name: 'smtpPort',\n type: 'number',\n admin: { width: '30%' },\n defaultValue: 587,\n },\n ],\n },\n {\n name: 'smtpUser',\n type: 'text',\n admin: {\n description: 'SMTP account username.',\n },\n },\n {\n name: 'smtpPassword',\n type: 'text',\n admin: {\n description: 'SMTP account password.',\n // Masked in the UI (••••) — stored plaintext, readable for SMTP auth.\n components: {\n Field: '@intecion/ipal-kit/client#MaskedField',\n },\n },\n },\n {\n name: 'smtpFromAddress',\n type: 'email',\n admin: {\n description: 'Default \"from\" address for outgoing mail.',\n },\n },\n {\n name: 'smtpFromName',\n type: 'text',\n admin: {\n description: 'Default \"from\" display name.',\n },\n },\n {\n name: 'emailTest',\n type: 'ui',\n admin: {\n components: {\n Field: '@intecion/ipal-kit/client#TestEmailButton',\n },\n },\n },\n buildIntegrationStatusField('emailStatus'),\n]\n"],"names":["buildIntegrationStatusBanner","buildIntegrationStatusField","smtpFields","name","type","admin","description","defaultValue","options","label","value","condition","_","siblingData","emailTransport","fields","placeholder","width","components","Field"],"mappings":"AAEA,SAASA,4BAA4B,EAAEC,2BAA2B,QAAQ,0CAAyC;AAEnH;;;;;;CAMC,GACD,OAAO,MAAMC,aAAsB;IACjC,gFAAgF;IAChFF,6BAA6B,eAAe;IAC5C;QACEG,MAAM;QACNC,MAAM;QACNC,OAAO;YACLC,aACE;QAMJ;QACAC,cAAc;QACdC,SAAS;YACP;gBAAEC,OAAO;gBAAQC,OAAO;YAAO;YAC/B;gBAAED,OAAO;gBAA8BC,OAAO;YAAQ;SACvD;IACH;IACA;QACEN,MAAM;QACNC,OAAO;YACL,mEAAmE;YACnEM,WAAW,CAACC,GAAGC,cAAgBA,aAAaC,mBAAmB;QACjE;QACAC,QAAQ;YACN;gBACEZ,MAAM;gBACNC,MAAM;gBACNC,OAAO;oBAAEW,aAAa;oBAAoBC,OAAO;gBAAM;YACzD;YACA;gBACEd,MAAM;gBACNC,MAAM;gBACNC,OAAO;oBAAEY,OAAO;gBAAM;gBACtBV,cAAc;YAChB;SACD;IACH;IACA;QACEJ,MAAM;QACNC,MAAM;QACNC,OAAO;YACLC,aAAa;QACf;IACF;IACA;QACEH,MAAM;QACNC,MAAM;QACNC,OAAO;YACLC,aAAa;YACb,sEAAsE;YACtEY,YAAY;gBACVC,OAAO;YACT;QACF;IACF;IACA;QACEhB,MAAM;QACNC,MAAM;QACNC,OAAO;YACLC,aAAa;QACf;IACF;IACA;QACEH,MAAM;QACNC,MAAM;QACNC,OAAO;YACLC,aAAa;QACf;IACF;IACA;QACEH,MAAM;QACNC,MAAM;QACNC,OAAO;YACLa,YAAY;gBACVC,OAAO;YACT;QACF;IACF;IACAlB,4BAA4B;CAC7B,CAAA"}
|
||||
+5
-1
@@ -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
|
||||
+1
-1
@@ -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"}
|
||||
{"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"}
|
||||
-4
@@ -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 {};
|
||||
|
||||
+26
-4
@@ -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,32 @@ import { turnstileFields } from './fields/turnstile.js';
|
||||
]
|
||||
}
|
||||
],
|
||||
hooks: {
|
||||
beforeChange: [
|
||||
// Keys edited in the panel → clear that integration's old status, so a stale
|
||||
// "not working" banner doesn't linger until the next form submission.
|
||||
({ context, data, originalDoc })=>{
|
||||
if (context?.ipalIntegrationStatus || !data) {
|
||||
return data;
|
||||
}
|
||||
const changed = (k)=>k in data && data[k] !== originalDoc?.[k];
|
||||
const cleared = {
|
||||
checkedAt: null,
|
||||
code: null,
|
||||
message: null,
|
||||
since: null,
|
||||
state: null
|
||||
};
|
||||
if (changed('turnstileSecretKey') || changed('turnstileSiteKey')) {
|
||||
data.turnstileStatus = cleared;
|
||||
}
|
||||
if (Object.keys(data).some((k)=>(k === 'emailTransport' || k.startsWith('smtp')) && changed(k))) {
|
||||
data.emailStatus = cleared;
|
||||
}
|
||||
return data;
|
||||
}
|
||||
]
|
||||
},
|
||||
label: 'Site Integrations'
|
||||
};
|
||||
}
|
||||
|
||||
+1
-1
@@ -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"}
|
||||
{"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 that integration's old 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 const cleared = { checkedAt: null, code: null, message: null, since: null, state: null }\n if (changed('turnstileSecretKey') || changed('turnstileSiteKey')) {data.turnstileStatus = cleared}\n if (Object.keys(data).some((k) => (k === 'emailTransport' || k.startsWith('smtp')) && changed(k))) {\n data.emailStatus = cleared\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","cleared","checkedAt","code","message","since","state","turnstileStatus","Object","keys","some","startsWith","emailStatus"],"mappings":"AAEA,SAASA,OAAO,QAAQ,gCAA+B;AACvD,SAASC,eAAe,QAAQ,wBAAuB;AACvD,SAASC,UAAU,QAAQ,mBAAkB;AAC7C,SAASC,eAAe,QAAQ,wBAAuB;AAOvD;;;;;;;;;;;CAWC,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,SAClB;wBAAC;4BAAEJ,QAAQT;4BAAkBY,OAAO;wBAAS;qBAAE,GAC/C,EAAE;iBACP;YACH;SACD;QACDE,OAAO;YACLC,cAAc;gBACZ,6EAA6E;gBAC7E,sEAAsE;gBACtE,CAAC,EAAEC,OAAO,EAAEC,IAAI,EAAEC,WAAW,EAAE;oBAC7B,IAAIF,SAASG,yBAAyB,CAACF,MAAM;wBAAC,OAAOA;oBAAI;oBACzD,MAAMG,UAAU,CAACC,IAAcA,KAAKJ,QAAQA,IAAI,CAACI,EAAE,KAAKH,aAAa,CAACG,EAAE;oBACxE,MAAMC,UAAU;wBAAEC,WAAW;wBAAMC,MAAM;wBAAMC,SAAS;wBAAMC,OAAO;wBAAMC,OAAO;oBAAK;oBACvF,IAAIP,QAAQ,yBAAyBA,QAAQ,qBAAqB;wBAACH,KAAKW,eAAe,GAAGN;oBAAO;oBACjG,IAAIO,OAAOC,IAAI,CAACb,MAAMc,IAAI,CAAC,CAACV,IAAM,AAACA,CAAAA,MAAM,oBAAoBA,EAAEW,UAAU,CAAC,OAAM,KAAMZ,QAAQC,KAAK;wBACjGJ,KAAKgB,WAAW,GAAGX;oBACrB;oBACA,OAAOL;gBACT;aACD;QACH;QACAL,OAAO;IACT;AACF"}
|
||||
Vendored
+2
@@ -52,6 +52,8 @@ export { buildCsp } from './modules/security/index.js';
|
||||
export type { BuildCspArgs } from './modules/security/index.js';
|
||||
export { buildIconsMetadata, buildOrganizationJsonLd, validateFaviconField } from './modules/seo/index.js';
|
||||
export { buildNoindexField } from './modules/seo/index.js';
|
||||
export { recordIntegrationStatus, buildIntegrationStatusField, buildIntegrationStatusBanner } from './modules/integrations/index.js';
|
||||
export type { IntegrationStatus, IntegrationState } from './modules/integrations/index.js';
|
||||
export { rowLabel } from './modules/admin-ui/index.js';
|
||||
export type { RowLabelProps } from './modules/admin-ui/index.js';
|
||||
export { buildLinkField, buildLinksField, resolveLinkHref } from './modules/links/index.js';
|
||||
|
||||
Vendored
+1
@@ -41,6 +41,7 @@ export { buildSecurityHeaders } from './modules/security/index.js';
|
||||
export { buildCsp } from './modules/security/index.js';
|
||||
export { buildIconsMetadata, buildOrganizationJsonLd, validateFaviconField } from './modules/seo/index.js';
|
||||
export { buildNoindexField } from './modules/seo/index.js';
|
||||
export { recordIntegrationStatus, buildIntegrationStatusField, buildIntegrationStatusBanner } from './modules/integrations/index.js';
|
||||
export { rowLabel } from './modules/admin-ui/index.js';
|
||||
export { buildLinkField, buildLinksField, resolveLinkHref } from './modules/links/index.js';
|
||||
export { buildSpeakableJsonLd } from './modules/seo/index.js';
|
||||
|
||||
Vendored
+1
-1
File diff suppressed because one or more lines are too long
+8
@@ -11,6 +11,14 @@ type CreateSearchRouteArgs = {
|
||||
getCachedPayload: () => Promise<BasePayload>;
|
||||
/** Home slug map/string so the home result collapses to root. */
|
||||
homeSlug?: Record<string, string> | string;
|
||||
/**
|
||||
* Per-IP limit (in memory, per instance). Default { max: 120, windowMs: 60_000 }.
|
||||
* `false` = off (a limiter in front, e.g. Cloudflare WAF rate limiting).
|
||||
*/
|
||||
rateLimit?: {
|
||||
max?: number;
|
||||
windowMs?: number;
|
||||
} | false;
|
||||
/** Field holding a richer AI summary (buildSummaryField) to prefer as description. */
|
||||
summaryField?: string;
|
||||
};
|
||||
|
||||
+22
@@ -1,3 +1,4 @@
|
||||
import { checkRateLimit, clientIp, tooManyRequests } from '../shared/rateLimit.js';
|
||||
import { searchContent } from './searchContent.js';
|
||||
/**
|
||||
* A JSON content-search endpoint. Powers both the site's own search UI and
|
||||
@@ -18,7 +19,28 @@ import { searchContent } from './searchContent.js';
|
||||
* Uses the global Request/Response — no next/server import.
|
||||
*/ export function createSearchRoute(args) {
|
||||
const { baseUrl, collection = 'pages', config, defaultLimit = 10, getCachedPayload, homeSlug, summaryField } = args;
|
||||
// 120/min: a debounced search-as-you-type box stays well under it; a scraper doesn't.
|
||||
const rl = args.rateLimit === false ? null : {
|
||||
max: 120,
|
||||
windowMs: 60_000,
|
||||
...args.rateLimit
|
||||
};
|
||||
return async (req)=>{
|
||||
if (rl) {
|
||||
const ip = clientIp(req);
|
||||
if (!checkRateLimit({
|
||||
key: ip,
|
||||
scope: 'search',
|
||||
...rl
|
||||
})) {
|
||||
return tooManyRequests(ip, 'search', {
|
||||
count: 0,
|
||||
error: 'Too many requests',
|
||||
query: '',
|
||||
results: []
|
||||
});
|
||||
}
|
||||
}
|
||||
const url = new URL(req.url);
|
||||
const query = url.searchParams.get('q')?.trim() ?? '';
|
||||
const locale = url.searchParams.get('locale') ?? undefined;
|
||||
|
||||
+1
-1
File diff suppressed because one or more lines are too long
Vendored
+3
-3
@@ -1,11 +1,11 @@
|
||||
import type { PayloadEmailAdapter } from 'payload';
|
||||
import { type GraphAdapterArgs } from './graphAdapter.js';
|
||||
import { type PanelSmtpAdapterArgs } from './panelSmtpAdapter.js';
|
||||
import { type GraphAdapterArgs } from './graphAdapter.js';
|
||||
export type MailAdapterArgs = {
|
||||
smtp?: PanelSmtpAdapterArgs;
|
||||
graph?: GraphAdapterArgs;
|
||||
fallbackFromAddress?: string;
|
||||
fallbackFromName?: string;
|
||||
graph?: GraphAdapterArgs;
|
||||
smtp?: PanelSmtpAdapterArgs;
|
||||
};
|
||||
/**
|
||||
* Dispatcher email adapter: wired into the config ONCE, but picks the transport
|
||||
|
||||
Vendored
+42
-7
@@ -1,6 +1,9 @@
|
||||
import { getSiteIntegrations } from '../payload/index.js';
|
||||
import { graphAdapter } from './graphAdapter.js';
|
||||
import { recordIntegrationStatus } from '../integrations/status.js';
|
||||
import { panelSmtpAdapter } from './panelSmtpAdapter.js';
|
||||
import { graphAdapter } from './graphAdapter.js';
|
||||
const STATUS_FIELD = 'emailStatus';
|
||||
/** Error text for the panel: first line, no stack, capped — SMTP errors don't carry the password. */ const describe = (err)=>(err instanceof Error ? err.message : String(err)).split('\n')[0].slice(0, 200);
|
||||
/** True when the agency Graph credentials are present in the environment. */ function graphAvailable() {
|
||||
return Boolean(process.env.GRAPH_TENANT_ID && process.env.GRAPH_CLIENT_ID && process.env.GRAPH_CLIENT_SECRET && process.env.GRAPH_SENDER);
|
||||
}
|
||||
@@ -41,16 +44,48 @@ import { panelSmtpAdapter } from './panelSmtpAdapter.js';
|
||||
sendEmail: async (message)=>{
|
||||
const settings = await getSiteIntegrations(payload);
|
||||
const choice = settings.emailTransport ?? 'smtp';
|
||||
if (choice === 'graph') {
|
||||
if (graphAvailable()) {
|
||||
return graph.sendEmail(message);
|
||||
}
|
||||
const previous = settings[STATUS_FIELD];
|
||||
const useGraph = choice === 'graph' && graphAvailable();
|
||||
const graphFallback = choice === 'graph' && !useGraph;
|
||||
if (graphFallback) {
|
||||
// Panel asked for Graph but the agency creds aren't configured for
|
||||
// this project. Fall back to SMTP rather than silently dropping mail.
|
||||
payload.logger.warn('[ipal] Transport set to Graph but GRAPH_* env vars are missing; falling back to SMTP.');
|
||||
return smtp.sendEmail(message);
|
||||
}
|
||||
return smtp.sendEmail(message);
|
||||
const transport = useGraph ? 'Microsoft Graph' : 'SMTP';
|
||||
const code = useGraph ? 'graph-error' : 'smtp-error';
|
||||
let result;
|
||||
try {
|
||||
result = await (useGraph ? graph : smtp).sendEmail(message);
|
||||
} catch (err) {
|
||||
await recordIntegrationStatus(payload, STATUS_FIELD, previous, {
|
||||
state: 'degraded',
|
||||
code,
|
||||
message: `${transport}: ${describe(err)}`
|
||||
});
|
||||
throw err // callers (form-builder, Send test) still see the failure
|
||||
;
|
||||
}
|
||||
// The delegates report failure as { sent: false, error, detail? } instead
|
||||
// of throwing (a broken mailbox must not crash a form submission).
|
||||
const failed = result;
|
||||
if (failed && typeof failed === 'object' && failed.sent === false) {
|
||||
await recordIntegrationStatus(payload, STATUS_FIELD, previous, {
|
||||
state: 'degraded',
|
||||
code,
|
||||
message: `${transport}: ${describe(failed.detail ?? failed.error ?? 'not sent')}`
|
||||
});
|
||||
return result;
|
||||
}
|
||||
// Graph selected but unavailable is a configuration problem even if SMTP delivered.
|
||||
await recordIntegrationStatus(payload, STATUS_FIELD, previous, graphFallback ? {
|
||||
state: 'degraded',
|
||||
code: 'graph-unavailable',
|
||||
message: 'Microsoft Graph is selected but not configured on the server — e-mails are sent over SMTP.'
|
||||
} : {
|
||||
state: 'ok'
|
||||
});
|
||||
return result;
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
+1
-1
File diff suppressed because one or more lines are too long
+12
-10
@@ -32,8 +32,8 @@ import { getSiteIntegrations } from '../payload/index.js';
|
||||
if (!host || !user || !pass) {
|
||||
payload.logger.error('[ipal] Email not sent: SMTP is not configured in Site Integrations.');
|
||||
return {
|
||||
error: 'SMTP is not configured in Site Integrations.',
|
||||
sent: false
|
||||
sent: false,
|
||||
error: 'SMTP is not configured in Site Integrations.'
|
||||
};
|
||||
}
|
||||
// The panel is the source of truth for the sender; fall back to whatever
|
||||
@@ -48,13 +48,13 @@ import { getSiteIntegrations } from '../payload/index.js';
|
||||
const stripCRLF = (v)=>String(v ?? '').replace(/[\r\n]+/g, ' ').trim();
|
||||
const { default: nodemailer } = await import('nodemailer');
|
||||
const transporter = nodemailer.createTransport({
|
||||
auth: {
|
||||
pass,
|
||||
user
|
||||
},
|
||||
host,
|
||||
port,
|
||||
secure: port === 465
|
||||
secure: port === 465,
|
||||
auth: {
|
||||
user,
|
||||
pass
|
||||
}
|
||||
});
|
||||
try {
|
||||
const info = await transporter.sendMail({
|
||||
@@ -65,16 +65,18 @@ import { getSiteIntegrations } from '../payload/index.js';
|
||||
} : {}
|
||||
});
|
||||
return {
|
||||
messageId: info.messageId,
|
||||
sent: true
|
||||
sent: true,
|
||||
messageId: info.messageId
|
||||
};
|
||||
} catch (err) {
|
||||
// Never surface SMTP internals to the caller — a form submission
|
||||
// shouldn't fail loudly because the mailbox is misconfigured.
|
||||
payload.logger.error(`[ipal] Email send failed: ${err.message}`);
|
||||
// `detail` is for the panel status (mailAdapter), not for end users.
|
||||
return {
|
||||
sent: false,
|
||||
error: 'Failed to send email.',
|
||||
sent: false
|
||||
detail: err.message
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
+1
-1
File diff suppressed because one or more lines are too long
+10
-4
@@ -3,9 +3,15 @@ import type { FormsOption } from './types.js';
|
||||
/**
|
||||
* Configures @payloadcms/plugin-form-builder from IPAL's FormsOption.
|
||||
*
|
||||
* Provides the form/form-submissions collections and field types. Email
|
||||
* delivery is intentionally NOT handled here — the plugin's own SMTP-from-panel
|
||||
* sender (submitForm) does that, so the form-builder's built-in email (which
|
||||
* needs a Payload email adapter) is left unused.
|
||||
* Provides the forms / form-submissions collections and field types. E-mails
|
||||
* after a submission are the form-builder's own (Forms → Emails), sent through
|
||||
* the project's email adapter (mailAdapter()).
|
||||
*
|
||||
* SECURITY: form-builder defaults form-submissions to `create: () => true`, i.e.
|
||||
* anyone can POST /api/form-submissions and skip everything submitForm enforces
|
||||
* (rate limit, Turnstile, GDPR consent, schema validation). Here REST/GraphQL
|
||||
* creation is limited to logged-in users; the site submits through submitForm
|
||||
* (server action → Local API, which bypasses access by design). A project that
|
||||
* really needs public REST submissions can override `formSubmissionOverrides.access.create`.
|
||||
*/
|
||||
export declare function buildFormsPlugin(forms: FormsOption): Plugin;
|
||||
|
||||
+53
-16
@@ -1,22 +1,33 @@
|
||||
import { formBuilderPlugin } from '@payloadcms/plugin-form-builder';
|
||||
/** REST/GraphQL: only logged-in users. Local API (submitForm) is unaffected. */ const submissionsCreateAccess = ({ req })=>Boolean(req.user);
|
||||
/**
|
||||
* Configures @payloadcms/plugin-form-builder from IPAL's FormsOption.
|
||||
*
|
||||
* Provides the form/form-submissions collections and field types. Email
|
||||
* delivery is intentionally NOT handled here — the plugin's own SMTP-from-panel
|
||||
* sender (submitForm) does that, so the form-builder's built-in email (which
|
||||
* needs a Payload email adapter) is left unused.
|
||||
* Provides the forms / form-submissions collections and field types. E-mails
|
||||
* after a submission are the form-builder's own (Forms → Emails), sent through
|
||||
* the project's email adapter (mailAdapter()).
|
||||
*
|
||||
* SECURITY: form-builder defaults form-submissions to `create: () => true`, i.e.
|
||||
* anyone can POST /api/form-submissions and skip everything submitForm enforces
|
||||
* (rate limit, Turnstile, GDPR consent, schema validation). Here REST/GraphQL
|
||||
* creation is limited to logged-in users; the site submits through submitForm
|
||||
* (server action → Local API, which bypasses access by design). A project that
|
||||
* really needs public REST submissions can override `formSubmissionOverrides.access.create`.
|
||||
*/ export function buildFormsPlugin(forms) {
|
||||
const adminGroup = forms.adminGroup === undefined ? 'Forms' : forms.adminGroup;
|
||||
const group = adminGroup ? {
|
||||
group: adminGroup
|
||||
} : {};
|
||||
return formBuilderPlugin({
|
||||
fields: {
|
||||
checkbox: true,
|
||||
email: true,
|
||||
message: true,
|
||||
number: true,
|
||||
payment: false,
|
||||
select: true,
|
||||
text: true,
|
||||
textarea: true,
|
||||
email: true,
|
||||
number: true,
|
||||
select: true,
|
||||
checkbox: true,
|
||||
message: true,
|
||||
payment: false,
|
||||
...forms.fields
|
||||
},
|
||||
...forms.redirectRelationships ? {
|
||||
@@ -25,12 +36,38 @@ import { formBuilderPlugin } from '@payloadcms/plugin-form-builder';
|
||||
// Client-supplied collection overrides (e.g. a per-form notification
|
||||
// address). The plugin provides the hook, not the opinion about which
|
||||
// extra fields a form should carry.
|
||||
...forms.formOverrides ? {
|
||||
formOverrides: forms.formOverrides
|
||||
} : {},
|
||||
...forms.formSubmissionOverrides ? {
|
||||
formSubmissionOverrides: forms.formSubmissionOverrides
|
||||
} : {}
|
||||
// Tidy panel by default: both collections under one sidebar group with plain
|
||||
// labels — no per-project overrides needed just to sort the sidebar.
|
||||
formOverrides: {
|
||||
labels: {
|
||||
singular: 'Form',
|
||||
plural: 'Forms'
|
||||
},
|
||||
...forms.formOverrides,
|
||||
admin: {
|
||||
...group,
|
||||
...forms.formOverrides?.admin
|
||||
}
|
||||
},
|
||||
formSubmissionOverrides: {
|
||||
labels: {
|
||||
singular: 'Submission',
|
||||
plural: 'Submissions'
|
||||
},
|
||||
...forms.formSubmissionOverrides,
|
||||
admin: {
|
||||
...group,
|
||||
defaultColumns: [
|
||||
'form',
|
||||
'createdAt'
|
||||
],
|
||||
...forms.formSubmissionOverrides?.admin
|
||||
},
|
||||
access: {
|
||||
create: submissionsCreateAccess,
|
||||
...forms.formSubmissionOverrides?.access
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -1 +1 @@
|
||||
{"version":3,"sources":["../../../src/modules/forms/formsPluginConfig.ts"],"sourcesContent":["import type { Plugin } from 'payload'\n\nimport { formBuilderPlugin } from '@payloadcms/plugin-form-builder'\n\nimport type { FormsOption } from './types.js'\n\n/**\n * Configures @payloadcms/plugin-form-builder from IPAL's FormsOption.\n *\n * Provides the form/form-submissions collections and field types. Email\n * delivery is intentionally NOT handled here — the plugin's own SMTP-from-panel\n * sender (submitForm) does that, so the form-builder's built-in email (which\n * needs a Payload email adapter) is left unused.\n */\nexport function buildFormsPlugin(forms: FormsOption): Plugin {\n return formBuilderPlugin({\n fields: {\n checkbox: true,\n email: true,\n message: true,\n number: true,\n payment: false,\n select: true,\n text: true,\n textarea: true,\n ...forms.fields,\n },\n ...(forms.redirectRelationships ? { redirectRelationships: forms.redirectRelationships } : {}),\n // Client-supplied collection overrides (e.g. a per-form notification\n // address). The plugin provides the hook, not the opinion about which\n // extra fields a form should carry.\n ...(forms.formOverrides ? { formOverrides: forms.formOverrides } : {}),\n ...(forms.formSubmissionOverrides\n ? { formSubmissionOverrides: forms.formSubmissionOverrides }\n : {}),\n })\n}\n"],"names":["formBuilderPlugin","buildFormsPlugin","forms","fields","checkbox","email","message","number","payment","select","text","textarea","redirectRelationships","formOverrides","formSubmissionOverrides"],"mappings":"AAEA,SAASA,iBAAiB,QAAQ,kCAAiC;AAInE;;;;;;;CAOC,GACD,OAAO,SAASC,iBAAiBC,KAAkB;IACjD,OAAOF,kBAAkB;QACvBG,QAAQ;YACNC,UAAU;YACVC,OAAO;YACPC,SAAS;YACTC,QAAQ;YACRC,SAAS;YACTC,QAAQ;YACRC,MAAM;YACNC,UAAU;YACV,GAAGT,MAAMC,MAAM;QACjB;QACA,GAAID,MAAMU,qBAAqB,GAAG;YAAEA,uBAAuBV,MAAMU,qBAAqB;QAAC,IAAI,CAAC,CAAC;QAC7F,qEAAqE;QACrE,sEAAsE;QACtE,oCAAoC;QACpC,GAAIV,MAAMW,aAAa,GAAG;YAAEA,eAAeX,MAAMW,aAAa;QAAC,IAAI,CAAC,CAAC;QACrE,GAAIX,MAAMY,uBAAuB,GAC7B;YAAEA,yBAAyBZ,MAAMY,uBAAuB;QAAC,IACzD,CAAC,CAAC;IACR;AACF"}
|
||||
{"version":3,"sources":["../../../src/modules/forms/formsPluginConfig.ts"],"sourcesContent":["import { formBuilderPlugin } from '@payloadcms/plugin-form-builder'\nimport type { Plugin } from 'payload'\nimport type { FormsOption } from './types.js'\n\n/** REST/GraphQL: only logged-in users. Local API (submitForm) is unaffected. */\nconst submissionsCreateAccess = ({ req }: { req: { user?: unknown } }) => Boolean(req.user)\n\n/**\n * Configures @payloadcms/plugin-form-builder from IPAL's FormsOption.\n *\n * Provides the forms / form-submissions collections and field types. E-mails\n * after a submission are the form-builder's own (Forms → Emails), sent through\n * the project's email adapter (mailAdapter()).\n *\n * SECURITY: form-builder defaults form-submissions to `create: () => true`, i.e.\n * anyone can POST /api/form-submissions and skip everything submitForm enforces\n * (rate limit, Turnstile, GDPR consent, schema validation). Here REST/GraphQL\n * creation is limited to logged-in users; the site submits through submitForm\n * (server action → Local API, which bypasses access by design). A project that\n * really needs public REST submissions can override `formSubmissionOverrides.access.create`.\n */\nexport function buildFormsPlugin(forms: FormsOption): Plugin {\n const adminGroup = forms.adminGroup === undefined ? 'Forms' : forms.adminGroup\n const group = adminGroup ? { group: adminGroup } : {}\n return formBuilderPlugin({\n fields: {\n text: true,\n textarea: true,\n email: true,\n number: true,\n select: true,\n checkbox: true,\n message: true,\n payment: false,\n ...forms.fields,\n },\n ...(forms.redirectRelationships\n ? { redirectRelationships: forms.redirectRelationships }\n : {}),\n // Client-supplied collection overrides (e.g. a per-form notification\n // address). The plugin provides the hook, not the opinion about which\n // extra fields a form should carry.\n // Tidy panel by default: both collections under one sidebar group with plain\n // labels — no per-project overrides needed just to sort the sidebar.\n formOverrides: {\n labels: { singular: 'Form', plural: 'Forms' },\n ...forms.formOverrides,\n admin: { ...group, ...forms.formOverrides?.admin },\n },\n formSubmissionOverrides: {\n labels: { singular: 'Submission', plural: 'Submissions' },\n ...forms.formSubmissionOverrides,\n admin: { ...group, defaultColumns: ['form', 'createdAt'], ...forms.formSubmissionOverrides?.admin },\n access: {\n create: submissionsCreateAccess,\n ...forms.formSubmissionOverrides?.access,\n },\n },\n })\n}\n"],"names":["formBuilderPlugin","submissionsCreateAccess","req","Boolean","user","buildFormsPlugin","forms","adminGroup","undefined","group","fields","text","textarea","email","number","select","checkbox","message","payment","redirectRelationships","formOverrides","labels","singular","plural","admin","formSubmissionOverrides","defaultColumns","access","create"],"mappings":"AAAA,SAASA,iBAAiB,QAAQ,kCAAiC;AAInE,8EAA8E,GAC9E,MAAMC,0BAA0B,CAAC,EAAEC,GAAG,EAA+B,GAAKC,QAAQD,IAAIE,IAAI;AAE1F;;;;;;;;;;;;;CAaC,GACD,OAAO,SAASC,iBAAiBC,KAAkB;IACjD,MAAMC,aAAaD,MAAMC,UAAU,KAAKC,YAAY,UAAUF,MAAMC,UAAU;IAC9E,MAAME,QAAQF,aAAa;QAAEE,OAAOF;IAAW,IAAI,CAAC;IACpD,OAAOP,kBAAkB;QACvBU,QAAQ;YACNC,MAAM;YACNC,UAAU;YACVC,OAAO;YACPC,QAAQ;YACRC,QAAQ;YACRC,UAAU;YACVC,SAAS;YACTC,SAAS;YACT,GAAGZ,MAAMI,MAAM;QACjB;QACA,GAAIJ,MAAMa,qBAAqB,GAC3B;YAAEA,uBAAuBb,MAAMa,qBAAqB;QAAC,IACrD,CAAC,CAAC;QACN,qEAAqE;QACrE,sEAAsE;QACtE,oCAAoC;QACpC,6EAA6E;QAC7E,qEAAqE;QACrEC,eAAe;YACbC,QAAQ;gBAAEC,UAAU;gBAAQC,QAAQ;YAAQ;YAC5C,GAAGjB,MAAMc,aAAa;YACtBI,OAAO;gBAAE,GAAGf,KAAK;gBAAE,GAAGH,MAAMc,aAAa,EAAEI,KAAK;YAAC;QACnD;QACAC,yBAAyB;YACvBJ,QAAQ;gBAAEC,UAAU;gBAAcC,QAAQ;YAAc;YACxD,GAAGjB,MAAMmB,uBAAuB;YAChCD,OAAO;gBAAE,GAAGf,KAAK;gBAAEiB,gBAAgB;oBAAC;oBAAQ;iBAAY;gBAAE,GAAGpB,MAAMmB,uBAAuB,EAAED,KAAK;YAAC;YAClGG,QAAQ;gBACNC,QAAQ3B;gBACR,GAAGK,MAAMmB,uBAAuB,EAAEE,MAAM;YAC1C;QACF;IACF;AACF"}
|
||||
Vendored
+2
-14
@@ -1,14 +1,2 @@
|
||||
export type RateLimitArgs = {
|
||||
/** Identifier to limit on — typically the client IP. */
|
||||
key: string;
|
||||
/** Max submissions allowed per window. Defaults to 5. */
|
||||
max?: number;
|
||||
/** Window length in ms. Defaults to 60_000 (one minute). */
|
||||
windowMs?: number;
|
||||
};
|
||||
/**
|
||||
* Returns true when the request is within the limit, false when it should be
|
||||
* rejected. A missing key (no IP) is allowed through — better to accept a
|
||||
* submission than to block everyone behind a proxy that strips the header.
|
||||
*/
|
||||
export declare function checkRateLimit({ key, max, windowMs }: RateLimitArgs): boolean;
|
||||
export { checkRateLimit, clientIp, retryAfterSeconds, tooManyRequests } from '../shared/rateLimit.js';
|
||||
export type { RateLimitArgs } from '../shared/rateLimit.js';
|
||||
|
||||
Vendored
+2
-49
@@ -1,51 +1,4 @@
|
||||
/**
|
||||
* Per-IP sliding window, in memory.
|
||||
*
|
||||
* Deliberately simple: no Redis, no dependency. The trade-off is that the
|
||||
* counter lives in one process — with several instances behind a load balancer
|
||||
* each keeps its own, so the effective limit is per-instance, not global. For a
|
||||
* contact form that's fine (it raises the cost of flooding without pretending
|
||||
* to be airtight); a high-security form should put a real limiter in front.
|
||||
*
|
||||
* State is module-level, so it survives between requests but resets on redeploy
|
||||
* — acceptable for abuse throttling.
|
||||
*/ const buckets = new Map();
|
||||
/** Sweep expired buckets occasionally so the map doesn't grow unbounded. */ let lastSweep = Date.now();
|
||||
const SWEEP_INTERVAL = 60_000;
|
||||
function sweep(now) {
|
||||
if (now - lastSweep < SWEEP_INTERVAL) {
|
||||
return;
|
||||
}
|
||||
lastSweep = now;
|
||||
for (const [key, bucket] of buckets){
|
||||
if (bucket.resetAt <= now) {
|
||||
buckets.delete(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Returns true when the request is within the limit, false when it should be
|
||||
* rejected. A missing key (no IP) is allowed through — better to accept a
|
||||
* submission than to block everyone behind a proxy that strips the header.
|
||||
*/ export function checkRateLimit({ key, max = 5, windowMs = 60_000 }) {
|
||||
if (!key) {
|
||||
return true;
|
||||
}
|
||||
const now = Date.now();
|
||||
sweep(now);
|
||||
const bucket = buckets.get(key);
|
||||
if (!bucket || bucket.resetAt <= now) {
|
||||
buckets.set(key, {
|
||||
count: 1,
|
||||
resetAt: now + windowMs
|
||||
});
|
||||
return true;
|
||||
}
|
||||
if (bucket.count >= max) {
|
||||
return false;
|
||||
}
|
||||
bucket.count += 1;
|
||||
return true;
|
||||
}
|
||||
// Moved to modules/shared/rateLimit.ts (shared with search and MCP routes).
|
||||
export { checkRateLimit, clientIp, retryAfterSeconds, tooManyRequests } from '../shared/rateLimit.js';
|
||||
|
||||
//# sourceMappingURL=rateLimit.js.map
|
||||
Vendored
+1
-1
@@ -1 +1 @@
|
||||
{"version":3,"sources":["../../../src/modules/forms/rateLimit.ts"],"sourcesContent":["type Bucket = { count: number; resetAt: number }\n\n/**\n * Per-IP sliding window, in memory.\n *\n * Deliberately simple: no Redis, no dependency. The trade-off is that the\n * counter lives in one process — with several instances behind a load balancer\n * each keeps its own, so the effective limit is per-instance, not global. For a\n * contact form that's fine (it raises the cost of flooding without pretending\n * to be airtight); a high-security form should put a real limiter in front.\n *\n * State is module-level, so it survives between requests but resets on redeploy\n * — acceptable for abuse throttling.\n */\nconst buckets = new Map<string, Bucket>()\n\n/** Sweep expired buckets occasionally so the map doesn't grow unbounded. */\nlet lastSweep = Date.now()\nconst SWEEP_INTERVAL = 60_000\n\nfunction sweep(now: number) {\n if (now - lastSweep < SWEEP_INTERVAL) {return}\n lastSweep = now\n for (const [key, bucket] of buckets) {\n if (bucket.resetAt <= now) {buckets.delete(key)}\n }\n}\n\nexport type RateLimitArgs = {\n /** Identifier to limit on — typically the client IP. */\n key: string\n /** Max submissions allowed per window. Defaults to 5. */\n max?: number\n /** Window length in ms. Defaults to 60_000 (one minute). */\n windowMs?: number\n}\n\n/**\n * Returns true when the request is within the limit, false when it should be\n * rejected. A missing key (no IP) is allowed through — better to accept a\n * submission than to block everyone behind a proxy that strips the header.\n */\nexport function checkRateLimit({ key, max = 5, windowMs = 60_000 }: RateLimitArgs): boolean {\n if (!key) {return true}\n\n const now = Date.now()\n sweep(now)\n\n const bucket = buckets.get(key)\n\n if (!bucket || bucket.resetAt <= now) {\n buckets.set(key, { count: 1, resetAt: now + windowMs })\n return true\n }\n\n if (bucket.count >= max) {\n return false\n }\n\n bucket.count += 1\n return true\n}\n"],"names":["buckets","Map","lastSweep","Date","now","SWEEP_INTERVAL","sweep","key","bucket","resetAt","delete","checkRateLimit","max","windowMs","get","set","count"],"mappings":"AAEA;;;;;;;;;;;CAWC,GACD,MAAMA,UAAU,IAAIC;AAEpB,0EAA0E,GAC1E,IAAIC,YAAYC,KAAKC,GAAG;AACxB,MAAMC,iBAAiB;AAEvB,SAASC,MAAMF,GAAW;IACxB,IAAIA,MAAMF,YAAYG,gBAAgB;QAAC;IAAM;IAC7CH,YAAYE;IACZ,KAAK,MAAM,CAACG,KAAKC,OAAO,IAAIR,QAAS;QACnC,IAAIQ,OAAOC,OAAO,IAAIL,KAAK;YAACJ,QAAQU,MAAM,CAACH;QAAI;IACjD;AACF;AAWA;;;;CAIC,GACD,OAAO,SAASI,eAAe,EAAEJ,GAAG,EAAEK,MAAM,CAAC,EAAEC,WAAW,MAAM,EAAiB;IAC/E,IAAI,CAACN,KAAK;QAAC,OAAO;IAAI;IAEtB,MAAMH,MAAMD,KAAKC,GAAG;IACpBE,MAAMF;IAEN,MAAMI,SAASR,QAAQc,GAAG,CAACP;IAE3B,IAAI,CAACC,UAAUA,OAAOC,OAAO,IAAIL,KAAK;QACpCJ,QAAQe,GAAG,CAACR,KAAK;YAAES,OAAO;YAAGP,SAASL,MAAMS;QAAS;QACrD,OAAO;IACT;IAEA,IAAIL,OAAOQ,KAAK,IAAIJ,KAAK;QACvB,OAAO;IACT;IAEAJ,OAAOQ,KAAK,IAAI;IAChB,OAAO;AACT"}
|
||||
{"version":3,"sources":["../../../src/modules/forms/rateLimit.ts"],"sourcesContent":["// Moved to modules/shared/rateLimit.ts (shared with search and MCP routes).\nexport { checkRateLimit, clientIp, retryAfterSeconds, tooManyRequests } from '../shared/rateLimit.js'\nexport type { RateLimitArgs } from '../shared/rateLimit.js'\n"],"names":["checkRateLimit","clientIp","retryAfterSeconds","tooManyRequests"],"mappings":"AAAA,4EAA4E;AAC5E,SAASA,cAAc,EAAEC,QAAQ,EAAEC,iBAAiB,EAAEC,eAAe,QAAQ,yBAAwB"}
|
||||
Vendored
+34
-28
@@ -1,15 +1,13 @@
|
||||
import 'server-only';
|
||||
import type { BasePayload } from 'payload';
|
||||
export type SubmitFormArgs = {
|
||||
/**
|
||||
* Name of the GDPR consent checkbox. A field with this name must be checked
|
||||
* for the submission to succeed (enforced server-side). Defaults to 'consent'.
|
||||
*/
|
||||
consentFieldName?: string;
|
||||
/** Submitted field data — shape matches the form's fields. */
|
||||
data: Record<string, unknown>;
|
||||
payload: BasePayload;
|
||||
/** Form-builder form ID this submission belongs to. */
|
||||
formId: string;
|
||||
/** Submitted field data — shape matches the form's fields. */
|
||||
data: Record<string, unknown>;
|
||||
/** Turnstile token; when present it is verified, when absent it is skipped. */
|
||||
turnstileToken?: string;
|
||||
/** Client IP — used for Turnstile and rate limiting. */
|
||||
ip?: string;
|
||||
/**
|
||||
@@ -17,9 +15,17 @@ export type SubmitFormArgs = {
|
||||
* Set to 0 to disable (e.g. when a real limiter sits in front).
|
||||
*/
|
||||
maxPerMinute?: number;
|
||||
payload: BasePayload;
|
||||
/** Turnstile token; when present it is verified, when absent it is skipped. */
|
||||
turnstileToken?: string;
|
||||
/**
|
||||
* Name of the GDPR consent checkbox. A field with this name must be checked
|
||||
* for the submission to succeed (enforced server-side). Defaults to 'consent'.
|
||||
*/
|
||||
consentFieldName?: string;
|
||||
/**
|
||||
* Turnstile can't be verified because of OUR side (missing/wrong secret,
|
||||
* Cloudflare unreachable): 'allow' (default) accepts the submission and shows
|
||||
* the problem in the panel; 'reject' refuses it.
|
||||
*/
|
||||
turnstileOnConfigError?: 'allow' | 'reject';
|
||||
};
|
||||
/**
|
||||
* Why a submission failed — a code, never a user-facing string.
|
||||
@@ -39,34 +45,34 @@ export type SubmitFormArgs = {
|
||||
* - `error` — persistence failed unexpectedly
|
||||
*/
|
||||
export type SubmitFailure = {
|
||||
success: false;
|
||||
reason: 'rate_limited';
|
||||
} | {
|
||||
success: false;
|
||||
reason: 'turnstile';
|
||||
} | {
|
||||
success: false;
|
||||
reason: 'validation';
|
||||
/** The offending field's name, when one field is at fault. */
|
||||
field?: string;
|
||||
/** What was wrong with it. */
|
||||
kind?: 'required' | 'too_long' | 'unknown_fields';
|
||||
reason: 'validation';
|
||||
success: false;
|
||||
} | {
|
||||
field?: string;
|
||||
success: false;
|
||||
reason: 'not_found';
|
||||
} | {
|
||||
success: false;
|
||||
/** A GDPR consent field existed on the form but wasn't checked. */
|
||||
reason: 'consent';
|
||||
success: false;
|
||||
field?: string;
|
||||
} | {
|
||||
success: false;
|
||||
reason: 'error';
|
||||
success: false;
|
||||
} | {
|
||||
reason: 'not_found';
|
||||
success: false;
|
||||
} | {
|
||||
reason: 'rate_limited';
|
||||
success: false;
|
||||
} | {
|
||||
reason: 'turnstile';
|
||||
success: false;
|
||||
};
|
||||
export type SubmitFormResult = {
|
||||
submissionId: number | string;
|
||||
export type SubmitFormResult = SubmitFailure | {
|
||||
success: true;
|
||||
} | SubmitFailure;
|
||||
submissionId: string | number;
|
||||
};
|
||||
/**
|
||||
* Handles a form submission end to end: rate limit, verify Turnstile, validate
|
||||
* against the form's own schema, then store.
|
||||
@@ -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<SubmitFormResult>;
|
||||
export declare function submitForm({ payload, formId, data, turnstileToken, ip, maxPerMinute, consentFieldName, turnstileOnConfigError, }: SubmitFormArgs): Promise<SubmitFormResult>;
|
||||
|
||||
Vendored
+18
-17
@@ -1,7 +1,7 @@
|
||||
import 'server-only';
|
||||
import { verifyTurnstile } from '../turnstile/index.js';
|
||||
import { checkRateLimit } from './rateLimit.js';
|
||||
import { validateSubmission } from './validateSubmission.js';
|
||||
import { checkRateLimit } from './rateLimit.js';
|
||||
/**
|
||||
* Handles a form submission end to end: rate limit, verify Turnstile, validate
|
||||
* against the form's own schema, then store.
|
||||
@@ -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({ payload, formId, data, turnstileToken, ip, maxPerMinute = 5, consentFieldName, turnstileOnConfigError = 'allow' }) {
|
||||
// 1. Rate limit — cheapest gate, drops a flood before any real work.
|
||||
if (maxPerMinute > 0 && ip) {
|
||||
if (!checkRateLimit({
|
||||
@@ -22,22 +22,23 @@ import { validateSubmission } from './validateSubmission.js';
|
||||
max: maxPerMinute
|
||||
})) {
|
||||
return {
|
||||
reason: 'rate_limited',
|
||||
success: false
|
||||
success: false,
|
||||
reason: 'rate_limited'
|
||||
};
|
||||
}
|
||||
}
|
||||
// 2. Turnstile — verify when a token is supplied; reject on failure.
|
||||
if (turnstileToken !== undefined) {
|
||||
const ok = await verifyTurnstile({
|
||||
ip,
|
||||
token: turnstileToken,
|
||||
payload,
|
||||
token: turnstileToken
|
||||
ip,
|
||||
onConfigError: turnstileOnConfigError
|
||||
});
|
||||
if (!ok) {
|
||||
return {
|
||||
reason: 'turnstile',
|
||||
success: false
|
||||
success: false,
|
||||
reason: 'turnstile'
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -47,20 +48,20 @@ import { validateSubmission } from './validateSubmission.js';
|
||||
if (!validation.ok) {
|
||||
if (validation.reason === 'not_found') {
|
||||
return {
|
||||
reason: 'not_found',
|
||||
success: false
|
||||
success: false,
|
||||
reason: 'not_found'
|
||||
};
|
||||
}
|
||||
if (validation.reason === 'consent') {
|
||||
return {
|
||||
field: validation.field,
|
||||
success: false,
|
||||
reason: 'consent',
|
||||
success: false
|
||||
field: validation.field
|
||||
};
|
||||
}
|
||||
return {
|
||||
reason: 'validation',
|
||||
success: false,
|
||||
reason: 'validation',
|
||||
...validation.field ? {
|
||||
field: validation.field
|
||||
} : {},
|
||||
@@ -83,14 +84,14 @@ import { validateSubmission } from './validateSubmission.js';
|
||||
}
|
||||
});
|
||||
return {
|
||||
submissionId: submission.id,
|
||||
success: true
|
||||
success: true,
|
||||
submissionId: submission.id
|
||||
};
|
||||
} catch (err) {
|
||||
payload.logger.error(`[ipal] Form submission failed: ${err.message}`);
|
||||
return {
|
||||
reason: 'error',
|
||||
success: false
|
||||
success: false,
|
||||
reason: 'error'
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
Vendored
+1
-1
File diff suppressed because one or more lines are too long
Vendored
+19
-13
@@ -18,23 +18,25 @@ export type FormsCollectionOverrides = {
|
||||
* form-builder plugin. Kept minimal; the plugin passes these through.
|
||||
*/
|
||||
export type FormsOption = {
|
||||
/** Field types available in the form builder. Sensible defaults applied. */
|
||||
fields?: {
|
||||
text?: boolean;
|
||||
textarea?: boolean;
|
||||
email?: boolean;
|
||||
number?: boolean;
|
||||
select?: boolean;
|
||||
checkbox?: boolean;
|
||||
message?: boolean;
|
||||
payment?: boolean;
|
||||
};
|
||||
/** Collections a form can redirect to (e.g. ['pages']). */
|
||||
redirectRelationships?: string[];
|
||||
/**
|
||||
* Name of the checkbox field treated as a GDPR consent gate. A form field
|
||||
* with this name must be checked for submission to succeed — enforced
|
||||
* server-side in submitForm. Defaults to 'consent'.
|
||||
*/
|
||||
consentFieldName?: string;
|
||||
/** Field types available in the form builder. Sensible defaults applied. */
|
||||
fields?: {
|
||||
checkbox?: boolean;
|
||||
email?: boolean;
|
||||
message?: boolean;
|
||||
number?: boolean;
|
||||
payment?: boolean;
|
||||
select?: boolean;
|
||||
text?: boolean;
|
||||
textarea?: boolean;
|
||||
};
|
||||
/**
|
||||
* Override the forms collection. The plugin stays opinion-free about what a
|
||||
* form needs beyond its fields — a client that wants, say, a per-form
|
||||
@@ -50,6 +52,10 @@ export type FormsOption = {
|
||||
formOverrides?: FormsCollectionOverrides;
|
||||
/** Override the form-submissions collection (same shape). */
|
||||
formSubmissionOverrides?: FormsCollectionOverrides;
|
||||
/** Collections a form can redirect to (e.g. ['pages']). */
|
||||
redirectRelationships?: string[];
|
||||
/**
|
||||
* Admin sidebar group for Forms + Form Submissions. Default 'Forms'.
|
||||
* `false` = Payload default ("Collections"). An explicit `admin.group` in
|
||||
* formOverrides / formSubmissionOverrides still wins.
|
||||
*/
|
||||
adminGroup?: string | false;
|
||||
};
|
||||
|
||||
Vendored
+1
-1
@@ -1 +1 @@
|
||||
{"version":3,"sources":["../../../src/modules/forms/types.ts"],"sourcesContent":["import type { CollectionConfig, Field } from 'payload'\n\n/**\n * Receives the collection's default fields and returns the final list — add,\n * remove, or reorder. Same shape the form-builder uses.\n */\nexport type FormsFieldsOverride = (args: { defaultFields: Field[] }) => Field[]\n\n/**\n * Overrides for a forms-related collection: replace the fields and/or any\n * other collection setting (admin, access, hooks…).\n */\nexport type FormsCollectionOverrides = {\n fields?: FormsFieldsOverride\n} & Partial<Omit<CollectionConfig, 'fields'>>\n\n/**\n * Forms configuration — mirrors the fields a client enables in the\n * form-builder plugin. Kept minimal; the plugin passes these through.\n */\nexport type FormsOption = {\n /**\n * Name of the checkbox field treated as a GDPR consent gate. A form field\n * with this name must be checked for submission to succeed — enforced\n * server-side in submitForm. Defaults to 'consent'.\n */\n consentFieldName?: string\n /** Field types available in the form builder. Sensible defaults applied. */\n fields?: {\n checkbox?: boolean\n email?: boolean\n message?: boolean\n number?: boolean\n payment?: boolean\n select?: boolean\n text?: boolean\n textarea?: boolean\n }\n /**\n * Override the forms collection. The plugin stays opinion-free about what a\n * form needs beyond its fields — a client that wants, say, a per-form\n * notification address adds it here:\n *\n * formOverrides: {\n * fields: ({ defaultFields }) => [\n * ...defaultFields,\n * { name: 'notificationEmail', type: 'email' },\n * ],\n * }\n */\n formOverrides?: FormsCollectionOverrides\n /** Override the form-submissions collection (same shape). */\n formSubmissionOverrides?: FormsCollectionOverrides\n /** Collections a form can redirect to (e.g. ['pages']). */\n redirectRelationships?: string[]\n}\n"],"names":[],"mappings":"AAgBA;;;CAGC,GACD,WAmCC"}
|
||||
{"version":3,"sources":["../../../src/modules/forms/types.ts"],"sourcesContent":["import type { CollectionConfig, Field } from 'payload'\n\n/**\n * Receives the collection's default fields and returns the final list — add,\n * remove, or reorder. Same shape the form-builder uses.\n */\nexport type FormsFieldsOverride = (args: { defaultFields: Field[] }) => Field[]\n\n/**\n * Overrides for a forms-related collection: replace the fields and/or any\n * other collection setting (admin, access, hooks…).\n */\nexport type FormsCollectionOverrides = {\n fields?: FormsFieldsOverride\n} & Partial<Omit<CollectionConfig, 'fields'>>\n\n/**\n * Forms configuration — mirrors the fields a client enables in the\n * form-builder plugin. Kept minimal; the plugin passes these through.\n */\nexport type FormsOption = {\n /** Field types available in the form builder. Sensible defaults applied. */\n fields?: {\n text?: boolean\n textarea?: boolean\n email?: boolean\n number?: boolean\n select?: boolean\n checkbox?: boolean\n message?: boolean\n payment?: boolean\n }\n /** Collections a form can redirect to (e.g. ['pages']). */\n redirectRelationships?: string[]\n /**\n * Name of the checkbox field treated as a GDPR consent gate. A form field\n * with this name must be checked for submission to succeed — enforced\n * server-side in submitForm. Defaults to 'consent'.\n */\n consentFieldName?: string\n /**\n * Override the forms collection. The plugin stays opinion-free about what a\n * form needs beyond its fields — a client that wants, say, a per-form\n * notification address adds it here:\n *\n * formOverrides: {\n * fields: ({ defaultFields }) => [\n * ...defaultFields,\n * { name: 'notificationEmail', type: 'email' },\n * ],\n * }\n */\n formOverrides?: FormsCollectionOverrides\n /** Override the form-submissions collection (same shape). */\n formSubmissionOverrides?: FormsCollectionOverrides\n /**\n * Admin sidebar group for Forms + Form Submissions. Default 'Forms'.\n * `false` = Payload default (\"Collections\"). An explicit `admin.group` in\n * formOverrides / formSubmissionOverrides still wins.\n */\n adminGroup?: string | false\n}\n"],"names":[],"mappings":"AAgBA;;;CAGC,GACD,WAyCC"}
|
||||
@@ -0,0 +1,16 @@
|
||||
import type { Payload } from 'payload';
|
||||
type Props = {
|
||||
/** Injected by Payload into admin server components. */
|
||||
payload?: Payload;
|
||||
/** Status groups to check: field name → label. */
|
||||
checks?: Record<string, string>;
|
||||
/** Admin route, for the link. Default '/admin'. */
|
||||
adminRoute?: string;
|
||||
};
|
||||
/**
|
||||
* 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({ payload, checks, adminRoute }: Props): Promise<import("react/jsx-runtime").JSX.Element | null>;
|
||||
export default IntegrationAlerts;
|
||||
+69
@@ -0,0 +1,69 @@
|
||||
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({ payload, checks = {
|
||||
turnstileStatus: 'Turnstile',
|
||||
emailStatus: 'Email'
|
||||
}, adminRoute = '/admin' }) {
|
||||
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: {
|
||||
marginBottom: '1.5rem',
|
||||
padding: '1rem 1.25rem',
|
||||
borderRadius: 4,
|
||||
border: '1px solid var(--theme-error-400, #e5484d)',
|
||||
background: 'var(--theme-error-50, rgba(229, 72, 77, 0.08))'
|
||||
},
|
||||
children: [
|
||||
/*#__PURE__*/ _jsx("strong", {
|
||||
children: "Integration problem — the site still works, but something needs attention."
|
||||
}),
|
||||
/*#__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
|
||||
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../../src/modules/integrations/IntegrationAlerts.tsx"],"sourcesContent":["import type { Payload } from 'payload'\nimport type { IntegrationStatus } from './status.js'\n\ntype Props = {\n /** Injected by Payload into admin server components. */\n payload?: Payload\n /** Status groups to check: field name → label. */\n checks?: Record<string, string>\n /** Admin route, for the link. Default '/admin'. */\n adminRoute?: string\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({ payload, checks = { turnstileStatus: 'Turnstile', emailStatus: 'Email' }, adminRoute = '/admin' }: Props) {\n if (!payload) return null\n let doc: Record<string, unknown>\n try {\n doc = (await payload.findGlobal({ slug: 'site-integrations' as never, depth: 0 })) as Record<string, unknown>\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 <div\n role=\"alert\"\n style={{\n marginBottom: '1.5rem',\n padding: '1rem 1.25rem',\n borderRadius: 4,\n border: '1px solid var(--theme-error-400, #e5484d)',\n background: 'var(--theme-error-50, rgba(229, 72, 77, 0.08))',\n }}\n >\n <strong>Integration problem — the site still works, but something needs attention.</strong>\n <ul style={{ margin: '0.5rem 0 0', paddingLeft: '1.2rem' }}>\n {failing.map(({ label, status }) => (\n <li key={label}>\n <strong>{label}:</strong> {status?.message ?? status?.code ?? 'error'}\n </li>\n ))}\n </ul>\n <a href={`${adminRoute.replace(/\\/$/, '')}/globals/site-integrations`} style={{ display: 'inline-block', marginTop: '0.5rem' }}>\n Open Site Integrations →\n </a>\n </div>\n )\n}\n\nexport default IntegrationAlerts\n"],"names":["IntegrationAlerts","payload","checks","turnstileStatus","emailStatus","adminRoute","doc","findGlobal","slug","depth","failing","Object","entries","map","field","label","status","filter","x","state","length","div","role","style","marginBottom","padding","borderRadius","border","background","strong","ul","margin","paddingLeft","li","message","code","a","href","replace","display","marginTop"],"mappings":";AAYA;;;;CAIC,GACD,OAAO,eAAeA,kBAAkB,EAAEC,OAAO,EAAEC,SAAS;IAAEC,iBAAiB;IAAaC,aAAa;AAAQ,CAAC,EAAEC,aAAa,QAAQ,EAAS;IAChJ,IAAI,CAACJ,SAAS,OAAO;IACrB,IAAIK;IACJ,IAAI;QACFA,MAAO,MAAML,QAAQM,UAAU,CAAC;YAAEC,MAAM;YAA8BC,OAAO;QAAE;IACjF,EAAE,OAAM;QACN,OAAO;IACT;IACA,MAAMC,UAAUC,OAAOC,OAAO,CAACV,QAC5BW,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,OAAO;IAE5B,qBACE,MAACC;QACCC,MAAK;QACLC,OAAO;YACLC,cAAc;YACdC,SAAS;YACTC,cAAc;YACdC,QAAQ;YACRC,YAAY;QACd;;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,GAAGhC,WAAWiC,OAAO,CAAC,OAAO,IAAI,0BAA0B,CAAC;gBAAEf,OAAO;oBAAEgB,SAAS;oBAAgBC,WAAW;gBAAS;0BAAG;;;;AAKtI;AAEA,eAAexC,kBAAiB"}
|
||||
@@ -0,0 +1,13 @@
|
||||
type Props = {
|
||||
/** Name of the hidden status group (buildIntegrationStatusField). */
|
||||
statusField: string;
|
||||
/** Integration name shown in the banner, e.g. 'Turnstile'. */
|
||||
label: 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({ statusField, label }: Props): import("react/jsx-runtime").JSX.Element | null;
|
||||
export default IntegrationStatusBanner;
|
||||
@@ -0,0 +1,83 @@
|
||||
'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({ statusField, label }) {
|
||||
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: {
|
||||
marginBottom: '1.5rem',
|
||||
fontSize: '0.85rem',
|
||||
opacity: 0.75
|
||||
},
|
||||
children: [
|
||||
"✓ ",
|
||||
label,
|
||||
" working",
|
||||
since ? ` since ${fmt(since)}` : '',
|
||||
"."
|
||||
]
|
||||
});
|
||||
}
|
||||
return /*#__PURE__*/ _jsxs("div", {
|
||||
role: "alert",
|
||||
style: {
|
||||
marginBottom: '1.5rem',
|
||||
padding: '0.9rem 1rem',
|
||||
borderRadius: 4,
|
||||
border: '1px solid var(--theme-error-400, #e5484d)',
|
||||
background: 'var(--theme-error-50, rgba(229, 72, 77, 0.08))'
|
||||
},
|
||||
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: {
|
||||
marginTop: '0.35rem',
|
||||
fontSize: '0.8rem',
|
||||
opacity: 0.75
|
||||
},
|
||||
children: [
|
||||
code ? `Code: ${code}. ` : '',
|
||||
since ? `Since ${fmt(since)}. ` : '',
|
||||
checkedAt ? `Last seen ${fmt(checkedAt)}.` : ''
|
||||
]
|
||||
}),
|
||||
/*#__PURE__*/ _jsx("div", {
|
||||
style: {
|
||||
marginTop: '0.35rem',
|
||||
fontSize: '0.8rem',
|
||||
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
|
||||
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../../src/modules/integrations/IntegrationStatusBanner.tsx"],"sourcesContent":["'use client'\nimport { useFormFields } from '@payloadcms/ui'\n\ntype Props = {\n /** Name of the hidden status group (buildIntegrationStatusField). */\n statusField: string\n /** Integration name shown in the banner, e.g. 'Turnstile'. */\n label: 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({ statusField, label }: 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 <div style={{ marginBottom: '1.5rem', fontSize: '0.85rem', opacity: 0.75 }}>\n ✓ {label} working{since ? ` since ${fmt(since)}` : ''}.\n </div>\n )\n }\n\n return (\n <div\n role=\"alert\"\n style={{\n marginBottom: '1.5rem',\n padding: '0.9rem 1rem',\n borderRadius: 4,\n border: '1px solid var(--theme-error-400, #e5484d)',\n background: 'var(--theme-error-50, rgba(229, 72, 77, 0.08))',\n }}\n >\n <strong>{label} is not working — forms are accepted without this check.</strong>\n {message ? <div style={{ marginTop: '0.35rem' }}>{message}</div> : null}\n <div style={{ marginTop: '0.35rem', fontSize: '0.8rem', opacity: 0.75 }}>\n {code ? `Code: ${code}. ` : ''}\n {since ? `Since ${fmt(since)}. ` : ''}\n {checkedAt ? `Last seen ${fmt(checkedAt)}.` : ''}\n </div>\n <div style={{ marginTop: '0.35rem', fontSize: '0.8rem', opacity: 0.75 }}>\n Fix the keys below and save — the status is checked again on the next form submission.\n </div>\n </div>\n )\n}\n\nexport default IntegrationStatusBanner\n"],"names":["useFormFields","fmt","iso","d","Date","Number","isNaN","getTime","toLocaleString","IntegrationStatusBanner","statusField","label","state","f","value","message","code","since","checkedAt","div","style","marginBottom","fontSize","opacity","role","padding","borderRadius","border","background","strong","marginTop"],"mappings":"AAAA;;AACA,SAASA,aAAa,QAAQ,iBAAgB;AAS9C,MAAMC,MAAM,CAACC;IACX,IAAI,OAAOA,QAAQ,YAAY,CAACA,KAAK,OAAO;IAC5C,MAAMC,IAAI,IAAIC,KAAKF;IACnB,OAAOG,OAAOC,KAAK,CAACH,EAAEI,OAAO,MAAM,KAAKJ,EAAEK,cAAc;AAC1D;AAEA;;;;CAIC,GACD,OAAO,SAASC,wBAAwB,EAAEC,WAAW,EAAEC,KAAK,EAAS;IACnE,MAAMC,QAAQZ,cAAc,CAAC,CAACa,EAAE,GAAKA,CAAC,CAAC,GAAGH,YAAY,MAAM,CAAC,CAAC,EAAEI;IAChE,MAAMC,UAAUf,cAAc,CAAC,CAACa,EAAE,GAAKA,CAAC,CAAC,GAAGH,YAAY,QAAQ,CAAC,CAAC,EAAEI;IACpE,MAAME,OAAOhB,cAAc,CAAC,CAACa,EAAE,GAAKA,CAAC,CAAC,GAAGH,YAAY,KAAK,CAAC,CAAC,EAAEI;IAC9D,MAAMG,QAAQjB,cAAc,CAAC,CAACa,EAAE,GAAKA,CAAC,CAAC,GAAGH,YAAY,MAAM,CAAC,CAAC,EAAEI;IAChE,MAAMI,YAAYlB,cAAc,CAAC,CAACa,EAAE,GAAKA,CAAC,CAAC,GAAGH,YAAY,UAAU,CAAC,CAAC,EAAEI;IAExE,IAAI,CAACF,OAAO,OAAO;IAEnB,IAAIA,UAAU,MAAM;QAClB,qBACE,MAACO;YAAIC,OAAO;gBAAEC,cAAc;gBAAUC,UAAU;gBAAWC,SAAS;YAAK;;gBAAG;gBACvEZ;gBAAM;gBAASM,QAAQ,CAAC,OAAO,EAAEhB,IAAIgB,QAAQ,GAAG;gBAAG;;;IAG5D;IAEA,qBACE,MAACE;QACCK,MAAK;QACLJ,OAAO;YACLC,cAAc;YACdI,SAAS;YACTC,cAAc;YACdC,QAAQ;YACRC,YAAY;QACd;;0BAEA,MAACC;;oBAAQlB;oBAAM;;;YACdI,wBAAU,KAACI;gBAAIC,OAAO;oBAAEU,WAAW;gBAAU;0BAAIf;iBAAiB;0BACnE,MAACI;gBAAIC,OAAO;oBAAEU,WAAW;oBAAWR,UAAU;oBAAUC,SAAS;gBAAK;;oBACnEP,OAAO,CAAC,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;oBAAEU,WAAW;oBAAWR,UAAU;oBAAUC,SAAS;gBAAK;0BAAG;;;;AAK/E;AAEA,eAAed,wBAAuB"}
|
||||
Vendored
+2
@@ -0,0 +1,2 @@
|
||||
export { recordIntegrationStatus, buildIntegrationStatusField, buildIntegrationStatusBanner, } from './status.js';
|
||||
export type { IntegrationStatus, IntegrationState } from './status.js';
|
||||
Vendored
+3
@@ -0,0 +1,3 @@
|
||||
export { recordIntegrationStatus, buildIntegrationStatusField, buildIntegrationStatusBanner } from './status.js';
|
||||
|
||||
//# sourceMappingURL=index.js.map
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"sources":["../../../src/modules/integrations/index.ts"],"sourcesContent":["export {\n recordIntegrationStatus,\n buildIntegrationStatusField,\n buildIntegrationStatusBanner,\n} from './status.js'\nexport type { IntegrationStatus, IntegrationState } from './status.js'\n"],"names":["recordIntegrationStatus","buildIntegrationStatusField","buildIntegrationStatusBanner"],"mappings":"AAAA,SACEA,uBAAuB,EACvBC,2BAA2B,EAC3BC,4BAA4B,QACvB,cAAa"}
|
||||
+37
@@ -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 = 'ok' | 'degraded';
|
||||
export type IntegrationStatus = {
|
||||
state?: IntegrationState | null;
|
||||
/** Machine code from the provider or the plugin, e.g. 'invalid-input-secret', 'missing-secret'. */
|
||||
code?: string | null;
|
||||
/** Human explanation shown in the panel (English — panel language). */
|
||||
message?: string | null;
|
||||
/** When the current state started. */
|
||||
since?: string | null;
|
||||
/** Last time the integration was used (refreshed at most every REFRESH_MS). */
|
||||
checkedAt?: string | null;
|
||||
};
|
||||
/** 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: {
|
||||
state: IntegrationState;
|
||||
code?: string;
|
||||
message?: string;
|
||||
}): Promise<void>;
|
||||
Vendored
+88
@@ -0,0 +1,88 @@
|
||||
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: {
|
||||
path: '@intecion/ipal-kit/client#IntegrationStatusBanner',
|
||||
clientProps: {
|
||||
statusField,
|
||||
label
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
/**
|
||||
* 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 = {
|
||||
state: next.state,
|
||||
code: next.code ?? null,
|
||||
message: next.message ?? null,
|
||||
since: changed ? now.toISOString() : previous?.since ?? now.toISOString(),
|
||||
checkedAt: now.toISOString()
|
||||
};
|
||||
try {
|
||||
await payload.updateGlobal({
|
||||
slug: SITE_INTEGRATIONS,
|
||||
data: {
|
||||
[field]: status
|
||||
},
|
||||
depth: 0,
|
||||
context: {
|
||||
ipalIntegrationStatus: true
|
||||
}
|
||||
});
|
||||
} catch (err) {
|
||||
console.warn(`[ipal] could not record ${field}:`, err instanceof Error ? err.message : err);
|
||||
}
|
||||
}
|
||||
|
||||
//# sourceMappingURL=status.js.map
|
||||
+1
File diff suppressed because one or more lines are too long
Vendored
+10
@@ -10,6 +10,16 @@ type CreateMcpRouteArgs = {
|
||||
/** Archive-backed collections (same as the plugin option) for get_page. */
|
||||
content?: ContentOption;
|
||||
getCachedPayload: () => Promise<BasePayload>;
|
||||
/** Max messages in one JSON-RPC batch. Default 10. */
|
||||
maxBatch?: number;
|
||||
/**
|
||||
* Per-IP limit on JSON-RPC messages (a batch counts every message) (in memory, per instance). Default { max: 60, windowMs: 60_000 }.
|
||||
* `false` = off (a limiter in front, e.g. Cloudflare WAF rate limiting).
|
||||
*/
|
||||
rateLimit?: {
|
||||
max?: number;
|
||||
windowMs?: number;
|
||||
} | false;
|
||||
/** Server name advertised in `initialize`. Default 'ipal-site'. */
|
||||
serverName?: string;
|
||||
/** Server version advertised in `initialize`. Default '1.0.0'. */
|
||||
|
||||
Vendored
+26
-1
@@ -1,5 +1,6 @@
|
||||
import { createMarkdownRenderer, searchContent } from '../content/index.js';
|
||||
import { getDefaultLocale, isValidLocale } from '../i18n/index.js';
|
||||
import { checkRateLimit, clientIp, tooManyRequests } from '../shared/rateLimit.js';
|
||||
/**
|
||||
* A read-only MCP (Model Context Protocol) server for the client site, as a Next
|
||||
* route handler. Lets Claude / any MCP client CONNECT to the site and query it
|
||||
@@ -59,7 +60,12 @@ function toolText(text, isError = false) {
|
||||
};
|
||||
}
|
||||
export function createMcpRoute(args) {
|
||||
const { baseUrl, collection = 'pages', config, content, getCachedPayload, serverName = 'ipal-site', serverVersion = '1.0.0', settingsSlug = 'site-settings', summaryField } = args;
|
||||
const { baseUrl, collection = 'pages', config, content, getCachedPayload, maxBatch = 10, serverName = 'ipal-site', serverVersion = '1.0.0', settingsSlug = 'site-settings', summaryField } = args;
|
||||
const rl = args.rateLimit === false ? null : {
|
||||
max: 60,
|
||||
windowMs: 60_000,
|
||||
...args.rateLimit
|
||||
};
|
||||
const origin = baseUrl?.replace(/\/$/, '') ?? '';
|
||||
const renderMarkdown = createMarkdownRenderer({
|
||||
collection,
|
||||
@@ -217,6 +223,25 @@ export function createMcpRoute(args) {
|
||||
status: 400
|
||||
});
|
||||
}
|
||||
// Limits: a batch counts as many requests as it has messages, and is capped —
|
||||
// otherwise one POST could carry hundreds of tool calls (DB queries).
|
||||
const messages = Array.isArray(body) ? body.length : 1;
|
||||
if (Array.isArray(body) && body.length > maxBatch) {
|
||||
return Response.json(rpcError(null, -32600, `Batch too large (max ${maxBatch})`), {
|
||||
status: 400
|
||||
});
|
||||
}
|
||||
if (rl) {
|
||||
const ip = clientIp(req);
|
||||
if (!checkRateLimit({
|
||||
cost: messages,
|
||||
key: ip,
|
||||
scope: 'mcp',
|
||||
...rl
|
||||
})) {
|
||||
return tooManyRequests(ip, 'mcp', rpcError(null, -32000, 'Too many requests'));
|
||||
}
|
||||
}
|
||||
// Batch or single.
|
||||
if (Array.isArray(body)) {
|
||||
const out = (await Promise.all(body.map((m)=>handleOne(m)))).filter((r)=>r !== null);
|
||||
|
||||
+1
-1
File diff suppressed because one or more lines are too long
Vendored
+28
@@ -0,0 +1,28 @@
|
||||
export type RateLimitArgs = {
|
||||
/** Identifier to limit on — typically the client IP. */
|
||||
key: string;
|
||||
/** Max submissions allowed per window. Defaults to 5. */
|
||||
max?: number;
|
||||
/** Separate counter space per feature, e.g. 'form', 'search', 'mcp'. Default 'form'. */
|
||||
scope?: string;
|
||||
/** Window length in ms. Defaults to 60_000 (one minute). */
|
||||
windowMs?: number;
|
||||
};
|
||||
/**
|
||||
* Returns true when the request is within the limit, false when it should be
|
||||
* rejected. A missing key (no IP) is allowed through — better to accept a
|
||||
* submission than to block everyone behind a proxy that strips the header.
|
||||
*/
|
||||
export declare function checkRateLimit({ cost, key, max, scope, windowMs }: {
|
||||
cost?: number;
|
||||
} & RateLimitArgs): boolean;
|
||||
/** Seconds until the key's window resets — for a Retry-After header. */
|
||||
export declare function retryAfterSeconds(key: string, scope?: string): number;
|
||||
/**
|
||||
* Client IP from a Request. Cloudflare's `cf-connecting-ip` first (set by the
|
||||
* edge, the real visitor), then the first `x-forwarded-for` hop, then
|
||||
* `x-real-ip`. Empty string when none — the limiter then lets the request through.
|
||||
*/
|
||||
export declare function clientIp(req: Request): string;
|
||||
/** Standard 429 for route handlers. */
|
||||
export declare function tooManyRequests(key: string, scope: string, body: unknown): Response;
|
||||
Vendored
+78
@@ -0,0 +1,78 @@
|
||||
/**
|
||||
* Per-key fixed window, in memory. Shared by submitForm, createSearchRoute and
|
||||
* createMcpRoute — each uses its own `scope`, so a busy search box never eats
|
||||
* into the contact form's budget.
|
||||
*
|
||||
* Deliberately simple: no Redis, no dependency. The trade-off is that the
|
||||
* counter lives in one process — with several instances behind a load balancer
|
||||
* each keeps its own, so the effective limit is per-instance, not global. For a
|
||||
* contact form that's fine (it raises the cost of flooding without pretending
|
||||
* to be airtight); a high-security form should put a real limiter in front.
|
||||
*
|
||||
* State is module-level, so it survives between requests but resets on redeploy
|
||||
* — acceptable for abuse throttling.
|
||||
*/ const buckets = new Map();
|
||||
/** Sweep expired buckets occasionally so the map doesn't grow unbounded. */ let lastSweep = Date.now();
|
||||
const SWEEP_INTERVAL = 60_000;
|
||||
function sweep(now) {
|
||||
if (now - lastSweep < SWEEP_INTERVAL) {
|
||||
return;
|
||||
}
|
||||
lastSweep = now;
|
||||
for (const [key, bucket] of buckets){
|
||||
if (bucket.resetAt <= now) {
|
||||
buckets.delete(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Returns true when the request is within the limit, false when it should be
|
||||
* rejected. A missing key (no IP) is allowed through — better to accept a
|
||||
* submission than to block everyone behind a proxy that strips the header.
|
||||
*/ export function checkRateLimit({ cost = 1, key, max = 5, scope = 'form', windowMs = 60_000 }) {
|
||||
if (!key) {
|
||||
return true;
|
||||
}
|
||||
const now = Date.now();
|
||||
sweep(now);
|
||||
const id = `${scope}:${key}`;
|
||||
const bucket = buckets.get(id);
|
||||
if (!bucket || bucket.resetAt <= now) {
|
||||
if (cost > max) {
|
||||
return false;
|
||||
}
|
||||
buckets.set(id, {
|
||||
count: cost,
|
||||
resetAt: now + windowMs
|
||||
});
|
||||
return true;
|
||||
}
|
||||
if (bucket.count + cost > max) {
|
||||
return false;
|
||||
}
|
||||
bucket.count += cost;
|
||||
return true;
|
||||
}
|
||||
/** Seconds until the key's window resets — for a Retry-After header. */ export function retryAfterSeconds(key, scope = 'form') {
|
||||
const bucket = buckets.get(`${scope}:${key}`);
|
||||
return bucket ? Math.max(1, Math.ceil((bucket.resetAt - Date.now()) / 1000)) : 1;
|
||||
}
|
||||
/**
|
||||
* Client IP from a Request. Cloudflare's `cf-connecting-ip` first (set by the
|
||||
* edge, the real visitor), then the first `x-forwarded-for` hop, then
|
||||
* `x-real-ip`. Empty string when none — the limiter then lets the request through.
|
||||
*/ export function clientIp(req) {
|
||||
const h = req.headers;
|
||||
return h.get('cf-connecting-ip')?.trim() || h.get('x-forwarded-for')?.split(',')[0]?.trim() || h.get('x-real-ip')?.trim() || '';
|
||||
}
|
||||
/** Standard 429 for route handlers. */ export function tooManyRequests(key, scope, body) {
|
||||
return Response.json(body, {
|
||||
headers: {
|
||||
'cache-control': 'no-store',
|
||||
'retry-after': String(retryAfterSeconds(key, scope))
|
||||
},
|
||||
status: 429
|
||||
});
|
||||
}
|
||||
|
||||
//# sourceMappingURL=rateLimit.js.map
|
||||
Vendored
+1
File diff suppressed because one or more lines are too long
Vendored
+2
-1
@@ -1,2 +1,3 @@
|
||||
export { verifyTurnstile, checkTurnstile } from './verify.js';
|
||||
export type { TurnstileCheck, TurnstileOutcome } from './verify.js';
|
||||
export { TurnstileProvider, useTurnstile } from './TurnstileProvider.js';
|
||||
export { verifyTurnstile } from './verify.js';
|
||||
|
||||
Vendored
+2
-2
@@ -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 { verifyTurnstile, checkTurnstile } from './verify.js';
|
||||
export { TurnstileProvider, useTurnstile } from './TurnstileProvider.js';
|
||||
|
||||
//# sourceMappingURL=index.js.map
|
||||
Vendored
+1
-1
@@ -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"}
|
||||
{"version":3,"sources":["../../../src/modules/turnstile/index.ts"],"sourcesContent":["// 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, checkTurnstile } from './verify.js'\nexport type { TurnstileCheck, TurnstileOutcome } from './verify.js'\nexport { TurnstileProvider, useTurnstile } from './TurnstileProvider.js'\n"],"names":["verifyTurnstile","checkTurnstile","TurnstileProvider","useTurnstile"],"mappings":"AAAA,8EAA8E;AAC9E,0EAA0E;AAC1E,SAASA,eAAe,EAAEC,cAAc,QAAQ,cAAa;AAE7D,SAASC,iBAAiB,EAAEC,YAAY,QAAQ,yBAAwB"}
|
||||
Vendored
+41
-14
@@ -1,23 +1,50 @@
|
||||
import 'server-only';
|
||||
import type { BasePayload } from 'payload';
|
||||
type VerifyTurnstileArgs = {
|
||||
/** Optional client IP for stricter verification. */
|
||||
ip?: string;
|
||||
/** Payload instance — used to read the secret from SiteIntegrations. */
|
||||
payload: BasePayload;
|
||||
/** Token produced by the client-side widget. */
|
||||
token: string;
|
||||
/** Payload instance — used to read the secret from SiteIntegrations. */
|
||||
payload: BasePayload;
|
||||
/** Client IP. Sent to Cloudflare only with `sendRemoteIp: true`. */
|
||||
ip?: string;
|
||||
/**
|
||||
* Send `remoteip` to Cloudflare. Default false: behind Cloudflare / Traefik /
|
||||
* Docker the IP the app sees can differ from the one that solved the challenge
|
||||
* (IPv6 on mobile vs IPv4 at the proxy), and Cloudflare's check doesn't need it.
|
||||
*/
|
||||
sendRemoteIp?: boolean;
|
||||
/**
|
||||
* What to do when verification can't run because of OUR side (missing/wrong
|
||||
* secret, Cloudflare unreachable). 'allow' (default): accept the submission —
|
||||
* rate limit, honeypot and validation still apply — and show the problem in
|
||||
* the panel. 'reject': refuse (fail closed).
|
||||
*/
|
||||
onConfigError?: 'allow' | 'reject';
|
||||
};
|
||||
/**
|
||||
* 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<boolean>;
|
||||
export type TurnstileOutcome = 'pass' | 'reject' | 'degraded';
|
||||
export type TurnstileCheck = {
|
||||
outcome: TurnstileOutcome;
|
||||
code?: string;
|
||||
};
|
||||
/**
|
||||
* 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({ token, payload, ip, sendRemoteIp, }: Omit<VerifyTurnstileArgs, 'onConfigError'>): Promise<TurnstileCheck>;
|
||||
/**
|
||||
* 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<boolean>;
|
||||
export {};
|
||||
|
||||
Vendored
+75
-26
@@ -1,41 +1,90 @@
|
||||
import 'server-only';
|
||||
import { getSiteIntegrations } from '../payload/index.js';
|
||||
import { recordIntegrationStatus } from '../integrations/status.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 = {
|
||||
'missing-input-secret': 'The secret key is missing in the request.',
|
||||
'invalid-input-secret': 'Cloudflare rejected the secret key — check Site Integrations → Turnstile (secret and site key must come from the same widget).',
|
||||
'internal-error': 'Cloudflare reported an internal error while verifying.'
|
||||
};
|
||||
const PLUGIN_ERRORS = {
|
||||
'missing-secret': `No secret key — fill in Site Integrations → Turnstile (or the ${ENV_SECRET} environment variable).`,
|
||||
'network-error': 'The server could not reach Cloudflare (challenges.cloudflare.com).',
|
||||
'bad-response': 'Cloudflare returned an unexpected response.'
|
||||
};
|
||||
/**
|
||||
* 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 }) {
|
||||
if (!token) {
|
||||
return false;
|
||||
}
|
||||
* 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({ token, payload, ip, sendRemoteIp = false }) {
|
||||
if (!token) return {
|
||||
outcome: 'reject',
|
||||
code: 'missing-input-response'
|
||||
};
|
||||
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)=>{
|
||||
const message = PLUGIN_ERRORS[code] ?? CONFIG_ERRORS[code] ?? `Cloudflare error: ${code}`;
|
||||
console.warn(`[ipal] Turnstile degraded (${code}): ${message}`);
|
||||
await recordIntegrationStatus(payload, STATUS_FIELD, previous, {
|
||||
state: 'degraded',
|
||||
code,
|
||||
message
|
||||
});
|
||||
return {
|
||||
outcome: 'degraded',
|
||||
code
|
||||
};
|
||||
};
|
||||
if (!secret) return degraded('missing-secret');
|
||||
const body = new URLSearchParams({
|
||||
response: token,
|
||||
secret
|
||||
secret,
|
||||
response: token
|
||||
});
|
||||
if (ip) {
|
||||
body.append('remoteip', ip);
|
||||
}
|
||||
if (sendRemoteIp && ip) body.append('remoteip', ip);
|
||||
let data;
|
||||
try {
|
||||
const res = await fetch('https://challenges.cloudflare.com/turnstile/v0/siteverify', {
|
||||
method: 'POST',
|
||||
body,
|
||||
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 {
|
||||
outcome: 'reject',
|
||||
code: codes[0] ?? 'unknown'
|
||||
};
|
||||
}
|
||||
/**
|
||||
* 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
|
||||
Vendored
+1
-1
File diff suppressed because one or more lines are too long
Vendored
+44
-33
@@ -1,14 +1,14 @@
|
||||
import { buildLocalizationConfig, validateI18nConfig } from './modules/i18n/index.js';
|
||||
import { injectRoles } from './modules/access/index.js';
|
||||
import { buildSeoPlugin, injectAutoFillMeta, injectSeoTabs } from './modules/seo/index.js';
|
||||
import { buildFormsPlugin } from './modules/forms/formsPluginConfig.js';
|
||||
import { buildSystemPagesFields } from './modules/pages/index.js';
|
||||
import { buildArchiveFields } from './modules/content/index.js';
|
||||
import { buildSiteSettings } from './globals/SiteSettings/index.js';
|
||||
import { buildSiteIntegrations } from './globals/SiteIntegrations/index.js';
|
||||
import { buildCookieSettings } from './globals/CookieSettings/index.js';
|
||||
import { buildNotifications } from './globals/Notifications/index.js';
|
||||
import { buildSiteIntegrations } from './globals/SiteIntegrations/index.js';
|
||||
import { buildSiteSettings } from './globals/SiteSettings/index.js';
|
||||
import { injectRoles } from './modules/access/index.js';
|
||||
import { buildArchiveFields } from './modules/content/index.js';
|
||||
import { testEmailEndpoint } from './modules/email/test/testEmailEndpoint.js';
|
||||
import { buildFormsPlugin } from './modules/forms/formsPluginConfig.js';
|
||||
import { buildLocalizationConfig, validateI18nConfig } from './modules/i18n/index.js';
|
||||
import { buildSystemPagesFields } from './modules/pages/index.js';
|
||||
import { buildSeoPlugin, injectAutoFillMeta, injectSeoTabs } from './modules/seo/index.js';
|
||||
/**
|
||||
* IPAL (Intecion Payload Advanced Library) plugin for Payload CMS 3.
|
||||
*
|
||||
@@ -100,12 +100,8 @@ import { buildSeoPlugin, injectAutoFillMeta, injectSeoTabs } from './modules/seo
|
||||
if (options.whiteLabel) {
|
||||
const wl = options.whiteLabel === true ? {} : options.whiteLabel;
|
||||
const serverProps = {};
|
||||
if (wl.settingsSlug) {
|
||||
serverProps.settingsSlug = wl.settingsSlug;
|
||||
}
|
||||
if (wl.nameField) {
|
||||
serverProps.nameField = wl.nameField;
|
||||
}
|
||||
if (wl.settingsSlug) serverProps.settingsSlug = wl.settingsSlug;
|
||||
if (wl.nameField) serverProps.nameField = wl.nameField;
|
||||
const logoProps = {
|
||||
...serverProps,
|
||||
...wl.logoField ? {
|
||||
@@ -135,26 +131,16 @@ import { buildSeoPlugin, injectAutoFillMeta, injectSeoTabs } from './modules/seo
|
||||
...config.admin?.components ?? {},
|
||||
graphics: {
|
||||
...config.admin?.components?.graphics ?? {},
|
||||
Icon: {
|
||||
path: '@intecion/ipal-kit/admin#AdminIcon',
|
||||
serverProps: iconProps
|
||||
},
|
||||
Logo: {
|
||||
path: '@intecion/ipal-kit/admin#AdminLogo',
|
||||
serverProps: logoProps
|
||||
},
|
||||
Icon: {
|
||||
path: '@intecion/ipal-kit/admin#AdminIcon',
|
||||
serverProps: iconProps
|
||||
}
|
||||
},
|
||||
...creditOn ? {
|
||||
afterLogin: [
|
||||
...config.admin?.components?.afterLogin ?? [],
|
||||
{
|
||||
path: '@intecion/ipal-kit/admin#IntecionCredit',
|
||||
serverProps: {
|
||||
...creditProps,
|
||||
variant: 'login'
|
||||
}
|
||||
}
|
||||
],
|
||||
afterNavLinks: [
|
||||
...config.admin?.components?.afterNavLinks ?? [],
|
||||
{
|
||||
@@ -164,6 +150,16 @@ import { buildSeoPlugin, injectAutoFillMeta, injectSeoTabs } from './modules/seo
|
||||
variant: 'nav'
|
||||
}
|
||||
}
|
||||
],
|
||||
afterLogin: [
|
||||
...config.admin?.components?.afterLogin ?? [],
|
||||
{
|
||||
path: '@intecion/ipal-kit/admin#IntecionCredit',
|
||||
serverProps: {
|
||||
...creditProps,
|
||||
variant: 'login'
|
||||
}
|
||||
}
|
||||
]
|
||||
} : {}
|
||||
},
|
||||
@@ -212,8 +208,8 @@ import { buildSeoPlugin, injectAutoFillMeta, injectSeoTabs } from './modules/seo
|
||||
config.globals = [
|
||||
...config.globals ?? [],
|
||||
buildSiteSettings({
|
||||
additionalFields: options.siteSettingsFields,
|
||||
systemPageFields
|
||||
systemPageFields,
|
||||
additionalFields: options.siteSettingsFields
|
||||
}),
|
||||
buildSiteIntegrations({
|
||||
additionalFields: options.integrationsFields
|
||||
@@ -225,12 +221,27 @@ 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)=>{
|
||||
if (incomingOnInit) {
|
||||
await incomingOnInit(payload);
|
||||
}
|
||||
if (incomingOnInit) await incomingOnInit(payload);
|
||||
payload.logger.info('[ipal] Plugin initialized.');
|
||||
};
|
||||
return config;
|
||||
|
||||
Vendored
+1
-1
File diff suppressed because one or more lines are too long
@@ -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 |
|
||||
|
||||
@@ -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;
|
||||
|
||||
+6
-2
@@ -315,8 +315,12 @@ Query: `?q=` (wymagane), `?locale=`, `?limit=`. Odpowiedź:
|
||||
"results": [{ "title": "O nas", "url": "https://x/pl/o-nas", "description": "…", "slug": "o-nas" }] }
|
||||
```
|
||||
|
||||
Brak `q` → 400. Tylko opublikowane, bez `noindex`. Błąd/baza offline → pusty
|
||||
wynik (200), nie 500. Niska wartość `s-maxage` (60s) — wyniki świeże, ale z
|
||||
Brak `q` → 400. Tylko opublikowane, bez `noindex`, maks. 50 wyników. Błąd/baza
|
||||
offline → pusty wynik (200), nie 500. **Limit zapytań:** 120/min na IP (w pamięci,
|
||||
per instancja) → `429` z `Retry-After`; zmiana: `rateLimit: { max, windowMs }`,
|
||||
wyłączenie (limiter z przodu, np. Cloudflare WAF): `rateLimit: false`.
|
||||
Kolizja z `@payloadcms/plugin-search` (kolekcja `search` → REST pod `/api/search/...`):
|
||||
przenieś route, np. `app/api/site-search/route.ts`. Niska wartość `s-maxage` (60s) — wyniki świeże, ale z
|
||||
cache'em CDN.
|
||||
|
||||
Sam helper (do własnej wyszukiwarki po stronie serwera):
|
||||
|
||||
@@ -490,6 +490,11 @@ 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 | `<script type="application/ld+json" dangerouslySetInnerHTML={{ __html: JSON.stringify(…) }}>` | `<JsonLdGraph schemas={[…]} />` z `@intecion/ipal-kit/rsc` (escapuje `<` — bez tego `</script>` 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 |
|
||||
| 15m | własny plugin przesuwający Notifications do grupy; `formOverrides`/`formSubmissionOverrides` tylko dla etykiet i grupy w panelu | usuń — plugin sam daje Notifications → Settings, a formularze → grupa „Forms” z etykietami (`forms.adminGroup`) | forms.md |
|
||||
| 15n | błędy maila widoczne tylko w logach | nic w projekcie: `mailAdapter()` pokazuje błąd wysyłki na dashboardzie i w Site Integrations → SMTP; `generate:importmap`, Postgres: `migrate:create` | email.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 |
|
||||
|
||||
@@ -189,3 +189,16 @@ czyta z bazy, nie z pola na ekranie.
|
||||
|
||||
> Bezcenne przy diagnozie Graph — od razu widzisz `ErrorSendAsDenied`,
|
||||
> `Insufficient privileges` itp. zamiast zgadywać.
|
||||
|
||||
## Status wysyłki w panelu
|
||||
|
||||
`mailAdapter()` zapisuje wynik wysyłek w Site Integrations (najwyżej raz na 10 min
|
||||
przy trwającym błędzie, od razu przy zmianie stanu). Gdy wysyłka się nie udaje:
|
||||
- **Dashboard** — czerwony alert z przyczyną i linkiem do Site Integrations,
|
||||
- **Site Integrations → SMTP** — baner z błędem (np. `SMTP: connect ECONNREFUSED …`,
|
||||
`SMTP is not configured…`, `Invalid login: 535 …`) i czasem.
|
||||
|
||||
Formularz przy tym **działa dalej** — zgłoszenie jest zapisane w Form Submissions,
|
||||
tylko mail nie wyszedł. Graph wybrany w panelu bez `GRAPH_*` w env → ostrzeżenie
|
||||
„sent over SMTP”. Zmiana pól SMTP / transportu w panelu czyści status; po kolejnej
|
||||
wysyłce (np. **Send test**) pojawi się aktualny.
|
||||
|
||||
+11
-1
@@ -48,7 +48,9 @@ ipalKit({
|
||||
```
|
||||
|
||||
Dodaje kolekcje **Forms** (edytor buduje formularze) i **Form Submissions**
|
||||
(zgłoszenia). Maile po zgłoszeniu wysyła form-builder według zakładki **Emails**
|
||||
(zgłoszenia) — w panelu w grupie **Forms** z etykietami „Form/Forms” i
|
||||
„Submission/Submissions” (bez nadpisań w projekcie). Inna grupa:
|
||||
`forms: { adminGroup: 'Content' }`; domyślna Payloada: `adminGroup: false`. Maile po zgłoszeniu wysyła form-builder według zakładki **Emails**
|
||||
formularza — przez adapter z `email:` w configu (sekcja „Maile” niżej).
|
||||
|
||||
## Front — submitForm (server)
|
||||
@@ -147,6 +149,14 @@ usuwać, zmieniać kolejność. Poza `fields` przyjmuje dowolne ustawienia kolek
|
||||
(in-memory, per IP), Turnstile, walidacja względem schematu formularza. Dopiero
|
||||
potem zapis. Flood ginie, zanim dotknie sieci czy bazy.
|
||||
|
||||
**REST zamknięty.** Form-builder domyślnie pozwala każdemu tworzyć zgłoszenia przez
|
||||
`POST /api/form-submissions` — z pominięciem wszystkich bramek poniżej. ipal-kit
|
||||
ustawia `access.create` kolekcji `form-submissions` na „tylko zalogowani”; front
|
||||
wysyła przez `submitForm` (server action → Local API), więc to go nie dotyczy.
|
||||
Świadomie publiczny REST (np. zewnętrzna aplikacja) →
|
||||
`forms: { formSubmissionOverrides: { access: { create: () => true } } }` — wtedy
|
||||
zabezpieczenia `submitForm` na tej drodze nie działają.
|
||||
|
||||
Walidacja jest istotna, bo server action to publiczny endpoint — da się go wołać
|
||||
z pominięciem formularza. Plugin ładuje definicję formularza i: odrzuca nieznane
|
||||
klucze, wymusza pola `required`, tnie długość (5000 znaków). Do bazy trafia tylko
|
||||
|
||||
+9
-2
@@ -58,7 +58,8 @@ wykona `initialize` → `tools/list` → i będzie mógł wołać `search_conten
|
||||
|
||||
`getCachedPayload`, `config` (wymagane); `baseUrl` (URL-e w wynikach), `collection`
|
||||
(`'pages'`), `settingsSlug`, `content` (kolekcje-archiwa dla `get_page`),
|
||||
`serverName` (`'ipal-site'`), `serverVersion` (`'1.0.0'`).
|
||||
`serverName` (`'ipal-site'`), `serverVersion` (`'1.0.0'`), `rateLimit`
|
||||
(`{ max: 60, windowMs: 60_000 }` na IP, `false` = wyłączony), `maxBatch` (`10`).
|
||||
|
||||
## Bezpieczeństwo
|
||||
|
||||
@@ -66,10 +67,16 @@ wykona `initialize` → `tools/list` → i będzie mógł wołać `search_conten
|
||||
- `search_content` używa `like` i odpada bezpiecznie (komunikat), gdy pole nie
|
||||
jest odpytywalne — nie wywala route'a.
|
||||
- Nie wystawiaj tu niczego spoza publicznej treści strony.
|
||||
- **Limit zapytań:** 60 wiadomości JSON-RPC/min na IP (batch liczy się jako tyle
|
||||
wiadomości, ile zawiera) → `429` z `Retry-After`. Batch > 10 → `400`. Limit jest w
|
||||
pamięci, per instancja — za Cloudflare dołóż regułę Rate limiting w WAF.
|
||||
- Za Cloudflare Access route musi mieć Bypass (klienci MCP nie wyślą Service Token)
|
||||
— patrz instrukcja Cloudflare Access.
|
||||
|
||||
## Protokół (dla debugowania)
|
||||
|
||||
Pojedynczy obiekt JSON-RPC albo batch (tablica). Notyfikacje (`notifications/*`,
|
||||
bez `id`) → HTTP 202 bez ciała. Żądania → `{ jsonrpc:'2.0', id, result }` albo
|
||||
`error` (`-32601` nieznana metoda, `-32700` parse error). `initialize` odbija
|
||||
`error` (`-32601` nieznana metoda, `-32700` parse error, `-32600` batch za duży,
|
||||
`-32000` limit zapytań). `initialize` odbija
|
||||
`protocolVersion` klienta (fallback `2025-06-18`).
|
||||
|
||||
+45
-3
@@ -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 <mongo> mongosh <db> --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
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@intecion/ipal-kit",
|
||||
"version": "1.8.10",
|
||||
"version": "1.8.13",
|
||||
"description": "Intecion Payload Advanced Library — a Payload CMS 3 plugin: i18n, SEO, forms, consent, analytics, blog/archives.",
|
||||
"license": "MIT",
|
||||
"repository": {
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
export { RowLabel } from '../modules/admin-ui/RowLabelComponent.js'
|
||||
/**
|
||||
* Entry point: @intecion/ipal-kit/admin
|
||||
*
|
||||
@@ -6,4 +5,6 @@ export { RowLabel } from '../modules/admin-ui/RowLabelComponent.js'
|
||||
* importMap can resolve them by a stable path when ipalKit injects
|
||||
* admin.components.graphics.Logo/Icon.
|
||||
*/
|
||||
export { AdminIcon, AdminLogo, IntecionCredit } from '../modules/branding/index.js'
|
||||
export { AdminLogo, AdminIcon, IntecionCredit } from '../modules/branding/index.js'
|
||||
export { RowLabel } from '../modules/admin-ui/RowLabelComponent.js'
|
||||
export { IntegrationAlerts } from '../modules/integrations/IntegrationAlerts.js'
|
||||
|
||||
+42
-41
@@ -1,13 +1,4 @@
|
||||
'use client'
|
||||
export { MaskedField } from '../globals/SiteIntegrations/components/MaskedField.js'
|
||||
export { TestEmailButton } from '../globals/SiteIntegrations/components/TestEmailButton.js'
|
||||
export { AccessibilityProvider, AccessibilityWidget, useAccessibility } from '../modules/accessibility/client.js'
|
||||
export type { A11yClassNames, A11yState, A11yTexts } from '../modules/accessibility/client.js'
|
||||
export { Analytics } from '../modules/analytics/client.js'
|
||||
export type { AnalyticsProps } from '../modules/analytics/client.js'
|
||||
|
||||
export { pushDataLayer } from '../modules/analytics/client.js'
|
||||
export { loadClarity, loadLinkedIn, loadMetaPixel, loadTikTok } from '../modules/analytics/client.js'
|
||||
/**
|
||||
* Entry point: ipal-kit/client
|
||||
*
|
||||
@@ -16,51 +7,61 @@ export { loadClarity, loadLinkedIn, loadMetaPixel, loadTikTok } from '../modules
|
||||
* client-only code.
|
||||
*/
|
||||
export {
|
||||
useConsent,
|
||||
ConsentProvider,
|
||||
ConsentScript,
|
||||
useConsentContext,
|
||||
CookieBanner,
|
||||
CookieButton,
|
||||
useConsent,
|
||||
useConsentContext,
|
||||
ConsentScript,
|
||||
} from '../modules/consent/client.js'
|
||||
export type { CookieBannerClassNames } from '../modules/consent/client.js'
|
||||
export { formAnalyticsOnSuccess } from '../modules/forms/formAnalytics.js'
|
||||
export type { FormAnalyticsConfig } from '../modules/forms/formAnalytics.js'
|
||||
export { HONEYPOT_FIELD, honeypotInputProps, isHoneypotTripped } from '../modules/forms/honeypot.js'
|
||||
export { useContactForm } from '../modules/forms/useContactForm.js'
|
||||
export type { ContactFormErrors, ContactFormValues, SubmitAction } from '../modules/forms/useContactForm.js'
|
||||
export { useForm } from '../modules/forms/useForm.js'
|
||||
export type { FormErrors, FormSubmitAction, Validator } from '../modules/forms/useForm.js'
|
||||
export {
|
||||
buildValidator,
|
||||
checked,
|
||||
custom,
|
||||
email,
|
||||
isEmail,
|
||||
maxLength,
|
||||
minLength,
|
||||
pattern,
|
||||
required,
|
||||
} from '../modules/forms/validators.js'
|
||||
export type { Rule } from '../modules/forms/validators.js'
|
||||
export { Turnstile } from '../modules/turnstile/client.js'
|
||||
export { TurnstileProvider, useTurnstile } from '../modules/turnstile/client.js'
|
||||
export { AccessibilityProvider, useAccessibility, AccessibilityWidget } from '../modules/accessibility/client.js'
|
||||
export type { A11yState, A11yTexts, A11yClassNames } from '../modules/accessibility/client.js'
|
||||
|
||||
// Pure i18n path helpers — no server/RSC deps, safe to import in client
|
||||
// components (e.g. a LanguageSwitcher that computes locale URLs on the client).
|
||||
export {
|
||||
buildLocalizedPath,
|
||||
getLocaleCodes,
|
||||
getLocalizedSlugs,
|
||||
switchLocalePath,
|
||||
buildLocalizedPath,
|
||||
getLocalizedSlugs,
|
||||
getLocaleCodes,
|
||||
} from '../modules/i18n/index.js'
|
||||
export type { I18nConfig, LocalizedSlugs } from '../modules/i18n/index.js'
|
||||
export type { LocalizedSlugs, I18nConfig } from '../modules/i18n/index.js'
|
||||
export type { TurnstileProps } from '../modules/turnstile/client.js'
|
||||
export { LocaleView } from '../modules/pages/LocaleView.js'
|
||||
export { Analytics } from '../modules/analytics/client.js'
|
||||
export type { AnalyticsProps } from '../modules/analytics/client.js'
|
||||
export { pushDataLayer } from '../modules/analytics/client.js'
|
||||
export { loadMetaPixel, loadClarity, loadLinkedIn, loadTikTok } from '../modules/analytics/client.js'
|
||||
export { MaskedField } from '../globals/SiteIntegrations/components/MaskedField.js'
|
||||
export { IntegrationStatusBanner } from '../modules/integrations/IntegrationStatusBanner.js'
|
||||
export { TestEmailButton } from '../globals/SiteIntegrations/components/TestEmailButton.js'
|
||||
export {
|
||||
AlternateLinksProvider,
|
||||
AlternateLinksUpdater,
|
||||
LanguageSwitcher,
|
||||
useAlternateLinks,
|
||||
useSetAlternateLinks,
|
||||
AlternateLinksUpdater,
|
||||
LanguageSwitcher,
|
||||
} from '../modules/i18n/index.js'
|
||||
export type { AlternateLinks, LanguageSwitcherClassNames } from '../modules/i18n/index.js'
|
||||
export { LocaleView } from '../modules/pages/LocaleView.js'
|
||||
export { Turnstile } from '../modules/turnstile/client.js'
|
||||
export { TurnstileProvider, useTurnstile } from '../modules/turnstile/client.js'
|
||||
export type { TurnstileProps } from '../modules/turnstile/client.js'
|
||||
export { useForm } from '../modules/forms/useForm.js'
|
||||
export type { FormErrors, FormSubmitAction, Validator } from '../modules/forms/useForm.js'
|
||||
export { useContactForm } from '../modules/forms/useContactForm.js'
|
||||
export type { ContactFormValues, ContactFormErrors, SubmitAction } from '../modules/forms/useContactForm.js'
|
||||
export {
|
||||
buildValidator,
|
||||
isEmail,
|
||||
required,
|
||||
email,
|
||||
minLength,
|
||||
maxLength,
|
||||
checked,
|
||||
pattern,
|
||||
custom,
|
||||
} from '../modules/forms/validators.js'
|
||||
export type { Rule } from '../modules/forms/validators.js'
|
||||
export { HONEYPOT_FIELD, honeypotInputProps, isHoneypotTripped } from '../modules/forms/honeypot.js'
|
||||
export { formAnalyticsOnSuccess } from '../modules/forms/formAnalytics.js'
|
||||
export type { FormAnalyticsConfig } from '../modules/forms/formAnalytics.js'
|
||||
|
||||
@@ -10,7 +10,8 @@
|
||||
* 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 { verifyTurnstile, checkTurnstile } from '../modules/turnstile/index.js'
|
||||
export type { TurnstileCheck, TurnstileOutcome } from '../modules/turnstile/index.js'
|
||||
export { sendEmail } from '../modules/email/index.js'
|
||||
export type { SendEmailArgs, SendEmailResult } from '../modules/email/index.js'
|
||||
export { submitForm } from '../modules/forms/index.js'
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import type { GlobalConfig } from 'payload'
|
||||
|
||||
import { notificationsFields } from './fields.js'
|
||||
|
||||
/**
|
||||
@@ -10,10 +9,11 @@ import { notificationsFields } from './fields.js'
|
||||
export function buildNotifications(): GlobalConfig {
|
||||
return {
|
||||
slug: 'notifications',
|
||||
label: 'Notifications',
|
||||
admin: { group: 'Settings' },
|
||||
access: {
|
||||
read: () => true, // texts are public-facing (shown to end users)
|
||||
},
|
||||
fields: notificationsFields,
|
||||
label: 'Notifications',
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,41 +1,69 @@
|
||||
'use client'
|
||||
import type { TextFieldClientComponent } from 'payload'
|
||||
|
||||
import { useField, FieldLabel, FieldDescription } from '@payloadcms/ui'
|
||||
import { useState } from 'react'
|
||||
import type { TextFieldClientComponent } from 'payload'
|
||||
|
||||
export const MaskedField: TextFieldClientComponent = (props: any) => {
|
||||
const { field, path, value: propValue, setValue: propSetValue, onChange: propOnChange } = props || {}
|
||||
const [internalValue, setInternalValue] = useState(propValue ?? '')
|
||||
/**
|
||||
* Masked text input for sensitive values (SMTP password, R2 secret key,
|
||||
* Turnstile secret key, etc.).
|
||||
*
|
||||
* Renders the value as a password field (••••) so secrets aren't shown in
|
||||
* plaintext on screen — protecting against shoulder-surfing and accidental
|
||||
* exposure when the panel is open. The value is still stored and returned
|
||||
* normally (UI masking, NOT hashing or encryption), because the plugin must
|
||||
* read it back to authenticate with SMTP/R2/Turnstile. A toggle reveals the
|
||||
* value when an authorised editor genuinely needs to check it.
|
||||
*
|
||||
* Uses a raw <input> driven by useField rather than @payloadcms/ui's TextInput,
|
||||
* because TextInput doesn't expose inputProps, so there's no way to switch its
|
||||
* inner input to type="password".
|
||||
*
|
||||
* Assigned via a field's admin.components.Field. Works on any `text` field.
|
||||
*/
|
||||
export const MaskedField: TextFieldClientComponent = ({ field, path }) => {
|
||||
const { value, setValue } = useField<string>({ path })
|
||||
const [revealed, setRevealed] = useState(false)
|
||||
const label = typeof field?.label === 'string' ? field.label : (field?.name ?? path)
|
||||
|
||||
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const newVal = e.target.value
|
||||
setInternalValue(newVal)
|
||||
if (typeof propSetValue === 'function') {
|
||||
propSetValue(newVal)
|
||||
}
|
||||
if (typeof propOnChange === 'function') {
|
||||
propOnChange(e)
|
||||
}
|
||||
}
|
||||
|
||||
const currentValue = propValue !== undefined ? propValue : internalValue
|
||||
const label =
|
||||
typeof field?.label === 'string' ? field.label : (field?.name ?? path)
|
||||
const description = field?.admin?.description
|
||||
|
||||
return (
|
||||
<div className="field-type text">
|
||||
{label && <label className="field-label">{label}</label>}
|
||||
<div style={{ display: 'flex', gap: '.5rem' }}>
|
||||
<div className="field-type text masked-field">
|
||||
<FieldLabel label={label} htmlFor={`field-${path}`} />
|
||||
|
||||
<div className="field-type__wrap" style={{ display: 'flex', gap: '.5rem', alignItems: 'center' }}>
|
||||
<input
|
||||
autoComplete="off"
|
||||
onChange={handleChange}
|
||||
style={{ flex: 1 }}
|
||||
id={`field-${path}`}
|
||||
type={revealed ? 'text' : 'password'}
|
||||
value={currentValue ?? ''}
|
||||
autoComplete="off"
|
||||
className="field-type__input"
|
||||
value={value ?? ''}
|
||||
onChange={(e) => setValue(e.target.value)}
|
||||
style={{ flex: 1 }}
|
||||
/>
|
||||
<button onClick={() => setRevealed((r) => !r)} type="button">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setRevealed((r) => !r)}
|
||||
style={{
|
||||
background: 'none',
|
||||
border: 'none',
|
||||
padding: '.25rem .5rem',
|
||||
cursor: 'pointer',
|
||||
font: 'inherit',
|
||||
textDecoration: 'underline',
|
||||
opacity: 0.75,
|
||||
whiteSpace: 'nowrap',
|
||||
}}
|
||||
>
|
||||
{revealed ? 'Hide' : 'Reveal'}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{description && typeof description === 'string' ? (
|
||||
<FieldDescription path={path} description={description} />
|
||||
) : null}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -14,10 +14,7 @@ import { useState } from 'react'
|
||||
export const TestEmailButton = () => {
|
||||
const [to, setTo] = useState('')
|
||||
const [status, setStatus] = useState<
|
||||
| { kind: 'error'; msg: string }
|
||||
| { kind: 'idle' }
|
||||
| { kind: 'ok'; msg: string }
|
||||
| { kind: 'sending' }
|
||||
{ kind: 'idle' } | { kind: 'sending' } | { kind: 'ok'; msg: string } | { kind: 'error'; msg: string }
|
||||
>({ kind: 'idle' })
|
||||
|
||||
const send = async () => {
|
||||
@@ -28,10 +25,10 @@ export const TestEmailButton = () => {
|
||||
setStatus({ kind: 'sending' })
|
||||
try {
|
||||
const res = await fetch('/api/ipal/test-email', {
|
||||
body: JSON.stringify({ to: to.trim() }),
|
||||
credentials: 'include',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
credentials: 'include',
|
||||
body: JSON.stringify({ to: to.trim() }),
|
||||
})
|
||||
const data = await res.json()
|
||||
if (data.ok) {
|
||||
@@ -47,23 +44,23 @@ export const TestEmailButton = () => {
|
||||
return (
|
||||
<div className="field-type" style={{ marginTop: '1rem' }}>
|
||||
<label className="field-label">Send a test email</label>
|
||||
<p style={{ fontSize: '.85rem', marginTop: 0, opacity: 0.7 }}>
|
||||
<p style={{ opacity: 0.7, fontSize: '.85rem', marginTop: 0 }}>
|
||||
Sends through the transport selected above. Save your changes first.
|
||||
</p>
|
||||
<div style={{ alignItems: 'center', display: 'flex', flexWrap: 'wrap', gap: '.5rem' }}>
|
||||
<div style={{ display: 'flex', gap: '.5rem', alignItems: 'center', flexWrap: 'wrap' }}>
|
||||
<input
|
||||
onChange={(e) => setTo(e.target.value)}
|
||||
placeholder="[email protected]"
|
||||
style={{ flex: 1, minWidth: '220px' }}
|
||||
type="email"
|
||||
placeholder="[email protected]"
|
||||
value={to}
|
||||
onChange={(e) => setTo(e.target.value)}
|
||||
style={{ flex: 1, minWidth: '220px' }}
|
||||
/>
|
||||
<button
|
||||
className="btn btn--style-secondary"
|
||||
disabled={status.kind === 'sending'}
|
||||
onClick={send}
|
||||
style={{ whiteSpace: 'nowrap' }}
|
||||
type="button"
|
||||
onClick={send}
|
||||
disabled={status.kind === 'sending'}
|
||||
className="btn btn--style-secondary"
|
||||
style={{ whiteSpace: 'nowrap' }}
|
||||
>
|
||||
{status.kind === 'sending' ? 'Sending…' : 'Send test'}
|
||||
</button>
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import type { Field } from 'payload'
|
||||
|
||||
import { buildIntegrationStatusBanner, buildIntegrationStatusField } from '../../../modules/integrations/status.js'
|
||||
|
||||
/**
|
||||
* SMTP transport settings for outbound email.
|
||||
*
|
||||
@@ -8,6 +10,8 @@ import type { Field } from 'payload'
|
||||
* panel while remaining inaccessible to anonymous API requests.
|
||||
*/
|
||||
export const smtpFields: Field[] = [
|
||||
// Status written by mailAdapter on every send (throttled) — banner on this tab.
|
||||
buildIntegrationStatusBanner('emailStatus', 'Email'),
|
||||
{
|
||||
name: 'emailTransport',
|
||||
type: 'select',
|
||||
@@ -87,4 +91,5 @@ export const smtpFields: Field[] = [
|
||||
},
|
||||
},
|
||||
},
|
||||
buildIntegrationStatusField('emailStatus'),
|
||||
]
|
||||
|
||||
@@ -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'),
|
||||
]
|
||||
|
||||
@@ -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,28 @@ 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 that integration's old status, so a stale
|
||||
// "not working" banner doesn't linger until the next form submission.
|
||||
({ context, data, originalDoc }) => {
|
||||
if (context?.ipalIntegrationStatus || !data) {return data}
|
||||
const changed = (k: string) => k in data && data[k] !== originalDoc?.[k]
|
||||
const cleared = { checkedAt: null, code: null, message: null, since: null, state: null }
|
||||
if (changed('turnstileSecretKey') || changed('turnstileSiteKey')) {data.turnstileStatus = cleared}
|
||||
if (Object.keys(data).some((k) => (k === 'emailTransport' || k.startsWith('smtp')) && changed(k))) {
|
||||
data.emailStatus = cleared
|
||||
}
|
||||
return data
|
||||
},
|
||||
],
|
||||
},
|
||||
label: 'Site Integrations',
|
||||
}
|
||||
}
|
||||
|
||||
@@ -156,6 +156,8 @@ export { buildCsp } from './modules/security/index.js'
|
||||
export type { BuildCspArgs } from './modules/security/index.js'
|
||||
export { buildIconsMetadata, buildOrganizationJsonLd, validateFaviconField } from './modules/seo/index.js'
|
||||
export { buildNoindexField } from './modules/seo/index.js'
|
||||
export { recordIntegrationStatus, buildIntegrationStatusField, buildIntegrationStatusBanner } from './modules/integrations/index.js'
|
||||
export type { IntegrationStatus, IntegrationState } from './modules/integrations/index.js'
|
||||
export { rowLabel } from './modules/admin-ui/index.js'
|
||||
export type { RowLabelProps } from './modules/admin-ui/index.js'
|
||||
export { buildLinkField, buildLinksField, resolveLinkHref } from './modules/links/index.js'
|
||||
|
||||
@@ -2,6 +2,7 @@ import type { BasePayload } from 'payload'
|
||||
|
||||
import type { I18nConfig } from '../i18n/index.js'
|
||||
|
||||
import { checkRateLimit, clientIp, tooManyRequests } from '../shared/rateLimit.js'
|
||||
import { searchContent } from './searchContent.js'
|
||||
|
||||
type CreateSearchRouteArgs = {
|
||||
@@ -15,6 +16,11 @@ type CreateSearchRouteArgs = {
|
||||
getCachedPayload: () => Promise<BasePayload>
|
||||
/** Home slug map/string so the home result collapses to root. */
|
||||
homeSlug?: Record<string, string> | string
|
||||
/**
|
||||
* Per-IP limit (in memory, per instance). Default { max: 120, windowMs: 60_000 }.
|
||||
* `false` = off (a limiter in front, e.g. Cloudflare WAF rate limiting).
|
||||
*/
|
||||
rateLimit?: { max?: number; windowMs?: number } | false
|
||||
/** Field holding a richer AI summary (buildSummaryField) to prefer as description. */
|
||||
summaryField?: string
|
||||
}
|
||||
@@ -37,20 +43,18 @@ type CreateSearchRouteArgs = {
|
||||
*
|
||||
* Uses the global Request/Response — no next/server import.
|
||||
*/
|
||||
export function createSearchRoute(
|
||||
args: CreateSearchRouteArgs,
|
||||
): (req: Request) => Promise<Response> {
|
||||
const {
|
||||
baseUrl,
|
||||
collection = 'pages',
|
||||
config,
|
||||
defaultLimit = 10,
|
||||
getCachedPayload,
|
||||
homeSlug,
|
||||
summaryField,
|
||||
} = args
|
||||
export function createSearchRoute(args: CreateSearchRouteArgs): (req: Request) => Promise<Response> {
|
||||
const { baseUrl, collection = 'pages', config, defaultLimit = 10, getCachedPayload, homeSlug, summaryField } = args
|
||||
// 120/min: a debounced search-as-you-type box stays well under it; a scraper doesn't.
|
||||
const rl = args.rateLimit === false ? null : { max: 120, windowMs: 60_000, ...args.rateLimit }
|
||||
|
||||
return async (req: Request) => {
|
||||
if (rl) {
|
||||
const ip = clientIp(req)
|
||||
if (!checkRateLimit({ key: ip, scope: 'search', ...rl })) {
|
||||
return tooManyRequests(ip, 'search', { count: 0, error: 'Too many requests', query: '', results: [] })
|
||||
}
|
||||
}
|
||||
const url = new URL(req.url)
|
||||
const query = url.searchParams.get('q')?.trim() ?? ''
|
||||
const locale = url.searchParams.get('locale') ?? undefined
|
||||
@@ -79,11 +83,7 @@ export function createSearchRoute(
|
||||
})
|
||||
return Response.json(
|
||||
{ count: results.length, locale: locale ?? config.defaultLocale, query, results },
|
||||
{
|
||||
headers: {
|
||||
'cache-control': 'public, max-age=0, s-maxage=60, stale-while-revalidate=600',
|
||||
},
|
||||
},
|
||||
{ headers: { 'cache-control': 'public, max-age=0, s-maxage=60, stale-while-revalidate=600' } },
|
||||
)
|
||||
} catch (err) {
|
||||
// DB unreachable (build) or unexpected — empty result rather than 500.
|
||||
|
||||
@@ -1,28 +1,34 @@
|
||||
import type { PayloadEmailAdapter, SendEmailOptions } from 'payload'
|
||||
|
||||
import { getSiteIntegrations } from '../payload/index.js'
|
||||
import { graphAdapter, type GraphAdapterArgs } from './graphAdapter.js'
|
||||
import { recordIntegrationStatus, type IntegrationStatus } from '../integrations/status.js'
|
||||
import { panelSmtpAdapter, type PanelSmtpAdapterArgs } from './panelSmtpAdapter.js'
|
||||
import { graphAdapter, type GraphAdapterArgs } from './graphAdapter.js'
|
||||
|
||||
type TransportIntegrations = {
|
||||
/** 'smtp' | 'graph' — chosen by the editor in SiteIntegrations. */
|
||||
emailTransport?: 'graph' | 'smtp' | null
|
||||
emailTransport?: 'smtp' | 'graph' | null
|
||||
emailStatus?: IntegrationStatus | null
|
||||
}
|
||||
|
||||
const STATUS_FIELD = 'emailStatus'
|
||||
/** Error text for the panel: first line, no stack, capped — SMTP errors don't carry the password. */
|
||||
const describe = (err: unknown) =>
|
||||
(err instanceof Error ? err.message : String(err)).split('\n')[0].slice(0, 200)
|
||||
|
||||
export type MailAdapterArgs = {
|
||||
smtp?: PanelSmtpAdapterArgs
|
||||
graph?: GraphAdapterArgs
|
||||
fallbackFromAddress?: string
|
||||
fallbackFromName?: string
|
||||
graph?: GraphAdapterArgs
|
||||
smtp?: PanelSmtpAdapterArgs
|
||||
}
|
||||
|
||||
/** True when the agency Graph credentials are present in the environment. */
|
||||
function graphAvailable(): boolean {
|
||||
return Boolean(
|
||||
process.env.GRAPH_TENANT_ID &&
|
||||
process.env.GRAPH_CLIENT_ID &&
|
||||
process.env.GRAPH_CLIENT_SECRET &&
|
||||
process.env.GRAPH_SENDER,
|
||||
process.env.GRAPH_CLIENT_ID &&
|
||||
process.env.GRAPH_CLIENT_SECRET &&
|
||||
process.env.GRAPH_SENDER,
|
||||
)
|
||||
}
|
||||
|
||||
@@ -69,20 +75,58 @@ export const mailAdapter =
|
||||
sendEmail: async (message: SendEmailOptions) => {
|
||||
const settings = await getSiteIntegrations<TransportIntegrations>(payload)
|
||||
const choice = settings.emailTransport ?? 'smtp'
|
||||
const previous = settings[STATUS_FIELD]
|
||||
const useGraph = choice === 'graph' && graphAvailable()
|
||||
const graphFallback = choice === 'graph' && !useGraph
|
||||
|
||||
if (choice === 'graph') {
|
||||
if (graphAvailable()) {
|
||||
return graph.sendEmail(message)
|
||||
}
|
||||
if (graphFallback) {
|
||||
// Panel asked for Graph but the agency creds aren't configured for
|
||||
// this project. Fall back to SMTP rather than silently dropping mail.
|
||||
payload.logger.warn(
|
||||
'[ipal] Transport set to Graph but GRAPH_* env vars are missing; falling back to SMTP.',
|
||||
)
|
||||
return smtp.sendEmail(message)
|
||||
}
|
||||
|
||||
return smtp.sendEmail(message)
|
||||
const transport = useGraph ? 'Microsoft Graph' : 'SMTP'
|
||||
const code = useGraph ? 'graph-error' : 'smtp-error'
|
||||
let result: unknown
|
||||
try {
|
||||
result = await (useGraph ? graph : smtp).sendEmail(message)
|
||||
} catch (err) {
|
||||
await recordIntegrationStatus(payload, STATUS_FIELD, previous, {
|
||||
state: 'degraded',
|
||||
code,
|
||||
message: `${transport}: ${describe(err)}`,
|
||||
})
|
||||
throw err // callers (form-builder, Send test) still see the failure
|
||||
}
|
||||
|
||||
// The delegates report failure as { sent: false, error, detail? } instead
|
||||
// of throwing (a broken mailbox must not crash a form submission).
|
||||
const failed = result as { sent?: boolean; error?: string; detail?: string } | null
|
||||
if (failed && typeof failed === 'object' && failed.sent === false) {
|
||||
await recordIntegrationStatus(payload, STATUS_FIELD, previous, {
|
||||
state: 'degraded',
|
||||
code,
|
||||
message: `${transport}: ${describe(failed.detail ?? failed.error ?? 'not sent')}`,
|
||||
})
|
||||
return result
|
||||
}
|
||||
|
||||
// Graph selected but unavailable is a configuration problem even if SMTP delivered.
|
||||
await recordIntegrationStatus(
|
||||
payload,
|
||||
STATUS_FIELD,
|
||||
previous,
|
||||
graphFallback
|
||||
? {
|
||||
state: 'degraded',
|
||||
code: 'graph-unavailable',
|
||||
message: 'Microsoft Graph is selected but not configured on the server — e-mails are sent over SMTP.',
|
||||
}
|
||||
: { state: 'ok' },
|
||||
)
|
||||
return result
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,15 +1,14 @@
|
||||
import type { PayloadEmailAdapter, SendEmailOptions } from 'payload'
|
||||
|
||||
import { getSiteIntegrations } from '../payload/index.js'
|
||||
|
||||
/** SMTP fields the adapter reads from SiteIntegrations. */
|
||||
type SmtpIntegrations = {
|
||||
smtpFromAddress?: null | string
|
||||
smtpFromName?: null | string
|
||||
smtpHost?: null | string
|
||||
smtpPassword?: null | string
|
||||
smtpPort?: null | number
|
||||
smtpUser?: null | string
|
||||
smtpHost?: string | null
|
||||
smtpPort?: number | null
|
||||
smtpUser?: string | null
|
||||
smtpPassword?: string | null
|
||||
smtpFromAddress?: string | null
|
||||
smtpFromName?: string | null
|
||||
}
|
||||
|
||||
export type PanelSmtpAdapterArgs = {
|
||||
@@ -59,8 +58,10 @@ export const panelSmtpAdapter =
|
||||
const pass = smtp.smtpPassword
|
||||
|
||||
if (!host || !user || !pass) {
|
||||
payload.logger.error('[ipal] Email not sent: SMTP is not configured in Site Integrations.')
|
||||
return { error: 'SMTP is not configured in Site Integrations.', sent: false }
|
||||
payload.logger.error(
|
||||
'[ipal] Email not sent: SMTP is not configured in Site Integrations.',
|
||||
)
|
||||
return { sent: false, error: 'SMTP is not configured in Site Integrations.' }
|
||||
}
|
||||
|
||||
// The panel is the source of truth for the sender; fall back to whatever
|
||||
@@ -77,18 +78,15 @@ export const panelSmtpAdapter =
|
||||
// normalises CRLF in standard headers, but the form-builder interpolates
|
||||
// user data into the subject via {{field}} placeholders, so strip any
|
||||
// newlines from header-bound values before they reach the transport.
|
||||
const stripCRLF = (v: unknown): string =>
|
||||
String(v ?? '')
|
||||
.replace(/[\r\n]+/g, ' ')
|
||||
.trim()
|
||||
const stripCRLF = (v: unknown): string => String(v ?? '').replace(/[\r\n]+/g, ' ').trim()
|
||||
|
||||
const { default: nodemailer } = await import('nodemailer')
|
||||
|
||||
const transporter = nodemailer.createTransport({
|
||||
auth: { pass, user },
|
||||
host,
|
||||
port,
|
||||
secure: port === 465, // implicit TLS on 465, STARTTLS otherwise
|
||||
auth: { user, pass },
|
||||
})
|
||||
|
||||
try {
|
||||
@@ -97,12 +95,13 @@ export const panelSmtpAdapter =
|
||||
from,
|
||||
...(message.subject ? { subject: stripCRLF(message.subject) } : {}),
|
||||
})
|
||||
return { messageId: info.messageId, sent: true }
|
||||
return { sent: true, messageId: info.messageId }
|
||||
} catch (err) {
|
||||
// Never surface SMTP internals to the caller — a form submission
|
||||
// shouldn't fail loudly because the mailbox is misconfigured.
|
||||
payload.logger.error(`[ipal] Email send failed: ${(err as Error).message}`)
|
||||
return { error: 'Failed to send email.', sent: false }
|
||||
// `detail` is for the panel status (mailAdapter), not for end users.
|
||||
return { sent: false, error: 'Failed to send email.', detail: (err as Error).message }
|
||||
}
|
||||
},
|
||||
})
|
||||
|
||||
@@ -1,37 +1,60 @@
|
||||
import type { Plugin } from 'payload'
|
||||
|
||||
import { formBuilderPlugin } from '@payloadcms/plugin-form-builder'
|
||||
|
||||
import type { Plugin } from 'payload'
|
||||
import type { FormsOption } from './types.js'
|
||||
|
||||
/** REST/GraphQL: only logged-in users. Local API (submitForm) is unaffected. */
|
||||
const submissionsCreateAccess = ({ req }: { req: { user?: unknown } }) => Boolean(req.user)
|
||||
|
||||
/**
|
||||
* Configures @payloadcms/plugin-form-builder from IPAL's FormsOption.
|
||||
*
|
||||
* Provides the form/form-submissions collections and field types. Email
|
||||
* delivery is intentionally NOT handled here — the plugin's own SMTP-from-panel
|
||||
* sender (submitForm) does that, so the form-builder's built-in email (which
|
||||
* needs a Payload email adapter) is left unused.
|
||||
* Provides the forms / form-submissions collections and field types. E-mails
|
||||
* after a submission are the form-builder's own (Forms → Emails), sent through
|
||||
* the project's email adapter (mailAdapter()).
|
||||
*
|
||||
* SECURITY: form-builder defaults form-submissions to `create: () => true`, i.e.
|
||||
* anyone can POST /api/form-submissions and skip everything submitForm enforces
|
||||
* (rate limit, Turnstile, GDPR consent, schema validation). Here REST/GraphQL
|
||||
* creation is limited to logged-in users; the site submits through submitForm
|
||||
* (server action → Local API, which bypasses access by design). A project that
|
||||
* really needs public REST submissions can override `formSubmissionOverrides.access.create`.
|
||||
*/
|
||||
export function buildFormsPlugin(forms: FormsOption): Plugin {
|
||||
const adminGroup = forms.adminGroup === undefined ? 'Forms' : forms.adminGroup
|
||||
const group = adminGroup ? { group: adminGroup } : {}
|
||||
return formBuilderPlugin({
|
||||
fields: {
|
||||
checkbox: true,
|
||||
email: true,
|
||||
message: true,
|
||||
number: true,
|
||||
payment: false,
|
||||
select: true,
|
||||
text: true,
|
||||
textarea: true,
|
||||
email: true,
|
||||
number: true,
|
||||
select: true,
|
||||
checkbox: true,
|
||||
message: true,
|
||||
payment: false,
|
||||
...forms.fields,
|
||||
},
|
||||
...(forms.redirectRelationships ? { redirectRelationships: forms.redirectRelationships } : {}),
|
||||
...(forms.redirectRelationships
|
||||
? { redirectRelationships: forms.redirectRelationships }
|
||||
: {}),
|
||||
// Client-supplied collection overrides (e.g. a per-form notification
|
||||
// address). The plugin provides the hook, not the opinion about which
|
||||
// extra fields a form should carry.
|
||||
...(forms.formOverrides ? { formOverrides: forms.formOverrides } : {}),
|
||||
...(forms.formSubmissionOverrides
|
||||
? { formSubmissionOverrides: forms.formSubmissionOverrides }
|
||||
: {}),
|
||||
// Tidy panel by default: both collections under one sidebar group with plain
|
||||
// labels — no per-project overrides needed just to sort the sidebar.
|
||||
formOverrides: {
|
||||
labels: { singular: 'Form', plural: 'Forms' },
|
||||
...forms.formOverrides,
|
||||
admin: { ...group, ...forms.formOverrides?.admin },
|
||||
},
|
||||
formSubmissionOverrides: {
|
||||
labels: { singular: 'Submission', plural: 'Submissions' },
|
||||
...forms.formSubmissionOverrides,
|
||||
admin: { ...group, defaultColumns: ['form', 'createdAt'], ...forms.formSubmissionOverrides?.admin },
|
||||
access: {
|
||||
create: submissionsCreateAccess,
|
||||
...forms.formSubmissionOverrides?.access,
|
||||
},
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1,62 +1,3 @@
|
||||
type Bucket = { count: number; resetAt: number }
|
||||
|
||||
/**
|
||||
* Per-IP sliding window, in memory.
|
||||
*
|
||||
* Deliberately simple: no Redis, no dependency. The trade-off is that the
|
||||
* counter lives in one process — with several instances behind a load balancer
|
||||
* each keeps its own, so the effective limit is per-instance, not global. For a
|
||||
* contact form that's fine (it raises the cost of flooding without pretending
|
||||
* to be airtight); a high-security form should put a real limiter in front.
|
||||
*
|
||||
* State is module-level, so it survives between requests but resets on redeploy
|
||||
* — acceptable for abuse throttling.
|
||||
*/
|
||||
const buckets = new Map<string, Bucket>()
|
||||
|
||||
/** Sweep expired buckets occasionally so the map doesn't grow unbounded. */
|
||||
let lastSweep = Date.now()
|
||||
const SWEEP_INTERVAL = 60_000
|
||||
|
||||
function sweep(now: number) {
|
||||
if (now - lastSweep < SWEEP_INTERVAL) {return}
|
||||
lastSweep = now
|
||||
for (const [key, bucket] of buckets) {
|
||||
if (bucket.resetAt <= now) {buckets.delete(key)}
|
||||
}
|
||||
}
|
||||
|
||||
export type RateLimitArgs = {
|
||||
/** Identifier to limit on — typically the client IP. */
|
||||
key: string
|
||||
/** Max submissions allowed per window. Defaults to 5. */
|
||||
max?: number
|
||||
/** Window length in ms. Defaults to 60_000 (one minute). */
|
||||
windowMs?: number
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true when the request is within the limit, false when it should be
|
||||
* rejected. A missing key (no IP) is allowed through — better to accept a
|
||||
* submission than to block everyone behind a proxy that strips the header.
|
||||
*/
|
||||
export function checkRateLimit({ key, max = 5, windowMs = 60_000 }: RateLimitArgs): boolean {
|
||||
if (!key) {return true}
|
||||
|
||||
const now = Date.now()
|
||||
sweep(now)
|
||||
|
||||
const bucket = buckets.get(key)
|
||||
|
||||
if (!bucket || bucket.resetAt <= now) {
|
||||
buckets.set(key, { count: 1, resetAt: now + windowMs })
|
||||
return true
|
||||
}
|
||||
|
||||
if (bucket.count >= max) {
|
||||
return false
|
||||
}
|
||||
|
||||
bucket.count += 1
|
||||
return true
|
||||
}
|
||||
// Moved to modules/shared/rateLimit.ts (shared with search and MCP routes).
|
||||
export { checkRateLimit, clientIp, retryAfterSeconds, tooManyRequests } from '../shared/rateLimit.js'
|
||||
export type { RateLimitArgs } from '../shared/rateLimit.js'
|
||||
|
||||
@@ -1,21 +1,17 @@
|
||||
import 'server-only'
|
||||
|
||||
import type { BasePayload } from 'payload'
|
||||
|
||||
import { verifyTurnstile } from '../turnstile/index.js'
|
||||
import { checkRateLimit } from './rateLimit.js'
|
||||
import { validateSubmission } from './validateSubmission.js'
|
||||
import { checkRateLimit } from './rateLimit.js'
|
||||
|
||||
export type SubmitFormArgs = {
|
||||
/**
|
||||
* Name of the GDPR consent checkbox. A field with this name must be checked
|
||||
* for the submission to succeed (enforced server-side). Defaults to 'consent'.
|
||||
*/
|
||||
consentFieldName?: string
|
||||
/** Submitted field data — shape matches the form's fields. */
|
||||
data: Record<string, unknown>
|
||||
payload: BasePayload
|
||||
/** Form-builder form ID this submission belongs to. */
|
||||
formId: string
|
||||
/** Submitted field data — shape matches the form's fields. */
|
||||
data: Record<string, unknown>
|
||||
/** Turnstile token; when present it is verified, when absent it is skipped. */
|
||||
turnstileToken?: string
|
||||
/** Client IP — used for Turnstile and rate limiting. */
|
||||
ip?: string
|
||||
/**
|
||||
@@ -23,9 +19,17 @@ export type SubmitFormArgs = {
|
||||
* Set to 0 to disable (e.g. when a real limiter sits in front).
|
||||
*/
|
||||
maxPerMinute?: number
|
||||
payload: BasePayload
|
||||
/** Turnstile token; when present it is verified, when absent it is skipped. */
|
||||
turnstileToken?: string
|
||||
/**
|
||||
* Name of the GDPR consent checkbox. A field with this name must be checked
|
||||
* for the submission to succeed (enforced server-side). Defaults to 'consent'.
|
||||
*/
|
||||
consentFieldName?: string
|
||||
/**
|
||||
* Turnstile can't be verified because of OUR side (missing/wrong secret,
|
||||
* Cloudflare unreachable): 'allow' (default) accepts the submission and shows
|
||||
* the problem in the panel; 'reject' refuses it.
|
||||
*/
|
||||
turnstileOnConfigError?: 'allow' | 'reject'
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -46,26 +50,26 @@ export type SubmitFormArgs = {
|
||||
* - `error` — persistence failed unexpectedly
|
||||
*/
|
||||
export type SubmitFailure =
|
||||
| { success: false; reason: 'rate_limited' }
|
||||
| { success: false; reason: 'turnstile' }
|
||||
| {
|
||||
success: false
|
||||
reason: 'validation'
|
||||
/** The offending field's name, when one field is at fault. */
|
||||
field?: string
|
||||
/** What was wrong with it. */
|
||||
kind?: 'required' | 'too_long' | 'unknown_fields'
|
||||
reason: 'validation'
|
||||
success: false
|
||||
}
|
||||
| { success: false; reason: 'not_found' }
|
||||
| {
|
||||
field?: string
|
||||
success: false
|
||||
/** A GDPR consent field existed on the form but wasn't checked. */
|
||||
reason: 'consent'
|
||||
success: false
|
||||
field?: string
|
||||
}
|
||||
| { reason: 'error'; success: false }
|
||||
| { reason: 'not_found'; success: false }
|
||||
| { reason: 'rate_limited'; success: false }
|
||||
| { reason: 'turnstile'; success: false }
|
||||
| { success: false; reason: 'error' }
|
||||
|
||||
export type SubmitFormResult = { submissionId: number | string; success: true } | SubmitFailure
|
||||
export type SubmitFormResult = SubmitFailure | { success: true; submissionId: string | number }
|
||||
|
||||
/**
|
||||
* Handles a form submission end to end: rate limit, verify Turnstile, validate
|
||||
@@ -81,26 +85,27 @@ export type SubmitFormResult = { submissionId: number | string; success: true }
|
||||
* server-only: touches the Turnstile secret.
|
||||
*/
|
||||
export async function submitForm({
|
||||
consentFieldName,
|
||||
data,
|
||||
payload,
|
||||
formId,
|
||||
data,
|
||||
turnstileToken,
|
||||
ip,
|
||||
maxPerMinute = 5,
|
||||
payload,
|
||||
turnstileToken,
|
||||
consentFieldName,
|
||||
turnstileOnConfigError = 'allow',
|
||||
}: SubmitFormArgs): Promise<SubmitFormResult> {
|
||||
// 1. Rate limit — cheapest gate, drops a flood before any real work.
|
||||
if (maxPerMinute > 0 && ip) {
|
||||
if (!checkRateLimit({ key: ip, max: maxPerMinute })) {
|
||||
return { reason: 'rate_limited', success: false }
|
||||
return { success: false, reason: 'rate_limited' }
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Turnstile — verify when a token is supplied; reject on failure.
|
||||
if (turnstileToken !== undefined) {
|
||||
const ok = await verifyTurnstile({ ip, payload, token: turnstileToken })
|
||||
const ok = await verifyTurnstile({ token: turnstileToken, payload, ip, onConfigError: turnstileOnConfigError })
|
||||
if (!ok) {
|
||||
return { reason: 'turnstile', success: false }
|
||||
return { success: false, reason: 'turnstile' }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -109,14 +114,14 @@ export async function submitForm({
|
||||
const validation = await validateSubmission(payload, formId, data, consentFieldName)
|
||||
if (!validation.ok) {
|
||||
if (validation.reason === 'not_found') {
|
||||
return { reason: 'not_found', success: false }
|
||||
return { success: false, reason: 'not_found' }
|
||||
}
|
||||
if (validation.reason === 'consent') {
|
||||
return { field: validation.field, reason: 'consent', success: false }
|
||||
return { success: false, reason: 'consent', field: validation.field }
|
||||
}
|
||||
return {
|
||||
reason: 'validation',
|
||||
success: false,
|
||||
reason: 'validation',
|
||||
...(validation.field ? { field: validation.field } : {}),
|
||||
...(validation.kind ? { kind: validation.kind } : {}),
|
||||
}
|
||||
@@ -135,9 +140,9 @@ export async function submitForm({
|
||||
})),
|
||||
} as never,
|
||||
})
|
||||
return { submissionId: submission.id, success: true }
|
||||
return { success: true, submissionId: submission.id }
|
||||
} catch (err) {
|
||||
payload.logger.error(`[ipal] Form submission failed: ${(err as Error).message}`)
|
||||
return { reason: 'error', success: false }
|
||||
return { success: false, reason: 'error' }
|
||||
}
|
||||
}
|
||||
|
||||
+19
-13
@@ -19,23 +19,25 @@ export type FormsCollectionOverrides = {
|
||||
* form-builder plugin. Kept minimal; the plugin passes these through.
|
||||
*/
|
||||
export type FormsOption = {
|
||||
/** Field types available in the form builder. Sensible defaults applied. */
|
||||
fields?: {
|
||||
text?: boolean
|
||||
textarea?: boolean
|
||||
email?: boolean
|
||||
number?: boolean
|
||||
select?: boolean
|
||||
checkbox?: boolean
|
||||
message?: boolean
|
||||
payment?: boolean
|
||||
}
|
||||
/** Collections a form can redirect to (e.g. ['pages']). */
|
||||
redirectRelationships?: string[]
|
||||
/**
|
||||
* Name of the checkbox field treated as a GDPR consent gate. A form field
|
||||
* with this name must be checked for submission to succeed — enforced
|
||||
* server-side in submitForm. Defaults to 'consent'.
|
||||
*/
|
||||
consentFieldName?: string
|
||||
/** Field types available in the form builder. Sensible defaults applied. */
|
||||
fields?: {
|
||||
checkbox?: boolean
|
||||
email?: boolean
|
||||
message?: boolean
|
||||
number?: boolean
|
||||
payment?: boolean
|
||||
select?: boolean
|
||||
text?: boolean
|
||||
textarea?: boolean
|
||||
}
|
||||
/**
|
||||
* Override the forms collection. The plugin stays opinion-free about what a
|
||||
* form needs beyond its fields — a client that wants, say, a per-form
|
||||
@@ -51,6 +53,10 @@ export type FormsOption = {
|
||||
formOverrides?: FormsCollectionOverrides
|
||||
/** Override the form-submissions collection (same shape). */
|
||||
formSubmissionOverrides?: FormsCollectionOverrides
|
||||
/** Collections a form can redirect to (e.g. ['pages']). */
|
||||
redirectRelationships?: string[]
|
||||
/**
|
||||
* Admin sidebar group for Forms + Form Submissions. Default 'Forms'.
|
||||
* `false` = Payload default ("Collections"). An explicit `admin.group` in
|
||||
* formOverrides / formSubmissionOverrides still wins.
|
||||
*/
|
||||
adminGroup?: string | false
|
||||
}
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
import type { Payload } from 'payload'
|
||||
import type { IntegrationStatus } from './status.js'
|
||||
|
||||
type Props = {
|
||||
/** Injected by Payload into admin server components. */
|
||||
payload?: Payload
|
||||
/** Status groups to check: field name → label. */
|
||||
checks?: Record<string, string>
|
||||
/** Admin route, for the link. Default '/admin'. */
|
||||
adminRoute?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* 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({ payload, checks = { turnstileStatus: 'Turnstile', emailStatus: 'Email' }, adminRoute = '/admin' }: Props) {
|
||||
if (!payload) return null
|
||||
let doc: Record<string, unknown>
|
||||
try {
|
||||
doc = (await payload.findGlobal({ slug: 'site-integrations' as never, depth: 0 })) as Record<string, unknown>
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
const failing = Object.entries(checks)
|
||||
.map(([field, label]) => ({ label, status: doc?.[field] as IntegrationStatus | undefined }))
|
||||
.filter((x) => x.status?.state === 'degraded')
|
||||
if (!failing.length) return null
|
||||
|
||||
return (
|
||||
<div
|
||||
role="alert"
|
||||
style={{
|
||||
marginBottom: '1.5rem',
|
||||
padding: '1rem 1.25rem',
|
||||
borderRadius: 4,
|
||||
border: '1px solid var(--theme-error-400, #e5484d)',
|
||||
background: 'var(--theme-error-50, rgba(229, 72, 77, 0.08))',
|
||||
}}
|
||||
>
|
||||
<strong>Integration problem — the site still works, but something needs attention.</strong>
|
||||
<ul style={{ margin: '0.5rem 0 0', paddingLeft: '1.2rem' }}>
|
||||
{failing.map(({ label, status }) => (
|
||||
<li key={label}>
|
||||
<strong>{label}:</strong> {status?.message ?? status?.code ?? 'error'}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
<a href={`${adminRoute.replace(/\/$/, '')}/globals/site-integrations`} style={{ display: 'inline-block', marginTop: '0.5rem' }}>
|
||||
Open Site Integrations →
|
||||
</a>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default IntegrationAlerts
|
||||
@@ -0,0 +1,64 @@
|
||||
'use client'
|
||||
import { useFormFields } from '@payloadcms/ui'
|
||||
|
||||
type Props = {
|
||||
/** Name of the hidden status group (buildIntegrationStatusField). */
|
||||
statusField: string
|
||||
/** Integration name shown in the banner, e.g. 'Turnstile'. */
|
||||
label: string
|
||||
}
|
||||
|
||||
const fmt = (iso: unknown) => {
|
||||
if (typeof iso !== 'string' || !iso) return ''
|
||||
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({ statusField, label }: Props) {
|
||||
const state = useFormFields(([f]) => f[`${statusField}.state`]?.value) as string | undefined
|
||||
const message = useFormFields(([f]) => f[`${statusField}.message`]?.value) as string | undefined
|
||||
const code = useFormFields(([f]) => f[`${statusField}.code`]?.value) as string | undefined
|
||||
const since = useFormFields(([f]) => f[`${statusField}.since`]?.value)
|
||||
const checkedAt = useFormFields(([f]) => f[`${statusField}.checkedAt`]?.value)
|
||||
|
||||
if (!state) return null
|
||||
|
||||
if (state === 'ok') {
|
||||
return (
|
||||
<div style={{ marginBottom: '1.5rem', fontSize: '0.85rem', opacity: 0.75 }}>
|
||||
✓ {label} working{since ? ` since ${fmt(since)}` : ''}.
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
role="alert"
|
||||
style={{
|
||||
marginBottom: '1.5rem',
|
||||
padding: '0.9rem 1rem',
|
||||
borderRadius: 4,
|
||||
border: '1px solid var(--theme-error-400, #e5484d)',
|
||||
background: 'var(--theme-error-50, rgba(229, 72, 77, 0.08))',
|
||||
}}
|
||||
>
|
||||
<strong>{label} is not working — forms are accepted without this check.</strong>
|
||||
{message ? <div style={{ marginTop: '0.35rem' }}>{message}</div> : null}
|
||||
<div style={{ marginTop: '0.35rem', fontSize: '0.8rem', opacity: 0.75 }}>
|
||||
{code ? `Code: ${code}. ` : ''}
|
||||
{since ? `Since ${fmt(since)}. ` : ''}
|
||||
{checkedAt ? `Last seen ${fmt(checkedAt)}.` : ''}
|
||||
</div>
|
||||
<div style={{ marginTop: '0.35rem', fontSize: '0.8rem', opacity: 0.75 }}>
|
||||
Fix the keys below and save — the status is checked again on the next form submission.
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default IntegrationStatusBanner
|
||||
@@ -0,0 +1,6 @@
|
||||
export {
|
||||
recordIntegrationStatus,
|
||||
buildIntegrationStatusField,
|
||||
buildIntegrationStatusBanner,
|
||||
} from './status.js'
|
||||
export type { IntegrationStatus, IntegrationState } from './status.js'
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user