Lint: fix all ESLint errors (391 -> 0), lint and typecheck tests
Mostly perfectionist import/key sorting and curly braces from --fix, plus: - spread instead of .apply() in the Meta Pixel stub - non-capturing group in the locale-code pattern - React 19 use(Context) / <Context value> in TurnstileProvider - email regex rewritten without super-linear backtracking (covered by a test) - console.warn/error allowed (deliberate server diagnostics) - test/tsconfig.json so the project service and tsc see test files Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
@@ -10,6 +10,6 @@ import type { RowLabelProps } from './RowLabelComponent.js'
|
||||
* After adding it to a project: `pnpm payload generate:importmap`.
|
||||
*/
|
||||
export function rowLabel(fields: string | string[], fallback = 'Item') {
|
||||
const clientProps: RowLabelProps = { fields: Array.isArray(fields) ? fields : [fields], fallback }
|
||||
return { RowLabel: { path: '@intecion/ipal-kit/admin#RowLabel', clientProps } }
|
||||
const clientProps: RowLabelProps = { fallback, fields: Array.isArray(fields) ? fields : [fields] }
|
||||
return { RowLabel: { clientProps, path: '@intecion/ipal-kit/admin#RowLabel' } }
|
||||
}
|
||||
|
||||
@@ -22,7 +22,7 @@ export function loadMetaPixel(id: string): void {
|
||||
if (w.fbq) {return}
|
||||
const n: any = (w.fbq = function (...args: unknown[]) {
|
||||
if (n.callMethod) {
|
||||
n.callMethod.apply(n, args)
|
||||
n.callMethod(...args)
|
||||
} else {
|
||||
n.queue.push(args)
|
||||
}
|
||||
|
||||
@@ -17,7 +17,7 @@
|
||||
* gates the tag in GTM (ad_storage) — this only emits the event.
|
||||
*/
|
||||
export function pushDataLayer(event: string, params: Record<string, unknown> = {}): void {
|
||||
if (typeof window === 'undefined') return
|
||||
if (typeof window === 'undefined') {return}
|
||||
const w = window as unknown as { dataLayer?: unknown[] }
|
||||
w.dataLayer = w.dataLayer || []
|
||||
w.dataLayer.push({ event, ...params })
|
||||
|
||||
@@ -9,17 +9,17 @@ export type ConsentCategory = (typeof CONSENT_CATEGORIES)[number]
|
||||
export type ConsentState = Record<ConsentCategory, boolean>
|
||||
|
||||
export const DEFAULT_CONSENT: ConsentState = {
|
||||
necessary: true,
|
||||
functional: false,
|
||||
analytics: false,
|
||||
functional: false,
|
||||
marketing: false,
|
||||
necessary: true,
|
||||
}
|
||||
|
||||
export const ACCEPT_ALL_CONSENT: ConsentState = {
|
||||
necessary: true,
|
||||
functional: true,
|
||||
analytics: true,
|
||||
functional: true,
|
||||
marketing: true,
|
||||
necessary: true,
|
||||
}
|
||||
|
||||
export const REJECT_ALL_CONSENT: ConsentState = { ...DEFAULT_CONSENT }
|
||||
|
||||
@@ -20,7 +20,7 @@ import { lexicalToMarkdown } from '../richtext/lexicalToMarkdown.js'
|
||||
* })
|
||||
*/
|
||||
|
||||
type Block = Record<string, unknown> & { blockType?: string }
|
||||
type Block = { blockType?: string } & Record<string, unknown>
|
||||
type BlockToMarkdown = (block: Block) => string
|
||||
|
||||
type BlocksToMarkdownArgs = {
|
||||
@@ -32,30 +32,30 @@ const HEADING_KEYS = new Set(['heading', 'title'])
|
||||
const SUBHEADING_KEYS = new Set(['subheading', 'subtitle'])
|
||||
const QUESTION_KEYS = new Set(['question'])
|
||||
const TEXT_KEYS = new Set([
|
||||
'answer',
|
||||
'body',
|
||||
'text',
|
||||
'caption',
|
||||
'content',
|
||||
'description',
|
||||
'excerpt',
|
||||
'summary',
|
||||
'answer',
|
||||
'caption',
|
||||
'label',
|
||||
'content',
|
||||
'summary',
|
||||
'text',
|
||||
])
|
||||
const ARRAY_KEYS = new Set([
|
||||
'items',
|
||||
'features',
|
||||
'faq',
|
||||
'faqs',
|
||||
'benefits',
|
||||
'cards',
|
||||
'columns',
|
||||
'rows',
|
||||
'faq',
|
||||
'faqs',
|
||||
'features',
|
||||
'items',
|
||||
'list',
|
||||
'points',
|
||||
'questions',
|
||||
'rows',
|
||||
'services',
|
||||
'steps',
|
||||
'points',
|
||||
'benefits',
|
||||
'list',
|
||||
])
|
||||
|
||||
/** A populated richText value is an object with a `root`. */
|
||||
@@ -65,7 +65,7 @@ function isRichText(v: unknown): boolean {
|
||||
|
||||
/** A populated upload (image) is an object with a `url`. */
|
||||
function imageMarkdown(v: unknown): string {
|
||||
if (!v || typeof v !== 'object') return ''
|
||||
if (!v || typeof v !== 'object') {return ''}
|
||||
const o = v as Record<string, unknown>
|
||||
const url = typeof o.url === 'string' ? o.url : ''
|
||||
const alt = typeof o.alt === 'string' ? o.alt : ''
|
||||
@@ -77,7 +77,7 @@ function extractBlock(block: Block, depth: number): string {
|
||||
const lines: string[] = []
|
||||
|
||||
for (const [key, value] of Object.entries(block)) {
|
||||
if (value == null) continue
|
||||
if (value == null) {continue}
|
||||
|
||||
if (HEADING_KEYS.has(key) && typeof value === 'string' && value.trim()) {
|
||||
lines.push(`## ${value.trim()}`)
|
||||
@@ -87,17 +87,17 @@ function extractBlock(block: Block, depth: number): string {
|
||||
lines.push(`**${value.trim()}**`)
|
||||
} else if (key === 'image') {
|
||||
const img = imageMarkdown(value)
|
||||
if (img) lines.push(img)
|
||||
if (img) {lines.push(img)}
|
||||
} else if (isRichText(value)) {
|
||||
const md = lexicalToMarkdown(value as never)
|
||||
if (md) lines.push(md)
|
||||
if (md) {lines.push(md)}
|
||||
} else if (TEXT_KEYS.has(key) && typeof value === 'string' && value.trim()) {
|
||||
lines.push(value.trim())
|
||||
} else if (ARRAY_KEYS.has(key) && Array.isArray(value) && depth < 4) {
|
||||
for (const item of value) {
|
||||
if (item && typeof item === 'object') {
|
||||
const sub = extractBlock(item as Block, depth + 1)
|
||||
if (sub.trim()) lines.push(sub)
|
||||
if (sub.trim()) {lines.push(sub)}
|
||||
} else if (typeof item === 'string' && item.trim()) {
|
||||
lines.push(`- ${item.trim()}`)
|
||||
}
|
||||
@@ -109,23 +109,23 @@ function extractBlock(block: Block, depth: number): string {
|
||||
}
|
||||
|
||||
export function blocksToMarkdown(layout: unknown, args: BlocksToMarkdownArgs = {}): string {
|
||||
if (!Array.isArray(layout)) return ''
|
||||
if (!Array.isArray(layout)) {return ''}
|
||||
const { overrides = {} } = args
|
||||
const out: string[] = []
|
||||
|
||||
for (const block of layout) {
|
||||
if (!block || typeof block !== 'object') continue
|
||||
if (!block || typeof block !== 'object') {continue}
|
||||
const b = block as Block
|
||||
const type = typeof b.blockType === 'string' ? b.blockType : ''
|
||||
|
||||
if (type && overrides[type]) {
|
||||
const md = overrides[type](b)
|
||||
if (md.trim()) out.push(md.trim())
|
||||
if (md.trim()) {out.push(md.trim())}
|
||||
continue
|
||||
}
|
||||
|
||||
const md = extractBlock(b, 0)
|
||||
if (md.trim()) out.push(md.trim())
|
||||
if (md.trim()) {out.push(md.trim())}
|
||||
}
|
||||
|
||||
return out.join('\n\n').trim()
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import type { BasePayload } from 'payload'
|
||||
|
||||
import type { I18nConfig } from '../i18n/index.js'
|
||||
|
||||
import type { ClientIpOptions } from '../shared/rateLimit.js'
|
||||
|
||||
import { clientIp, consumeRateLimit, tooManyRequests } from '../shared/rateLimit.js'
|
||||
|
||||
@@ -9,12 +9,12 @@
|
||||
* "Artykuły" to "Wpisy" and the path follows, per locale, with no deploy.
|
||||
*/
|
||||
export type ContentCollectionOption = {
|
||||
/** Slug of the client's collection, e.g. 'posts'. */
|
||||
slug: string
|
||||
/** Admin label for the archive assignment. Defaults to the slug. */
|
||||
label?: string
|
||||
/** Entries per page in listings. Defaults to 10. */
|
||||
perPage?: number
|
||||
/** Slug of the client's collection, e.g. 'posts'. */
|
||||
slug: string
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,13 +1,14 @@
|
||||
import type { PayloadEmailAdapter, SendEmailOptions } from 'payload'
|
||||
|
||||
import { type IntegrationStatus, recordIntegrationStatus } from '../integrations/status.js'
|
||||
import { getSiteIntegrations } from '../payload/index.js'
|
||||
import { recordIntegrationStatus, type IntegrationStatus } from '../integrations/status.js'
|
||||
import { panelSmtpAdapter, type PanelSmtpAdapterArgs } from './panelSmtpAdapter.js'
|
||||
import { graphAdapter, type GraphAdapterArgs } from './graphAdapter.js'
|
||||
import { panelSmtpAdapter, type PanelSmtpAdapterArgs } from './panelSmtpAdapter.js'
|
||||
|
||||
type TransportIntegrations = {
|
||||
/** 'smtp' | 'graph' — chosen by the editor in SiteIntegrations. */
|
||||
emailTransport?: 'smtp' | 'graph' | null
|
||||
emailStatus?: IntegrationStatus | null
|
||||
/** 'smtp' | 'graph' — chosen by the editor in SiteIntegrations. */
|
||||
emailTransport?: 'graph' | 'smtp' | null
|
||||
}
|
||||
|
||||
const STATUS_FIELD = 'emailStatus'
|
||||
@@ -16,10 +17,10 @@ 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. */
|
||||
@@ -94,21 +95,21 @@ export const mailAdapter =
|
||||
result = await (useGraph ? graph : smtp).sendEmail(message)
|
||||
} catch (err) {
|
||||
await recordIntegrationStatus(payload, STATUS_FIELD, previous, {
|
||||
state: 'degraded',
|
||||
code,
|
||||
message: `${transport}: ${describe(err)}`,
|
||||
state: 'degraded',
|
||||
})
|
||||
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
|
||||
const failed = result as { detail?: string; error?: string; sent?: boolean } | 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')}`,
|
||||
state: 'degraded',
|
||||
})
|
||||
return result
|
||||
}
|
||||
@@ -120,9 +121,9 @@ export const mailAdapter =
|
||||
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: 'degraded',
|
||||
}
|
||||
: { state: 'ok' },
|
||||
)
|
||||
|
||||
@@ -1,14 +1,15 @@
|
||||
import type { PayloadEmailAdapter, SendEmailOptions } from 'payload'
|
||||
|
||||
import { getSiteIntegrations } from '../payload/index.js'
|
||||
|
||||
/** SMTP fields the adapter reads from SiteIntegrations. */
|
||||
type SmtpIntegrations = {
|
||||
smtpHost?: string | null
|
||||
smtpPort?: number | null
|
||||
smtpUser?: string | null
|
||||
smtpPassword?: string | null
|
||||
smtpFromAddress?: string | null
|
||||
smtpFromName?: string | null
|
||||
smtpFromAddress?: null | string
|
||||
smtpFromName?: null | string
|
||||
smtpHost?: null | string
|
||||
smtpPassword?: null | string
|
||||
smtpPort?: null | number
|
||||
smtpUser?: null | string
|
||||
}
|
||||
|
||||
export type PanelSmtpAdapterArgs = {
|
||||
@@ -61,7 +62,7 @@ export const panelSmtpAdapter =
|
||||
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.' }
|
||||
return { error: 'SMTP is not configured in Site Integrations.', sent: false }
|
||||
}
|
||||
|
||||
// The panel is the source of truth for the sender; fall back to whatever
|
||||
@@ -83,10 +84,10 @@ export const panelSmtpAdapter =
|
||||
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 {
|
||||
@@ -95,13 +96,13 @@ export const panelSmtpAdapter =
|
||||
from,
|
||||
...(message.subject ? { subject: stripCRLF(message.subject) } : {}),
|
||||
})
|
||||
return { sent: true, messageId: info.messageId }
|
||||
return { messageId: info.messageId, sent: true }
|
||||
} 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}`)
|
||||
// `detail` is for the panel status (mailAdapter), not for end users.
|
||||
return { sent: false, error: 'Failed to send email.', detail: (err as Error).message }
|
||||
return { detail: (err as Error).message, error: 'Failed to send email.', sent: false }
|
||||
}
|
||||
},
|
||||
})
|
||||
|
||||
Vendored
+1
-1
@@ -1,4 +1,4 @@
|
||||
export { assertEnv } from './assertEnv.js'
|
||||
export type { EnvRule, EnvKind, AssertEnvOptions } from './assertEnv.js'
|
||||
export type { AssertEnvOptions, EnvKind, EnvRule } from './assertEnv.js'
|
||||
export { ipalEnvRules } from './ipalEnvRules.js'
|
||||
export type { IpalEnvFeatures } from './ipalEnvRules.js'
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import { formBuilderPlugin } from '@payloadcms/plugin-form-builder'
|
||||
import type { Plugin } from 'payload'
|
||||
|
||||
import { formBuilderPlugin } from '@payloadcms/plugin-form-builder'
|
||||
|
||||
import type { FormsOption } from './types.js'
|
||||
|
||||
/** REST/GraphQL: only logged-in users. Local API (submitForm) is unaffected. */
|
||||
@@ -24,14 +26,14 @@ export function buildFormsPlugin(forms: FormsOption): Plugin {
|
||||
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
|
||||
@@ -43,18 +45,18 @@ export function buildFormsPlugin(forms: FormsOption): Plugin {
|
||||
// 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' },
|
||||
labels: { plural: 'Forms', singular: 'Form' },
|
||||
...forms.formOverrides,
|
||||
admin: { ...group, ...forms.formOverrides?.admin },
|
||||
},
|
||||
formSubmissionOverrides: {
|
||||
labels: { singular: 'Submission', plural: 'Submissions' },
|
||||
labels: { plural: 'Submissions', singular: 'Submission' },
|
||||
...forms.formSubmissionOverrides,
|
||||
admin: { ...group, defaultColumns: ['form', 'createdAt'], ...forms.formSubmissionOverrides?.admin },
|
||||
access: {
|
||||
create: submissionsCreateAccess,
|
||||
...forms.formSubmissionOverrides?.access,
|
||||
},
|
||||
admin: { ...group, defaultColumns: ['form', 'createdAt'], ...forms.formSubmissionOverrides?.admin },
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1,22 +1,22 @@
|
||||
import 'server-only'
|
||||
|
||||
import type { BasePayload } from 'payload'
|
||||
|
||||
import { getTurnstileConfig } from '../turnstile/config.js'
|
||||
import { verifyTurnstile } from '../turnstile/verify.js'
|
||||
import { validateSubmission } from './validateSubmission.js'
|
||||
import { consumeRateLimit } from './rateLimit.js'
|
||||
import { validateSubmission } from './validateSubmission.js'
|
||||
|
||||
export type SubmitFormArgs = {
|
||||
payload: BasePayload
|
||||
/** Form-builder form ID this submission belongs to. */
|
||||
formId: 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
|
||||
/** Submitted field data — shape matches the form's fields. */
|
||||
data: Record<string, unknown>
|
||||
/**
|
||||
* Turnstile token. Required whenever Turnstile is configured (both keys —
|
||||
* see getTurnstileConfig): a missing token is then rejected. Ignored when
|
||||
* Turnstile is not configured.
|
||||
*/
|
||||
turnstileToken?: string
|
||||
/** Form-builder form ID this submission belongs to. */
|
||||
formId: string
|
||||
/** Client IP — used for Turnstile and rate limiting. */
|
||||
ip?: string
|
||||
/**
|
||||
@@ -24,17 +24,19 @@ export type SubmitFormArgs = {
|
||||
* Set to 0 to disable (e.g. when a real limiter sits in front).
|
||||
*/
|
||||
maxPerMinute?: number
|
||||
/**
|
||||
* 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
|
||||
payload: BasePayload
|
||||
/**
|
||||
* Turnstile can't be verified because of OUR side (missing/wrong secret,
|
||||
* Cloudflare unreachable): 'allow' (default) accepts the submission and shows
|
||||
* the problem in the panel; 'reject' refuses it.
|
||||
*/
|
||||
turnstileOnConfigError?: 'allow' | 'reject'
|
||||
/**
|
||||
* Turnstile token. Required whenever Turnstile is configured (both keys —
|
||||
* see getTurnstileConfig): a missing token is then rejected. Ignored when
|
||||
* Turnstile is not configured.
|
||||
*/
|
||||
turnstileToken?: string
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -55,26 +57,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'
|
||||
}
|
||||
| { success: false; reason: 'not_found' }
|
||||
| {
|
||||
reason: 'validation'
|
||||
success: false
|
||||
}
|
||||
| {
|
||||
field?: string
|
||||
/** A GDPR consent field existed on the form but wasn't checked. */
|
||||
reason: 'consent'
|
||||
field?: string
|
||||
success: false
|
||||
}
|
||||
| { success: false; reason: 'error' }
|
||||
| { reason: 'error'; success: false }
|
||||
| { reason: 'not_found'; success: false }
|
||||
| { reason: 'rate_limited'; success: false }
|
||||
| { reason: 'turnstile'; success: false }
|
||||
|
||||
export type SubmitFormResult = SubmitFailure | { success: true; submissionId: string | number }
|
||||
export type SubmitFormResult = { submissionId: number | string; success: true } | SubmitFailure
|
||||
|
||||
/**
|
||||
* Handles a form submission end to end: rate limit, verify Turnstile, validate
|
||||
@@ -90,19 +92,19 @@ export type SubmitFormResult = SubmitFailure | { success: true; submissionId: st
|
||||
* server-only: touches the Turnstile secret.
|
||||
*/
|
||||
export async function submitForm({
|
||||
payload,
|
||||
formId,
|
||||
consentFieldName,
|
||||
data,
|
||||
turnstileToken,
|
||||
formId,
|
||||
ip,
|
||||
maxPerMinute = 5,
|
||||
consentFieldName,
|
||||
payload,
|
||||
turnstileOnConfigError = 'allow',
|
||||
turnstileToken,
|
||||
}: SubmitFormArgs): Promise<SubmitFormResult> {
|
||||
// 1. Rate limit — cheapest gate, drops a flood before any real work.
|
||||
if (maxPerMinute > 0 && ip) {
|
||||
if (!(await consumeRateLimit({ key: ip, max: maxPerMinute })).ok) {
|
||||
return { success: false, reason: 'rate_limited' }
|
||||
return { reason: 'rate_limited', success: false }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -112,9 +114,9 @@ export async function submitForm({
|
||||
if ((await getTurnstileConfig(payload)).enabled) {
|
||||
const ok =
|
||||
Boolean(turnstileToken) &&
|
||||
(await verifyTurnstile({ token: turnstileToken!, payload, ip, onConfigError: turnstileOnConfigError }))
|
||||
(await verifyTurnstile({ ip, onConfigError: turnstileOnConfigError, payload, token: turnstileToken! }))
|
||||
if (!ok) {
|
||||
return { success: false, reason: 'turnstile' }
|
||||
return { reason: 'turnstile', success: false }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -123,14 +125,14 @@ export async function submitForm({
|
||||
const validation = await validateSubmission(payload, formId, data, consentFieldName)
|
||||
if (!validation.ok) {
|
||||
if (validation.reason === 'not_found') {
|
||||
return { success: false, reason: 'not_found' }
|
||||
return { reason: 'not_found', success: false }
|
||||
}
|
||||
if (validation.reason === 'consent') {
|
||||
return { success: false, reason: 'consent', field: validation.field }
|
||||
return { field: validation.field, reason: 'consent', success: false }
|
||||
}
|
||||
return {
|
||||
success: false,
|
||||
reason: 'validation',
|
||||
success: false,
|
||||
...(validation.field ? { field: validation.field } : {}),
|
||||
...(validation.kind ? { kind: validation.kind } : {}),
|
||||
}
|
||||
@@ -149,9 +151,9 @@ export async function submitForm({
|
||||
})),
|
||||
} as never,
|
||||
})
|
||||
return { success: true, submissionId: submission.id }
|
||||
return { submissionId: submission.id, success: true }
|
||||
} catch (err) {
|
||||
payload.logger.error(`[ipal] Form submission failed: ${(err as Error).message}`)
|
||||
return { success: false, reason: 'error' }
|
||||
return { reason: 'error', success: false }
|
||||
}
|
||||
}
|
||||
|
||||
+19
-19
@@ -19,25 +19,29 @@ 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[]
|
||||
/**
|
||||
* Admin sidebar group for Forms + Form Submissions. Default 'Forms'.
|
||||
* `false` = Payload default ("Collections"). An explicit `admin.group` in
|
||||
* formOverrides / formSubmissionOverrides still wins.
|
||||
*/
|
||||
adminGroup?: false | 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
|
||||
@@ -53,10 +57,6 @@ export type FormsOption = {
|
||||
formOverrides?: FormsCollectionOverrides
|
||||
/** Override the form-submissions collection (same shape). */
|
||||
formSubmissionOverrides?: FormsCollectionOverrides
|
||||
/**
|
||||
* 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
|
||||
/** Collections a form can redirect to (e.g. ['pages']). */
|
||||
redirectRelationships?: string[]
|
||||
}
|
||||
|
||||
@@ -24,9 +24,9 @@ import type { FormErrors, Validator } from './useForm.js'
|
||||
*/
|
||||
|
||||
/** A rule returns `true` when the value is OK, or an error message string. */
|
||||
export type Rule = (value: unknown, values: Record<string, unknown>) => true | string
|
||||
export type Rule = (value: unknown, values: Record<string, unknown>) => string | true
|
||||
|
||||
const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
|
||||
const EMAIL_RE = /^[^\s@]+@[^\s@][^\s.@]*\.[^\s@]+$/
|
||||
|
||||
/** Standalone e-mail check, handy outside the rule system too. */
|
||||
export const isEmail = (v: unknown): boolean => typeof v === 'string' && EMAIL_RE.test(v.trim())
|
||||
@@ -35,9 +35,9 @@ export const isEmail = (v: unknown): boolean => typeof v === 'string' && EMAIL_R
|
||||
export const required =
|
||||
(msg = 'required'): Rule =>
|
||||
(v) => {
|
||||
if (v == null) return msg
|
||||
if (typeof v === 'string' && !v.trim()) return msg
|
||||
if (v === false) return msg
|
||||
if (v == null) {return msg}
|
||||
if (typeof v === 'string' && !v.trim()) {return msg}
|
||||
if (v === false) {return msg}
|
||||
return true
|
||||
}
|
||||
|
||||
@@ -86,7 +86,7 @@ export function buildValidator<T extends Record<string, unknown>>(
|
||||
const all = values as Record<string, unknown>
|
||||
for (const key in schema) {
|
||||
const rules = schema[key as keyof T]
|
||||
if (!rules || rules.length === 0) continue
|
||||
if (!rules || rules.length === 0) {continue}
|
||||
for (const rule of rules) {
|
||||
const res = rule(all[key], all)
|
||||
if (res !== true) {
|
||||
|
||||
@@ -1,15 +1,16 @@
|
||||
import type { I18nConfig } from '../i18n/index.js'
|
||||
import { negotiateLocale, isValidLocale, LOCALE_COOKIE_NAME } from '../i18n/index.js'
|
||||
|
||||
import { CONSENT_COOKIE, parseConsent } from '../consent/storage.js'
|
||||
import { isValidLocale, LOCALE_COOKIE_NAME, negotiateLocale } from '../i18n/index.js'
|
||||
|
||||
/**
|
||||
* Minimal request shape the middleware reads. Kept structural so the plugin
|
||||
* doesn't hard-depend on next/server types; a Next.js `NextRequest` satisfies it.
|
||||
*/
|
||||
type MiddlewareRequest = {
|
||||
nextUrl: { pathname: string; search: string; clone: () => URL }
|
||||
cookies: { get: (name: string) => { value: string } | undefined }
|
||||
headers: { get: (name: string) => string | null }
|
||||
headers: { get: (name: string) => null | string }
|
||||
nextUrl: { clone: () => URL; pathname: string; search: string }
|
||||
url: string
|
||||
}
|
||||
|
||||
@@ -19,13 +20,11 @@ type MiddlewareRequest = {
|
||||
* `next` means let the request pass through untouched.
|
||||
*/
|
||||
export type LocaleMiddlewareResult =
|
||||
| { type: 'next'; cookie?: { name: string; value: string } }
|
||||
| { type: 'redirect'; location: string; cookie?: { name: string; value: string } }
|
||||
| { cookie?: { name: string; value: string }; location: string; type: 'redirect' }
|
||||
| { cookie?: { name: string; value: string }; type: 'next' }
|
||||
|
||||
type CreateLocaleMiddlewareArgs = {
|
||||
config: I18nConfig
|
||||
/** Cookie name for the locale choice. Defaults to LOCALE_COOKIE_NAME. */
|
||||
cookieName?: string
|
||||
/**
|
||||
* Consent category that gates *persisting* the locale cookie. The locale is
|
||||
* always detected (routing works regardless), but the choice is only written
|
||||
@@ -33,9 +32,11 @@ type CreateLocaleMiddlewareArgs = {
|
||||
* 'functional'. Pass 'necessary' to always persist (treat locale as strictly
|
||||
* necessary), which restores the pre-consent behaviour.
|
||||
*/
|
||||
consentCategory?: 'necessary' | 'functional'
|
||||
consentCategory?: 'functional' | 'necessary'
|
||||
/** Name of the consent cookie to read. Defaults to CONSENT_COOKIE. */
|
||||
consentCookieName?: string
|
||||
/** Cookie name for the locale choice. Defaults to LOCALE_COOKIE_NAME. */
|
||||
cookieName?: string
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -75,14 +76,14 @@ function firstSegment(pathname: string): string {
|
||||
*/
|
||||
export function createLocaleMiddleware({
|
||||
config,
|
||||
cookieName = LOCALE_COOKIE_NAME,
|
||||
consentCategory = 'functional',
|
||||
consentCookieName = CONSENT_COOKIE,
|
||||
cookieName = LOCALE_COOKIE_NAME,
|
||||
}: CreateLocaleMiddlewareArgs) {
|
||||
// Whether the locale cookie may be written: 'necessary' is always granted;
|
||||
// 'functional' (default) requires the visitor to have consented.
|
||||
function mayPersistLocale(request: MiddlewareRequest): boolean {
|
||||
if (consentCategory === 'necessary') return true
|
||||
if (consentCategory === 'necessary') {return true}
|
||||
const consent = parseConsent(request.cookies.get(consentCookieName)?.value)
|
||||
return consent?.[consentCategory] === true
|
||||
}
|
||||
@@ -116,9 +117,9 @@ export function createLocaleMiddleware({
|
||||
|
||||
// Resolve the locale to use
|
||||
const locale = negotiateLocale({
|
||||
cookieLocale: request.cookies.get(cookieName)?.value ?? null,
|
||||
acceptLanguage: request.headers.get('accept-language'),
|
||||
config,
|
||||
cookieLocale: request.cookies.get(cookieName)?.value ?? null,
|
||||
})
|
||||
|
||||
// Redirect to the locale-prefixed path, preserving the rest
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { I18nConfig } from './types.js'
|
||||
|
||||
import { isValidLocale } from './helpers.js'
|
||||
|
||||
/**
|
||||
@@ -11,10 +12,6 @@ import { isValidLocale } from './helpers.js'
|
||||
export type LocalizedSlugs = Record<string, string>
|
||||
|
||||
type BuildPathArgs = {
|
||||
/** slug per locale, e.g. { pl: 'strona-glowna', en: 'home' } */
|
||||
slugs: LocalizedSlugs
|
||||
/** Target locale to build the path for */
|
||||
locale: string
|
||||
config: I18nConfig
|
||||
/**
|
||||
* Slug(s) representing the site root (served at /{locale} with no trailing
|
||||
@@ -26,7 +23,9 @@ type BuildPathArgs = {
|
||||
* otherwise the home page collapses to '/pl' but '/de/startseite' stays
|
||||
* un-collapsed, breaking hreflang return tags (a real GSC error).
|
||||
*/
|
||||
homeSlug?: string | Record<string, string>
|
||||
homeSlug?: Record<string, string> | string
|
||||
/** Target locale to build the path for */
|
||||
locale: string
|
||||
/**
|
||||
* Localized segment the document lives under, e.g.
|
||||
* `{ pl: 'artykuly', en: 'articles' }` → /pl/artykuly/moj-post.
|
||||
@@ -36,6 +35,8 @@ type BuildPathArgs = {
|
||||
* A document under a prefix is never the home page, so homeSlug is ignored.
|
||||
*/
|
||||
prefix?: LocalizedSlugs
|
||||
/** slug per locale, e.g. { pl: 'strona-glowna', en: 'home' } */
|
||||
slugs: LocalizedSlugs
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -61,11 +62,11 @@ type BuildPathArgs = {
|
||||
* // → '/en/articles/my-post'
|
||||
*/
|
||||
export function buildLocalizedPath({
|
||||
slugs,
|
||||
locale,
|
||||
config,
|
||||
homeSlug = 'home',
|
||||
locale,
|
||||
prefix,
|
||||
slugs,
|
||||
}: BuildPathArgs): string | undefined {
|
||||
if (!isValidLocale(locale, config)) {
|
||||
return undefined
|
||||
@@ -109,11 +110,11 @@ export function buildLocalizedPath({
|
||||
}
|
||||
|
||||
type SwitchLocaleArgs = {
|
||||
config: I18nConfig
|
||||
homeSlug?: Record<string, string> | string
|
||||
prefix?: LocalizedSlugs
|
||||
slugs: LocalizedSlugs
|
||||
targetLocale: string
|
||||
config: I18nConfig
|
||||
homeSlug?: string | Record<string, string>
|
||||
prefix?: LocalizedSlugs
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -125,17 +126,17 @@ type SwitchLocaleArgs = {
|
||||
* to the locale root otherwise — the closest place the visitor would want.
|
||||
*/
|
||||
export function switchLocalePath({
|
||||
slugs,
|
||||
targetLocale,
|
||||
config,
|
||||
homeSlug = 'home',
|
||||
prefix,
|
||||
slugs,
|
||||
targetLocale,
|
||||
}: SwitchLocaleArgs): string {
|
||||
const path = buildLocalizedPath({ slugs, locale: targetLocale, config, homeSlug, prefix })
|
||||
if (path) return path
|
||||
const path = buildLocalizedPath({ config, homeSlug, locale: targetLocale, prefix, slugs })
|
||||
if (path) {return path}
|
||||
|
||||
const archiveSegment = prefix?.[targetLocale]
|
||||
if (archiveSegment) return `/${targetLocale}/${archiveSegment}`
|
||||
if (archiveSegment) {return `/${targetLocale}/${archiveSegment}`}
|
||||
|
||||
return `/${targetLocale}`
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { I18nConfig } from './types.js'
|
||||
|
||||
const LOCALE_CODE_PATTERN = /^[a-z]{2,3}(-[A-Z]{2})?$/
|
||||
const LOCALE_CODE_PATTERN = /^[a-z]{2,3}(?:-[A-Z]{2})?$/
|
||||
|
||||
/**
|
||||
* Validates i18n config at plugin initialization.
|
||||
|
||||
@@ -1,13 +1,14 @@
|
||||
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
|
||||
/** Status groups to check: field name → label. */
|
||||
checks?: Record<string, string>
|
||||
/** Injected by Payload into admin server components. */
|
||||
payload?: Payload
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -15,8 +16,8 @@ type Props = {
|
||||
* are currently failing, with a link to Site Integrations. Renders nothing when
|
||||
* everything is fine — and never throws (DB not ready → nothing).
|
||||
*/
|
||||
export async function IntegrationAlerts({ payload, checks = { turnstileStatus: 'Turnstile', emailStatus: 'Email' }, adminRoute = '/admin' }: Props) {
|
||||
if (!payload) return null
|
||||
export async function IntegrationAlerts({ adminRoute = '/admin', checks = { emailStatus: 'Email', turnstileStatus: 'Turnstile' }, payload }: Props) {
|
||||
if (!payload) {return null}
|
||||
let doc: Record<string, unknown>
|
||||
try {
|
||||
doc = (await payload.findGlobal({ slug: 'site-integrations' as never, depth: 0 })) as Record<string, unknown>
|
||||
@@ -26,17 +27,17 @@ export async function IntegrationAlerts({ payload, checks = { turnstileStatus: '
|
||||
const failing = Object.entries(checks)
|
||||
.map(([field, label]) => ({ label, status: doc?.[field] as IntegrationStatus | undefined }))
|
||||
.filter((x) => x.status?.state === 'degraded')
|
||||
if (!failing.length) return null
|
||||
if (!failing.length) {return null}
|
||||
|
||||
return (
|
||||
<div
|
||||
role="alert"
|
||||
style={{
|
||||
background: 'var(--theme-error-50, rgba(229, 72, 77, 0.08))',
|
||||
border: '1px solid var(--theme-error-400, #e5484d)',
|
||||
borderRadius: 4,
|
||||
marginBottom: '1.5rem',
|
||||
padding: '1rem 1.25rem',
|
||||
borderRadius: 4,
|
||||
border: '1px solid var(--theme-error-400, #e5484d)',
|
||||
background: 'var(--theme-error-50, rgba(229, 72, 77, 0.08))',
|
||||
}}
|
||||
>
|
||||
<strong>Integration problem — the site still works, but something needs attention.</strong>
|
||||
|
||||
@@ -2,14 +2,14 @@
|
||||
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
|
||||
/** Name of the hidden status group (buildIntegrationStatusField). */
|
||||
statusField: string
|
||||
}
|
||||
|
||||
const fmt = (iso: unknown) => {
|
||||
if (typeof iso !== 'string' || !iso) return ''
|
||||
if (typeof iso !== 'string' || !iso) {return ''}
|
||||
const d = new Date(iso)
|
||||
return Number.isNaN(d.getTime()) ? '' : d.toLocaleString()
|
||||
}
|
||||
@@ -19,18 +19,18 @@ const fmt = (iso: unknown) => {
|
||||
* the integration has been used once; a red box while it's failing; a short
|
||||
* green line once it works again.
|
||||
*/
|
||||
export function IntegrationStatusBanner({ statusField, label }: Props) {
|
||||
export function IntegrationStatusBanner({ label, statusField }: Props) {
|
||||
const state = useFormFields(([f]) => f[`${statusField}.state`]?.value) as string | undefined
|
||||
const message = useFormFields(([f]) => f[`${statusField}.message`]?.value) as string | undefined
|
||||
const code = useFormFields(([f]) => f[`${statusField}.code`]?.value) as string | undefined
|
||||
const since = useFormFields(([f]) => f[`${statusField}.since`]?.value)
|
||||
const checkedAt = useFormFields(([f]) => f[`${statusField}.checkedAt`]?.value)
|
||||
|
||||
if (!state) return null
|
||||
if (!state) {return null}
|
||||
|
||||
if (state === 'ok') {
|
||||
return (
|
||||
<div style={{ marginBottom: '1.5rem', fontSize: '0.85rem', opacity: 0.75 }}>
|
||||
<div style={{ fontSize: '0.85rem', marginBottom: '1.5rem', opacity: 0.75 }}>
|
||||
✓ {label} working{since ? ` since ${fmt(since)}` : ''}.
|
||||
</div>
|
||||
)
|
||||
@@ -40,21 +40,21 @@ export function IntegrationStatusBanner({ statusField, label }: Props) {
|
||||
<div
|
||||
role="alert"
|
||||
style={{
|
||||
background: 'var(--theme-error-50, rgba(229, 72, 77, 0.08))',
|
||||
border: '1px solid var(--theme-error-400, #e5484d)',
|
||||
borderRadius: 4,
|
||||
marginBottom: '1.5rem',
|
||||
padding: '0.9rem 1rem',
|
||||
borderRadius: 4,
|
||||
border: '1px solid var(--theme-error-400, #e5484d)',
|
||||
background: 'var(--theme-error-50, rgba(229, 72, 77, 0.08))',
|
||||
}}
|
||||
>
|
||||
<strong>{label} is not working — forms are accepted without this check.</strong>
|
||||
{message ? <div style={{ marginTop: '0.35rem' }}>{message}</div> : null}
|
||||
<div style={{ marginTop: '0.35rem', fontSize: '0.8rem', opacity: 0.75 }}>
|
||||
<div style={{ fontSize: '0.8rem', marginTop: '0.35rem', opacity: 0.75 }}>
|
||||
{code ? `Code: ${code}. ` : ''}
|
||||
{since ? `Since ${fmt(since)}. ` : ''}
|
||||
{checkedAt ? `Last seen ${fmt(checkedAt)}.` : ''}
|
||||
</div>
|
||||
<div style={{ marginTop: '0.35rem', fontSize: '0.8rem', opacity: 0.75 }}>
|
||||
<div style={{ fontSize: '0.8rem', marginTop: '0.35rem', opacity: 0.75 }}>
|
||||
Fix the keys below and save — the status is checked again on the next form submission.
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
export {
|
||||
recordIntegrationStatus,
|
||||
buildIntegrationStatusField,
|
||||
buildIntegrationStatusBanner,
|
||||
buildIntegrationStatusField,
|
||||
recordIntegrationStatus,
|
||||
} from './status.js'
|
||||
export type { IntegrationStatus, IntegrationState } from './status.js'
|
||||
export type { IntegrationState, IntegrationStatus } from './status.js'
|
||||
|
||||
@@ -12,18 +12,18 @@ import type { BasePayload, Field } from 'payload'
|
||||
* busy form doesn't turn every submission into a DB write.
|
||||
*/
|
||||
|
||||
export type IntegrationState = 'ok' | 'degraded'
|
||||
export type IntegrationState = 'degraded' | 'ok'
|
||||
|
||||
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
|
||||
checkedAt?: null | string
|
||||
/** Machine code from the provider or the plugin, e.g. 'invalid-input-secret', 'missing-secret'. */
|
||||
code?: null | string
|
||||
/** Human explanation shown in the panel (English — panel language). */
|
||||
message?: null | string
|
||||
/** When the current state started. */
|
||||
since?: null | string
|
||||
state?: IntegrationState | null
|
||||
}
|
||||
|
||||
const REFRESH_MS = 10 * 60_000
|
||||
@@ -53,8 +53,8 @@ export function buildIntegrationStatusBanner(statusField: string, label: string)
|
||||
admin: {
|
||||
components: {
|
||||
Field: {
|
||||
clientProps: { label, statusField },
|
||||
path: '@intecion/ipal-kit/client#IntegrationStatusBanner',
|
||||
clientProps: { statusField, label },
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -69,7 +69,7 @@ export async function recordIntegrationStatus(
|
||||
payload: BasePayload,
|
||||
field: string,
|
||||
previous: IntegrationStatus | null | undefined,
|
||||
next: { state: IntegrationState; code?: string; message?: string },
|
||||
next: { code?: string; message?: string; state: IntegrationState },
|
||||
): Promise<void> {
|
||||
const now = new Date()
|
||||
const changed = previous?.state !== next.state || (next.state === 'degraded' && previous?.code !== next.code)
|
||||
@@ -78,22 +78,22 @@ export async function recordIntegrationStatus(
|
||||
(!previous?.checkedAt || now.getTime() - new Date(previous.checkedAt).getTime() > REFRESH_MS)
|
||||
|
||||
// Healthy and already recorded as healthy (or never recorded) → nothing to do.
|
||||
if (!changed && !stale) return
|
||||
if (next.state === 'ok' && !previous?.state) return
|
||||
if (!changed && !stale) {return}
|
||||
if (next.state === 'ok' && !previous?.state) {return}
|
||||
|
||||
const status: IntegrationStatus = {
|
||||
state: next.state,
|
||||
checkedAt: now.toISOString(),
|
||||
code: next.code ?? null,
|
||||
message: next.message ?? null,
|
||||
since: changed ? now.toISOString() : (previous?.since ?? now.toISOString()),
|
||||
checkedAt: now.toISOString(),
|
||||
state: next.state,
|
||||
}
|
||||
try {
|
||||
await payload.updateGlobal({
|
||||
slug: SITE_INTEGRATIONS as never,
|
||||
context: { ipalIntegrationStatus: true },
|
||||
data: { [field]: status } as never,
|
||||
depth: 0,
|
||||
context: { ipalIntegrationStatus: true },
|
||||
})
|
||||
} catch (err) {
|
||||
console.warn(`[ipal] could not record ${field}:`, err instanceof Error ? err.message : err)
|
||||
|
||||
@@ -2,11 +2,10 @@ import type { BasePayload } from 'payload'
|
||||
|
||||
import type { ContentOption } from '../content/index.js'
|
||||
import type { I18nConfig } from '../i18n/index.js'
|
||||
import type { ClientIpOptions } from '../shared/rateLimit.js'
|
||||
|
||||
import { createMarkdownRenderer, searchContent } from '../content/index.js'
|
||||
import { getDefaultLocale, isValidLocale } from '../i18n/index.js'
|
||||
import type { ClientIpOptions } from '../shared/rateLimit.js'
|
||||
|
||||
import { clientIp, consumeRateLimit, tooManyRequests } from '../shared/rateLimit.js'
|
||||
|
||||
/**
|
||||
@@ -249,11 +248,13 @@ export function createMcpRoute(args: CreateMcpRouteArgs) {
|
||||
}
|
||||
|
||||
// No server→client SSE stream in this read-only server.
|
||||
async function GET(): Promise<Response> {
|
||||
return new Response('Method Not Allowed — POST JSON-RPC to this endpoint.', {
|
||||
headers: { allow: 'POST' },
|
||||
status: 405,
|
||||
})
|
||||
function GET(): Promise<Response> {
|
||||
return Promise.resolve(
|
||||
new Response('Method Not Allowed — POST JSON-RPC to this endpoint.', {
|
||||
headers: { allow: 'POST' },
|
||||
status: 405,
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
return { GET, POST }
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { CollectionBeforeOperationHook } from 'payload'
|
||||
|
||||
import slugify from 'slugify'
|
||||
|
||||
/**
|
||||
@@ -44,8 +45,8 @@ export function normalizeFilename(filename: string): string {
|
||||
* import { normalizeFilenameHook } from '@intecion/ipal-kit'
|
||||
* hooks: { beforeOperation: [normalizeFilenameHook] }
|
||||
*/
|
||||
export const normalizeFilenameHook: CollectionBeforeOperationHook = ({ req, operation }) => {
|
||||
if (operation !== 'create' && operation !== 'update') return
|
||||
export const normalizeFilenameHook: CollectionBeforeOperationHook = ({ operation, req }) => {
|
||||
if (operation !== 'create' && operation !== 'update') {return}
|
||||
const file = req.file
|
||||
if (file?.name) {
|
||||
file.name = normalizeFilename(file.name)
|
||||
|
||||
@@ -7,12 +7,12 @@ import type { NotificationTexts } from './types.js'
|
||||
*/
|
||||
export const NOTIFICATION_FALLBACK: NotificationTexts = {
|
||||
form: {
|
||||
success: 'Thank you — your message has been sent.',
|
||||
consent: 'Please accept the privacy policy to continue.',
|
||||
error: 'Something went wrong. Please try again later.',
|
||||
notFound: 'This form is no longer available.',
|
||||
rateLimited: 'Too many attempts. Please wait a moment and try again.',
|
||||
success: 'Thank you — your message has been sent.',
|
||||
turnstile: 'Captcha verification failed. Please try again.',
|
||||
validation: 'Please check the {field} field and try again.',
|
||||
consent: 'Please accept the privacy policy to continue.',
|
||||
notFound: 'This form is no longer available.',
|
||||
},
|
||||
}
|
||||
|
||||
@@ -3,15 +3,15 @@
|
||||
* `form` maps submitForm result codes to user-facing messages.
|
||||
*/
|
||||
export type FormNotificationTexts = {
|
||||
success: string
|
||||
/** Shown when a required GDPR consent checkbox was left unchecked. */
|
||||
consent: string
|
||||
error: string
|
||||
notFound: string
|
||||
rateLimited: string
|
||||
success: string
|
||||
turnstile: string
|
||||
/** May contain the {field} placeholder — resolve with resolveValidationText. */
|
||||
validation: string
|
||||
/** Shown when a required GDPR consent checkbox was left unchecked. */
|
||||
consent: string
|
||||
notFound: string
|
||||
}
|
||||
|
||||
export type NotificationTexts = {
|
||||
|
||||
@@ -21,7 +21,7 @@ type GetSystemPagePathArgs = {
|
||||
* page's slug in the target locale equals this, the path collapses to the
|
||||
* locale root (/pl, /en).
|
||||
*/
|
||||
homeSlug?: string | Record<string, string>
|
||||
homeSlug?: Record<string, string> | string
|
||||
/** Target locale to build the path for. */
|
||||
locale: string
|
||||
/**
|
||||
|
||||
@@ -1,25 +1,25 @@
|
||||
type MediaLike = { url?: string | null } | null | undefined
|
||||
type MediaLike = { url?: null | string } | null | undefined
|
||||
|
||||
type ArticleJsonLdArgs = {
|
||||
/** Article headline (the title). */
|
||||
headline: string
|
||||
/** Absolute URL of the article. */
|
||||
url: string
|
||||
description?: string
|
||||
/** Cover/hero image. */
|
||||
image?: MediaLike
|
||||
/** ISO date the article was first published, e.g. '2026-01-15'. */
|
||||
datePublished?: string
|
||||
/** ISO date of the last modification. Defaults to datePublished. */
|
||||
dateModified?: string
|
||||
/** Author name (person or org). */
|
||||
author?: string
|
||||
/** Publisher (usually the site/organization) name. */
|
||||
publisherName?: string
|
||||
/** ISO date of the last modification. Defaults to datePublished. */
|
||||
dateModified?: string
|
||||
/** ISO date the article was first published, e.g. '2026-01-15'. */
|
||||
datePublished?: string
|
||||
description?: string
|
||||
/** Article headline (the title). */
|
||||
headline: string
|
||||
/** Cover/hero image. */
|
||||
image?: MediaLike
|
||||
/** Publisher logo (for the Article rich result). */
|
||||
publisherLogo?: MediaLike
|
||||
/** Publisher (usually the site/organization) name. */
|
||||
publisherName?: string
|
||||
/** 'Article' (default), 'BlogPosting', or 'NewsArticle'. */
|
||||
type?: 'Article' | 'BlogPosting' | 'NewsArticle'
|
||||
/** Absolute URL of the article. */
|
||||
url: string
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -41,39 +41,39 @@ type ArticleJsonLdArgs = {
|
||||
* and dates for the rich result; supply them from the post's real fields.
|
||||
*/
|
||||
export function buildArticleJsonLd({
|
||||
headline,
|
||||
url,
|
||||
description,
|
||||
image,
|
||||
datePublished,
|
||||
dateModified,
|
||||
author,
|
||||
publisherName,
|
||||
publisherLogo,
|
||||
type = 'Article',
|
||||
author,
|
||||
dateModified,
|
||||
datePublished,
|
||||
description,
|
||||
headline,
|
||||
image,
|
||||
publisherLogo,
|
||||
publisherName,
|
||||
url,
|
||||
}: ArticleJsonLdArgs) {
|
||||
const imageUrl = image?.url
|
||||
const logoUrl = publisherLogo?.url
|
||||
|
||||
const abs = (u: string | null | undefined): string | undefined =>
|
||||
const abs = (u: null | string | undefined): string | undefined =>
|
||||
u ? (u.startsWith('http') ? u : `${url.split('/').slice(0, 3).join('/')}${u}`) : undefined
|
||||
|
||||
return {
|
||||
'@context': 'https://schema.org',
|
||||
'@type': type,
|
||||
headline,
|
||||
mainEntityOfPage: { '@id': url, '@type': 'WebPage' },
|
||||
url,
|
||||
mainEntityOfPage: { '@type': 'WebPage', '@id': url },
|
||||
...(description ? { description } : {}),
|
||||
...(imageUrl ? { image: abs(imageUrl) } : {}),
|
||||
...(datePublished ? { datePublished } : {}),
|
||||
...(dateModified || datePublished ? { dateModified: dateModified ?? datePublished } : {}),
|
||||
...(author ? { author: { '@type': 'Person', name: author } } : {}),
|
||||
...(author ? { author: { name: author, '@type': 'Person' } } : {}),
|
||||
...(publisherName
|
||||
? {
|
||||
publisher: {
|
||||
'@type': 'Organization',
|
||||
name: publisherName,
|
||||
'@type': 'Organization',
|
||||
...(logoUrl ? { logo: { '@type': 'ImageObject', url: abs(logoUrl) } } : {}),
|
||||
},
|
||||
}
|
||||
|
||||
@@ -65,8 +65,8 @@ export function buildSitemapXml(
|
||||
e.lastModified instanceof Date ? e.lastModified.toISOString() : String(e.lastModified)
|
||||
parts.push(` <lastmod>${esc(iso)}</lastmod>`)
|
||||
}
|
||||
if (e.changeFrequency) parts.push(` <changefreq>${e.changeFrequency}</changefreq>`)
|
||||
if (typeof e.priority === 'number') parts.push(` <priority>${e.priority}</priority>`)
|
||||
if (e.changeFrequency) {parts.push(` <changefreq>${e.changeFrequency}</changefreq>`)}
|
||||
if (typeof e.priority === 'number') {parts.push(` <priority>${e.priority}</priority>`)}
|
||||
const alternates = e.alternates?.languages
|
||||
if (alternates) {
|
||||
for (const [lang, href] of Object.entries(alternates)) {
|
||||
|
||||
@@ -2,14 +2,14 @@
|
||||
export type TitleOrder = 'page-first' | 'site-first'
|
||||
|
||||
type ComposeTitleArgs = {
|
||||
/** Page-specific title, e.g. 'About Us'. */
|
||||
pageTitle?: string | null
|
||||
/** Site name, e.g. 'Acme Inc'. */
|
||||
siteName?: string | null
|
||||
/** Separator between page title and site name. Defaults to ' | '. */
|
||||
separator?: string
|
||||
/** Defaults to 'page-first' — the page title is what a visitor scans for. */
|
||||
order?: TitleOrder
|
||||
/** Page-specific title, e.g. 'About Us'. */
|
||||
pageTitle?: null | string
|
||||
/** Separator between page title and site name. Defaults to ' | '. */
|
||||
separator?: string
|
||||
/** Site name, e.g. 'Acme Inc'. */
|
||||
siteName?: null | string
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -24,10 +24,10 @@ type ComposeTitleArgs = {
|
||||
* Pure function — no dependency on Payload or request state.
|
||||
*/
|
||||
export function composeTitle({
|
||||
pageTitle,
|
||||
siteName,
|
||||
separator = ' | ',
|
||||
order = 'page-first',
|
||||
pageTitle,
|
||||
separator = ' | ',
|
||||
siteName,
|
||||
}: ComposeTitleArgs): string {
|
||||
const page = pageTitle?.trim()
|
||||
const site = siteName?.trim()
|
||||
|
||||
@@ -20,7 +20,7 @@ type CreateMetadataGeneratorArgs = {
|
||||
baseUrl?: string
|
||||
config: I18nConfig
|
||||
/** Home slug that collapses to the locale root. Defaults to 'home'. */
|
||||
homeSlug?: string | Record<string, string>
|
||||
homeSlug?: Record<string, string> | string
|
||||
/**
|
||||
* Resolves the document to build metadata for, given route params.
|
||||
* The client supplies this (they own the collections and routing); it should
|
||||
|
||||
@@ -1,20 +1,21 @@
|
||||
import type { I18nConfig, LocalizedSlugs } from '../i18n/index.js'
|
||||
|
||||
import { buildLocalizedPath, getLocaleCodes } from '../i18n/index.js'
|
||||
|
||||
type BuildHreflangArgs = {
|
||||
/** slug per locale for the current document, e.g. { pl: 'o-nas', en: 'about' } */
|
||||
slugs: LocalizedSlugs
|
||||
config: I18nConfig
|
||||
/** Absolute site origin, e.g. 'https://example.com'. Omit for relative paths. */
|
||||
baseUrl?: string
|
||||
config: I18nConfig
|
||||
/** Home slug that collapses to the locale root. Defaults to 'home'. */
|
||||
homeSlug?: string | Record<string, string>
|
||||
homeSlug?: Record<string, string> | string
|
||||
/**
|
||||
* Localized segment the document lives under (an archive page's slugs),
|
||||
* e.g. { pl: 'artykuly', en: 'articles' }. Locales missing from the prefix
|
||||
* are omitted — an entry with no archive in that language has no URL there.
|
||||
*/
|
||||
prefix?: LocalizedSlugs
|
||||
/** slug per locale for the current document, e.g. { pl: 'o-nas', en: 'about' } */
|
||||
slugs: LocalizedSlugs
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -34,11 +35,11 @@ type BuildHreflangArgs = {
|
||||
* // → { pl: 'https://example.com/pl/o-nas', en: 'https://example.com/en/about' }
|
||||
*/
|
||||
export function buildHreflangAlternates({
|
||||
slugs,
|
||||
config,
|
||||
baseUrl,
|
||||
config,
|
||||
homeSlug = 'home',
|
||||
prefix,
|
||||
slugs,
|
||||
}: BuildHreflangArgs): Record<string, string> {
|
||||
const origin = baseUrl?.replace(/\/$/, '') ?? ''
|
||||
const alternates: Record<string, string> = {}
|
||||
@@ -52,7 +53,7 @@ export function buildHreflangAlternates({
|
||||
}
|
||||
|
||||
for (const locale of getLocaleCodes(config)) {
|
||||
const path = buildLocalizedPath({ slugs, locale, config, homeSlug, prefix })
|
||||
const path = buildLocalizedPath({ config, homeSlug, locale, prefix, slugs })
|
||||
if (path) {
|
||||
alternates[locale] = `${origin}${path}`
|
||||
}
|
||||
|
||||
+32
-32
@@ -1,41 +1,41 @@
|
||||
export type { SeoOption, SeoMeta } from './types.js'
|
||||
export { composeTitle } from './composeTitle.js'
|
||||
export type { TitleOrder } from './composeTitle.js'
|
||||
export { buildHreflangAlternates } from './hreflang.js'
|
||||
export { buildAutoFillMetaHook } from './autoFillMeta.js'
|
||||
export type { AutoFillMapping } from './autoFillMeta.js'
|
||||
export { buildArticleJsonLd } from './buildArticleJsonLd.js'
|
||||
export { buildBreadcrumbJsonLd } from './buildBreadcrumbJsonLd.js'
|
||||
export { buildFaqJsonLd } from './buildFaqJsonLd.js'
|
||||
export { buildIconsMetadata } from './buildIconsMetadata.js'
|
||||
export { buildLlmsTxt } from './buildLlmsTxt.js'
|
||||
export { buildLocalBusinessJsonLd } from './buildLocalBusinessJsonLd.js'
|
||||
export { createManifestHandler } from './buildManifest.js'
|
||||
export { buildMetadata } from './buildMetadata.js'
|
||||
export type { PageMetadata } from './buildMetadata.js'
|
||||
export { buildSeoPlugin } from './seoPluginConfig.js'
|
||||
export { buildAutoFillMetaHook } from './autoFillMeta.js'
|
||||
export { injectAutoFillMeta } from './injectAutoFillMeta.js'
|
||||
export { injectSeoTabs } from './injectSeoTabs.js'
|
||||
export type { AutoFillMapping } from './autoFillMeta.js'
|
||||
export { createMetadataGenerator } from './createMetadataGenerator.js'
|
||||
export { createPageMetadata } from './createPageMetadata.js'
|
||||
export { readSiteMetaConfig } from './readSiteMetaConfig.js'
|
||||
export type { SiteMetaConfig } from './readSiteMetaConfig.js'
|
||||
export { slugsAcrossLocales } from './slugsAcrossLocales.js'
|
||||
export { buildSitemapEntries } from './buildSitemapEntries.js'
|
||||
export { buildSitemapXml } from './buildSitemapXml.js'
|
||||
export type { SitemapEntry } from './buildSitemapEntries.js'
|
||||
export { buildRobots, AI_ASSISTANT_BOTS, AI_TRAINING_BOTS } from './buildRobots.js'
|
||||
export type { RobotsRules, RobotsOptions } from './buildRobots.js'
|
||||
export { buildIconsMetadata } from './buildIconsMetadata.js'
|
||||
export { buildOrganizationJsonLd } from './buildOrganizationJsonLd.js'
|
||||
export { validateFaviconField } from './validateFavicon.js'
|
||||
export { buildNoindexField } from './buildNoindexField.js'
|
||||
export { buildOrganizationJsonLd } from './buildOrganizationJsonLd.js'
|
||||
export { AI_ASSISTANT_BOTS, AI_TRAINING_BOTS, buildRobots } from './buildRobots.js'
|
||||
export type { RobotsOptions, RobotsRules } from './buildRobots.js'
|
||||
export { buildServiceJsonLd } from './buildServiceJsonLd.js'
|
||||
export { buildSitemapEntries } from './buildSitemapEntries.js'
|
||||
export type { SitemapEntry } from './buildSitemapEntries.js'
|
||||
export { buildSitemapXml } from './buildSitemapXml.js'
|
||||
export { buildSiteNavigationJsonLd } from './buildSiteNavigationJsonLd.js'
|
||||
export { buildSpeakableJsonLd } from './buildSpeakableJsonLd.js'
|
||||
export { buildSummaryField } from './buildSummaryField.js'
|
||||
export { buildWebSiteJsonLd } from './buildWebSiteJsonLd.js'
|
||||
export { buildBreadcrumbJsonLd } from './buildBreadcrumbJsonLd.js'
|
||||
export { buildSiteNavigationJsonLd } from './buildSiteNavigationJsonLd.js'
|
||||
export { buildLocalBusinessJsonLd } from './buildLocalBusinessJsonLd.js'
|
||||
export { buildFaqJsonLd } from './buildFaqJsonLd.js'
|
||||
export { buildServiceJsonLd } from './buildServiceJsonLd.js'
|
||||
export { buildArticleJsonLd } from './buildArticleJsonLd.js'
|
||||
export { buildLlmsTxt } from './buildLlmsTxt.js'
|
||||
export { composeTitle } from './composeTitle.js'
|
||||
export type { TitleOrder } from './composeTitle.js'
|
||||
export { createMetadataGenerator } from './createMetadataGenerator.js'
|
||||
export { createPageMetadata } from './createPageMetadata.js'
|
||||
export { buildHreflangAlternates } from './hreflang.js'
|
||||
export { injectAutoFillMeta } from './injectAutoFillMeta.js'
|
||||
export { injectSeoTabs } from './injectSeoTabs.js'
|
||||
export { JsonLdGraph } from './JsonLdGraph.js'
|
||||
export { readSiteMetaConfig } from './readSiteMetaConfig.js'
|
||||
export type { SiteMetaConfig } from './readSiteMetaConfig.js'
|
||||
export { createLlmsTxtRoute, createSitemapRouteHandler } from './routeHandlers.js'
|
||||
export type { SitemapRouteOptions } from './routeHandlers.js'
|
||||
export { buildSitemapCss, SITEMAP_STYLE_PARAM, DEFAULT_SITEMAP_CREDIT } from './sitemapStyle.js'
|
||||
export { buildSeoPlugin } from './seoPluginConfig.js'
|
||||
export { buildSitemapCss, DEFAULT_SITEMAP_CREDIT, SITEMAP_STYLE_PARAM } from './sitemapStyle.js'
|
||||
export type { SitemapStyleOptions } from './sitemapStyle.js'
|
||||
export { createManifestHandler } from './buildManifest.js'
|
||||
export { JsonLdGraph } from './JsonLdGraph.js'
|
||||
export { slugsAcrossLocales } from './slugsAcrossLocales.js'
|
||||
export type { SeoMeta, SeoOption } from './types.js'
|
||||
export { validateFaviconField } from './validateFavicon.js'
|
||||
|
||||
@@ -1,17 +1,18 @@
|
||||
'use client'
|
||||
|
||||
import { createContext, useCallback, useContext, useState } from 'react'
|
||||
import { createContext, use, useCallback, useState } from 'react'
|
||||
|
||||
import { Turnstile } from './Turnstile.js'
|
||||
|
||||
type TurnstileContextValue = {
|
||||
setToken: (t: null | string) => void
|
||||
/** Public site key from the provider (read server-side, passed once). */
|
||||
siteKey: string | null
|
||||
siteKey: null | string
|
||||
/** Current token (null until solved / after expiry). */
|
||||
token: string | null
|
||||
setToken: (t: string | null) => void
|
||||
token: null | string
|
||||
}
|
||||
|
||||
const TurnstileContext = createContext<TurnstileContextValue | null>(null)
|
||||
const TurnstileContext = createContext<null | TurnstileContextValue>(null)
|
||||
|
||||
/**
|
||||
* Provides the Turnstile site key once for the whole app, like ConsentProvider
|
||||
@@ -29,17 +30,17 @@ const TurnstileContext = createContext<TurnstileContextValue | null>(null)
|
||||
* token stays null — submitForm skips the check too, so the form just works.
|
||||
*/
|
||||
export function TurnstileProvider({
|
||||
siteKey,
|
||||
children,
|
||||
siteKey,
|
||||
}: {
|
||||
siteKey: string | null
|
||||
children: React.ReactNode
|
||||
siteKey: null | string
|
||||
}) {
|
||||
const [token, setToken] = useState<string | null>(null)
|
||||
const [token, setToken] = useState<null | string>(null)
|
||||
return (
|
||||
<TurnstileContext.Provider value={{ siteKey, token, setToken }}>
|
||||
<TurnstileContext value={{ setToken, siteKey, token }}>
|
||||
{children}
|
||||
</TurnstileContext.Provider>
|
||||
</TurnstileContext>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -53,27 +54,27 @@ export function TurnstileProvider({
|
||||
* // after submit: reset() // clear for the next submission
|
||||
*/
|
||||
export function useTurnstile(): {
|
||||
token: string | null
|
||||
TurnstileWidget: (props?: { theme?: 'light' | 'dark' | 'auto' }) => React.ReactNode
|
||||
reset: () => void
|
||||
/** True when Turnstile is configured (site key present). */
|
||||
enabled: boolean
|
||||
reset: () => void
|
||||
token: null | string
|
||||
TurnstileWidget: (props?: { theme?: 'auto' | 'dark' | 'light' }) => React.ReactNode
|
||||
} {
|
||||
const ctx = useContext(TurnstileContext)
|
||||
const ctx = use(TurnstileContext)
|
||||
if (!ctx) {
|
||||
throw new Error('useTurnstile must be used within <TurnstileProvider>')
|
||||
}
|
||||
const { siteKey, token, setToken } = ctx
|
||||
const { setToken, siteKey, token } = ctx
|
||||
|
||||
const reset = useCallback(() => setToken(null), [setToken])
|
||||
|
||||
const TurnstileWidget = useCallback(
|
||||
(props?: { theme?: 'light' | 'dark' | 'auto' }) => {
|
||||
if (!siteKey) return null
|
||||
return <Turnstile siteKey={siteKey} onToken={setToken} theme={props?.theme} />
|
||||
(props?: { theme?: 'auto' | 'dark' | 'light' }) => {
|
||||
if (!siteKey) {return null}
|
||||
return <Turnstile onToken={setToken} siteKey={siteKey} theme={props?.theme} />
|
||||
},
|
||||
[siteKey, setToken],
|
||||
)
|
||||
|
||||
return { token, TurnstileWidget, reset, enabled: Boolean(siteKey) }
|
||||
return { enabled: Boolean(siteKey), reset, token, TurnstileWidget }
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// 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, checkTurnstile } from './verify.js'
|
||||
export type { TurnstileCheck, TurnstileOutcome } from './verify.js'
|
||||
export { getTurnstileConfig } from './config.js'
|
||||
export type { TurnstileConfig } from './config.js'
|
||||
export { TurnstileProvider, useTurnstile } from './TurnstileProvider.js'
|
||||
// Server-only exports. verify.ts imports 'server-only', so this must never be
|
||||
// imported from a client component — use ./client for the widget instead.
|
||||
export { checkTurnstile, verifyTurnstile } from './verify.js'
|
||||
export type { TurnstileCheck, TurnstileOutcome } from './verify.js'
|
||||
|
||||
@@ -1,34 +1,26 @@
|
||||
import 'server-only'
|
||||
|
||||
import type { BasePayload } from 'payload'
|
||||
|
||||
import { type IntegrationStatus, recordIntegrationStatus } from '../integrations/status.js'
|
||||
import { getSiteIntegrations } from '../payload/index.js'
|
||||
import { recordIntegrationStatus, type IntegrationStatus } from '../integrations/status.js'
|
||||
import { TURNSTILE_SECRET_ENV as ENV_SECRET } from './config.js'
|
||||
|
||||
type SiteverifyResponse = {
|
||||
success: boolean
|
||||
'error-codes'?: string[]
|
||||
challenge_ts?: string
|
||||
'error-codes'?: string[]
|
||||
hostname?: string
|
||||
success: boolean
|
||||
}
|
||||
|
||||
type IntegrationsWithTurnstile = {
|
||||
turnstileSecretKey?: string | null
|
||||
turnstileSecretKey?: null | string
|
||||
turnstileStatus?: IntegrationStatus | null
|
||||
}
|
||||
|
||||
type VerifyTurnstileArgs = {
|
||||
/** Token produced by the client-side widget. */
|
||||
token: string
|
||||
/** Payload instance — used to read the secret from SiteIntegrations. */
|
||||
payload: BasePayload
|
||||
/** Client IP. Sent to Cloudflare only with `sendRemoteIp: true`. */
|
||||
ip?: string
|
||||
/**
|
||||
* Send `remoteip` to Cloudflare. Default false: behind Cloudflare / Traefik /
|
||||
* Docker the IP the app sees can differ from the one that solved the challenge
|
||||
* (IPv6 on mobile vs IPv4 at the proxy), and Cloudflare's check doesn't need it.
|
||||
*/
|
||||
sendRemoteIp?: boolean
|
||||
/**
|
||||
* What to do when verification can't run because of OUR side (missing/wrong
|
||||
* secret, Cloudflare unreachable). 'allow' (default): accept the submission —
|
||||
@@ -36,6 +28,16 @@ type VerifyTurnstileArgs = {
|
||||
* the panel. 'reject': refuse (fail closed).
|
||||
*/
|
||||
onConfigError?: 'allow' | 'reject'
|
||||
/** Payload instance — used to read the secret from SiteIntegrations. */
|
||||
payload: BasePayload
|
||||
/**
|
||||
* Send `remoteip` to Cloudflare. Default false: behind Cloudflare / Traefik /
|
||||
* Docker the IP the app sees can differ from the one that solved the challenge
|
||||
* (IPv6 on mobile vs IPv4 at the proxy), and Cloudflare's check doesn't need it.
|
||||
*/
|
||||
sendRemoteIp?: boolean
|
||||
/** Token produced by the client-side widget. */
|
||||
token: string
|
||||
}
|
||||
|
||||
const STATUS_FIELD = 'turnstileStatus'
|
||||
@@ -47,20 +49,20 @@ const STATUS_FIELD = 'turnstileStatus'
|
||||
* erroring) → the visitor can't fix it; by default the submission
|
||||
* is accepted and the panel shows the problem.
|
||||
*/
|
||||
export type TurnstileOutcome = 'pass' | 'reject' | 'degraded'
|
||||
export type TurnstileCheck = { outcome: TurnstileOutcome; code?: string }
|
||||
export type TurnstileOutcome = 'degraded' | 'pass' | 'reject'
|
||||
export type TurnstileCheck = { code?: string; outcome: TurnstileOutcome }
|
||||
|
||||
/** Cloudflare error codes caused by our configuration / Cloudflare itself — not by the visitor. */
|
||||
const CONFIG_ERRORS: Record<string, string> = {
|
||||
'missing-input-secret': 'The secret key is missing in the request.',
|
||||
'internal-error': 'Cloudflare reported an internal error while verifying.',
|
||||
'invalid-input-secret':
|
||||
'Cloudflare rejected the secret key — check Site Integrations → Turnstile (secret and site key must come from the same widget).',
|
||||
'internal-error': 'Cloudflare reported an internal error while verifying.',
|
||||
'missing-input-secret': 'The secret key is missing in the request.',
|
||||
}
|
||||
const PLUGIN_ERRORS: Record<string, string> = {
|
||||
'bad-response': 'Cloudflare returned an unexpected response.',
|
||||
'missing-secret': `No secret key — fill in Site Integrations → Turnstile (or the ${ENV_SECRET} environment variable).`,
|
||||
'network-error': 'The server could not reach Cloudflare (challenges.cloudflare.com).',
|
||||
'bad-response': 'Cloudflare returned an unexpected response.',
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -71,12 +73,12 @@ const PLUGIN_ERRORS: Record<string, string> = {
|
||||
* SiteIntegrations is updated (throttled) so the panel shows failures.
|
||||
*/
|
||||
export async function checkTurnstile({
|
||||
token,
|
||||
payload,
|
||||
ip,
|
||||
payload,
|
||||
sendRemoteIp = false,
|
||||
token,
|
||||
}: Omit<VerifyTurnstileArgs, 'onConfigError'>): Promise<TurnstileCheck> {
|
||||
if (!token) return { outcome: 'reject', code: 'missing-input-response' }
|
||||
if (!token) {return { code: 'missing-input-response', outcome: 'reject' }}
|
||||
|
||||
const integrations = await getSiteIntegrations<IntegrationsWithTurnstile>(payload)
|
||||
const previous = integrations[STATUS_FIELD]
|
||||
@@ -85,29 +87,29 @@ export async function checkTurnstile({
|
||||
const degraded = async (code: string): Promise<TurnstileCheck> => {
|
||||
const message = PLUGIN_ERRORS[code] ?? CONFIG_ERRORS[code] ?? `Cloudflare error: ${code}`
|
||||
console.warn(`[ipal] Turnstile degraded (${code}): ${message}`)
|
||||
await recordIntegrationStatus(payload, STATUS_FIELD, previous, { state: 'degraded', code, message })
|
||||
return { outcome: 'degraded', code }
|
||||
await recordIntegrationStatus(payload, STATUS_FIELD, previous, { code, message, state: 'degraded' })
|
||||
return { code, outcome: 'degraded' }
|
||||
}
|
||||
|
||||
if (!secret) return degraded('missing-secret')
|
||||
if (!secret) {return degraded('missing-secret')}
|
||||
|
||||
const body = new URLSearchParams({ secret, response: token })
|
||||
if (sendRemoteIp && ip) body.append('remoteip', ip)
|
||||
const body = new URLSearchParams({ response: token, secret })
|
||||
if (sendRemoteIp && ip) {body.append('remoteip', ip)}
|
||||
|
||||
let data: SiteverifyResponse
|
||||
try {
|
||||
const res = await fetch('https://challenges.cloudflare.com/turnstile/v0/siteverify', {
|
||||
method: 'POST',
|
||||
body,
|
||||
method: 'POST',
|
||||
signal: AbortSignal.timeout(8000),
|
||||
})
|
||||
if (res.status >= 500) return degraded('internal-error')
|
||||
if (res.status >= 500) {return degraded('internal-error')}
|
||||
data = (await res.json()) as SiteverifyResponse
|
||||
} catch (err) {
|
||||
console.warn('[ipal] Turnstile: siteverify request failed:', err instanceof Error ? err.message : err)
|
||||
return degraded('network-error')
|
||||
}
|
||||
if (typeof data?.success !== 'boolean') return degraded('bad-response')
|
||||
if (typeof data?.success !== 'boolean') {return degraded('bad-response')}
|
||||
|
||||
if (data.success) {
|
||||
await recordIntegrationStatus(payload, STATUS_FIELD, previous, { state: 'ok' })
|
||||
@@ -116,11 +118,11 @@ export async function checkTurnstile({
|
||||
|
||||
const codes = data['error-codes'] ?? []
|
||||
const configCode = codes.find((c) => c in CONFIG_ERRORS)
|
||||
if (configCode) return degraded(configCode)
|
||||
if (configCode) {return degraded(configCode)}
|
||||
|
||||
// Visitor-side: invalid-input-response, timeout-or-duplicate, missing-input-response, bad-request.
|
||||
console.warn(`[ipal] Turnstile rejected: ${codes.join(', ') || 'unknown'}${data.hostname ? ` (hostname ${data.hostname})` : ''}`)
|
||||
return { outcome: 'reject', code: codes[0] ?? 'unknown' }
|
||||
return { code: codes[0] ?? 'unknown', outcome: 'reject' }
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
Reference in New Issue
Block a user