Merge main (security-perf + SEO) into docs; finish English docs and agent guide
- Resolve conflicts in analytics, consent, content, i18n, mcp and stats, keeping the docs fixes and the new code behaviour, verified against src - Translate the remaining 14 module pages, ipal-seo-check skill and script - Integrate the security-perf and SEO agent-guide text: getRobots, isPathVisible, Search & AI (DNS verification first, meta fields optional), sitemap index/cache/503, consentMode basic/advanced, policyVersion, globalOverrides, revalidatePath / buildGlobalRevalidateHook, authAccess, firstUserAdmin, allowCollectionMismatch, unknown-IP rate limit; stale claims fixed across AGENT.md, skills, frontend, developer guide, vibe - docsConsistency: pending list removed (all docs English); relative links now also check #anchors Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
@@ -0,0 +1,241 @@
|
||||
import type { Access, CollectionConfig, Config, Field, GlobalConfig } from 'payload'
|
||||
|
||||
import { describe, expect, test, vi } from 'vitest'
|
||||
|
||||
import type { I18nConfig } from '../src/modules/i18n/types.js'
|
||||
|
||||
import { ipalKit } from '../src/plugin.js'
|
||||
|
||||
const i18n: I18nConfig = {
|
||||
defaultLocale: 'pl',
|
||||
locales: [
|
||||
{ code: 'pl', label: 'Polski' },
|
||||
{ code: 'en', label: 'English' },
|
||||
],
|
||||
}
|
||||
|
||||
const empty = (extra: Partial<Config> = {}): Config =>
|
||||
({ collections: [], secret: 'x', ...extra }) as unknown as Config
|
||||
|
||||
const admin = { id: 1, roles: ['admin'] }
|
||||
const editor = { id: 2, roles: ['editor'] }
|
||||
const user = { id: 3, roles: ['user'] }
|
||||
|
||||
/** Runs a collection/global access function the way Payload does. */
|
||||
const run = (fn: Access | undefined, u: unknown) =>
|
||||
fn ? fn({ req: { user: u } } as never) : 'payload-default'
|
||||
|
||||
describe('injected auth collection', () => {
|
||||
test('with roles: a plain user can only see and edit itself, never create or delete', async () => {
|
||||
const config = await ipalKit({ access: { authCollection: 'users' }, i18n, twoFactor: false })(empty())
|
||||
const access = config.collections?.find((c) => c.slug === 'users')?.access ?? {}
|
||||
|
||||
expect(run(access.update, user)).toEqual({ id: { equals: 3 } })
|
||||
expect(run(access.read, user)).toEqual({ id: { equals: 3 } })
|
||||
expect(run(access.delete, user)).toBe(false)
|
||||
expect(run(access.create, user)).toBe(false)
|
||||
expect(run(access.delete, editor)).toBe(false)
|
||||
expect(run(access.update, null)).toBe(false)
|
||||
|
||||
expect(run(access.update, admin)).toBe(true)
|
||||
expect(run(access.delete, admin)).toBe(true)
|
||||
expect(run(access.create, admin)).toBe(true)
|
||||
})
|
||||
|
||||
test("the project's own auth collection keeps its own access", async () => {
|
||||
const own = { slug: 'users', access: { read: () => true }, auth: true, fields: [] }
|
||||
const config = await ipalKit({ access: { authCollection: 'users' }, i18n, twoFactor: false })(
|
||||
empty({ collections: [own] as CollectionConfig[] }),
|
||||
)
|
||||
expect(config.collections?.find((c) => c.slug === 'users')?.access).toBe(own.access)
|
||||
})
|
||||
})
|
||||
|
||||
describe('2FA wraps the auth collection people log in with', () => {
|
||||
const totp = () => vi.fn((_: unknown) => (c: Config) => c)
|
||||
|
||||
test('defaults to access.authCollection, not a literal "users"', async () => {
|
||||
const plugin = totp()
|
||||
await ipalKit({ access: { authCollection: 'admins' }, i18n, twoFactor: { issuer: 'A', plugin: plugin as never } })(
|
||||
empty(),
|
||||
)
|
||||
expect(plugin).toHaveBeenCalledWith(expect.objectContaining({ collection: 'admins' }))
|
||||
})
|
||||
|
||||
test('defaults to admin.user when access is not configured', async () => {
|
||||
const plugin = totp()
|
||||
await ipalKit({ i18n, twoFactor: { issuer: 'A', plugin: plugin as never } })(
|
||||
empty({ admin: { user: 'staff' } } as Partial<Config>),
|
||||
)
|
||||
expect(plugin).toHaveBeenCalledWith(expect.objectContaining({ collection: 'staff' }))
|
||||
})
|
||||
|
||||
const twoAuth = () =>
|
||||
empty({
|
||||
admin: { user: 'admins' },
|
||||
collections: [
|
||||
{ slug: 'admins', auth: true, fields: [] },
|
||||
{ slug: 'users', auth: true, fields: [] },
|
||||
{ slug: 'pages', fields: [] },
|
||||
],
|
||||
} as Partial<Config>)
|
||||
|
||||
test('admin.user wins over access.authCollection as the default target', async () => {
|
||||
const plugin = totp()
|
||||
await ipalKit({ access: { authCollection: 'users' }, i18n, twoFactor: { issuer: 'A', plugin: plugin as never } })(twoAuth())
|
||||
expect(plugin).toHaveBeenCalledWith(expect.objectContaining({ collection: 'admins' }))
|
||||
})
|
||||
|
||||
test('a target other than the panel login collection fails at init…', async () => {
|
||||
const plugin = totp()
|
||||
await expect(
|
||||
ipalKit({ i18n, twoFactor: { collectionSlug: 'users', issuer: 'A', plugin: plugin as never } })(twoAuth()),
|
||||
).rejects.toThrow(/admin panel logs in with "admins"/)
|
||||
})
|
||||
|
||||
test('…unless allowCollectionMismatch says it is deliberate', async () => {
|
||||
const plugin = totp()
|
||||
await ipalKit({
|
||||
i18n,
|
||||
twoFactor: { allowCollectionMismatch: true, collectionSlug: 'users', issuer: 'A', plugin: plugin as never },
|
||||
})(twoAuth())
|
||||
expect(plugin).toHaveBeenCalledWith(expect.objectContaining({ collection: 'users' }))
|
||||
})
|
||||
|
||||
test('a target that is not an auth collection always fails', async () => {
|
||||
const plugin = totp()
|
||||
await expect(
|
||||
ipalKit({
|
||||
i18n,
|
||||
twoFactor: { allowCollectionMismatch: true, collectionSlug: 'pages', issuer: 'A', plugin: plugin as never },
|
||||
})(twoAuth()),
|
||||
).rejects.toThrow(/"pages" is not an auth collection/)
|
||||
})
|
||||
})
|
||||
|
||||
describe('globals: public read, editor+ write', () => {
|
||||
test.each(['site-settings', 'cookie-settings', 'notifications'])('%s', async (slug) => {
|
||||
const config = await ipalKit({ access: { authCollection: 'users' }, i18n, twoFactor: false })(empty())
|
||||
const access = (config.globals?.find((g) => g.slug === slug) as GlobalConfig).access ?? {}
|
||||
expect(run(access.read, null)).toBe(true)
|
||||
expect(run(access.update, user)).toBe(false)
|
||||
expect(run(access.update, null)).toBe(false)
|
||||
expect(run(access.update, editor)).toBe(true)
|
||||
expect(run(access.update, admin)).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('forms collection: public read, editor+ write, Emails hidden from plain users', () => {
|
||||
const build = async () => {
|
||||
const config = await ipalKit({ access: { authCollection: 'users' }, forms: {}, i18n, twoFactor: false })(empty())
|
||||
return config.collections?.find((c) => c.slug === 'forms') as CollectionConfig
|
||||
}
|
||||
|
||||
test('create / update / delete need editor', async () => {
|
||||
const { access = {} } = await build()
|
||||
expect(run(access.read, null)).toBe(true)
|
||||
for (const op of ['create', 'update', 'delete'] as const) {
|
||||
expect(run(access[op], user)).toBe(false)
|
||||
expect(run(access[op], editor)).toBe(true)
|
||||
}
|
||||
})
|
||||
|
||||
test('the Emails field (recipients, BCC) is unreadable for a plain user', async () => {
|
||||
const forms = await build()
|
||||
const emails = forms.fields.find((f: Field) => 'name' in f && f.name === 'emails') as {
|
||||
access?: { read?: (a: unknown) => boolean }
|
||||
}
|
||||
expect(emails.access?.read?.({ req: { user } })).toBe(false)
|
||||
expect(emails.access?.read?.({ req: { user: editor } })).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('roles field: the first-register account becomes admin', () => {
|
||||
const hook = async (totalDocs: number, value: string[], pathname = '/api/users/first-register') => {
|
||||
const config = await ipalKit({ access: { authCollection: 'users' }, i18n, twoFactor: false })(empty())
|
||||
const users = config.collections?.find((c) => c.slug === 'users') as CollectionConfig
|
||||
const roles = users.fields.find((f) => 'name' in f && f.name === 'roles') as { hooks?: { beforeChange?: ((a: unknown) => unknown)[] } }
|
||||
const count = vi.fn(async () => ({ totalDocs }))
|
||||
return roles.hooks?.beforeChange?.[0]?.({
|
||||
collection: { slug: 'users' },
|
||||
operation: 'create',
|
||||
req: { pathname, payload: { count } },
|
||||
value,
|
||||
})
|
||||
}
|
||||
|
||||
test('empty collection → admin, whatever was sent', async () => {
|
||||
expect(await hook(0, ['user'])).toEqual(['admin'])
|
||||
})
|
||||
|
||||
test('later accounts keep what access allowed', async () => {
|
||||
expect(await hook(1, ['user'])).toEqual(['user'])
|
||||
})
|
||||
|
||||
test('an open sign-up on an empty collection is not promoted', async () => {
|
||||
expect(await hook(0, ['user'], '/api/users')).toEqual(['user'])
|
||||
})
|
||||
})
|
||||
|
||||
describe('every access default can be overridden by the project', () => {
|
||||
test('injected users: unlock is admin-only by default; access.authAccess keys win', async () => {
|
||||
const base = await ipalKit({ access: { authCollection: 'users' }, i18n, twoFactor: false })(empty())
|
||||
const def = base.collections?.find((c) => c.slug === 'users')?.access ?? {}
|
||||
expect(run(def.unlock, user)).toBe(false)
|
||||
expect(run(def.unlock, admin)).toBe(true)
|
||||
|
||||
const config = await ipalKit({
|
||||
access: { authAccess: { read: () => true }, authCollection: 'users' },
|
||||
i18n,
|
||||
twoFactor: false,
|
||||
})(empty())
|
||||
const access = config.collections?.find((c) => c.slug === 'users')?.access ?? {}
|
||||
expect(run(access.read, user)).toBe(true)
|
||||
expect(run(access.delete, user)).toBe(false) // the rest keeps the plugin default
|
||||
})
|
||||
|
||||
test('access.firstUserAdmin: false keeps what the first-register form sent', async () => {
|
||||
const config = await ipalKit({ access: { authCollection: 'users', firstUserAdmin: false }, i18n, twoFactor: false })(empty())
|
||||
const users = config.collections?.find((c) => c.slug === 'users') as CollectionConfig
|
||||
const roles = users.fields.find((f) => 'name' in f && f.name === 'roles') as { hooks?: unknown }
|
||||
expect(roles.hooks).toBeUndefined()
|
||||
})
|
||||
|
||||
test('globalOverrides: an object merges access (project wins), a function takes over', async () => {
|
||||
const config = await ipalKit({
|
||||
access: { authCollection: 'users' },
|
||||
globalOverrides: {
|
||||
'cookie-settings': (g) => ({ ...g, label: 'Cookies' }),
|
||||
notifications: { access: { update: ({ req }) => Boolean(req.user) } },
|
||||
},
|
||||
i18n,
|
||||
twoFactor: false,
|
||||
})(empty())
|
||||
const notifications = config.globals?.find((g) => g.slug === 'notifications') as GlobalConfig
|
||||
expect(run(notifications.access?.update, user)).toBe(true)
|
||||
expect(run(notifications.access?.read, null)).toBe(true)
|
||||
expect(config.globals?.find((g) => g.slug === 'cookie-settings')?.label).toBe('Cookies')
|
||||
// untouched globals keep the secure default
|
||||
expect(run((config.globals?.find((g) => g.slug === 'site-settings') as GlobalConfig).access?.update, user)).toBe(false)
|
||||
})
|
||||
|
||||
test('forms: formOverrides.access wins; a read rule on the Emails field wins', async () => {
|
||||
const config = await ipalKit({
|
||||
access: { authCollection: 'users' },
|
||||
forms: {
|
||||
formOverrides: {
|
||||
access: { update: () => true },
|
||||
fields: ({ defaultFields }) =>
|
||||
defaultFields.map((f) => ('name' in f && f.name === 'emails' ? ({ ...f, access: { read: () => true } } as Field) : f)),
|
||||
},
|
||||
},
|
||||
i18n,
|
||||
twoFactor: false,
|
||||
})(empty())
|
||||
const forms = config.collections?.find((c) => c.slug === 'forms') as CollectionConfig
|
||||
expect(run(forms.access?.update, user)).toBe(true)
|
||||
expect(run(forms.access?.delete, user)).toBe(false)
|
||||
const emails = forms.fields.find((f: Field) => 'name' in f && f.name === 'emails') as { access?: { read?: (a: unknown) => boolean } }
|
||||
expect(emails.access?.read?.({ req: { user } })).toBe(true)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,19 @@
|
||||
import { describe, expect, test } from 'vitest'
|
||||
|
||||
import { shouldLoadGoogle } from '../src/modules/analytics/Analytics.js'
|
||||
|
||||
const none = { analytics: false, marketing: false }
|
||||
|
||||
describe("Google tag and consent", () => {
|
||||
test("'basic': no Google request before an analytics or marketing grant", () => {
|
||||
expect(shouldLoadGoogle({ consentMode: 'basic', ready: true, state: none })).toBe(false)
|
||||
expect(shouldLoadGoogle({ consentMode: 'basic', ready: true, state: { ...none, analytics: true } })).toBe(true)
|
||||
expect(shouldLoadGoogle({ consentMode: 'basic', ready: true, state: { ...none, marketing: true } })).toBe(true)
|
||||
})
|
||||
|
||||
test("'advanced' (default) loads with denied signals; `defer` still holds both back", () => {
|
||||
expect(shouldLoadGoogle({ consentMode: 'advanced', ready: true, state: none })).toBe(true)
|
||||
expect(shouldLoadGoogle({ consentMode: 'advanced', ready: false, state: none })).toBe(false)
|
||||
expect(shouldLoadGoogle({ consentMode: 'basic', ready: false, state: { analytics: true } })).toBe(false)
|
||||
})
|
||||
})
|
||||
@@ -7,7 +7,7 @@ import path from 'node:path'
|
||||
import { buildConfig, getPayload } from 'payload'
|
||||
import { afterAll, beforeAll, describe, expect, test, vi } from 'vitest'
|
||||
|
||||
import { constructionNoticeHref, isPathAllowed, normalizePath } from '../src/modules/construction/logic.js'
|
||||
import { constructionNoticeHref, isPathAllowed, isPathVisibleIn, normalizePath } from '../src/modules/construction/logic.js'
|
||||
import { createContentHelpers } from '../src/modules/frontend/createContentHelpers.js'
|
||||
import { createPageRoute } from '../src/modules/frontend/pageRoute.js'
|
||||
import { ipalKit } from '../src/plugin.js'
|
||||
@@ -22,6 +22,12 @@ describe('under construction — path logic', () => {
|
||||
expect(isPathAllowed('/pl/o-nas', ['/pl', '/pl/brief'])).toBe(false)
|
||||
expect(constructionNoticeHref('/pl')).toBe('/pl?notice=construction')
|
||||
})
|
||||
|
||||
test('isPathVisibleIn: off → everything; on → allowed paths only', () => {
|
||||
expect(isPathVisibleIn({ allowedPaths: [], enabled: false }, '/pl/o-nas')).toBe(true)
|
||||
expect(isPathVisibleIn({ allowedPaths: ['/pl', '/pl/brief'], enabled: true }, '/pl/brief/')).toBe(true)
|
||||
expect(isPathVisibleIn({ allowedPaths: ['/pl', '/pl/brief'], enabled: true }, '/pl/o-nas')).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('under construction — Site Settings → createPageRoute', () => {
|
||||
@@ -87,4 +93,66 @@ describe('under construction — Site Settings → createPageRoute', () => {
|
||||
await expect(open('pl', ['o-nas'])).rejects.toThrow('REDIRECT /pl?notice=construction')
|
||||
await expect(open('pl', ['nie-ma'])).rejects.toThrow('REDIRECT /pl?notice=construction')
|
||||
})
|
||||
|
||||
test('on: Markdown, MCP and search hide the same pages the page route hides', async () => {
|
||||
const helpers = createContentHelpers({ baseUrl: 'https://acme.pl', config: configPromise, i18n })
|
||||
expect((await helpers.getConstructionMode('pl')).enabled).toBe(true)
|
||||
|
||||
const md = (slug: string[]) => helpers.markdownRoute(new Request('https://acme.pl/md'), { params: Promise.resolve({ slug, locale: 'pl' }) })
|
||||
expect((await md(['o-nas'])).status).toBe(404)
|
||||
expect((await md(['brief'])).status).toBe(200)
|
||||
|
||||
const rpc = async (name: string, args: Record<string, unknown>) => {
|
||||
const res = await helpers.mcpPOST(
|
||||
new Request('https://acme.pl/api/mcp', {
|
||||
body: JSON.stringify({ id: 1, jsonrpc: '2.0', method: 'tools/call', params: { name, arguments: args } }),
|
||||
headers: { 'content-type': 'application/json', 'x-real-ip': '198.51.100.4' },
|
||||
method: 'POST',
|
||||
}),
|
||||
)
|
||||
return ((await res.json()) as { result: { content: { text: string }[] } }).result.content[0].text
|
||||
}
|
||||
const list = await rpc('list_pages', { locale: 'pl' })
|
||||
expect(list).toContain('/pl/brief')
|
||||
expect(list).not.toContain('/pl/o-nas')
|
||||
expect(await rpc('get_page', { path: '/pl/o-nas' })).toMatch(/No page found/)
|
||||
expect(await rpc('search_content', { locale: 'pl', query: 'nas' })).not.toContain('/pl/o-nas')
|
||||
|
||||
// a whole list shares one construction-mode read (React cache doesn't dedupe in route handlers)
|
||||
const readsFor = async (n: number) => {
|
||||
const spy = vi.spyOn(payload, 'findGlobal')
|
||||
await Promise.all(Array.from({ length: n }, (_, i) => helpers.isPathVisible(`/pl/p-${i}`, 'pl')))
|
||||
const count = spy.mock.calls.length
|
||||
spy.mockRestore()
|
||||
return count
|
||||
}
|
||||
expect(await readsFor(50)).toBe(await readsFor(1))
|
||||
|
||||
expect(await helpers.isPathVisible('/pl/o-nas', 'pl')).toBe(false)
|
||||
expect(await helpers.isPathVisible('/pl/brief', 'pl')).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('under construction — opting out per route', () => {
|
||||
test('a project can pass its own isPathVisible to Markdown / MCP', async () => {
|
||||
const { createMcpRoute } = await import('../src/modules/mcp/createMcpRoute.js')
|
||||
const seen: string[] = []
|
||||
const mcp = createMcpRoute({
|
||||
config: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'PL' }, { code: 'en', label: 'EN' }] },
|
||||
getCachedPayload: async () => ({}) as never,
|
||||
isPathVisible: (path) => {
|
||||
seen.push(path)
|
||||
return false
|
||||
},
|
||||
rateLimit: false,
|
||||
})
|
||||
const res = await mcp.POST(
|
||||
new Request('https://x/api/mcp', {
|
||||
body: JSON.stringify({ id: 1, jsonrpc: '2.0', method: 'tools/call', params: { name: 'get_page', arguments: { path: '/pl/o-nas' } } }),
|
||||
method: 'POST',
|
||||
}),
|
||||
)
|
||||
expect(JSON.stringify(await res.json())).toContain('No page found')
|
||||
expect(seen).toEqual(['/pl/o-nas'])
|
||||
})
|
||||
})
|
||||
|
||||
@@ -129,8 +129,10 @@ describe('docs ↔ code', () => {
|
||||
test('relative links between docs point at existing files', () => {
|
||||
const broken: string[] = []
|
||||
for (const file of [...docs, 'README.md'].filter((f) => f.endsWith('.md'))) {
|
||||
for (const m of read(file).matchAll(/\]\((?!https?:|mailto:|#)([^)\s#]+)(?:#[^)]*)?\)/g)) {
|
||||
if (!existsSync(path.join(root, path.dirname(file), m[1]))) {broken.push(`${file}: ${m[1]}`)}
|
||||
for (const m of read(file).matchAll(/\]\((?!https?:|mailto:|#)([^)\s#]+)(?:#([^)]*))?\)/g)) {
|
||||
const target = path.join(path.dirname(file), m[1])
|
||||
if (!existsSync(path.join(root, target))) {broken.push(`${file}: ${m[1]}`); continue}
|
||||
if (m[2] && target.endsWith('.md') && !anchorsOf(target).has(decodeURIComponent(m[2]))) {broken.push(`${file}: ${m[1]}#${m[2]}`)}
|
||||
}
|
||||
}
|
||||
expect(broken).toEqual([])
|
||||
@@ -187,18 +189,11 @@ describe('docs ↔ code', () => {
|
||||
* blocks, inline code or quoted strings (e.g. a 'pl' seed value, a slug, a file name).
|
||||
*/
|
||||
describe('docs are in English', () => {
|
||||
// Translated after the code branches that edit them are merged — remove from this list then.
|
||||
const pending = new Set([
|
||||
'docs/access.md', 'docs/agent/skills/ipal-seo-check/SKILL.md', 'docs/analytics.md', 'docs/consent.md', 'docs/construction.md',
|
||||
'docs/content.md', 'docs/forms.md', 'docs/hooks.md', 'docs/mcp.md', 'docs/notifications.md',
|
||||
'docs/richtext.md', 'docs/security.md', 'docs/seo.md', 'docs/stats.md', 'docs/turnstile.md',
|
||||
])
|
||||
|
||||
test('no Polish prose outside code and quoted sample data', () => {
|
||||
// Diacritics, or common Polish words for text written without them.
|
||||
const polish = /[ąćęłńóśźż]|\b(?:albo|czy|dla|gdy|jest|lub|nie|oraz|przez|tylko)\b/i
|
||||
const offending: string[] = []
|
||||
for (const file of [...docs, 'README.md'].filter((f) => f.endsWith('.md') && !pending.has(f))) {
|
||||
for (const file of [...docs, 'README.md'].filter((f) => f.endsWith('.md'))) {
|
||||
const prose = read(file)
|
||||
.replace(/```[\s\S]*?```/g, '')
|
||||
.replace(/`[^`\n]*`/g, '')
|
||||
@@ -274,6 +269,18 @@ function walk(dir: string): string[] {
|
||||
})
|
||||
}
|
||||
|
||||
/** GitHub-style heading anchors of a Markdown file (code blocks skipped, duplicates get -1, -2 …). */
|
||||
function anchorsOf(file: string): Set<string> {
|
||||
const seen = new Map<string, number>()
|
||||
const text = read(file).replace(/```[\s\S]*?```/g, '')
|
||||
return new Set([...text.matchAll(/^#{1,6} (.+)$/gm)].map((m) => {
|
||||
const slug = m[1].trim().toLowerCase().replace(/[^\p{L}\p{N}\s_-]/gu, '').replace(/\s/g, '-')
|
||||
const n = seen.get(slug) ?? 0
|
||||
seen.set(slug, n + 1)
|
||||
return n ? `${slug}-${n}` : slug
|
||||
}))
|
||||
}
|
||||
|
||||
function srcFiles(dir = 'src'): string[] {
|
||||
return readdirSync(path.join(root, dir)).flatMap((name) => {
|
||||
const rel = path.join(dir, name)
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
/**
|
||||
* The main entry (payload.config, the payload CLI, server code) and the proxy
|
||||
* entry must not load 'use client' modules: in plain Node every re-exported
|
||||
* module is evaluated, and the proxy bundle should stay free of React UI.
|
||||
*/
|
||||
import { existsSync, readFileSync } from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import { describe, expect, test } from 'vitest'
|
||||
|
||||
const root = path.resolve(import.meta.dirname, '..')
|
||||
|
||||
function resolve(from: string, spec: string): null | string {
|
||||
if (!spec.startsWith('.')) {return null}
|
||||
const base = path.resolve(path.dirname(from), spec).replace(/\.js$/, '')
|
||||
for (const ext of ['.ts', '.tsx', '/index.ts']) {
|
||||
if (existsSync(base + ext)) {return base + ext}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/** Runtime (non-type) imports and re-exports reachable from `entry`; returns the 'use client' ones. */
|
||||
function clientModulesReachable(entry: string): string[] {
|
||||
const seen = new Set<string>()
|
||||
const hits: string[] = []
|
||||
const stack = [path.join(root, entry)]
|
||||
while (stack.length) {
|
||||
const file = stack.pop()!
|
||||
if (seen.has(file)) {continue}
|
||||
seen.add(file)
|
||||
const src = readFileSync(file, 'utf8')
|
||||
if (/^\s*['"]use client['"]/.test(src)) {hits.push(path.relative(root, file))}
|
||||
for (const m of src.matchAll(/^(?:import|export) (?!type\b)[^'"]*?from ['"]([^'"]+)['"]/gm)) {
|
||||
const next = resolve(file, m[1])
|
||||
if (next) {stack.push(next)}
|
||||
}
|
||||
}
|
||||
return hits.sort()
|
||||
}
|
||||
|
||||
describe('server entries load no client modules', () => {
|
||||
test.each(['src/exports/next-middleware.ts', 'src/index.ts'])('%s', (entry) => {
|
||||
expect(clientModulesReachable(entry)).toEqual([])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,46 @@
|
||||
/** Hooks run their Local API calls inside the save's request (transaction) without corrupting it. */
|
||||
import { describe, expect, test, vi } from 'vitest'
|
||||
|
||||
import { buildCrossLocaleFieldSync } from '../src/modules/hooks/buildCrossLocaleFieldSync.js'
|
||||
import { buildPreventDeleteSystemPage } from '../src/modules/hooks/preventDeleteSystemPage.js'
|
||||
|
||||
const config = { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'PL' }, { code: 'en', label: 'EN' }] } as const
|
||||
|
||||
/** Mimics the Local API: a call with `req` sets req.locale / req.fallbackLocale to its own. */
|
||||
function fakeReq() {
|
||||
const req: Record<string, unknown> = { fallbackLocale: 'pl', locale: 'pl' }
|
||||
const adopt = (args: { locale?: string; req?: Record<string, unknown> }) => {
|
||||
if (args.req && args.locale) {
|
||||
args.req.locale = args.locale
|
||||
args.req.fallbackLocale = 'null'
|
||||
}
|
||||
}
|
||||
const findByID = vi.fn(async (args: { locale?: string; req?: Record<string, unknown> }) => {
|
||||
adopt(args)
|
||||
return { id: 1, layout: [{ id: 'r1', blockType: 'hero', image: 7 }] }
|
||||
})
|
||||
const update = vi.fn(async (args: { locale?: string; req?: Record<string, unknown> }) => {
|
||||
adopt(args)
|
||||
return {}
|
||||
})
|
||||
req.payload = { findByID, findGlobal: vi.fn(async () => ({})), logger: { error: vi.fn() }, update }
|
||||
return { findByID, req, update }
|
||||
}
|
||||
|
||||
describe('hooks pass req', () => {
|
||||
test('cross-locale sync reads and writes in the request, then restores its locale', async () => {
|
||||
const { findByID, req, update } = fakeReq()
|
||||
const hook = buildCrossLocaleFieldSync({ collection: 'pages', config, fields: ['image'] })
|
||||
await hook({ doc: { id: 1, layout: [{ id: 'r1', blockType: 'hero', image: 9 }] }, req } as never)
|
||||
expect(findByID).toHaveBeenCalledWith(expect.objectContaining({ locale: 'en', req }))
|
||||
expect(update).toHaveBeenCalledWith(expect.objectContaining({ locale: 'en', req }))
|
||||
expect(req.locale).toBe('pl')
|
||||
expect(req.fallbackLocale).toBe('pl')
|
||||
})
|
||||
|
||||
test('preventDeleteSystemPage reads Site Settings in the request', async () => {
|
||||
const { req } = fakeReq()
|
||||
await buildPreventDeleteSystemPage()({ id: 3, req } as never)
|
||||
expect((req.payload as { findGlobal: ReturnType<typeof vi.fn> }).findGlobal).toHaveBeenCalledWith(expect.objectContaining({ req }))
|
||||
})
|
||||
})
|
||||
@@ -74,6 +74,12 @@ describe('IndexNow hook', () => {
|
||||
await run({})
|
||||
expect(fetchSpy).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
test('staging copy (IPAL_NOINDEX) sends nothing even in production', async () => {
|
||||
vi.stubEnv('IPAL_NOINDEX', '1')
|
||||
await run({ _status: 'published' })
|
||||
expect(fetchSpy).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
describe('IndexNow key', () => {
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
import { describe, expect, test } from 'vitest'
|
||||
|
||||
import { CONSENT_COOKIE, serializeConsent } from '../src/modules/consent/storage.js'
|
||||
import { createLocaleMiddleware } from '../src/modules/i18n/localeMiddleware.js'
|
||||
import { LOCALE_COOKIE_NAME } from '../src/modules/i18n/negotiateLocale.js'
|
||||
|
||||
const config = { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'PL' }, { code: 'en', label: 'EN' }] } as const
|
||||
const state = { analytics: false, functional: true, marketing: false, necessary: true }
|
||||
|
||||
function request(path: string, cookies: Record<string, string>) {
|
||||
const url = new URL(`https://acme.pl${path}`)
|
||||
return {
|
||||
cookies: { get: (name: string) => (name in cookies ? { value: cookies[name] } : undefined) },
|
||||
headers: new Headers(),
|
||||
nextUrl: { clone: () => new URL(url), pathname: url.pathname, search: url.search },
|
||||
url: url.toString(),
|
||||
}
|
||||
}
|
||||
|
||||
describe('locale cookie and the consent policy version', () => {
|
||||
const switchToEn = (version: number, policyVersion?: number) =>
|
||||
createLocaleMiddleware({ config, ...(policyVersion ? { policyVersion } : {}) })(
|
||||
request('/en/o-nas', { [CONSENT_COOKIE]: decodeURIComponent(serializeConsent(state, version)), [LOCALE_COOKIE_NAME]: 'pl' }) as never,
|
||||
)
|
||||
|
||||
test('a consent saved under a bumped policy version still lets the locale be saved', () => {
|
||||
expect(switchToEn(3).cookie).toMatchObject({ name: LOCALE_COOKIE_NAME, value: 'en' })
|
||||
})
|
||||
|
||||
test('policyVersion pins the version the proxy requires', () => {
|
||||
expect(switchToEn(3, 4).cookie).toBeUndefined()
|
||||
expect(switchToEn(4, 4).cookie).toMatchObject({ value: 'en' })
|
||||
})
|
||||
})
|
||||
@@ -104,6 +104,16 @@ describe('createMcpRoute', () => {
|
||||
expect((await mcp.GET()).status).toBe(405)
|
||||
})
|
||||
|
||||
test('a null, number or string message gets Invalid Request, not a 500', async () => {
|
||||
for (const body of [null, 42, 'x']) {
|
||||
const res = await rpc(body)
|
||||
expect(res.status).toBe(200)
|
||||
expect(res.body.error.code).toBe(-32600)
|
||||
}
|
||||
const batch = await rpc([null, { id: 2, jsonrpc: '2.0', method: 'ping' }])
|
||||
expect(batch.body.map((m: { error?: { code: number } }) => m.error?.code ?? 'ok')).toEqual([-32600, 'ok'])
|
||||
})
|
||||
|
||||
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' }))
|
||||
|
||||
+12
-3
@@ -45,9 +45,18 @@ describe('ipalKit — config transform', () => {
|
||||
expect(totp).toHaveBeenCalledWith(expect.objectContaining({ forceSetup: true, totp: { issuer: 'Acme' } }))
|
||||
})
|
||||
|
||||
test('enabled: false leaves the config untouched', async () => {
|
||||
const config = base()
|
||||
expect(await ipalKit({ enabled: false, i18n, twoFactor: false })(config)).toBe(config)
|
||||
test('enabled: false keeps the schema (collections, globals) but adds no endpoints, onInit or admin components', async () => {
|
||||
const config = await ipalKit({ access: { authCollection: 'users' }, consentLog: true, enabled: false, i18n, stats: true, twoFactor: false })(base())
|
||||
expect(config.globals?.map((g) => g.slug)).toEqual(expect.arrayContaining(['site-settings', 'site-integrations', 'cookie-settings', 'notifications']))
|
||||
expect(config.collections?.map((c) => c.slug)).toEqual(expect.arrayContaining(['users', 'consent-records', 'stats-visits']))
|
||||
expect(config.endpoints ?? []).toEqual([])
|
||||
expect(config.onInit).toBeUndefined()
|
||||
expect(config.admin?.components).toBeUndefined()
|
||||
})
|
||||
|
||||
test('forms.consentFieldName reaches submitForm through config.custom.ipal', async () => {
|
||||
const config = await ipalKit({ forms: { consentFieldName: 'zgoda' }, i18n, twoFactor: false })(base())
|
||||
expect((config.custom as { ipal?: { consentFieldName?: string } }).ipal?.consentFieldName).toBe('zgoda')
|
||||
})
|
||||
|
||||
test('invalid i18n fails fast', () => {
|
||||
|
||||
+13
-2
@@ -5,6 +5,8 @@ import {
|
||||
clientIp,
|
||||
consumeRateLimit,
|
||||
setRateLimitStore,
|
||||
setUnknownIpFactor,
|
||||
UNKNOWN_IP_FACTOR,
|
||||
} from '../src/modules/shared/rateLimit.js'
|
||||
|
||||
const req = (headers: Record<string, string>) => new Request('http://x/', { headers })
|
||||
@@ -64,8 +66,17 @@ describe('checkRateLimit (in memory)', () => {
|
||||
expect(checkRateLimit({ cost: 4, key: `k-${Math.random()}`, max: 3 })).toBe(false)
|
||||
})
|
||||
|
||||
test('no key → allowed', () => {
|
||||
expect(checkRateLimit({ key: '', max: 0 })).toBe(true)
|
||||
test('setUnknownIpFactor(0) restores the old free pass; the default comes back', () => {
|
||||
setUnknownIpFactor(0)
|
||||
expect(checkRateLimit({ key: '', max: 0, scope: `z-${Math.random()}` })).toBe(true)
|
||||
setUnknownIpFactor(UNKNOWN_IP_FACTOR)
|
||||
expect(checkRateLimit({ key: '', max: 0, scope: `z-${Math.random()}` })).toBe(false)
|
||||
})
|
||||
|
||||
test('no key → one shared bucket with a roomier limit, not a free pass', () => {
|
||||
const scope = `s-${Math.random()}`
|
||||
for (let i = 0; i < 2 * UNKNOWN_IP_FACTOR; i++) {expect(checkRateLimit({ key: '', max: 2, scope })).toBe(true)}
|
||||
expect(checkRateLimit({ key: '', max: 2, scope })).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
import type { BasePayload } from 'payload'
|
||||
|
||||
import { describe, expect, test, vi } from 'vitest'
|
||||
|
||||
import { resolveRedirect } from '../src/modules/content/resolveRedirect.js'
|
||||
|
||||
const config = { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'PL' }] } as const
|
||||
const payloadWith = (doc: object) => ({ find: vi.fn(async () => ({ docs: [doc] })) }) as unknown as BasePayload
|
||||
|
||||
describe('old-slug redirects and drafts', () => {
|
||||
test('a published page redirects from its old slug', async () => {
|
||||
const payload = payloadWith({ slug: 'nowa-oferta', _status: 'published' })
|
||||
expect(await resolveRedirect({ config, locale: 'pl', payload, segments: ['oferta'] })).toBe('/nowa-oferta')
|
||||
})
|
||||
|
||||
test('a never-published draft does not redirect (its new slug stays private)', async () => {
|
||||
const payload = payloadWith({ slug: 'tajny-projekt', _status: 'draft' })
|
||||
expect(await resolveRedirect({ config, locale: 'pl', payload, segments: ['oferta'] })).toBeNull()
|
||||
})
|
||||
|
||||
test('draft: true (preview) redirects drafts too', async () => {
|
||||
const payload = payloadWith({ slug: 'tajny-projekt', _status: 'draft' })
|
||||
expect(await resolveRedirect({ config, draft: true, locale: 'pl', payload, segments: ['oferta'] })).toBe('/tajny-projekt')
|
||||
})
|
||||
|
||||
test('collections without drafts still redirect', async () => {
|
||||
const payload = payloadWith({ slug: 'kontakt-2' })
|
||||
expect(await resolveRedirect({ config, locale: 'pl', payload, segments: ['kontakt'] })).toBe('/kontakt-2')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,70 @@
|
||||
/** Retention purges must never hold a visitor's request. */
|
||||
import type { PayloadRequest } from 'payload'
|
||||
|
||||
import { describe, expect, test, vi } from 'vitest'
|
||||
|
||||
import { buildConsentLogEndpoint } from '../src/modules/consent/consentLog.js'
|
||||
import { buildStatsEndpoint } from '../src/modules/stats/endpoint.js'
|
||||
|
||||
const CHROME = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0 Safari/537.36'
|
||||
|
||||
/** A purge that never finishes — the request must still answer. */
|
||||
function fakePayload() {
|
||||
return {
|
||||
create: vi.fn(async ({ data }: { data: object }) => ({ id: 1, ...data })),
|
||||
db: { deleteMany: vi.fn(() => new Promise<void>(() => {})) },
|
||||
delete: vi.fn(() => new Promise(() => {})),
|
||||
find: vi.fn(async () => ({ docs: [] })),
|
||||
findGlobal: vi.fn(async () => ({})),
|
||||
logger: { error: vi.fn() },
|
||||
}
|
||||
}
|
||||
|
||||
const call = (endpoint: { handler: unknown }, payload: unknown, body: unknown) =>
|
||||
(endpoint.handler as (r: PayloadRequest) => Promise<Response>)(
|
||||
Object.assign(
|
||||
new Request('http://acme.pl/api/x', {
|
||||
body: JSON.stringify(body),
|
||||
headers: { 'content-type': 'application/json', host: 'acme.pl', 'user-agent': CHROME, 'x-real-ip': '203.0.113.9' },
|
||||
method: 'POST',
|
||||
}),
|
||||
{ payload, user: null },
|
||||
) as unknown as PayloadRequest,
|
||||
)
|
||||
|
||||
const settle = <T>(p: Promise<T>) => Promise.race([p, new Promise<'hung'>((r) => setTimeout(() => r('hung'), 200))])
|
||||
|
||||
describe('retention purge runs off the request', () => {
|
||||
test('stats hit answers while the purge is still running; one bulk query, once a day', async () => {
|
||||
const payload = fakePayload()
|
||||
const endpoint = buildStatsEndpoint({ timeZone: 'UTC' })
|
||||
const res = await settle(call(endpoint, payload, { p: '/pl' }))
|
||||
expect(res).not.toBe('hung')
|
||||
expect((res as Response).status).toBe(204)
|
||||
await new Promise((r) => setTimeout(r, 0))
|
||||
expect(payload.db.deleteMany).toHaveBeenCalledOnce()
|
||||
expect(payload.delete).not.toHaveBeenCalled()
|
||||
await call(endpoint, payload, { p: '/pl/oferta' })
|
||||
expect(payload.db.deleteMany).toHaveBeenCalledOnce()
|
||||
})
|
||||
|
||||
test('consent log answers while the purge is still running', async () => {
|
||||
const payload = fakePayload()
|
||||
const body = { id: 'ab'.repeat(16), state: { analytics: true, functional: true, marketing: false, necessary: true }, version: 1 }
|
||||
const res = await settle(call(buildConsentLogEndpoint(), payload, body))
|
||||
expect(res).not.toBe('hung')
|
||||
expect((res as Response).status).toBe(201)
|
||||
await new Promise((r) => setTimeout(r, 0))
|
||||
expect(payload.db.deleteMany).toHaveBeenCalledOnce()
|
||||
})
|
||||
|
||||
test('a failed purge is logged, not thrown at the visitor', async () => {
|
||||
const payload = { ...fakePayload(), db: { deleteMany: vi.fn(async () => { throw new Error('db down') }) } }
|
||||
vi.useFakeTimers({ now: Date.now() + 2 * 86_400_000, toFake: ['Date'] })
|
||||
const res = await call(buildStatsEndpoint({ timeZone: 'UTC' }), payload, { p: '/pl' })
|
||||
vi.useRealTimers()
|
||||
expect(res.status).toBe(204)
|
||||
await new Promise((r) => setTimeout(r, 0))
|
||||
expect(payload.logger.error).toHaveBeenCalledWith(expect.stringContaining('retention purge failed'))
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,34 @@
|
||||
import type { Config, GlobalConfig } from 'payload'
|
||||
|
||||
import { afterEach, describe, expect, test, vi } from 'vitest'
|
||||
|
||||
import { buildGlobalRevalidateHook } from '../src/modules/hooks/buildRevalidateHook.js'
|
||||
import { ipalKit } from '../src/plugin.js'
|
||||
|
||||
const i18n = { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] } as const
|
||||
const run = (g: GlobalConfig | undefined, context: object = {}) =>
|
||||
g?.hooks?.afterChange?.forEach((h) => h({ context, doc: {}, global: g, previousDoc: {}, req: {} } as never))
|
||||
|
||||
describe('globals revalidate the site layout on save', () => {
|
||||
afterEach(() => vi.unstubAllEnvs())
|
||||
|
||||
test('ipalKit({ revalidatePath }) wires every plugin global', async () => {
|
||||
vi.stubEnv('NEXT_RUNTIME', 'nodejs')
|
||||
const revalidatePath = vi.fn()
|
||||
const config = await ipalKit({ i18n, revalidatePath, twoFactor: false })({ collections: [], secret: 'x' } as unknown as Config)
|
||||
for (const slug of ['site-settings', 'site-integrations', 'cookie-settings', 'notifications']) {
|
||||
revalidatePath.mockClear()
|
||||
run(config.globals?.find((g) => g.slug === slug))
|
||||
expect(revalidatePath, slug).toHaveBeenCalledWith('/', 'layout')
|
||||
}
|
||||
})
|
||||
|
||||
test('outside a Next server, or with disableRevalidate, nothing happens', () => {
|
||||
const revalidatePath = vi.fn()
|
||||
const hook = buildGlobalRevalidateHook({ revalidatePath })
|
||||
hook({ context: {}, doc: {} } as never)
|
||||
vi.stubEnv('NEXT_RUNTIME', 'nodejs')
|
||||
hook({ context: { disableRevalidate: true }, doc: {} } as never)
|
||||
expect(revalidatePath).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,51 @@
|
||||
import { describe, expect, test } from 'vitest'
|
||||
|
||||
import { sanitizeRichTextLinks } from '../src/modules/richtext/sanitizeLinks.js'
|
||||
|
||||
const link = (url: string, type = 'link', linkType = 'custom') => ({ type, children: [{ type: 'text', text: 'x' }], fields: { linkType, url } })
|
||||
const doc = (...nodes: object[]) => ({ root: { type: 'root', children: [{ type: 'paragraph', children: nodes }] } })
|
||||
const urls = (d: ReturnType<typeof doc>) =>
|
||||
(d.root.children[0].children as { fields: { url: string } }[]).map((n) => n.fields.url)
|
||||
|
||||
describe('rich text links', () => {
|
||||
test.each(['javascript:alert(1)', ' JaVaScRiPt:alert(1)', 'java\tscript:alert(1)', 'data:text/html,<script>alert(1)</script>', 'vbscript:x'])(
|
||||
'%j is neutralised to #',
|
||||
(bad) => {
|
||||
expect(urls(sanitizeRichTextLinks(doc(link(bad), link(bad, 'autolink'))))).toEqual(['#', '#'])
|
||||
},
|
||||
)
|
||||
|
||||
test('safe links are kept and an untouched document is returned as is', () => {
|
||||
const d = doc(link('https://acme.pl'), link('/pl/kontakt'), link('mailto:[email protected]'), link('tel:+48123'), link('#faq'))
|
||||
expect(sanitizeRichTextLinks(d)).toBe(d)
|
||||
})
|
||||
|
||||
test('only the path to an unsafe link is copied; the input is not mutated', () => {
|
||||
const d = doc(link('https://acme.pl'), link('javascript:alert(1)'))
|
||||
const out = sanitizeRichTextLinks(d)
|
||||
expect(urls(d)).toEqual(['https://acme.pl', 'javascript:alert(1)'])
|
||||
expect(urls(out)).toEqual(['https://acme.pl', '#'])
|
||||
expect(out.root.children[0].children[0]).toBe(d.root.children[0].children[0])
|
||||
})
|
||||
})
|
||||
|
||||
describe('RenderRichText', () => {
|
||||
const state = {
|
||||
root: {
|
||||
type: 'root', children: [{ type: 'paragraph', children: [{ type: 'link', children: [{ type: 'text', detail: 0, format: 0, mode: 'normal', style: '', text: 'klik', version: 1 }], fields: { linkType: 'custom', url: 'data:text/html,<script>alert(1)</script>' }, version: 3 }], version: 1 }],
|
||||
direction: null, format: '', indent: 0, version: 1,
|
||||
},
|
||||
}
|
||||
|
||||
// React 19 already blocks javascript: hrefs; data: URLs it renders as is.
|
||||
test('renders unsafe links as # by default; safeLinks={false} keeps them', async () => {
|
||||
const { renderToStaticMarkup } = await import('react-dom/server')
|
||||
const { createElement } = await import('react')
|
||||
const { RenderRichText } = await import('../src/modules/richtext/RenderRichText.js')
|
||||
const html = renderToStaticMarkup(createElement(RenderRichText, { data: state as never }))
|
||||
expect(html).toContain('href="#"')
|
||||
expect(html).not.toContain('data:')
|
||||
const raw = renderToStaticMarkup(createElement(RenderRichText, { data: state as never, safeLinks: false }))
|
||||
expect(raw).toContain('href="data:text/html')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,118 @@
|
||||
import type { Payload } from 'payload'
|
||||
|
||||
import { sqliteAdapter } from '@payloadcms/db-sqlite'
|
||||
import { lexicalEditor } from '@payloadcms/richtext-lexical'
|
||||
import os from 'node:os'
|
||||
import path from 'node:path'
|
||||
import { buildConfig, getPayload } from 'payload'
|
||||
import { afterAll, beforeAll, describe, expect, test, vi } from 'vitest'
|
||||
|
||||
import { createContentHelpers } from '../src/modules/frontend/createContentHelpers.js'
|
||||
import { ipalKit } from '../src/plugin.js'
|
||||
|
||||
vi.mock('server-only', () => ({}))
|
||||
|
||||
/**
|
||||
* Sitemap, llms.txt and robots against a real (SQLite) Payload: the batched,
|
||||
* `select`-ed, published-only reads must work with the database adapter, and
|
||||
* Site Settings → Search & AI / Under construction must reach the output.
|
||||
*/
|
||||
describe('SEO outputs against a real database', () => {
|
||||
let payload: Payload
|
||||
let configPromise: Parameters<typeof getPayload>[0]['config']
|
||||
const i18n = { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }, { code: 'en', label: 'English' }] } as const
|
||||
const helpers = () => createContentHelpers({ baseUrl: 'https://acme.pl', config: configPromise, i18n })
|
||||
const urls = async () => (await helpers().sitemap()).map((e) => e.url).sort()
|
||||
|
||||
beforeAll(async () => {
|
||||
configPromise = buildConfig({
|
||||
collections: [
|
||||
{ slug: 'users', auth: true, fields: [] },
|
||||
{
|
||||
slug: 'pages',
|
||||
fields: [
|
||||
{ name: 'title', type: 'text' },
|
||||
{ name: 'slug', type: 'text', index: true, localized: true },
|
||||
{ name: 'noindex', type: 'checkbox' },
|
||||
],
|
||||
versions: { drafts: true },
|
||||
},
|
||||
{ slug: 'media', fields: [], upload: { staticDir: path.join(os.tmpdir(), 'ipal-test-media-seo') } },
|
||||
],
|
||||
db: sqliteAdapter({ client: { url: 'file::memory:' }, push: true }),
|
||||
editor: lexicalEditor(),
|
||||
plugins: [ipalKit({ access: { authCollection: 'users' }, i18n, pages: { slug: 'pages' }, twoFactor: false })],
|
||||
secret: 'seo-integration-test-secret',
|
||||
telemetry: false,
|
||||
})
|
||||
payload = await getPayload({ config: configPromise })
|
||||
|
||||
const create = async (slug: Record<string, string>, extra: Record<string, unknown> = {}) => {
|
||||
const doc = await payload.create({
|
||||
collection: 'pages' as never,
|
||||
data: { slug: slug.pl, _status: 'published', title: slug.pl, ...extra } as never,
|
||||
locale: 'pl' as never,
|
||||
})
|
||||
await payload.update({ id: doc.id, collection: 'pages' as never, data: { slug: slug.en } as never, locale: 'en' as never })
|
||||
return doc
|
||||
}
|
||||
const home = await create({ en: 'home', pl: 'start' })
|
||||
await create({ en: 'about', pl: 'o-nas' })
|
||||
await create({ en: 'hidden', pl: 'ukryta' }, { noindex: true })
|
||||
await create({ en: 'draft', pl: 'szkic' }, { _status: 'draft' })
|
||||
await payload.updateGlobal({ slug: 'site-settings' as never, data: { homepage: home.id, siteName: 'Acme' } as never })
|
||||
}, 60_000)
|
||||
|
||||
afterAll(async () => {
|
||||
await payload?.destroy()
|
||||
})
|
||||
|
||||
test('sitemap: published and indexable pages in every language', async () => {
|
||||
expect(await urls()).toEqual(['https://acme.pl/en', 'https://acme.pl/en/about', 'https://acme.pl/pl', 'https://acme.pl/pl/o-nas'])
|
||||
})
|
||||
|
||||
test('project overrides: sitemapEntries has the last word', async () => {
|
||||
const h = createContentHelpers({
|
||||
baseUrl: 'https://acme.pl',
|
||||
config: configPromise,
|
||||
i18n,
|
||||
sitemapEntries: (entries) => [...entries.filter((e) => !e.url.endsWith('/en')), { url: 'https://acme.pl/custom' }],
|
||||
})
|
||||
const list = (await h.sitemap()).map((e) => e.url)
|
||||
expect(list).toContain('https://acme.pl/custom')
|
||||
expect(list).not.toContain('https://acme.pl/en')
|
||||
})
|
||||
|
||||
test('verification codes and AI crawler rules from Site Settings → Search & AI', async () => {
|
||||
await payload.updateGlobal({
|
||||
slug: 'site-settings' as never,
|
||||
data: {
|
||||
aiCrawlers: { policy: 'block-training', rules: [{ access: 'disallow', userAgent: 'PerplexityBot' }] },
|
||||
searchVerification: { google: '<meta name="google-site-verification" content="G-tok_1" />' },
|
||||
} as never,
|
||||
})
|
||||
const stored = (await payload.findGlobal({ slug: 'site-settings' as never })) as { searchVerification?: { google?: string } }
|
||||
expect(stored.searchVerification?.google).toBe('G-tok_1')
|
||||
|
||||
const meta = await helpers().generatePageMetadata('pl', ['o-nas'])
|
||||
expect(meta.verification).toEqual({ google: 'G-tok_1' })
|
||||
|
||||
const rules = (await helpers().getRobots()).rules as { disallow?: string[]; userAgent: string | string[] }[]
|
||||
expect(rules).toContainEqual({ disallow: ['/'], userAgent: ['PerplexityBot'] })
|
||||
const assistants = rules.find((r) => Array.isArray(r.userAgent) && r.userAgent.includes('ClaudeBot'))
|
||||
expect(assistants?.userAgent).not.toContain('PerplexityBot')
|
||||
// the code-only handler ignores the panel
|
||||
expect(helpers().robots().rules).not.toContainEqual({ disallow: ['/'], userAgent: ['PerplexityBot'] })
|
||||
})
|
||||
|
||||
test('under construction: sitemap and llms.txt list only the open pages', async () => {
|
||||
await payload.updateGlobal({ slug: 'site-settings' as never, data: { construction: { enabled: true } } as never, locale: 'pl' as never })
|
||||
expect(await urls()).toEqual(['https://acme.pl/en', 'https://acme.pl/pl'])
|
||||
const llms = await (await helpers().llmsRoute()).text()
|
||||
expect(llms).not.toContain('o-nas')
|
||||
const unfiltered = createContentHelpers({ baseUrl: 'https://acme.pl', config: configPromise, i18n, underConstructionSeo: false })
|
||||
expect(await unfiltered.sitemap()).toHaveLength(4)
|
||||
await payload.updateGlobal({ slug: 'site-settings' as never, data: { construction: { enabled: false } } as never, locale: 'pl' as never })
|
||||
expect(await urls()).toHaveLength(4)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,320 @@
|
||||
import type { Config } from 'payload'
|
||||
|
||||
import { afterEach, describe, expect, test, vi } from 'vitest'
|
||||
|
||||
import type { I18nConfig } from '../src/modules/i18n/types.js'
|
||||
import type { SitemapEntry } from '../src/modules/seo/buildSitemapEntries.js'
|
||||
|
||||
import { buildLlmsTxt } from '../src/modules/seo/buildLlmsTxt.js'
|
||||
import { buildMetadata } from '../src/modules/seo/buildMetadata.js'
|
||||
import { AI_TRAINING_BOTS, buildRobots } from '../src/modules/seo/buildRobots.js'
|
||||
import { buildSitemapEntries } from '../src/modules/seo/buildSitemapEntries.js'
|
||||
import { buildSitemapIndexXml } from '../src/modules/seo/buildSitemapXml.js'
|
||||
import { createPageMetadata } from '../src/modules/seo/createPageMetadata.js'
|
||||
import { createLlmsTxtRoute, createSitemapRouteHandler, DEFAULT_SITEMAP_CACHE_CONTROL } from '../src/modules/seo/routeHandlers.js'
|
||||
import { llmsIntroFrom, normalizeVerificationToken, robotsOptionsFrom, verificationFrom } from '../src/modules/seo/searchSettings.js'
|
||||
import { collectSiteIndex } from '../src/modules/seo/siteIndex.js'
|
||||
import { ipalKit } from '../src/plugin.js'
|
||||
|
||||
const config: I18nConfig = {
|
||||
defaultLocale: 'pl',
|
||||
locales: [
|
||||
{ code: 'pl', label: 'Polski' },
|
||||
{ code: 'en', label: 'English' },
|
||||
],
|
||||
}
|
||||
const single: I18nConfig = { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] }
|
||||
|
||||
type Rule = { allow?: string; disallow?: string[]; userAgent: string | string[] }
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
vi.unstubAllEnvs()
|
||||
})
|
||||
|
||||
describe('search verification (Site Settings → Search & AI)', () => {
|
||||
test('keeps the code from a bare value or a pasted <meta> tag', () => {
|
||||
expect(normalizeVerificationToken(' abc-123_XYZ ')).toBe('abc-123_XYZ')
|
||||
expect(normalizeVerificationToken('<meta name="google-site-verification" content="Tok_9-x" />')).toBe('Tok_9-x')
|
||||
expect(normalizeVerificationToken("<meta name='msvalidate.01' content='ABCDEF0123' />")).toBe('ABCDEF0123')
|
||||
})
|
||||
|
||||
test('drops anything that is not a plain token', () => {
|
||||
expect(normalizeVerificationToken('"><script>alert(1)</script>')).toBe('')
|
||||
expect(normalizeVerificationToken('two words')).toBe('')
|
||||
expect(normalizeVerificationToken(42)).toBe('')
|
||||
})
|
||||
|
||||
test('maps to Next Metadata.verification; empty group → undefined', () => {
|
||||
expect(verificationFrom({ searchVerification: { bing: 'B1', google: 'G1', yandex: null } })).toEqual({
|
||||
google: 'G1',
|
||||
other: { 'msvalidate.01': 'B1' },
|
||||
})
|
||||
expect(verificationFrom({ searchVerification: { bing: '', google: null } })).toBeUndefined()
|
||||
expect(verificationFrom({})).toBeUndefined()
|
||||
})
|
||||
|
||||
test('every page gets the tags from Site Settings', async () => {
|
||||
const pageMetadata = createPageMetadata({
|
||||
baseUrl: 'https://acme.pl',
|
||||
config,
|
||||
loaders: {
|
||||
getSettings: async () => ({ homepage: null, searchVerification: { google: 'G1' }, siteName: 'Acme' }),
|
||||
resolveRoute: async () => null,
|
||||
},
|
||||
})
|
||||
const metadata = await pageMetadata({ slug: ['x'], locale: 'pl', payload: {} as never })
|
||||
expect(metadata.verification).toEqual({ google: 'G1' })
|
||||
})
|
||||
|
||||
test('an unknown route is noindex', async () => {
|
||||
const pageMetadata = createPageMetadata({
|
||||
config,
|
||||
loaders: { getSettings: async () => ({ homepage: null, siteName: 'Acme' }), resolveRoute: async () => null },
|
||||
})
|
||||
const metadata = await pageMetadata({ slug: ['nope'], locale: 'pl', payload: {} as never })
|
||||
expect(metadata.robots?.index).toBe(false)
|
||||
})
|
||||
|
||||
test('no verification → no key in metadata', () => {
|
||||
const m = buildMetadata({ config, locale: 'pl', slugs: { pl: 'a' } })
|
||||
expect('verification' in m).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('AI crawlers (robots)', () => {
|
||||
test('panel policy and exceptions become buildRobots options; "default" changes nothing', () => {
|
||||
expect(robotsOptionsFrom({ aiCrawlers: { policy: 'default', rules: [] } })).toEqual({})
|
||||
expect(
|
||||
robotsOptionsFrom({
|
||||
aiCrawlers: {
|
||||
policy: 'block-training',
|
||||
rules: [
|
||||
{ access: 'allow', userAgent: ' GPTBot ' },
|
||||
{ access: 'disallow', userAgent: 'Evil\nDisallow: /' },
|
||||
{ access: 'disallow', userAgent: 'Bad Bot' },
|
||||
],
|
||||
},
|
||||
}),
|
||||
).toEqual({ aiBotRules: [{ access: 'allow', userAgent: 'GPTBot' }], aiBots: 'block-training' })
|
||||
})
|
||||
|
||||
test('an exception takes the bot out of its policy group', () => {
|
||||
const rules = buildRobots({
|
||||
aiBotRules: [
|
||||
{ access: 'allow', userAgent: 'gptbot' },
|
||||
{ access: 'disallow', userAgent: 'SomeNewBot' },
|
||||
],
|
||||
aiBots: 'block-training',
|
||||
baseUrl: 'https://acme.pl',
|
||||
}).rules as Rule[]
|
||||
const training = rules.find((r) => Array.isArray(r.userAgent) && r.userAgent.includes(AI_TRAINING_BOTS[1]))
|
||||
expect(training?.disallow).toEqual(['/'])
|
||||
expect(training?.userAgent).not.toContain('GPTBot')
|
||||
expect(rules).toContainEqual({ allow: '/', disallow: ['/admin', '/api'], userAgent: ['gptbot'] })
|
||||
expect(rules).toContainEqual({ disallow: ['/'], userAgent: ['SomeNewBot'] })
|
||||
})
|
||||
|
||||
test('exceptions still apply with aiBots: false', () => {
|
||||
const rules = buildRobots({ aiBotRules: [{ access: 'disallow', userAgent: 'Bytespider' }], aiBots: false, baseUrl: 'https://acme.pl' })
|
||||
.rules as Rule[]
|
||||
expect(rules).toHaveLength(2)
|
||||
expect(rules[1]).toEqual({ disallow: ['/'], userAgent: ['Bytespider'] })
|
||||
})
|
||||
|
||||
test('IPAL_NOINDEX still wins over every exception', () => {
|
||||
vi.stubEnv('IPAL_NOINDEX', '1')
|
||||
const r = buildRobots({ aiBotRules: [{ access: 'allow', userAgent: 'GPTBot' }], baseUrl: 'https://acme.pl' })
|
||||
expect(r.rules).toEqual({ disallow: ['/'], userAgent: '*' })
|
||||
})
|
||||
})
|
||||
|
||||
/** Payload stub: `docs` per collection, served in pages of the requested limit. */
|
||||
function fakePayload(docs: Record<string, Record<string, unknown>[]>, opts: { drafts?: string[]; fields?: string[] } = {}) {
|
||||
const find = vi.fn(async ({ collection, limit, page = 1 }: { collection: string; limit: number; page?: number }) => {
|
||||
const all = docs[collection] ?? []
|
||||
const start = (page - 1) * limit
|
||||
return { docs: all.slice(start, start + limit), hasNextPage: start + limit < all.length }
|
||||
})
|
||||
const collections = Object.fromEntries(
|
||||
Object.keys(docs).map((slug) => [
|
||||
slug,
|
||||
{
|
||||
config: {
|
||||
flattenedFields: (opts.fields ?? ['slug', 'title', 'meta']).map((name) => ({ name })),
|
||||
labels: { plural: slug },
|
||||
versions: opts.drafts?.includes(slug) ? { drafts: true } : false,
|
||||
},
|
||||
},
|
||||
]),
|
||||
)
|
||||
return { collections, find, findGlobal: vi.fn(async () => ({})) }
|
||||
}
|
||||
|
||||
describe('buildSitemapEntries at scale', () => {
|
||||
const pages = Array.from({ length: 1203 }, (_, i) => ({
|
||||
id: i,
|
||||
slug: { en: `p${i}`, pl: `s${i}` },
|
||||
_status: 'published',
|
||||
updatedAt: '2026-01-01T00:00:00.000Z',
|
||||
}))
|
||||
|
||||
test('reads in batches, published only, selected fields', async () => {
|
||||
const payload = fakePayload({ pages }, { drafts: ['pages'], fields: ['slug', 'title', 'meta', 'noindex', 'layout'] })
|
||||
const entries = await buildSitemapEntries({ baseUrl: 'https://acme.pl', config, payload: payload as never })
|
||||
expect(entries).toHaveLength(1203 * 2)
|
||||
expect(payload.find).toHaveBeenCalledTimes(3)
|
||||
const args = payload.find.mock.calls[0][0] as unknown as Record<string, unknown>
|
||||
expect(args.limit).toBe(500)
|
||||
expect(args.where).toEqual({ _status: { equals: 'published' } })
|
||||
expect(args.select).toEqual({ slug: true, _status: true, meta: true, noindex: true, updatedAt: true })
|
||||
})
|
||||
|
||||
test('custom images → whole documents (no select)', async () => {
|
||||
const payload = fakePayload({ pages: pages.slice(0, 2) })
|
||||
await buildSitemapEntries({ baseUrl: 'https://acme.pl', config, images: () => [], payload: payload as never })
|
||||
const args = payload.find.mock.calls[0][0] as unknown as Record<string, unknown>
|
||||
expect(args.select).toBeUndefined()
|
||||
expect(args.where).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
describe('sitemap route: split, cache, errors', () => {
|
||||
const make = (n: number): SitemapEntry[] =>
|
||||
Array.from({ length: n }, (_, i) => ({ lastModified: `2026-01-${String((i % 28) + 1).padStart(2, '0')}T00:00:00.000Z`, url: `https://acme.pl/p${i}` }))
|
||||
|
||||
test('small site: one urlset with the default Cache-Control', async () => {
|
||||
const res = await createSitemapRouteHandler(async () => make(3), { style: false })(new Request('https://acme.pl/sitemap.xml'))
|
||||
expect(res.headers.get('cache-control')).toBe(DEFAULT_SITEMAP_CACHE_CONTROL)
|
||||
const xml = await res.text()
|
||||
expect(xml).toContain('<urlset')
|
||||
expect(xml.match(/<url>/g)).toHaveLength(3)
|
||||
})
|
||||
|
||||
test('over maxUrls: an index, parts by ?part=N, unknown part 404', async () => {
|
||||
const handler = createSitemapRouteHandler(async () => make(5), { maxUrls: 2, style: false })
|
||||
const index = await (await handler(new Request('https://acme.pl/sitemap.xml'))).text()
|
||||
expect(index).toContain('<sitemapindex')
|
||||
expect(index.match(/<sitemap>/g)).toHaveLength(3)
|
||||
expect(index).toContain('<loc>https://acme.pl/sitemap.xml?part=3</loc>')
|
||||
expect(index).toContain('<lastmod>2026-01-02T00:00:00.000Z</lastmod>')
|
||||
|
||||
const part = await (await handler(new Request('https://acme.pl/sitemap.xml?part=3'))).text()
|
||||
expect(part.match(/<url>/g)).toHaveLength(1)
|
||||
expect(part).toContain('https://acme.pl/p4')
|
||||
expect((await handler(new Request('https://acme.pl/sitemap.xml?part=4'))).status).toBe(404)
|
||||
expect((await handler(new Request('https://acme.pl/sitemap.xml?part=x'))).status).toBe(404)
|
||||
})
|
||||
|
||||
test('entries are reused within memoSeconds, rebuilt when 0', async () => {
|
||||
const source = vi.fn(async () => make(1))
|
||||
const memo = createSitemapRouteHandler(source, { style: false })
|
||||
await memo(new Request('https://acme.pl/sitemap.xml'))
|
||||
await memo(new Request('https://acme.pl/sitemap.xml'))
|
||||
expect(source).toHaveBeenCalledTimes(1)
|
||||
|
||||
const fresh = vi.fn(async () => make(1))
|
||||
const noMemo = createSitemapRouteHandler(fresh, { memoSeconds: 0, style: false })
|
||||
await noMemo(new Request('https://acme.pl/sitemap.xml'))
|
||||
await noMemo(new Request('https://acme.pl/sitemap.xml'))
|
||||
expect(fresh).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
test('runtime error → 503 Retry-After; empty → not cached and not reused', async () => {
|
||||
vi.spyOn(console, 'warn').mockImplementation(() => {})
|
||||
const failing = await createSitemapRouteHandler(async () => {
|
||||
throw new Error('db down')
|
||||
})(new Request('https://acme.pl/sitemap.xml'))
|
||||
expect(failing.status).toBe(503)
|
||||
expect(failing.headers.get('retry-after')).toBe('300')
|
||||
|
||||
const empty = vi.fn(async () => [] as SitemapEntry[])
|
||||
const handler = createSitemapRouteHandler(empty, { style: false })
|
||||
const res = await handler(new Request('https://acme.pl/sitemap.xml'))
|
||||
expect(res.headers.get('cache-control')).toBe('no-store')
|
||||
await handler(new Request('https://acme.pl/sitemap.xml'))
|
||||
expect(empty).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
test('during next build an error still gives an empty urlset', async () => {
|
||||
vi.spyOn(console, 'warn').mockImplementation(() => {})
|
||||
vi.stubEnv('NEXT_PHASE', 'phase-production-build')
|
||||
const res = await createSitemapRouteHandler(async () => {
|
||||
throw new Error('no db')
|
||||
})(new Request('https://acme.pl/sitemap.xml'))
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.text()).toContain('<urlset')
|
||||
})
|
||||
|
||||
test('buildSitemapIndexXml escapes', () => {
|
||||
expect(buildSitemapIndexXml([{ url: 'https://acme.pl/s.xml?a=1&b=2' }])).toContain('?a=1&b=2')
|
||||
})
|
||||
})
|
||||
|
||||
describe('collectSiteIndex and llms.txt', () => {
|
||||
const pages = Array.from({ length: 1205 }, (_, i) => ({ id: i, slug: `p${i}`, title: `Page ${i}` }))
|
||||
|
||||
test('no silent 1000 cap; limit still caps', async () => {
|
||||
const payload = fakePayload({ pages })
|
||||
expect(await collectSiteIndex({ config: single, payload: payload as never })).toHaveLength(1205)
|
||||
expect(await collectSiteIndex({ config: single, limit: 10, payload: payload as never })).toHaveLength(10)
|
||||
})
|
||||
|
||||
test('include filters by path', async () => {
|
||||
const payload = fakePayload({ pages: pages.slice(0, 5) })
|
||||
const index = await collectSiteIndex({ config: single, include: (p) => p === '/p2', payload: payload as never })
|
||||
expect(index.map((e) => e.path)).toEqual(['/p2'])
|
||||
})
|
||||
|
||||
test('llms.txt carries the editor note under the summary', async () => {
|
||||
const payload = fakePayload({ pages: pages.slice(0, 1) })
|
||||
payload.findGlobal.mockResolvedValue({ llmsIntro: 'Acme repairs boilers in Kraków since 1998.', siteDescription: 'Boilers', siteName: 'Acme' })
|
||||
const body = await buildLlmsTxt({ baseUrl: 'https://acme.pl', config: single, payload: payload as never })
|
||||
expect(body.startsWith('# Acme\n\n> Boilers\n\nAcme repairs boilers in Kraków since 1998.\n')).toBe(true)
|
||||
expect(llmsIntroFrom({ llmsIntro: ' ' })).toBe('')
|
||||
})
|
||||
|
||||
test('llms route: only included paths, cached for a CDN', async () => {
|
||||
const payload = fakePayload({ pages: pages.slice(0, 3) })
|
||||
const res = await createLlmsTxtRoute({
|
||||
baseUrl: 'https://acme.pl',
|
||||
config: single,
|
||||
getCachedPayload: async () => payload as never,
|
||||
getIncludedPaths: async () => ['/p1/'],
|
||||
})()
|
||||
const body = await res.text()
|
||||
expect(body).toContain('(https://acme.pl/p1)')
|
||||
expect(body).not.toContain('/p0')
|
||||
expect(res.headers.get('cache-control')).toBe(DEFAULT_SITEMAP_CACHE_CONTROL)
|
||||
})
|
||||
})
|
||||
|
||||
describe('plugin: Search & AI tab', () => {
|
||||
const base = (): Config => ({ collections: [{ slug: 'users', auth: true, fields: [] }], secret: 'test' }) as unknown as Config
|
||||
const tabs = (c: Config) => {
|
||||
const settings = c.globals?.find((g) => g.slug === 'site-settings')
|
||||
const field = settings?.fields[0] as { tabs: { label: string }[] }
|
||||
return field.tabs.map((t) => t.label)
|
||||
}
|
||||
|
||||
test('on by default, off with seo.searchSettings: false', async () => {
|
||||
const on = await ipalKit({ access: { authCollection: 'users' }, i18n: config, twoFactor: false })(base())
|
||||
expect(tabs(on)).toContain('Search & AI')
|
||||
const off = await ipalKit({
|
||||
access: { authCollection: 'users' },
|
||||
i18n: config,
|
||||
seo: { collections: [], searchSettings: false },
|
||||
twoFactor: false,
|
||||
})(base())
|
||||
expect(tabs(off)).not.toContain('Search & AI')
|
||||
const custom = await ipalKit({
|
||||
access: { authCollection: 'users' },
|
||||
i18n: config,
|
||||
seo: { collections: [], searchSettings: (fields) => fields.filter((f) => 'name' in f && f.name !== 'llmsIntro') },
|
||||
twoFactor: false,
|
||||
})(base())
|
||||
const settings = custom.globals?.find((g) => g.slug === 'site-settings')
|
||||
const tab = (settings?.fields[0] as { tabs: { fields: { name?: string }[]; label: string }[] }).tabs.find((t) => t.label === 'Search & AI')
|
||||
expect(tab?.fields.map((f) => f.name)).toEqual(['searchVerification', 'aiCrawlers'])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,92 @@
|
||||
/** Site Settings must stay shallow on every request; the rendered page is re-fetched at page depth. */
|
||||
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 } from 'vitest'
|
||||
|
||||
import { resolveRoute } from '../src/modules/content/resolveRoute.js'
|
||||
import { createContentHelpers } from '../src/modules/frontend/createContentHelpers.js'
|
||||
import { ipalKit } from '../src/plugin.js'
|
||||
|
||||
let payload: Payload
|
||||
let configPromise: ReturnType<typeof buildConfig>
|
||||
let mediaId: number | string
|
||||
|
||||
beforeAll(async () => {
|
||||
configPromise = buildConfig({
|
||||
collections: [
|
||||
{
|
||||
slug: 'pages',
|
||||
fields: [
|
||||
{ name: 'title', type: 'text' },
|
||||
{ name: 'slug', type: 'text', localized: true },
|
||||
{ name: 'hero', type: 'upload', relationTo: 'media' },
|
||||
],
|
||||
},
|
||||
{ slug: 'posts', fields: [{ name: 'title', type: 'text' }, { name: 'slug', type: 'text', localized: true }] },
|
||||
{ slug: 'media', fields: [{ name: 'alt', type: 'text' }], upload: { staticDir: path.join(os.tmpdir(), 'ipal-test-media') } },
|
||||
],
|
||||
db: sqliteAdapter({ client: { url: 'file::memory:' }, push: true }),
|
||||
editor: lexicalEditor(),
|
||||
plugins: [
|
||||
ipalKit({
|
||||
access: { authCollection: 'users' },
|
||||
content: { collections: [{ slug: 'posts' }] },
|
||||
i18n: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'Polski' }] },
|
||||
pages: { slug: 'pages' },
|
||||
// a project field, e.g. a menu linking pages — not capped by maxDepth
|
||||
siteSettingsFields: [{ name: 'featured', type: 'relationship', relationTo: 'pages' }],
|
||||
twoFactor: false,
|
||||
}),
|
||||
],
|
||||
secret: 'depth-test',
|
||||
telemetry: false,
|
||||
})
|
||||
payload = await getPayload({ config: configPromise })
|
||||
const png = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==', 'base64')
|
||||
const media = await payload.create({
|
||||
collection: 'media' as never,
|
||||
data: { alt: 'hero' } as never,
|
||||
file: { name: 'hero.png', data: png, mimetype: 'image/png', size: png.length },
|
||||
})
|
||||
mediaId = media.id
|
||||
const home = await payload.create({ collection: 'pages' as never, data: { slug: 'home', hero: mediaId, title: 'Home' } as never })
|
||||
const blog = await payload.create({ collection: 'pages' as never, data: { slug: 'blog', hero: mediaId, title: 'Blog' } as never })
|
||||
await payload.updateGlobal({ slug: 'site-settings' as never, data: { featured: home.id, homepage: home.id, postsArchive: blog.id, siteName: 'Acme' } as never })
|
||||
}, 60_000)
|
||||
|
||||
afterAll(async () => {
|
||||
await payload?.destroy()
|
||||
})
|
||||
|
||||
describe('Site Settings depth', () => {
|
||||
test('getSettings populates related pages one level only (their media stays an id)', async () => {
|
||||
const { getSettings } = createContentHelpers({ config: configPromise })
|
||||
const settings = (await getSettings('pl')) as { featured: { hero: unknown; slug: string } }
|
||||
expect(settings.featured.slug).toBe('home')
|
||||
expect(settings.featured.hero).toBe(mediaId)
|
||||
})
|
||||
|
||||
test('the archive page is re-fetched at page depth, so its blocks and media render', async () => {
|
||||
const route = await resolveRoute({
|
||||
content: { collections: [{ slug: 'posts' }] },
|
||||
locale: 'pl',
|
||||
payload,
|
||||
segments: ['blog'],
|
||||
})
|
||||
expect(route?.type).toBe('archive')
|
||||
expect((route?.doc as { hero: { alt?: string } }).hero).toMatchObject({ alt: 'hero' })
|
||||
})
|
||||
})
|
||||
|
||||
describe('settingsDepth option', () => {
|
||||
test('a project that needs deeper settings can raise the depth', async () => {
|
||||
const { getSettings } = createContentHelpers({ config: configPromise, settingsDepth: 2 })
|
||||
const settings = (await getSettings('pl')) as { featured: { hero: { alt?: string } } }
|
||||
expect(settings.featured.hero).toMatchObject({ alt: 'hero' })
|
||||
})
|
||||
})
|
||||
@@ -1,6 +1,7 @@
|
||||
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest'
|
||||
|
||||
import { submitForm } from '../src/modules/forms/submitForm.js'
|
||||
import { UNKNOWN_IP_FACTOR } from '../src/modules/shared/rateLimit.js'
|
||||
import { fakePayload } from './helpers.js'
|
||||
|
||||
vi.mock('server-only', () => ({}))
|
||||
@@ -82,6 +83,19 @@ describe('submitForm — Turnstile', () => {
|
||||
expect(create).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
test('turnstileHostnames: a token solved on another host is rejected', async () => {
|
||||
mockSiteverify({ hostname: 'evil.example', success: true })
|
||||
const { create, payload } = fakePayload({ forms, integrations: keys })
|
||||
const base = { data, formId: 'contact', payload, turnstileToken: 'tok' }
|
||||
expect(await submitForm({ ...base, ip: nextIp(), turnstileHostnames: ['www.firma.pl'] })).toEqual({
|
||||
reason: 'turnstile',
|
||||
success: false,
|
||||
})
|
||||
expect(create).not.toHaveBeenCalled()
|
||||
mockSiteverify({ hostname: 'WWW.firma.pl', success: true })
|
||||
expect((await submitForm({ ...base, ip: nextIp(), turnstileHostnames: ['www.firma.pl'] })).success).toBe(true)
|
||||
})
|
||||
|
||||
test('configured + Cloudflare rejects OUR secret → allowed by default, refused with reject', async () => {
|
||||
mockSiteverify({ 'error-codes': ['invalid-input-secret'], success: false })
|
||||
const { payload } = fakePayload({ forms, integrations: keys })
|
||||
@@ -97,6 +111,15 @@ describe('submitForm — Turnstile', () => {
|
||||
describe('submitForm — other gates', () => {
|
||||
afterEach(() => vi.restoreAllMocks())
|
||||
|
||||
test('no client IP is not a free pass — it shares one capped bucket', async () => {
|
||||
const { payload } = fakePayload({ forms })
|
||||
let accepted = 0
|
||||
for (let i = 0; i < 50; i++) {
|
||||
if ((await submitForm({ data, formId: 'contact', maxPerMinute: 1, payload })).success) {accepted++}
|
||||
}
|
||||
expect(accepted).toBe(UNKNOWN_IP_FACTOR)
|
||||
})
|
||||
|
||||
test('rate limit per IP', async () => {
|
||||
const { payload } = fakePayload({ forms })
|
||||
const ip = nextIp()
|
||||
@@ -109,6 +132,18 @@ describe('submitForm — other gates', () => {
|
||||
})
|
||||
})
|
||||
|
||||
test('ipalKit forms.consentFieldName (payload.config.custom) names the consent field', async () => {
|
||||
const { payload } = fakePayload({ forms: { f: { fields: [{ name: 'zgoda', blockType: 'checkbox' }] } } })
|
||||
Object.assign(payload, { config: { custom: { ipal: { consentFieldName: 'zgoda' } } } })
|
||||
expect(await submitForm({ data: { zgoda: false }, formId: 'f', ip: nextIp(), payload })).toEqual({
|
||||
field: 'zgoda',
|
||||
reason: 'consent',
|
||||
success: false,
|
||||
})
|
||||
// an explicit argument still wins
|
||||
expect((await submitForm({ consentFieldName: 'other', data: { zgoda: false }, formId: 'f', ip: nextIp(), payload })).success).toBe(true)
|
||||
})
|
||||
|
||||
test('consent must be checked', async () => {
|
||||
const { payload } = fakePayload({ forms })
|
||||
expect(await submitForm({ data: { ...data, consent: false }, formId: 'contact', ip: nextIp(), payload })).toEqual({
|
||||
|
||||
Reference in New Issue
Block a user