diff --git a/CLAUDE.md b/CLAUDE.md index 3e76769..d4d50e8 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -2,3 +2,20 @@ This project uses the Payload CMS skill at `.claude/skills/payload/`. Start with `.claude/skills/payload/SKILL.md` for a quick reference, then see `.claude/skills/payload/reference/` for detailed docs. + +## Main rule: the plugin helps projects, never limits them + +ipal-kit is a plugin. Every change must leave the consuming project free to adapt it. + +- Every module and feature can be turned off on its own. Turning one off never takes away anything the project still needs. +- Every default can be overridden: access rules, fields, hooks, labels, routes, collections and globals. The project's own config is merged with the plugin's and wins. +- Secure defaults are welcome. They come with an option to loosen or extend them, never as a hard lock. +- Export the building blocks (helpers, builders, hooks), not only finished features. +- Never force a dependency, route, UI or data shape where an option or an exported piece would do. + +## Rule: an agent that adds the plugin gets the complete guide + +When an agent adds ipal-kit to a project, `docs/agent/AGENT.md` and the `ipal-*` skills (installed by `ipal-skills`) must tell it how to set up and use every function the plugin supports. + +- Every export, option, env var, route, middleware, layout component, admin import-map entry and hook a project must wire is documented, with steps and a way to verify it. +- A change that adds or alters a feature updates the agent guide and the matching skill in the same change. diff --git a/docs/access.md b/docs/access.md index 1a751cf..70f9b14 100644 --- a/docs/access.md +++ b/docs/access.md @@ -1,45 +1,87 @@ # access -Kontrola dostępu oparta na rolach: hierarchia **admin > editor > user**. -Plugin wstrzykuje sztywne pole `roles` do klienckiej kolekcji auth i dostarcza -predykaty oraz gotowe funkcje dostępu (collection-level i field-level). +Role-based access control: hierarchy **admin > editor > user**. +The plugin injects a fixed `roles` field into the client's auth collection and provides +predicates and ready access functions (collection-level and field-level). ## Config (payload.config.ts) ```ts ipalKit({ access: { - authCollection: 'users', // slug Twojej kolekcji auth - // defaultRole: 'user', // rola nowych użytkowników, domyślnie 'user' + authCollection: 'users', // slug of your auth collection (required) + // defaultRole: 'user', // role of new accounts + // firstUserAdmin: true, // the account from "Create first user" → admin + // authAccess: { … }, // access of the injected auth collection (your keys win) + }, + // globalOverrides: { … }, // access / admin / hooks / fields of the plugin's globals +}) +``` + +| Option | Default | What it does | +|---|---|---| +| `access.authCollection` | — (required) | the auth collection that gets the `roles` field | +| `access.defaultRole` | `'user'` | role of a new account when an admin did not set one | +| `access.firstUserAdmin` | `true` | the account from the "Create first user" screen (`…/first-register` on an empty collection) gets `['admin']`, even when the form picked `user`; `false` = it gets what was submitted | +| `access.authAccess` | see the table below | `access` of the **injected** auth collection, merged over the default (your keys win) | +| `globalOverrides` | — | changes to the plugin's globals: an object merges `access` / `admin` key by key (your keys win) and appends `hooks` (yours run after the plugin's), other keys (label, fields, …) replace; a function `(global) => global` takes over the whole global | + +The `roles` field (select hasMany, required, `saveToJWT`): readable without limits; only an admin +can set and change it — also on account creation, so an open sign-up cannot +push `roles: ['admin']` through. The first-user screen and the Local API (seed) run with +`overrideAccess`. An account without roles meets no threshold (not even `'user'`); `authenticated` +only checks that someone is logged in. + +**Auth collection when the project has none.** The plugin adds a minimal collection (`auth: true`, +`admin.useAsTitle: 'email'`) with the slug `access.authCollection` (or `twoFactor.collectionSlug`, +`admin.user`, `'users'`). The project's own collection with that slug always wins whole. + +## What the plugin locks down by itself + +| Resource | Read | Write | How to change | +|---|---|---|---| +| auth collection **injected** by the plugin, with roles | admin: everyone; others: only themselves | `create` / `delete` / `unlock`: admin; `update`: admin or self | `access.authAccess`, or your own collection | +| Site Settings, Cookie Settings, Notifications | public | `editor+` | `globalOverrides` | +| Site Integrations | admin | admin | `globalOverrides` | +| Forms | public (Emails tab only `editor+`) | `editor+` | `forms.formOverrides.access`, the Emails field in `formOverrides.fields` | +| Form submissions | `editor+` | REST `create`: logged-in users; `delete`: admin | `forms.formSubmissionOverrides.access` | + +```ts +import { authenticated } from '@intecion/ipal-kit' +ipalKit({ + access: { authCollection: 'users', authAccess: { read: authenticated } }, // editors see the account list + globalOverrides: { + notifications: { access: { update: authenticated } }, // any logged-in account edits the texts + 'site-settings': (g) => ({ ...g, admin: { ...g.admin, group: 'Configuration' } }), }, }) ``` -Wstrzykuje pole `roles` (select hasMany, `saveToJWT`, tylko admin może -nadawać i zmieniać role — także przy tworzeniu konta, więc otwarta rejestracja nie -przepuści `roles: ['admin']`; nie-admin dostaje `defaultRole`) do wskazanej kolekcji. -Ekran pierwszego użytkownika i Local API (seed) działają z `overrideAccess`, więc -pierwszego admina nadal da się utworzyć. Kolekcja należy do Ciebie -(create-payload-app) — plugin tylko dokłada pole. +The project's own auth collection keeps its own `access` — the plugin only adds the +`roles` field. Give it at least `update: adminOrSelf`, `delete: adminOnly`, `create: adminOnly`, +`unlock: adminOnly`: Payload's default lets any logged-in account change the email and password +of another account and unlock any account. A collection injected **without** `access` (no roles) +keeps Payload's default rules — without roles all accounts are equal. -> Po dodaniu: zadbaj, by seed / pierwszy user miał `roles: ['admin']`, inaczej -> stracisz dostęp do zasobów admin-only (np. SiteIntegrations). +> **Without `access` there is no `roles` field**, so `isAdmin` always returns `false`: the Site +> Integrations global and the `/api/ipal/test-email` endpoint then work only through the Local API +> (`overrideAccess`). The seed / first user must have `roles: ['admin']`. -## Predykaty (front / hooki / access) +## Predicates (front end / hooks / access) ```ts import { isAdmin, isEditor, hasMinimumRole } from '@intecion/ipal-kit' isAdmin(user) // admin? -isEditor(user) // editor lub admin (hierarchia) -hasMinimumRole(user, 'editor') // co najmniej editor +isEditor(user) // editor or admin (hierarchy) +hasMinimumRole(user, 'editor') // at least editor ``` -Przyjmują luźno typowanego usera (jak `req.user`), czytają `roles` defensywnie. +They take a loosely typed user (like `req.user`) and read `roles` defensively. -## Gotowe funkcje dostępu +## Ready access functions -### Collection-level (zwracają boolean | Where) +### Collection-level (return boolean | Where) ```ts import { adminOnly, adminOrEditor, adminOrSelf, requireRole, authenticated } from '@intecion/ipal-kit' @@ -55,14 +97,14 @@ export const Articles = { // ... } -// Users: każdy widzi siebie, admin widzi wszystkich +// Users: everyone sees themselves, an admin sees everyone access: { read: adminOrSelf } -// dowolny minimalny próg +// any minimum threshold access: { update: requireRole('editor') } ``` -### Field-level (zwracają boolean) +### Field-level (return boolean) ```ts import { adminOnlyField, adminOrEditorField, requireRoleField } from '@intecion/ipal-kit' @@ -74,9 +116,33 @@ import { adminOnlyField, adminOrEditorField, requireRoleField } from '@intecion/ } ``` -## Hierarchia +## Hierarchy ```ts import { ROLE_HIERARCHY } from '@intecion/ipal-kit' -// ['user', 'editor', 'admin'] — wyższa rola spełnia wymóg niższej +// ['user', 'editor', 'admin'] — a higher role meets a lower role's requirement ``` + +## Building blocks: buildRolesField, injectRoles, applyGlobalOverrides + +```ts +import { applyGlobalOverrides, buildRolesField, injectRoles } from '@intecion/ipal-kit' + +buildRolesField('user', { firstUserAdmin: true }) // just the roles field — for your own collection +injectRoles(config, { authCollection: 'members' }) // add the field to a collection in a finished config +applyGlobalOverrides(globals, { notifications: { … } }) // the same logic as the globalOverrides option +``` + +Types: `AccessOption`, `Role`, `GlobalOverride`, `GlobalOverrides`, `IpalGlobalSlug`. + +## Turn off, override, extend + +- **Turn off:** leave out `access` — no `roles` field, the auth collection keeps Payload's rules + (or yours). `access.firstUserAdmin: false` stops giving admin to the first account. +- **Override:** `access.authAccess` (injected collection), your own auth collection (wins whole), + `globalOverrides` (globals), `forms.formOverrides` / `formSubmissionOverrides` (forms), + `defaultRole`. The role hierarchy (`ROLE_HIERARCHY`) is fixed. +- **Extend:** `requireRole` / `requireRoleField`, predicates, `buildRolesField`, `injectRoles`, + `applyGlobalOverrides` in your own collections and globals. +- **Check:** log in with a `user` account → `PATCH /api/globals/site-settings` = 403, + `DELETE /api/users/` = 403; the account from "Create first user" has the `admin` role. diff --git a/docs/agent/AGENT.md b/docs/agent/AGENT.md index f7d8f3d..4e9eb5b 100644 --- a/docs/agent/AGENT.md +++ b/docs/agent/AGENT.md @@ -96,16 +96,17 @@ site), **P** = a test in the panel. Full code: PROGRAMISTA.md §2. |---|---|---|---|---| | 1 | i18n + routing | `src/proxy.ts`, `[locale]/[[...slug]]/page.tsx` = `createPageRoute(content, {…})` + a literal `revalidate`, `not-found.tsx` = `createNotFoundPage(content, { load })` + `notFoundView.ts` (`renderNotFoundView`) | `createProxy`, `createContentHelpers`, `createPageRoute`, `createNotFoundPage` (`/rsc`) | A, S | | 2 | **SEO** — meta | `generateMetadata` in every page route; favicon and OG from Site Settings; `htmlLimitedBots` in `next.config.ts`; SEO tab + `buildNoindexField` in Pages | `generatePageMetadata`, `buildIconsMetadata`, `buildNoindexField` | A, S | -| 3 | **SEO** — maps | `src/app/sitemap.xml/route.ts`, `src/app/robots.ts`, `src/app/manifest.ts` — each is a re-export from `lib/content` (`sitemapRoute`, `robots`, `manifest`) + `force-dynamic` except robots | `sitemapRoute`, `robots`, `manifest` | A, S | +| 3 | **SEO** — maps | `src/app/sitemap.xml/route.ts` (`export { sitemapRoute as GET }` + `force-dynamic`), `src/app/robots.ts` (`export { getRobots as default }` + `force-dynamic` — AI bots from the panel), `src/app/manifest.ts` — re-exports from `lib/content` | `sitemapRoute`, `getRobots` (or `robots` without the panel), `manifest` | A, S | +| 3a | **Search Console / Bing** | recommended: **domain verification via DNS** (TXT record, deployment.md §6) — the plugin does nothing, the verification fields stay empty; only for URL-prefix verification: code in **Site Settings → Search & AI** (Google, Bing, Yandex), `generatePageMetadata` adds the `` itself; sitemap `https:///sitemap.xml` submitted in GSC and Bing | panel (optional), `verificationFrom` | P | | 4 | **SEO** — structured data | layout: `` gives `WebSite` + `Organization` (`sameAs`) from Site Settings; local business → `createContentHelpers({ siteJsonLd })` with `buildLocalBusinessJsonLd` (`type`, hours → `formatOpeningHours`); navigation: ``; page: `createPageRoute` adds `getPageJsonLd` (WebPage/BlogPosting, breadcrumbs, FAQ — `pageJsonLd: { faq }`) | `getSiteShell`, `SiteProviders`, `build*JsonLd`, `getPageJsonLd` | A, S | | 5 | **GEO** — llms | `src/app/llms.txt/route.ts` (`llmsRoute`) and `src/app/llms-full.txt/route.ts` (`llmsFullRoute`) from `lib/content`; the `buildSummaryField()` field in Pages, `summaryField: 'aiSummary'` in `createContentHelpers` | `llmsRoute`, `llmsFullRoute`, `buildSummaryField` | A, S | | 6 | **GEO** — Markdown | `src/app/md/[locale]/[[...slug]]/route.ts` (single-language: `src/app/md/[[...slug]]/route.ts`) = `export { markdownRoute as GET } from '@/lib/content'`; `createContentHelpers({ markdownAlternate: true })` (link in ``); `createProxy(…, { NextResponse, markdown: true })` (without it `/md/…` gets redirected to a language) | `markdownRoute`, `markdownAlternate`, `createProxy({ markdown })` | A, S | | 7 | **GEO** — MCP | `src/app/api/mcp/route.ts` = `export { mcpGET as GET, mcpPOST as POST } from '@/lib/content'` (public — AI browses the site: `get_site_info`, `list_pages`, `search_content`, `get_page`); name: `createContentHelpers({ mcp: { serverName } })` | `mcpGET`, `mcpPOST` | A, S | -| 8 | **GEO** — AI bots + IndexNow | robots **lets in** AI bots (default `aiBots: 'allow'`; block only on a client decision); `ipalKit({ indexNow: true })` + `src/app/indexnow-key.txt/route.ts` (`indexNowKeyRoute`; publishing → Bing/ChatGPT Search within minutes) | `buildRobots`, `indexNowKeyRoute` | A, S | +| 8 | **GEO** — AI bots + IndexNow | robots **lets in** AI bots (default `aiBots: 'allow'`; block only on a client decision); AI bot policy and per-bot exceptions — Site Settings → Search & AI → AI crawlers (works only with `getRobots`); `ipalKit({ indexNow: true })` + `src/app/indexnow-key.txt/route.ts` (`indexNowKeyRoute`; publishing → Bing/ChatGPT Search within minutes; IndexNow sends nothing with `IPAL_NOINDEX=1`) | `buildRobots`, `getRobots`, `indexNowKeyRoute` | A, S | | 9 | **Media / R2 / speed** | `Media` with `focalPoint`, `normalizeFilenameHook`, `buildOptimizeUploadHook`, `buildMediaPlaceholderHook` + field; **always** `buildR2Storage(['media'], { s3Storage })` + `@payloadcms/storage-s3`; `R2_*` in `.env.example`; ``; `images: buildImagesConfig()` and `buildUploadSecurityHeaders()` in `next.config.ts`; the project's `` via `mediaImageProps`/`videoProps` (§6.11b) | `buildR2Storage`, `mediaImageProps`, `videoProps`, `buildImagesConfig` | A, S | | 10 | **Forms** | every form from a **seed** (`scripts/seed-form-*.ts`: fields, confirmation, mail to the company **and** confirmation to the customer, every language); a block with `` + `formClasses.ts` (look, once); `actions.ts` = `createSubmitAction({ getCachedPayload, headers })`; `forms: {…}` in `ipalKit`; `email: mailAdapter()` | `RenderForm` (`/rsc`), `createSubmitAction`, `mailAdapter` | A, P | | 11 | **Turnstile** | `` in `[locale]/layout.tsx` (wires `TurnstileProvider` with the key from the panel); `RenderForm` renders the widget; keys in Site Integrations | `SiteProviders`, `getTurnstileConfig`, `TurnstileProvider` | A, P | -| 12 | Consent + analytics | `ipalKit({ consentLog: true })` (without it the `/api/ipal/consent` endpoint does not exist) + `}>` (ConsentProvider, banner, CookieButton, Analytics in the right order); settings window mode (`settings`: `inline` / `modal` / `detailed`) per the design, brief is silent → `detailed`, the decision goes to "Project decisions"; tool IDs in the panel; the cookie list from a scan (cookie-scan → import) — feeds `` on the policy page **and** the lists in the `detailed` window; Cookie Settings → Detail labels in every language | consent.md, analytics.md | A, `ipal-consent-check` | +| 12 | Consent + analytics | Consent Mode: `'advanced'` (default — the Google tag loads at once with every signal `denied`) or `'basic'` (`` — no request to Google before consent; a client who wants zero requests), the choice goes to "Project decisions"; `ipalKit({ consentLog: true })` (without it the `/api/ipal/consent` endpoint does not exist) + `}>` (ConsentProvider, banner, CookieButton, Analytics in the right order); settings window mode (`settings`: `inline` / `modal` / `detailed`) per the design, brief is silent → `detailed`, the decision goes to "Project decisions"; tool IDs in the panel; the cookie list from a scan (cookie-scan → import) — feeds `` on the policy page **and** the lists in the `detailed` window; Cookie Settings → Detail labels in every language | consent.md, analytics.md | A, `ipal-consent-check` | | 13 | Security | `buildSecurityHeaders` in `next.config.ts`; `twoFactor: { issuer, plugin: payloadTotp }`; CSP `report-only` → `enforce`; `IPAL_IP_HEADER` in production | security.md, forms.md | A | | 14 | Operations | `src/app/api/health/route.ts` (`healthRoute`); `src/instrumentation.ts` with `assertEnv(ipalEnvRules({ storage: true, ipHeader: true }))`; staging with `IPAL_NOINDEX=1`; smoke tests (§8a) | `healthRoute`, `assertEnv`, `ipalEnvRules` | A | | 15 | System pages | Site Settings → System Pages: homepage, 404, privacy policy, cookies; legal links in the footer by role (`getSystemLinks(locale)`) | `getSystemLinks`, `getSystemPagePath`, `getNotFoundPage` | P | @@ -129,7 +130,8 @@ Do not make the provider or the widget conditional in code — always wire them. | your own `api/contact` / `api/send` / `api/form` route, `nodemailer` / `resend` / `@sendgrid` in the project | bypasses the `submitForm` validation and gates, a second mail transport | the `sendForm` server action → `submitForm`, mails from Forms → Emails via `mailAdapter()` | | reCAPTCHA, hCaptcha, your own captcha | a second mechanism, no status in the panel | Turnstile from the plugin | | a hand-written `', '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:a@acme.pl'), 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,' }, 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') + }) +}) diff --git a/test/seoIntegration.test.ts b/test/seoIntegration.test.ts new file mode 100644 index 0000000..53687d6 --- /dev/null +++ b/test/seoIntegration.test.ts @@ -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[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, extra: Record = {}) => { + 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: '' }, + } 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) + }) +}) diff --git a/test/seoSearch.test.ts b/test/seoSearch.test.ts new file mode 100644 index 0000000..2fa829e --- /dev/null +++ b/test/seoSearch.test.ts @@ -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 tag', () => { + expect(normalizeVerificationToken(' abc-123_XYZ ')).toBe('abc-123_XYZ') + expect(normalizeVerificationToken('')).toBe('Tok_9-x') + expect(normalizeVerificationToken("")).toBe('ABCDEF0123') + }) + + test('drops anything that is not a plain token', () => { + expect(normalizeVerificationToken('">')).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[]>, 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 + 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 + 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('/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('/g)).toHaveLength(3) + expect(index).toContain('https://acme.pl/sitemap.xml?part=3') + expect(index).toContain('2026-01-02T00:00:00.000Z') + + const part = await (await handler(new Request('https://acme.pl/sitemap.xml?part=3'))).text() + expect(part.match(//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(' { + 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']) + }) +}) diff --git a/test/settingsDepth.test.ts b/test/settingsDepth.test.ts new file mode 100644 index 0000000..d59dbd5 --- /dev/null +++ b/test/settingsDepth.test.ts @@ -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 +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' }) + }) +}) diff --git a/test/submitForm.test.ts b/test/submitForm.test.ts index cfa39ee..d953475 100644 --- a/test/submitForm.test.ts +++ b/test/submitForm.test.ts @@ -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({