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
+134
View File
@@ -0,0 +1,134 @@
/**
* End-to-end through a REAL Payload (SQLite in memory): plugin config → form
* built in the "panel" (Local API) → submitForm → stored submission. Catches
* what unit tests with a fake payload can't: schema, access control, hooks.
*/
import type { Payload } from 'payload'
import { sqliteAdapter } from '@payloadcms/db-sqlite'
import { lexicalEditor } from '@payloadcms/richtext-lexical'
import os from 'os'
import path from 'path'
import { buildConfig, getPayload } from 'payload'
import { afterAll, beforeAll, describe, expect, test, vi } from 'vitest'
import { submitForm } from '../src/modules/forms/submitForm.js'
import { ipalKit } from '../src/plugin.js'
vi.mock('server-only', () => ({}))
let payload: Payload
let formId: string
beforeAll(async () => {
const config = buildConfig({
collections: [
// Open sign-up, the risky setup the roles field guard exists for.
{ slug: 'users', access: { create: () => true }, auth: true, fields: [] },
{ slug: 'pages', fields: [{ name: 'title', type: 'text' }] },
// SiteSettings' logo/favicon upload fields point here.
{ slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), 'ipal-test-media') } },
],
db: sqliteAdapter({ client: { url: 'file::memory:' }, push: true }),
editor: lexicalEditor(),
plugins: [
ipalKit({
access: { authCollection: 'users' },
forms: {},
i18n: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] },
twoFactor: false,
}),
],
secret: 'integration-test-secret',
telemetry: false,
})
payload = await getPayload({ config })
const form = await payload.create({
collection: 'forms' as never,
data: {
confirmationMessage: {
root: {
type: 'root',
children: [
{
type: 'paragraph',
children: [{ type: 'text', detail: 0, format: 0, mode: 'normal', style: '', text: 'Dziękujemy', version: 1 }],
direction: null,
format: '',
indent: 0,
version: 1,
},
],
direction: null,
format: '',
indent: 0,
version: 1,
},
},
fields: [
{ name: 'name', blockType: 'text', label: 'Imię', required: true },
{ name: 'consent', blockType: 'checkbox', label: 'Zgoda' },
],
title: 'Kontakt',
} as never,
})
formId = String(form.id)
}, 60_000)
afterAll(async () => {
await payload?.destroy()
})
describe('forms against a real Payload', () => {
test('a valid submission is stored with only the form fields', async () => {
const result = await submitForm({ data: { name: 'Ala', consent: true }, formId, ip: '10.7.0.1', payload })
expect(result.success).toBe(true)
if (!result.success) {return}
const stored = (await payload.findByID({
id: result.submissionId,
collection: 'form-submissions' as never,
depth: 0,
})) as unknown as { form: number | string; submissionData: { field: string; value: string }[] }
expect(String(stored.form)).toBe(formId)
expect(stored.submissionData.map(({ field, value }) => ({ field, value }))).toEqual([
{ field: 'name', value: 'Ala' },
{ field: 'consent', value: 'true' },
])
})
test('the gates hold: consent, required, unknown keys', async () => {
const send = (data: Record<string, unknown>) => submitForm({ data, formId, ip: '10.7.0.2', maxPerMinute: 0, payload })
expect(await send({ name: 'Ala', consent: false })).toMatchObject({ reason: 'consent' })
expect(await send({ consent: true })).toMatchObject({ field: 'name', reason: 'validation' })
expect(await send({ name: 'Ala', consent: true, role: 'admin' })).toMatchObject({ kind: 'unknown_fields' })
})
test('REST/anonymous creation of submissions is closed (only submitForm writes)', async () => {
await expect(
payload.create({
collection: 'form-submissions' as never,
data: { form: formId, submissionData: [] } as never,
overrideAccess: false,
}),
).rejects.toThrow()
})
test('open sign-up cannot self-assign admin — roles fall back to the default', async () => {
const user = (await payload.create({
collection: 'users',
data: { email: '[email protected]', password: 'Passw0rd!x', roles: ['admin'] } as never,
overrideAccess: false,
})) as unknown as { roles: string[] }
expect(user.roles).toEqual(['user'])
})
test('seed / Local API with overrideAccess can still create an admin', async () => {
const admin = (await payload.create({
collection: 'users',
data: { email: '[email protected]', password: 'Passw0rd!x', roles: ['admin'] } as never,
})) as unknown as { roles: string[] }
expect(admin.roles).toEqual(['admin'])
})
})
+113
View File
@@ -0,0 +1,113 @@
import type { BasePayload } from 'payload'
import { afterEach, describe, expect, test, vi } from 'vitest'
import type { I18nConfig } from '../src/modules/i18n/types.js'
import { createMcpRoute } from '../src/modules/mcp/createMcpRoute.js'
const config: I18nConfig = {
defaultLocale: 'pl',
locales: [
{ code: 'pl', label: 'Polski' },
{ code: 'en', label: 'English' },
],
}
const pages = [
{ id: 1, slug: 'o-nas', _status: 'published', meta: { description: 'Kim jesteśmy' }, title: 'O nas' },
{ id: 2, slug: 'szkic', _status: 'draft', title: 'Szkic' },
{ id: 3, slug: 'ukryta', _status: 'published', noindex: true, title: 'Ukryta' },
{ id: 4, slug: 'strona-glowna', _status: 'published', title: 'Start' },
]
const payload = {
find: vi.fn(async () => ({ docs: pages })),
findGlobal: vi.fn(async () => ({
homepage: { id: 4, slug: 'strona-glowna' },
siteDescription: 'Usługi IT',
siteName: 'Acme',
})),
} as unknown as BasePayload
let n = 0
const mcp = createMcpRoute({ baseUrl: 'https://acme.pl/', config, getCachedPayload: async () => payload })
async function rpc(body: unknown, ip = `10.1.0.${++n}`) {
const res = await mcp.POST(
new Request('https://acme.pl/api/mcp', {
body: JSON.stringify(body),
headers: { 'content-type': 'application/json', 'x-real-ip': ip },
method: 'POST',
}),
)
return { body: res.status === 202 ? null : await res.json(), status: res.status }
}
const call = async (name: string, args: Record<string, unknown> = {}) => {
const { body } = await rpc({ id: 1, jsonrpc: '2.0', method: 'tools/call', params: { name, arguments: args } })
return (body as { result: { content: { text: string }[]; isError?: boolean } }).result
}
describe('createMcpRoute', () => {
afterEach(() => vi.clearAllMocks())
test('initialize + tools/list advertise the four read-only tools', async () => {
const init = await rpc({ id: 1, jsonrpc: '2.0', method: 'initialize', params: { protocolVersion: '2025-06-18' } })
expect(init.body.result.capabilities.tools).toBeDefined()
const list = await rpc({ id: 2, jsonrpc: '2.0', method: 'tools/list' })
expect(list.body.result.tools.map((t: { name: string }) => t.name)).toEqual([
'get_site_info',
'list_pages',
'search_content',
'get_page',
])
})
test('get_site_info: name, description, languages, home URL', async () => {
const text = (await call('get_site_info')).content[0].text
expect(text).toContain('Site: Acme')
expect(text).toContain('Description: Usługi IT')
expect(text).toContain('pl (Polski), en (English) — default pl')
expect(text).toContain('Home: https://acme.pl/pl')
expect(text).toContain('Sitemap: https://acme.pl/sitemap.xml')
})
test('list_pages: only published, indexable pages; home collapses to the root', async () => {
const text = (await call('list_pages')).content[0].text
expect(text).toContain('- O nas (https://acme.pl/pl/o-nas) — Kim jesteśmy')
expect(text).toContain('- Start (https://acme.pl/pl)')
expect(text).not.toContain('Szkic')
expect(text).not.toContain('Ukryta')
})
test('search_content needs a query', async () => {
expect((await call('search_content')).content[0].text).toBe('No query provided.')
expect((await call('search_content', { query: 'nas' })).content[0].text).toContain('O nas')
})
test('tool errors stay generic (no internals leak)', async () => {
vi.spyOn(console, 'warn').mockImplementation(() => {})
;(payload.find as ReturnType<typeof vi.fn>).mockRejectedValueOnce(new Error('ECONNREFUSED db:5432'))
const res = await call('get_page', { path: '/pl/o-nas' })
expect(res.isError).toBe(true)
expect(res.content[0].text).toBe('Tool execution failed.')
})
test('protocol edges: notifications, unknown method, parse error, batch cap', async () => {
expect((await rpc({ jsonrpc: '2.0', method: 'notifications/initialized' })).status).toBe(202)
expect((await rpc({ id: 9, jsonrpc: '2.0', method: 'nope' })).body.error.code).toBe(-32601)
const bad = await mcp.POST(new Request('https://acme.pl/api/mcp', { body: '{', method: 'POST' }))
expect(bad.status).toBe(400)
const batch = Array.from({ length: 11 }, (_, i) => ({ id: i, jsonrpc: '2.0', method: 'ping' }))
expect((await rpc(batch)).status).toBe(400)
expect((await mcp.GET()).status).toBe(405)
})
test('rate limit counts every message in a batch', async () => {
const ip = '10.9.9.9'
const batch = Array.from({ length: 10 }, (_, i) => ({ id: i, jsonrpc: '2.0', method: 'ping' }))
for (let i = 0; i < 6; i++) {expect((await rpc(batch, ip)).status).toBe(200)}
expect((await rpc(batch, ip)).status).toBe(429)
})
})
+4 -1
View File
@@ -35,7 +35,10 @@ describe('ipalKit — config transform', () => {
})
test('enforces 2FA unless explicitly disabled', async () => {
await expect(ipalKit({ i18n })(base())).rejects.toThrow(/twoFactor\.issuer is required/)
await expect(ipalKit({ i18n } as never)(base())).rejects.toThrow(/twoFactor\.issuer is required/)
await expect(ipalKit({ i18n, twoFactor: { issuer: 'Acme' } } as never)(base())).rejects.toThrow(
/no 2FA plugin was injected/,
)
const totp = vi.fn(() => (c: Config) => c)
await ipalKit({ i18n, twoFactor: { issuer: 'Acme', plugin: totp as never } })(base())
+18
View File
@@ -95,3 +95,21 @@ describe('consumeRateLimit', () => {
warn.mockRestore()
})
})
describe('IPAL_IP_HEADER', () => {
afterEach(() => {
vi.unstubAllEnvs()
vi.restoreAllMocks()
})
test('ipalEnvRules({ ipHeader }) requires it in production only', async () => {
const { assertEnv } = await import('../src/modules/env/assertEnv.js')
const { ipalEnvRules } = await import('../src/modules/env/ipalEnvRules.js')
const base = { DATABASE_URI: 'x', NEXT_PUBLIC_SERVER_URL: 'https://acme.pl', PAYLOAD_SECRET: 'x' }
vi.stubEnv('NODE_ENV', 'production')
expect(() => assertEnv(ipalEnvRules({ ipHeader: true }), { env: base })).toThrow(/IPAL_IP_HEADER/)
expect(() => assertEnv(ipalEnvRules({ ipHeader: true }), { env: { ...base, IPAL_IP_HEADER: 'cf-connecting-ip' } })).not.toThrow()
vi.stubEnv('NODE_ENV', 'development')
expect(() => assertEnv(ipalEnvRules({ ipHeader: true }), { env: base })).not.toThrow()
})
})
+161
View File
@@ -0,0 +1,161 @@
import { describe, expect, test } from 'vitest'
import type { I18nConfig } from '../src/modules/i18n/types.js'
import { parseConsent, serializeConsent } from '../src/modules/consent/storage.js'
import { markdownHref, prefersMarkdown } from '../src/modules/content/markdownNegotiation.js'
import { lexicalToMarkdown } from '../src/modules/richtext/lexicalToMarkdown.js'
import { buildCsp } from '../src/modules/security/buildCsp.js'
import { buildSecurityHeaders } from '../src/modules/security/buildSecurityHeaders.js'
import { AI_TRAINING_BOTS, buildRobots } from '../src/modules/seo/buildRobots.js'
import { buildSitemapXml } from '../src/modules/seo/buildSitemapXml.js'
import { buildHreflangAlternates } from '../src/modules/seo/hreflang.js'
const config: I18nConfig = {
defaultLocale: 'pl',
locales: [
{ code: 'pl', label: 'Polski' },
{ code: 'en', label: 'English' },
],
}
describe('buildRobots', () => {
test('defaults: allow all but admin/api, sitemap, explicit AI allow', () => {
const r = buildRobots({ baseUrl: 'https://acme.pl/' })
expect(r.sitemap).toBe('https://acme.pl/sitemap.xml')
expect(r.host).toBe('https://acme.pl')
const [base, ai] = r.rules as { disallow: string[]; userAgent: string | string[] }[]
expect(base.disallow).toEqual(['/admin', '/api'])
expect(ai.userAgent).toEqual(expect.arrayContaining(['ClaudeBot', 'GPTBot']))
})
test('hidden admin route is not revealed', () => {
const r = buildRobots({ adminRoute: false, aiBots: false, baseUrl: 'https://acme.pl' })
expect((r.rules as { disallow: string[] }).disallow).toEqual(['/api'])
})
test('block-training keeps assistants, blocks training crawlers', () => {
const rules = buildRobots({ aiBots: 'block-training', baseUrl: 'https://acme.pl' }).rules as {
disallow: string[]
userAgent: string[]
}[]
const training = rules.find((r) => r.userAgent.includes(AI_TRAINING_BOTS[0]))
expect(training?.disallow).toEqual(['/'])
})
test('disallowParams covers the param in any position', () => {
const r = buildRobots({ aiBots: false, baseUrl: 'https://acme.pl', disallowParams: ['s'] })
expect((r.rules as { disallow: string[] }).disallow).toEqual(['/admin', '/api', '/*?s=', '/*&s='])
})
})
describe('buildSitemapXml', () => {
test('escapes URLs and emits hreflang alternates', () => {
const xml = buildSitemapXml(
[
{
alternates: { languages: { en: 'https://acme.pl/en/a', pl: 'https://acme.pl/pl/a' } },
lastModified: new Date('2026-01-02T00:00:00Z'),
url: 'https://acme.pl/pl/a?x=1&y=2',
},
],
{ cssUrl: '/sitemap.css' },
)
expect(xml).toMatch(/^<\?xml/)
expect(xml).toContain('<?xml-stylesheet type="text/css" href="/sitemap.css"?>')
expect(xml).toContain('<loc>https://acme.pl/pl/a?x=1&amp;y=2</loc>')
expect(xml).toContain('<lastmod>2026-01-02T00:00:00.000Z</lastmod>')
expect(xml).toContain('<xhtml:link rel="alternate" hreflang="en" href="https://acme.pl/en/a"/>')
})
})
describe('buildHreflangAlternates', () => {
test('one URL per locale plus x-default → default locale', () => {
expect(
buildHreflangAlternates({ baseUrl: 'https://acme.pl', config, slugs: { en: 'about', pl: 'o-nas' } }),
).toEqual({
en: 'https://acme.pl/en/about',
pl: 'https://acme.pl/pl/o-nas',
'x-default': 'https://acme.pl/pl/o-nas',
})
})
test('single-locale sites get no alternates', () => {
const single: I18nConfig = { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] }
expect(buildHreflangAlternates({ config: single, slugs: { pl: 'o-nas' } })).toEqual({})
})
})
describe('security headers', () => {
test('CSP: hard defaults, opt-in sources, report-only header name', () => {
const csp = buildCsp({ turnstile: true })
expect(csp.key).toBe('Content-Security-Policy')
expect(csp.value).toContain("frame-ancestors 'none'")
expect(csp.value).toContain("object-src 'none'")
expect(csp.value).toMatch(/script-src [^;]*https:\/\/challenges\.cloudflare\.com/)
expect(csp.value).not.toContain('unsafe-eval')
expect(buildCsp({ mode: 'report-only' }).key).toBe('Content-Security-Policy-Report-Only')
})
test('CSP: relative R2 URL is not added (already self)', () => {
expect(buildCsp({ r2Url: '/media' }).value).not.toContain('/media')
expect(buildCsp({ r2Url: 'https://cdn.acme.pl' }).value).toContain('https://cdn.acme.pl')
})
test('headers: HSTS, nosniff, overrides by key', () => {
const headers = buildSecurityHeaders({ additional: [{ key: 'x-frame-options', value: 'SAMEORIGIN' }] })
const get = (k: string) => headers.find((h) => h.key.toLowerCase() === k.toLowerCase())?.value
expect(get('Strict-Transport-Security')).toBe('max-age=63072000; includeSubDomains')
expect(get('X-Content-Type-Options')).toBe('nosniff')
expect(get('X-Frame-Options')).toBe('SAMEORIGIN')
expect(headers.filter((h) => h.key.toLowerCase() === 'x-frame-options')).toHaveLength(1)
})
})
describe('Markdown for AI', () => {
test('markdownHref', () => {
expect(markdownHref('/pl/o-nas')).toBe('/md/pl/o-nas')
expect(markdownHref('/')).toBe('/md')
expect(markdownHref('pl', '/ai/')).toBe('/ai/pl')
})
test('prefersMarkdown respects q-values', () => {
expect(prefersMarkdown('text/markdown')).toBe(true)
expect(prefersMarkdown('text/html,text/markdown;q=0.5')).toBe(false)
expect(prefersMarkdown(new Headers({ accept: 'text/markdown, text/html' }))).toBe(true)
expect(prefersMarkdown('text/html')).toBe(false)
expect(prefersMarkdown(undefined)).toBe(false)
})
test('lexicalToMarkdown renders the common nodes', () => {
const text = (t: string, format = 0) => ({ type: 'text', format, text: t })
const md = lexicalToMarkdown({
root: {
children: [
{ type: 'heading', children: [text('Tytuł')], tag: 'h2' },
{ type: 'paragraph', children: [text('Zwykły '), text('gruby', 1), text(' i '), text('kursywa', 2)] },
{ type: 'paragraph', children: [{ type: 'link', children: [text('link')], fields: { url: 'https://acme.pl' } }] },
{ type: 'paragraph', children: [] },
{ type: 'upload', value: { alt: 'Logo', url: '/media/logo.png' } },
],
},
} as never)
expect(md).toBe(
'## Tytuł\n\nZwykły **gruby** i _kursywa_\n\n[link](https://acme.pl)\n\n![Logo](/media/logo.png)',
)
expect(lexicalToMarkdown(null)).toBe('')
})
})
describe('consent cookie', () => {
test('round-trips and always keeps necessary on', () => {
const raw = serializeConsent({ analytics: true, functional: false, marketing: false, necessary: false } as never)
expect(parseConsent(raw)).toMatchObject({ analytics: true, marketing: false, necessary: true })
})
test('garbage or an old version → null (ask again)', () => {
expect(parseConsent('%%%')).toBeNull()
expect(parseConsent(encodeURIComponent(JSON.stringify({ state: {}, version: 0 })))).toBeNull()
expect(parseConsent(undefined)).toBeNull()
})
})
+14
View File
@@ -157,3 +157,17 @@ describe('submitForm — other gates', () => {
)
})
})
describe('turnstileKeyProblem', () => {
afterEach(() => vi.unstubAllEnvs())
test('only flags a half-configured setup', async () => {
const { turnstileKeyProblem } = await import('../src/modules/turnstile/config.js')
expect(turnstileKeyProblem({})).toBeNull()
expect(turnstileKeyProblem({ turnstileSecretKey: 's', turnstileSiteKey: 'k' })).toBeNull()
expect(turnstileKeyProblem({ turnstileSiteKey: 'k' })).toMatch(/Secret key is missing/)
expect(turnstileKeyProblem({ turnstileSecretKey: 's' })).toMatch(/Site key is missing/)
vi.stubEnv('TURNSTILE_SECRET_KEY', 's')
expect(turnstileKeyProblem({ turnstileSiteKey: 'k' })).toBeNull()
})
})