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 { buildAutoFillMetaHook } from '../src/modules/seo/autoFillMeta.js' import { AI_TRAINING_BOTS, buildRobots } from '../src/modules/seo/buildRobots.js' import { buildSitemapXml } from '../src/modules/seo/buildSitemapXml.js' import { createPageMetadata } from '../src/modules/seo/createPageMetadata.js' import { buildHreflangAlternates } from '../src/modules/seo/hreflang.js' import { describeFromMarkdown } from '../src/modules/seo/plainText.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('') expect(xml).toContain('https://acme.pl/pl/a?x=1&y=2') expect(xml).toContain('2026-01-02T00:00:00.000Z') expect(xml).toContain('') }) }) 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 }) }) describe('safeHref / resolveLinkHref', () => { test('only safe schemes survive', async () => { const { resolveLinkHref, safeHref } = await import('../src/modules/links/resolveLinkHref.js') for (const ok of ['https://acme.pl', 'mailto:a@b.pl', 'tel:+48123', '#kontakt', '/pl/o-nas']) {expect(safeHref(ok)).toBe(ok)} for (const bad of ['javascript:alert(1)', ' JavaScript:alert(1)', 'java\tscript:alert(1)', 'data:text/html,x', '//evil.com', 'vbscript:x', '']) { expect(safeHref(bad)).toBeNull() } expect(resolveLinkHref({ type: 'external', url: 'javascript:alert(1)' }, { config, locale: 'pl' })).toBeNull() }) }) describe('buildUploadSecurityHeaders', () => { test('sandboxes files served from upload routes', async () => { const { buildUploadSecurityHeaders } = await import('../src/modules/security/buildSecurityHeaders.js') const rules = buildUploadSecurityHeaders({ collections: ['media', 'documents'] }) // the upload routes, and the panel icon endpoint (it answers with a file's bytes too) expect(rules.map((r) => r.source)).toEqual(['/api/media/file/:path*', '/api/documents/file/:path*', '/api/ipal/admin-icon']) const csp = rules[0].headers.find((h) => h.key === 'Content-Security-Policy')?.value ?? '' expect(csp).toContain('sandbox') expect(csp).toContain("default-src 'none'") expect(csp).not.toContain('script-src') }) }) describe('site-wide noindex (IAPL_NOINDEX) and Markdown headers', () => { test('staging blocks crawling everywhere', async () => { const { vi } = await import('vitest') vi.stubEnv('IAPL_NOINDEX', '1') try { expect(buildRobots({ baseUrl: 'https://staging.acme.pl' })).toEqual({ rules: { disallow: ['/'], userAgent: '*' } }) expect(buildSecurityHeaders().find((h) => h.key === 'X-Robots-Tag')?.value).toBe('noindex, nofollow') const { buildMetadata } = await import('../src/modules/seo/buildMetadata.js') expect(buildMetadata({ config, locale: 'pl', slugs: { pl: 'x' } }).robots).toEqual({ follow: false, index: false }) } finally { vi.unstubAllEnvs() } expect(buildSecurityHeaders().some((h) => h.key === 'X-Robots-Tag')).toBe(false) }) test('Markdown mirrors are noindex with a canonical link to the HTML page', async () => { const { markdownResponse } = await import('../src/modules/content/createMarkdownRenderer.js') const res = markdownResponse('# x', { canonical: 'https://acme.pl/pl/o-nas' }) expect(res.headers.get('x-robots-tag')).toBe('noindex') expect(res.headers.get('link')).toBe('; rel="canonical"') }) }) describe('createPageMetadata — siteDescription fallback', () => { // Regresja 1.10.0: readSiteMetaConfig czytał siteDescription, ale nie trafiał do buildMetadata — // strona bez meta.description nie miała (Lighthouse SEO). const settings = { homepage: null, siteDescription: 'Opis firmy z Site Settings', siteName: 'Acme' } const payload = {} as never test('page without its own description gets Site Settings → siteDescription', async () => { const pageMetadata = createPageMetadata({ baseUrl: 'https://acme.pl', config, loaders: { getSettings: async () => settings, resolveRoute: async () => null }, }) const metadata = await pageMetadata({ slug: ['o-nas'], locale: 'pl', payload }) expect(metadata.description).toBe('Opis firmy z Site Settings') expect(metadata.openGraph?.description).toBe('Opis firmy z Site Settings') }) test('no siteDescription → no description (field omitted, not invented)', async () => { const pageMetadata = createPageMetadata({ baseUrl: 'https://acme.pl', config, loaders: { getSettings: async () => ({ ...settings, siteDescription: null }), resolveRoute: async () => null }, }) const metadata = await pageMetadata({ slug: ['o-nas'], locale: 'pl', payload }) expect(metadata.description).toBeUndefined() }) }) describe('buildProductJsonLd', () => { test('an Offer only for a real price; "from" is a minimum, not a price', async () => { const { buildProductJsonLd } = await import('../src/modules/seo/buildProductJsonLd.js') const base = { name: 'Pierścionek', url: 'https://acme.pl/pl/wyroby/p' } expect(buildProductJsonLd(base)).not.toHaveProperty('offers') expect(buildProductJsonLd({ ...base, price: { amount: 6900, currency: 'PLN', kind: 'exact' } }).offers).toMatchObject({ price: 6900, priceCurrency: 'PLN' }) expect(buildProductJsonLd({ ...base, availability: 'MadeToOrder', price: { amount: 6900, currency: 'PLN', kind: 'from' } }).offers).toMatchObject({ availability: 'https://schema.org/MadeToOrder', priceSpecification: { minPrice: 6900 }, }) }) }) describe('meta description auto-fill', () => { const layout = [ { blockType: 'hero', heading: 'Car detailing in Opole', subheading: 'For drivers who expect more' }, { blockType: 'content', body: 'We apply Gtechniq ceramic coatings and correct paint. Every car gets a written report.' }, { blockType: 'content', body: 'Book a free consultation — we will advise on the scope. Opening hours are listed on the contact page.' }, ] // the hook ignores everything but data and originalDoc const run = (data: Record, originalDoc?: Record, mapping = {}) => buildAutoFillMetaHook(mapping)({ data, operation: originalDoc ? 'update' : 'create', originalDoc } as never) as Record test('describeFromMarkdown skips headings and keeps whole sentences', () => { const md = '## Title\n\nFirst sentence here. Second one.\n\n### Sub\n\nThird part without a stop' expect(describeFromMarkdown(md)).toBe('First sentence here. Second one. Third part without a stop.') const long = describeFromMarkdown('One short sentence. ' + 'word '.repeat(60), 155) expect(long).toBe('One short sentence.') expect(describeFromMarkdown('## Only a heading')).toBe('Only a heading.') expect(describeFromMarkdown('')).toBe('') }) test('fills an empty description from the page blocks', () => { const out = run({ layout, title: 'Detailing' }) const meta = out.meta as Record expect(meta.title).toBe('Detailing') expect(meta.description).toBe( 'We apply Gtechniq ceramic coatings and correct paint. Every car gets a written report. Book a free consultation — we will advise on the scope.', ) expect(meta.description.length).toBeLessThanOrEqual(155) }) test('never replaces a description — typed now or already stored', () => { expect((run({ layout, meta: { description: 'Mine' } }).meta as Record).description).toBe('Mine') // partial update: data carries only the layout, the stored doc has a description const out = run({ layout }, { meta: { description: 'Stored', title: 'T' } }) expect(out.meta).toBeUndefined() }) test('mapped description field wins; content: false turns the fallback off', () => { expect((run({ excerpt: 'Excerpt text', layout }, undefined, { description: 'excerpt' }).meta as Record).description).toBe('Excerpt text') expect((run({ layout, title: 'T' }, undefined, { content: false }).meta as Record).description).toBeUndefined() }) })