MCP site tools, Turnstile key alert, required 2FA injection, a11y, more tests

- MCP: new get_site_info and list_pages tools (public by design, published
  and indexable content only); search results collapse the homepage to root.
  New listContent() helper shared with searchContent.
- Dashboard alert when Turnstile is half-configured (it is silently off then).
- twoFactor.plugin is now required; the dynamic-import fallback (which never
  worked under Next and caused a Turbopack warning) is gone.
- a11y: cookie category checkboxes are labelled, buttons have type, test-email
  input is labelled; tab labels keep localized collection labels.
- IPAL_IP_HEADER: one-time production warning when unset, opt-in
  ipalEnvRules({ ipHeader: true }).
- Tests: SEO/robots/sitemap/hreflang, CSP, Markdown, consent, MCP, and a real
  Payload + SQLite integration test for forms and the roles guard (74 total).
- Drop unused mongodb-memory-server; dev .env.example for SQLite.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
2026-10-16 01:15:19 +02:00
co-authored by Claude Opus 5.5
parent 86e69b0bcf
commit ab854ef37a
36 changed files with 708 additions and 328 deletions
+1
View File
@@ -13,6 +13,7 @@ export type BlockData = {
* Maps a blockType to the client's component for it.
* The client owns the components; the plugin only receives this map.
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- each block component has its own props shape
export type BlockComponentMap = Record<string, ComponentType<any>>
/**
+1
View File
@@ -93,6 +93,7 @@ export function ConsentScript({
if (asyncAttr) {el.async = true}
if (defer) {el.defer = true}
if (attributes) {for (const [k, v] of Object.entries(attributes)) {el.setAttribute(k, v)}}
// eslint-disable-next-line @eslint-react/web-api/no-leaked-event-listener -- one-shot, and the script is never unloaded (see below)
el.addEventListener('load', runInline, { once: true })
document.head.appendChild(el)
} else {
+11 -7
View File
@@ -101,13 +101,13 @@ export function CookieBanner({ classNames }: { classNames?: CookieBannerClassNam
</p>
</div>
<div className="flex shrink-0 gap-2">
<button className={secondaryClass} data-ipal="settings" onClick={() => setShowSettings(true)}>
<button className={secondaryClass} data-ipal="settings" onClick={() => setShowSettings(true)} type="button">
{texts.buttons.settings}
</button>
<button className={secondaryClass} data-ipal="reject" onClick={rejectAll}>
<button className={secondaryClass} data-ipal="reject" onClick={rejectAll} type="button">
{texts.buttons.reject}
</button>
<button className={primaryClass} data-ipal="accept" onClick={acceptAll}>
<button className={primaryClass} data-ipal="accept" onClick={acceptAll} type="button">
{texts.buttons.acceptAll}
</button>
</div>
@@ -122,12 +122,16 @@ export function CookieBanner({ classNames }: { classNames?: CookieBannerClassNam
{CONSENT_CATEGORIES.map((cat) => (
<li className="flex items-start justify-between gap-4" key={cat}>
<div>
<p className={`text-sm font-medium ${strongText}`}>
<p className={`text-sm font-medium ${strongText}`} id={`ipal-consent-${cat}`}>
{texts.categories[cat].title}
</p>
<p className={`text-xs ${mutedText}`}>{texts.categories[cat].description}</p>
<p className={`text-xs ${mutedText}`} id={`ipal-consent-${cat}-desc`}>
{texts.categories[cat].description}
</p>
</div>
<input
aria-describedby={`ipal-consent-${cat}-desc`}
aria-labelledby={`ipal-consent-${cat}`}
checked={cat === 'necessary' ? true : choices[cat]}
className="mt-1 h-4 w-4 shrink-0 accent-[var(--ipal-primary,#2563eb)]"
disabled={cat === 'necessary'}
@@ -138,10 +142,10 @@ export function CookieBanner({ classNames }: { classNames?: CookieBannerClassNam
))}
</ul>
<div className="flex justify-end gap-2">
<button className={secondaryClass} data-ipal="back" onClick={() => setShowSettings(false)}>
<button className={secondaryClass} data-ipal="back" onClick={() => setShowSettings(false)} type="button">
{texts.buttons.back}
</button>
<button className={primaryClass} data-ipal="save" onClick={() => savePreferences(choices)}>
<button className={primaryClass} data-ipal="save" onClick={() => savePreferences(choices)} type="button">
{texts.buttons.save}
</button>
</div>
+1
View File
@@ -36,6 +36,7 @@ export function CookieButton({ className }: { className?: string } = {}) {
className={cls}
data-ipal="cookie-button"
onClick={reopen}
type="button"
>
<Cookie
aria-hidden="true"
+1 -1
View File
@@ -10,7 +10,7 @@ export { resolveNotFoundPage } from './resolveNotFoundPage.js'
export { resolveRedirect } from './resolveRedirect.js'
export { resolveRoute } from './resolveRoute.js'
export type { ResolvedRoute } from './resolveRoute.js'
export { searchContent } from './searchContent.js'
export { listContent, searchContent } from './searchContent.js'
export type { SearchResult } from './searchContent.js'
export type { ContentCollectionOption, ContentOption } from './types.js'
export { archiveFieldName } from './types.js'
+52 -2
View File
@@ -89,6 +89,20 @@ export async function searchContent({
return []
}
return toResults(docs, { config, homeSlug, locale: loc, max, origin, summaryField })
}
type ToResultsArgs = {
config: I18nConfig
homeSlug?: Record<string, string> | string
locale: string
max: number
origin: string
summaryField?: string
}
/** Published, indexable docs → results. Shared by searchContent and listContent. */
function toResults(docs: PageRow[], { config, homeSlug, locale, max, origin, summaryField }: ToResultsArgs): SearchResult[] {
const results: SearchResult[] = []
for (const doc of docs) {
if (doc._status && doc._status !== 'published') {continue}
@@ -96,7 +110,7 @@ export async function searchContent({
const title = typeof doc.title === 'string' ? doc.title : undefined
const slug = typeof doc.slug === 'string' ? doc.slug : undefined
if (!title || !slug) {continue}
const path = buildLocalizedPath({ config, homeSlug, locale: loc, slugs: { [loc]: slug } })
const path = buildLocalizedPath({ config, homeSlug, locale, slugs: { [locale]: slug } })
// Prefer the richer AI summary when configured and present, else meta.description.
const summary =
summaryField && typeof doc[summaryField] === 'string'
@@ -113,6 +127,42 @@ export async function searchContent({
})
if (results.length >= max) {break}
}
return results
}
/**
* Every published, indexable page of a collection (title order), as the same
* structured results searchContent returns — the "table of contents" an AI
* agent browses before fetching pages. Behind the MCP server's list_pages tool.
*
* Degrades to [] (never throws) like searchContent.
*/
export async function listContent({
baseUrl,
collection = 'pages',
config,
homeSlug,
limit = 50,
locale,
payload,
summaryField,
}: Omit<SearchContentArgs, 'query'>): Promise<SearchResult[]> {
const loc = locale && isValidLocale(locale, config) ? locale : getDefaultLocale(config)
const max = Math.min(Math.max(Math.trunc(limit) || 50, 1), 200)
const origin = baseUrl?.replace(/\/$/, '') ?? ''
let docs: PageRow[] = []
try {
const res = await payload.find({
collection: collection as never,
depth: 0,
limit: max * 2, // over-fetch; drafts/noindex filtered in memory
locale: loc as never,
sort: 'title',
})
docs = (res?.docs ?? []) as PageRow[]
} catch {
return []
}
return toResults(docs, { config, homeSlug, locale: loc, max, origin, summaryField })
}
+2 -1
View File
@@ -137,7 +137,8 @@ export const graphAdapter =
// Graph accepts either HTML or Text; Payload gives us html and/or text.
const isHtml = typeof message.html === 'string' && message.html.length > 0
const content = isHtml ? String(message.html) : String(message.text ?? '')
const text = typeof message.text === 'string' ? message.text : ''
const content = isHtml ? (message.html as string) : text
// Reply-To: prefer whatever the caller set; otherwise the panel address.
const replyTo = message.replyTo
+1 -1
View File
@@ -79,7 +79,7 @@ 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: string): string => v.replace(/[\r\n]+/g, ' ').trim()
const { default: nodemailer } = await import('nodemailer')
+15
View File
@@ -7,6 +7,11 @@ export type IpalEnvFeatures = {
databaseVar?: string
/** Microsoft Graph e-mail (graphAdapter). Adds the GRAPH_* vars. */
emailGraph?: boolean
/**
* Require IPAL_IP_HEADER in production — the header the rate limit trusts for
* the client IP (see clientIp). Outside production it stays optional.
*/
ipHeader?: boolean
/** Override the Payload secret var. Default 'PAYLOAD_SECRET'. */
secretVar?: string
/** Override the site-URL var. Default 'NEXT_PUBLIC_SERVER_URL'. */
@@ -44,6 +49,7 @@ export function ipalEnvRules(features: IpalEnvFeatures = {}): EnvRule[] {
const {
databaseVar = 'DATABASE_URI',
emailGraph = false,
ipHeader = false,
secretVar = 'PAYLOAD_SECRET',
serverUrlVar = 'NEXT_PUBLIC_SERVER_URL',
storage = false,
@@ -94,6 +100,15 @@ export function ipalEnvRules(features: IpalEnvFeatures = {}): EnvRule[] {
)
}
if (ipHeader) {
rules.push({
name: 'IPAL_IP_HEADER',
description: 'Header holding the real client IP, e.g. cf-connecting-ip (Cloudflare) or x-forwarded-for',
required: process.env.NODE_ENV === 'production',
validate: (v) => (/^[a-z0-9-]+$/i.test(v) ? true : `IPAL_IP_HEADER must be a header name (got "${v}")`),
})
}
if (turnstile) {
const names = typeof turnstile === 'object' ? turnstile : {}
rules.push(
+1 -1
View File
@@ -147,7 +147,7 @@ export async function submitForm({
form: formId,
submissionData: Object.entries(validation.cleaned).map(([field, value]) => ({
field,
value: value == null ? '' : String(value),
value: value == null ? '' : typeof value === 'object' ? JSON.stringify(value) : String(value as boolean | number | string),
})),
} as never,
})
@@ -1,4 +1,4 @@
import type { BasePayload, CollectionAfterChangeHook } from 'payload'
import type { CollectionAfterChangeHook } from 'payload'
import type { I18nConfig } from '../i18n/index.js'
+1 -1
View File
@@ -33,7 +33,7 @@ export function buildPreventDeleteSystemPage(
const assigned = settings[field]
const assignedId =
assigned && typeof assigned === 'object' ? (assigned as { id?: unknown }).id : assigned
if (assignedId != null && String(assignedId) === String(id)) {
if ((typeof assignedId === 'string' || typeof assignedId === 'number') && String(assignedId) === String(id)) {
throw new APIError(
`Cannot delete a page assigned to the system role "${field}". ` +
`Detach the role in Site Settings first.`,
+1 -1
View File
@@ -21,7 +21,7 @@ export function buildValidateUniqueRole(args: { siblingFields: string[] }): Fiel
for (const sibling of args.siblingFields) {
const other = (siblingData as Record<string, unknown>)?.[sibling]
const otherId = other && typeof other === 'object' ? (other as { id?: unknown }).id : other
if (otherId != null && String(otherId) === String(thisId)) {
if ((typeof otherId === 'string' || typeof otherId === 'number') && String(otherId) === String(thisId)) {
const name = typeof field === 'object' && 'name' in field ? field.name : 'ta rola'
throw new APIError(
`Ta sama strona jest przypisana do "${name}" i "${sibling}". ` +
+1 -1
View File
@@ -20,5 +20,5 @@ export function resolveLocalized(value: unknown, locale: string, fallback = ''):
const first = Object.values(map).find((v) => typeof v === 'string')
return (first) ?? fallback
}
return String(value)
return typeof value === 'number' || typeof value === 'boolean' ? String(value) : fallback
}
+15 -4
View File
@@ -2,6 +2,8 @@ import type { Payload } from 'payload'
import type { IntegrationStatus } from './status.js'
import { turnstileKeyProblem } from '../turnstile/config.js'
type Props = {
/** Admin route, for the link. Default '/admin'. */
adminRoute?: string
@@ -25,8 +27,17 @@ export async function IntegrationAlerts({ adminRoute = '/admin', checks = { emai
return null
}
const failing = Object.entries(checks)
.map(([field, label]) => ({ label, status: doc?.[field] as IntegrationStatus | undefined }))
.filter((x) => x.status?.state === 'degraded')
.map(([field, label]) => {
const status = doc?.[field] as IntegrationStatus | undefined
return { label, message: status?.state === 'degraded' ? (status.message ?? status.code ?? 'error') : null }
})
.filter((x): x is { label: string; message: string } => x.message !== null)
// Configuration problems no request will ever record (nothing is verified
// while Turnstile is off) — checked live from the saved keys.
const keyProblem = turnstileKeyProblem(doc ?? {})
if (keyProblem && !failing.some((f) => f.label === 'Turnstile')) {
failing.push({ label: 'Turnstile', message: keyProblem })
}
if (!failing.length) {return null}
return (
@@ -42,9 +53,9 @@ export async function IntegrationAlerts({ adminRoute = '/admin', checks = { emai
>
<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 }) => (
{failing.map(({ label, message }) => (
<li key={label}>
<strong>{label}:</strong> {status?.message ?? status?.code ?? 'error'}
<strong>{label}:</strong> {message}
</li>
))}
</ul>
+87 -10
View File
@@ -4,8 +4,9 @@ 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 { createMarkdownRenderer, listContent, searchContent } from '../content/index.js'
import { getDefaultLocale, isValidLocale } from '../i18n/index.js'
import { readSiteMetaConfig } from '../seo/readSiteMetaConfig.js'
import { clientIp, consumeRateLimit, tooManyRequests } from '../shared/rateLimit.js'
/**
@@ -20,10 +21,15 @@ import { clientIp, consumeRateLimit, tooManyRequests } from '../shared/rateLimit
* transport: initialize, tools/list, tools/call, ping. Uses the global
* Request/Response — no next/server import.
*
* Exposes two tools:
* Exposes four tools:
* - get_site_info({ locale? }) → site name, description, languages, key URLs
* - list_pages({ locale?, limit? }) → every published page (title, url, description)
* - search_content({ query, locale?, limit? }) → matching pages (title, url, description)
* - get_page({ path }) → that page as Markdown
*
* Public on purpose — it exposes exactly what the public site shows (published,
* non-noindex content), so AI assistants can browse it like any visitor.
*
* // app/api/mcp/route.ts
* import { createMcpRoute } from '@intecion/ipal-kit'
* import { getCachedPayload } from '@/lib/content'
@@ -99,7 +105,27 @@ export function createMcpRoute(args: CreateMcpRouteArgs) {
const origin = baseUrl?.replace(/\/$/, '') ?? ''
const renderMarkdown = createMarkdownRenderer({ collection, content, settingsSlug })
const localeProp = { type: 'string', description: `Locale code (default ${config.defaultLocale})` }
const TOOLS = [
{
name: 'get_site_info',
description:
'Overview of the site: name, description, available languages and key URLs. Call this first.',
inputSchema: { type: 'object', properties: { locale: localeProp } },
},
{
name: 'list_pages',
description:
'List all published pages of the site with title, URL and description — the table of contents. Fetch one with get_page.',
inputSchema: {
type: 'object',
properties: {
limit: { type: 'number', description: 'Max results (default 50, max 200)' },
locale: localeProp,
},
},
},
{
name: 'search_content',
description:
@@ -108,7 +134,7 @@ export function createMcpRoute(args: CreateMcpRouteArgs) {
type: 'object',
properties: {
limit: { type: 'number', description: 'Max results (default 10)' },
locale: { type: 'string', description: `Locale code (default ${config.defaultLocale})` },
locale: localeProp,
query: { type: 'string', description: 'Search keywords' },
},
required: ['query'],
@@ -128,21 +154,72 @@ export function createMcpRoute(args: CreateMcpRouteArgs) {
},
]
const pickLocale = (params: Record<string, unknown>): string =>
typeof params.locale === 'string' && isValidLocale(params.locale, config)
? params.locale
: getDefaultLocale(config)
const formatResults = (results: { description?: string; title: string; url: string }[]) =>
results.map((r) => `- ${r.title} (${r.url})${r.description ? ` — ${r.description}` : ''}`).join('\n')
async function siteMeta(payload: BasePayload, locale: string) {
try {
return await readSiteMetaConfig({ locale, pagesSlug: collection, payload, settingsSlug })
} catch {
return null
}
}
async function getSiteInfo(params: Record<string, unknown>): Promise<string> {
const locale = pickLocale(params)
const payload = await getCachedPayload()
const meta = await siteMeta(payload, locale)
// The homepage always collapses to the language root ('/' on single-locale sites).
const home = config.locales.length === 1 ? '/' : `/${locale}`
const lines = [
`Site: ${meta?.siteName || serverName}`,
...(meta?.siteDescription ? [`Description: ${meta.siteDescription}`] : []),
`Languages: ${config.locales.map((l) => `${l.code} (${l.label})`).join(', ')} — default ${config.defaultLocale}`,
`Home: ${origin}${home}`,
...(origin ? [`Sitemap: ${origin}/sitemap.xml`] : []),
'Tools: list_pages (all pages), search_content (keyword search), get_page (one page as Markdown).',
]
return lines.join('\n')
}
async function runList(params: Record<string, unknown>): Promise<string> {
const locale = pickLocale(params)
const limit = typeof params.limit === 'number' ? params.limit : 50
const payload = await getCachedPayload()
const meta = await siteMeta(payload, locale)
const results = await listContent({
baseUrl: origin,
collection,
config,
homeSlug: meta?.homeSlug,
limit,
locale,
payload,
summaryField,
})
if (results.length === 0) {return 'No published pages.'}
return formatResults(results)
}
async function runSearch(params: Record<string, unknown>): Promise<string> {
const query = typeof params.query === 'string' ? params.query.trim() : ''
if (!query) {return 'No query provided.'}
const locale =
typeof params.locale === 'string' && isValidLocale(params.locale, config)
? params.locale
: getDefaultLocale(config)
const locale = pickLocale(params)
const limit = typeof params.limit === 'number' ? params.limit : 10
const payload = await getCachedPayload()
const meta = await siteMeta(payload, locale)
// Shared with the JSON search route — one ranking everywhere.
const results = await searchContent({
baseUrl: origin,
collection,
config,
homeSlug: meta?.homeSlug,
limit,
locale,
payload,
@@ -150,9 +227,7 @@ export function createMcpRoute(args: CreateMcpRouteArgs) {
summaryField,
})
if (results.length === 0) {return `No pages matched "${query}".`}
return results
.map((r) => `- ${r.title} (${r.url})${r.description ? ` — ${r.description}` : ''}`)
.join('\n')
return formatResults(results)
}
async function getPage(params: Record<string, unknown>): Promise<string> {
@@ -193,6 +268,8 @@ export function createMcpRoute(args: CreateMcpRouteArgs) {
const p = (params ?? {}) as { arguments?: Record<string, unknown>; name?: string }
const toolArgs = p.arguments ?? {}
try {
if (p.name === 'get_site_info') {return rpcResult(id, toolText(await getSiteInfo(toolArgs)))}
if (p.name === 'list_pages') {return rpcResult(id, toolText(await runList(toolArgs)))}
if (p.name === 'search_content') {return rpcResult(id, toolText(await runSearch(toolArgs)))}
if (p.name === 'get_page') {return rpcResult(id, toolText(await getPage(toolArgs)))}
return rpcResult(id, toolText(`Unknown tool: ${p.name}`, true))
-1
View File
@@ -1,5 +1,4 @@
import type { I18nConfig } from '../i18n/index.js'
import type { SystemPageRole } from './types.js'
import { buildLocalizedPath, getLocalizedSlugs } from '../i18n/index.js'
+1 -1
View File
@@ -55,7 +55,7 @@ export function injectSeoTabs(config: Config, seo: SeoOption): Config {
const tabs: TabsField = {
type: 'tabs',
tabs: [
{ fields: otherFields, label: collection.labels?.singular?.toString() || 'Content' },
{ fields: otherFields, label: collection.labels?.singular || 'Content' },
{ fields: [metaField], label: 'SEO' },
],
}
+10
View File
@@ -167,9 +167,19 @@ export type ClientIpOptions = {
* Empty string when nothing usable is present — the limiter then lets the
* request through.
*/
let warnedUnpinned = false
export function clientIp(source: Headers | Request, options: ClientIpOptions = {}): string {
const h = source instanceof Headers ? source : source.headers
const pinned = options.header ?? process.env.IPAL_IP_HEADER
if (!pinned && !warnedUnpinned && process.env.NODE_ENV === 'production') {
warnedUnpinned = true
console.warn(
'[ipal] IPAL_IP_HEADER is not set — the rate limit trusts whichever IP header a request carries, ' +
'so a client reaching the app directly can spoof it. Set IPAL_IP_HEADER=cf-connecting-ip ' +
'(behind Cloudflare) or x-forwarded-for (behind Traefik/nginx only).',
)
}
if (pinned) {
const value = h.get(pinned)
if (!value) {return ''}
+20 -2
View File
@@ -20,6 +20,25 @@ export type TurnstileConfig = {
let warnedPartial = false
function resolveKeys(integrations: IntegrationsWithTurnstileKeys) {
return {
secret: integrations.turnstileSecretKey?.trim() || process.env[TURNSTILE_SECRET_ENV]?.trim() || '',
siteKey: integrations.turnstileSiteKey?.trim() || process.env[TURNSTILE_SITE_KEY_ENV]?.trim() || '',
}
}
/**
* Why Turnstile is half-configured (only one of the two keys set), or null when
* it's fully on or fully off. Shown as a dashboard alert by IntegrationAlerts —
* the half-configured state silently turns Turnstile OFF, which an editor who
* just pasted one key wouldn't expect.
*/
export function turnstileKeyProblem(integrations: IntegrationsWithTurnstileKeys): null | string {
const { secret, siteKey } = resolveKeys(integrations)
if (Boolean(siteKey) === Boolean(secret)) {return null}
return `${siteKey ? 'Secret key' : 'Site key'} is missing, so Turnstile is OFF — forms are not protected. Fill in both keys (or clear both).`
}
/**
* Whether Turnstile is on, and the public key to render it with.
*
@@ -41,8 +60,7 @@ let warnedPartial = false
*/
export async function getTurnstileConfig(payload: BasePayload): Promise<TurnstileConfig> {
const integrations = await getSiteIntegrations<IntegrationsWithTurnstileKeys>(payload)
const siteKey = integrations.turnstileSiteKey?.trim() || process.env[TURNSTILE_SITE_KEY_ENV]?.trim() || ''
const secret = integrations.turnstileSecretKey?.trim() || process.env[TURNSTILE_SECRET_ENV]?.trim() || ''
const { secret, siteKey } = resolveKeys(integrations)
if (siteKey && secret) {return { enabled: true, siteKey }}