Files
ipal-kit/test/seo.test.ts
T
radoslaw.smolinskiandClaude Opus 5.5 ebf70d49bd Consent: withdrawal clears tool cookies, policy version, consent log, cookie scan; form input hardening
Consent (GDPR)
- Withdrawing consent now deletes GA/Meta/Ads/Clarity/LinkedIn/TikTok/Hotjar
  cookies (prefix patterns) on the host AND parent domains — previously only
  the locale cookie was removed and _ga & co. stayed. Projects extend the list
  via <ConsentProvider cookieMap>, merged with the defaults.
- Cookie Settings → Policy version: raising it asks every visitor again.
- <CookieBanner equalChoice>: Reject styled like Accept (UODO/EDPB), opt-in.
- Opt-in consent log (ipalKit({ consentLog: true }) + logEndpoint): random id,
  choices, version, time — no IP/UA; admin-only collection, retention purge.
- Cookie Settings → Cookies + getCookieTable + unstyled <CookieTable> (/rsc).
- Consent cookie gets Secure on HTTPS; consent id stored with the decision.
- ipal-consent-check: cookie-scan.mjs (before/after consent, known-tool
  catalog PL/EN, flags non-necessary cookies set before consent) and
  import-cookies.ts into the panel (idempotent, keeps editor edits).

Forms
- Server-side type checks per field from the panel definition: email = one
  address (blocks "a@x, b@y" recipient injection into {{email}} confirmations
  and CR/LF header injection), select/radio only configured options, numbers,
  booleans; objects/arrays rejected; control and bidi characters stripped.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-16 02:31:58 +02:00

216 lines
9.4 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()
})
})
describe('buildNavigationJsonLd', () => {
test('resolves page links per locale, keeps own-site links only, dedupes, walks submenus', async () => {
const { buildNavigationJsonLd } = await import('../src/modules/seo/buildSiteNavigationJsonLd.js')
const page = (slug: string) => ({ type: 'internal' as const, page: { slug } })
const nav = buildNavigationJsonLd({
baseUrl: 'https://acme.pl/',
config,
homeSlug: { en: 'home', pl: 'start' },
items: [
{ link: { ...page('start'), label: 'Start' } },
{ link: { ...page('uslugi'), label: 'Usługi' }, subItems: [{ link: { ...page('audyt'), label: 'Audyt' } }] },
{ link: { type: 'external', label: 'Blog firmy X', url: 'https://medium.com/x' } },
{ link: { ...page('uslugi'), label: 'Usługi (dup)' } },
{ link: { ...page('bez-etykiety') } },
],
locale: 'pl',
})
expect(nav?.itemListElement.map((i: { name: string; url: string }) => [i.name, i.url])).toEqual([
['Start', 'https://acme.pl/pl'],
['Usługi', 'https://acme.pl/pl/uslugi'],
['Audyt', 'https://acme.pl/pl/audyt'],
])
})
})
describe('buildCsp — googleMaps', () => {
test('covers Maps JS API domains in every needed directive, no duplicates', () => {
const { value } = buildCsp({ googleMaps: true })
const dir = (name: string) => value.split('; ').find((d) => d.startsWith(`${name} `)) ?? ''
for (const d of ['script-src', 'img-src', 'connect-src']) {
expect(dir(d)).toContain('https://*.googleapis.com')
expect(dir(d)).toContain('https://*.gstatic.com')
}
expect(dir('frame-src')).toContain('https://*.google.com')
expect(dir('worker-src')).toContain('blob:')
for (const d of value.split('; ')) {
const parts = d.split(' ').slice(1)
expect(new Set(parts).size).toBe(parts.length)
}
expect(buildCsp().value).toContain('https://fonts.gstatic.com')
})
})
describe('consent storage — version and id', () => {
test('a consent from another policy version is ignored; id round-trips', async () => {
const { readConsentRecord, serializeConsent } = await import('../src/modules/consent/storage.js')
const state = { analytics: true, functional: true, marketing: false, necessary: true }
const raw = serializeConsent(state, 2, 'abc123')
expect(readConsentRecord(raw, 2)).toMatchObject({ id: 'abc123', state, version: 2 })
expect(readConsentRecord(raw, 3)).toBeNull()
expect(readConsentRecord(raw)).toBeNull() // default version 1
})
})