Files
ipal-kit/test/seo.test.ts
T
radoslaw.smolinskiandClaude Opus 5.5 ab854ef37a 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]>
2026-10-16 01:15:19 +02:00

162 lines
7.0 KiB
TypeScript

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()
})
})