noindex tooling, content/noindex/component/testing guidelines for agents

- IPAL_NOINDEX=1: whole-site noindex for staging (robots Disallow /, robots
  meta noindex,nofollow, X-Robots-Tag via buildSecurityHeaders).
- Markdown mirrors and llms files: X-Robots-Tag noindex; Markdown adds a
  Link rel=canonical to the HTML page.
- buildNoindexField refuses noindex on the homepage and archive pages.
- AGENT.md §0c: writing pages for Google and AI (structure, answer-first,
  facts, E-E-A-T, entity consistency, sameAs, aiSummary, meta) and a
  when-to-noindex table (legal pages stay indexed by default; drafts instead
  of noindexed pages; staging via env).
- AGENT.md §6.0: ten component rules (small, Button styled once, buttons as
  '+ Add Button' array, variants, panel clarity); audit warns on buttons
  styled inside sections.
- AGENT.md §8a + smoke.spec.template.ts: what to test in a client project;
  PROGRAMISTA §8.1a: how the plugin itself is tested.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
2026-10-16 03:13:44 +02:00
co-authored by Claude Opus 5.5
parent 8e2dd28b83
commit f7466cf77f
13 changed files with 314 additions and 10 deletions
+101 -2
View File
@@ -100,6 +100,62 @@ Klucze: `llms`, `llms-full`, `markdown`, `mcp`, `jsonld`, `r2`, `turnstile`,
---
## 0c. TREŚĆ POD GOOGLE I AI (SEO + GEO) — jak piszesz i układasz strony
Technika z §0b sprawia, że strona *może* być dobrze widoczna. To, czy Google ją
wypozycjonuje, a asystent AI zacytuje, zależy od treści. Wpisując treść z briefu do
panelu (seed, faza 6 w ipal-site), stosujesz poniższe — nie wymyślając faktów.
### Struktura każdej strony
- **Jedno `h1`** (nagłówek hero/strony), potem `h2` sekcji, `h3` w środku — bez przeskoków
poziomów. `SectionHeader` dostaje `as="h1"` tylko w pierwszej sekcji.
- **Najpierw odpowiedź.** Pierwsze 1–2 zdania sekcji odpowiadają wprost na jej nagłówek
(„Ile kosztuje…?” → „Od 1500 zł netto za…”). AI cytuje dokładnie takie zdania.
- **Nagłówki = pytania i frazy klientów**, nie hasła („Jak przebiega montaż?”, nie „Proces”).
- **Fakty zamiast ogólników:** liczby, zakres, obszar działania, czas realizacji, ceny „od” —
tylko z briefu; brak → `[DO UZUPEŁNIENIA]`. Zero „najlepsza jakość”, „profesjonalne podejście”.
- **Treść w HTML, nie w obrazach.** Kluczowa informacja nie może być tylko na grafice ani w
wideo. `alt` opisuje, co jest na obrazie (nie „zdjęcie1”, nie słowa kluczowe).
- **Każda strona linkuje dalej:** usługa → powiązane usługi + kontakt; wpis → usługa, której
dotyczy. Żadna strona bez linków wewnętrznych (CMSLink).
- **FAQ z prawdziwych pytań** z briefu → blok FAQ + `getPageJsonLd(…, { faq })` (FAQPage).
Pytania i odpowiedzi w JSON-LD = widoczne na stronie, słowo w słowo.
- **Długość:** strona usługi ≥ ~300 słów sensownej treści; krótsza = „cienka” — połącz z inną
albo poproś o materiał.
### Wiarygodność (E-E-A-T) i encja firmy
- Strona **O nas** z ludźmi, doświadczeniem, certyfikatami (z briefu); wpisy z autorem i datą.
- **Te same dane firmy wszędzie** (nazwa, adres, telefon): stopka, kontakt, JSON-LD
(`LocalBusiness`/`Organization`), wizytówka Google. Jeden global Company jako źródło.
- **Site Settings → sameAs:** profile firmy (Google Business Profile, LinkedIn, Facebook…).
- **Site Settings → opis strony** (2–3 zdania: kto, co, gdzie) — zasila llms.txt, MCP i meta.
- **`aiSummary`** ważnych stron: popraw auto-fill, gdy streszczenie jest słabe (1–3 zdania, fakty).
### Meta w zakładce SEO
Tytuł ≤ 60 znaków, unikalny, fraza na początku; opis ≤ 155 znaków, z konkretem i zachętą;
obraz udostępniania (1200×630) na stronach z ofertą — reszta dziedziczy domyślny z Site Settings.
### noindex — kiedy TAK, kiedy NIE
| Strona | noindex? |
|---|---|
| „Dziękujemy” po formularzu, strona potwierdzenia | **tak** |
| wyniki wewnętrznej wyszukiwarki, strony filtrów/parametrów | **tak** (+ `disallowParams` w robots) |
| strona testowa, robocza, landing tylko dla kampanii płatnej | **tak** |
| staging, preview, kopia testowa całej strony | **`IPAL_NOINDEX=1` w env tego środowiska** — nie checkbox |
| strona główna, archiwa (blog, realizacje) | **nigdy** — panel zablokuje zapis |
| usługi, oferta, kontakt, o nas, wpisy | **nigdy** |
| polityka prywatności, cookies, regulamin | **nie** domyślnie (to sygnał wiarygodności, nie szkodzą); `noindex` tylko na prośbę klienta |
| 404 | nie dotyczy — plugin wyklucza ją z sitemapy i zwraca prawdziwe 404 |
noindex **nie** zastępuje przekierowania ani usunięcia: stary adres → zmiana sluga (308 z
`trackSlugHistoryHook`), strona do skasowania → usuń ją. Treść roboczą trzymasz jako **draft**
(niepublikowana nie jest dostępna publicznie), nie jako opublikowaną stronę z noindex.
Kontrole: `ipal-seo-check` (jedno h1, kolejność nagłówków, alt, obraz OG, cienkie strony,
linki wewnętrzne, noindex w sitemapie).
---
## 0a. JAK PRACUJESZ — samodzielnie, jak doświadczony pracownik
Budujesz stronę od briefu do oddania. Człowiek dostarcza **decyzje biznesowe i
@@ -356,6 +412,23 @@ Trzy problemy, których nie wolno powtarzać: **zoo pól CTA** (`ctaLabel`,
`cta2Text`, `buttonUrl`…), **pliki jako tekst** (`pdfUrl: '/files/x.pdf'`),
**sekcja-monolit** (200–400 linii z kartami, ikonami SVG i stylami przycisków).
### 6.0 Dziesięć zasad komponentu (skrót — szczegóły niżej)
1. **Mały:** `Component.tsx` sekcji ≤ ~80 linii JSX; element listy > 5 linii → własny `XxxCard.tsx`.
2. **Jedna rzecz = jeden komponent, stylowany RAZ.** Przycisk to `Button` (wygląd) + `CMSLink`
(cel z panelu) — w sekcjach nigdy własne klasy przycisku. Zmiana wyglądu wszystkich
przycisków = jedna zmiana w `Button.tsx`. To samo: obraz → `Media`, nagłówek → `SectionHeader`.
3. **Powtarzalne = tablica „+ Add …”**, nigdy numerowane pola. Przyciski: `buildLinksField()` →
redaktor klika „Add Button” tyle razy, ile potrzebuje (`maxRows` = ile mieści projekt).
`cta1`/`cta2`/`cta3`, `feature1Title`…, `image2` = błąd audytu.
4. **Panel czytelny bez znajomości kodu:** etykiety EN 1–3 słowa, zwinięte wiersze z treścią
(`rowLabel`), ≤ 6 pozycji widocznych po dodaniu bloku, ustawienia techniczne w sidebarze.
5. **Wariant zamiast kopii:** inny wygląd tej samej sekcji = `variant` (select), nie drugi blok.
6. **Zero tekstu, linku i obrazu w JSX** — wszystko z panelu, w każdym języku.
7. **Puste pole = element się nie renderuje** (nie „Lorem”, nie pusty `<div>`).
8. **Serwer domyślnie;** interakcja w osobnym, małym pliku `'use client'` z prostymi propsami.
9. **Typy z `@/payload-types`**, eksport nazwany, import z `@/…`, bez barreli.
10. **Każdy nowy blok:** test pustego bloku w panelu (§6.5a) + `ipal-audit --quick`.
### 6.1 Trzy warstwy
```
WARSTWA 1 — wspólne pola: linki z pluginu (buildLinkField, buildLinksField)
@@ -664,8 +737,8 @@ Przykładowy `styles.css`: [kod-sekcji.md](./skills/ipal-block/resources/kod-sek
**Compliance (PL/EU) — mechanizm z pluginu, treść od klienta:** strony polityk
jako System Pages, `CookieBanner` + `CookieButton`, checkbox `consent` w
formularzach (enforcement server-side), dane administratora w globalu, polityki z
`noindex`. Treści prawnych nie piszesz. Widget dostępności — tylko gdy klient
formularzach (enforcement server-side), dane administratora w globalu, tabela
ciasteczek z panelu (`<CookieTable>`, skan: ipal-consent-check). Treści prawnych nie piszesz. Widget dostępności — tylko gdy klient
wymaga (accessibility.md).
**Bezpieczeństwo:** 2FA wymuszone (`ipalKit({ twoFactor: { issuer, plugin:
@@ -674,6 +747,32 @@ payloadTotp } })`, nigdy `twoFactor: false` bez decyzji klienta). CSP: najpierw
---
## 8a. TESTY — co sprawdzasz i jak
Testujesz **zachowanie, które klient i Google widzą**, nie implementację pluginu (ten ma
własne testy). Kolejność od najtańszych:
| Poziom | Co | Kiedy |
|---|---|---|
| Typy | `pnpm generate:types && pnpm tsc --noEmit` | po każdej zmianie schematu |
| Reguły | `ipal-audit --quick` (hardkody, komplet §0b, panel) | po każdym bloku / kolekcji |
| Build | `pnpm build` — trasy stron `●` (SSG), nie `ƒ` | przed każdym „gotowe” |
| Smoke (Playwright) | `ipal-audit/resources/smoke.spec.template.ts` → `tests/smoke.spec.ts`: wszystkie URL-e z sitemapy 200 + tytuł + jedno h1, 404, trasy GEO, baner, formularz end-to-end | przed oddaniem i po każdej aktualizacji ipal-kit |
| Strona w przeglądarce | `ipal-seo-check`, `ipal-consent-check`, `cookie-scan` | przed oddaniem, po deployu |
| Logika projektu | vitest dla własnych funkcji (mapowanie danych firmy na JSON-LD, helpery, hooki, skrypty migracji z `--dry-run`) | gdy piszesz logikę, której plugin nie ma |
| Panel | test redaktora (§11) i test pustego bloku (§6.5a) | każdy nowy blok / global |
Zasady:
- **Test niezależny od treści** — szuka elementów po rolach i `data-ipal`, URL-i z sitemapy, nie po
tekstach, które redaktor zmieni jutro.
- **Każdy naprawiony błąd = test**, który by go złapał (smoke albo vitest), żeby nie wrócił.
- **Formularz testujesz naprawdę**: wysyłka → rekord w Form Submissions → mail do firmy **i**
potwierdzenie do klienta (lokalnie: Site Integrations → Send test + logi adaptera).
- **Nie testujesz pluginu w projekcie** (np. czy `submitForm` waliduje) — to robi ipal-kit. Gdy
zachowanie pluginu jest złe: ipal-plugin-gap.
- Testy w CI projektu: typy + audit `--quick` + build na każdy push; smoke na stagingu
(`IPAL_NOINDEX=1`) przed wdrożeniem produkcji.
## 8. STANDARDY KODU
**Typy**
@@ -0,0 +1,78 @@
/**
* Smoke tests of a client site (Playwright) — the few things that must never
* break: every language's homepage, a real 404, the form end to end, the
* language switch, the GEO routes. Copy to tests/smoke.spec.ts and run against
* a production build:
*
* pnpm add -D @playwright/test && pnpm exec playwright install chromium
* pnpm build && pnpm start &
* BASE_URL=http://localhost:3000 pnpm exec playwright test tests/smoke.spec.ts
*
* Content-agnostic on purpose: it reads locales from the sitemap and finds the
* form by its renderer, so it survives editors changing texts in the panel.
* Turnstile: run with the test keys in Site Integrations (1x00000000000000000000AA /
* 1x0000000000000000000000000000000AA) or without keys.
*/
import { expect, test } from '@playwright/test'
const BASE = (process.env.BASE_URL ?? 'http://localhost:3000').replace(/\/$/, '')
async function sitemapUrls(): Promise<string[]> {
const xml = await (await fetch(`${BASE}/sitemap.xml`)).text()
return [...xml.matchAll(/<loc>\s*([^<\s]+)\s*<\/loc>/g)].map((m) => m[1].replace(/^https?:\/\/[^/]+/, BASE))
}
test('every sitemap URL answers 200 with a title and one h1', async ({ page }) => {
const urls = (await sitemapUrls()).slice(0, 30)
expect(urls.length).toBeGreaterThan(0)
for (const url of urls) {
const res = await page.goto(url)
expect(res?.status(), url).toBe(200)
await expect(page, url).toHaveTitle(/\S/)
expect(await page.locator('h1').count(), `${url}: exactly one h1`).toBe(1)
}
})
test('unknown URL is a real 404', async ({ request }) => {
const res = await request.get(`${BASE}/this-page-does-not-exist-${Date.now()}`, { maxRedirects: 5 })
expect(res.status()).toBe(404)
})
test('GEO routes answer', async ({ request }) => {
for (const path of ['/robots.txt', '/sitemap.xml', '/llms.txt', '/llms-full.txt', '/api/health']) {
expect((await request.get(`${BASE}${path}`)).status(), path).toBe(200)
}
const mcp = await request.post(`${BASE}/api/mcp`, { data: { id: 1, jsonrpc: '2.0', method: 'tools/list' } })
expect(((await mcp.json()) as { result: { tools: unknown[] } }).result.tools.length).toBeGreaterThan(0)
})
test('cookie banner: reject hides it and survives a reload', async ({ page }) => {
await page.goto(BASE)
await page.locator('[data-ipal="reject"]').click()
await expect(page.locator('[data-ipal="banner"]')).toBeHidden()
await page.reload()
await expect(page.locator('[data-ipal="banner"]')).toBeHidden()
})
test('the first form on the site submits and shows the confirmation', async ({ page }) => {
const urls = await sitemapUrls()
let found = false
for (const url of urls) {
await page.goto(url)
const form = page.locator('form').filter({ has: page.locator('[type="submit"]') }).first()
if (!(await form.count())) {continue}
found = true
await page.locator('[data-ipal="reject"]').click().catch(() => {})
for (const input of await form.locator('input:not([type=hidden]):not([type=checkbox]), textarea').all()) {
const type = await input.getAttribute('type')
if (await input.getAttribute('name') === 'company_url') {continue} // honeypot stays empty
await input.fill(type === 'email' ? '[email protected]' : type === 'number' ? '1' : 'Smoke test')
}
for (const box of await form.locator('input[type=checkbox]').all()) {await box.check()}
for (const select of await form.locator('select').all()) {await select.selectOption({ index: 1 }).catch(() => {})}
await form.locator('[type="submit"]').click()
await expect(page.locator('[role="status"], [role="alert"]').first()).toBeVisible({ timeout: 15_000 })
break
}
test.skip(!found, 'no form on the site')
})
@@ -105,6 +105,9 @@ if [ -n "$BLOCKS" ]; then
report ERROR "hardcoded href/src/file paths in blocks" "§2, §6 use CMSLink / Media" \
"$(g 'href=\{?["`]/|<img |/files/|/images/|\.pdf' $BLOCKS --include=*.tsx | nc '(href|<img|/files/|/images/|\.pdf)')"
report WARNING "button styled inside a section" "§6.0 style buttons once in Button.tsx — sections render <CMSLink> (appearance from the panel)" \
"$(g '<button[^>]*className=[^>]*(bg-|rounded|px-[0-9])' $BLOCKS --include=*.tsx)"
report ERROR "raw <a>/<Link> in blocks" "§6.3 links from the panel render via CMSLink" \
"$(g '<(a|Link)[ >]' $BLOCKS --include=*.tsx)"
+18
View File
@@ -615,6 +615,24 @@ wersji z czerwonymi testami. `prepare` buduje paczkę przy instalacji z gita.
Przed commitem: `pnpm typecheck && pnpm lint && pnpm test:int` (to samo puszcza CI
w `.gitea/workflows/ci.yml` na każdy push i PR).
### 8.1a Testy pluginu
`test/` (poza `src`, nie trafia do `dist`), vitest: `pnpm test:int` (raz), `pnpm test:watch`.
| Rodzaj | Gdzie | Dla czego |
|---|---|---|
| jednostkowe | `test/<moduł>.test.ts` | czyste funkcje: ścieżki, metadata, robots, CSP, parsery (godziny, Markdown), walidacja |
| z atrapą Payloada | `test/helpers.ts` → `fakePayload()` | logika na Local API bez bazy: `submitForm`, Turnstile, MCP, IndexNow |
| integracyjne | `test/integration.test.ts`, `test/drafts.test.ts` — **prawdziwy Payload + SQLite w pamięci** | dostęp (access), hooki, schemat pól, drafty, globale — wszystko, czego atrapa nie odda |
| kontrakt pakietu | `test/exports.test.ts` | każda ścieżka `@intecion/ipal-kit/…` z docs istnieje w `exports` |
Zasady: **każdy naprawiony błąd = test regresyjny** (sprawdź, że na starym kodzie pada);
zero sieci (`vi.spyOn(globalThis, 'fetch')`); env przez `vi.stubEnv` + `unstubAllEnvs`;
`server-only` mockowane (`vi.mock('server-only', () => ({}))`); test zmiany zachowania
widocznej dla projektów → wpis w `docs/CHANGELOG.md`. Skrypty skilli (`audit.sh`,
`seo-check.mjs`, `cookie-scan.mjs`) testujesz na atrapie strony/projektu w scratchpadzie:
pusty projekt (same błędy) i kompletny (0 błędów). CI (`.gitea/workflows/ci.yml`) puszcza
typecheck, lint, testy i build na każdy push.
### 8.2 package.json pluginu
- `"files": ["dist", "docs", "bin"]` — **docs i komenda `ipal-skills` jadą w pakiecie**; agenci w projektach
czytają `node_modules/@intecion/ipal-kit/docs/agent/AGENT.md`. Bez `docs` nie mają nic.
+16 -6
View File
@@ -105,10 +105,8 @@ export function createMarkdownRenderer(args: CreateMarkdownRendererArgs = {}) {
const fm = ['---', `locale: ${locale}`]
if (title) {fm.push(`title: ${yamlEscape(title)}`)}
if (description) {fm.push(`description: ${yamlEscape(description)}`)}
if (baseUrl) {
const segments = config?.locales.length === 1 ? (slug ?? []) : [locale, ...(slug ?? [])]
fm.push(`url: ${baseUrl.replace(/\/$/, '')}/${segments.join('/')}`.replace(/\/$/, ''))
}
const url = canonicalOf(baseUrl, config, locale, slug)
if (url) {fm.push(`url: ${url}`)}
if (typeof doc.updatedAt === 'string') {fm.push(`updated: ${doc.updatedAt.slice(0, 10)}`)}
fm.push('---')
parts.push(fm.join('\n'))
@@ -127,7 +125,7 @@ export function createMarkdownRenderer(args: CreateMarkdownRendererArgs = {}) {
* Wraps a Markdown string in a `text/markdown` Response, or a 404 when null.
* Uses the global Response — no next/server import.
*/
export function markdownResponse(md: null | string): Response {
export function markdownResponse(md: null | string, options: { canonical?: string } = {}): Response {
if (md == null) {
return new Response('Not found', { headers: { 'content-type': 'text/plain' }, status: 404 })
}
@@ -135,11 +133,22 @@ export function markdownResponse(md: null | string): Response {
headers: {
'cache-control': 'public, max-age=0, s-maxage=3600, stale-while-revalidate=86400',
'content-type': 'text/markdown; charset=utf-8',
// A mirror of an HTML page: AI agents read it, search engines must not
// index it as a duplicate — and should credit the HTML page instead.
'x-robots-tag': 'noindex',
...(options.canonical ? { link: `<${options.canonical}>; rel="canonical"` } : {}),
},
status: 200,
})
}
/** Canonical HTML URL of a Markdown page — same rule as the frontmatter `url:`. */
function canonicalOf(baseUrl: string | undefined, config: { locales: readonly unknown[] } | undefined, locale: string, slug?: string[]) {
if (!baseUrl) {return undefined}
const segments = config?.locales.length === 1 ? (slug ?? []) : [locale, ...(slug ?? [])]
return `${baseUrl.replace(/\/$/, '')}/${segments.join('/')}`.replace(/\/$/, '')
}
type MarkdownRouteContext = { params: Promise<{ locale: string; slug?: string[] }> }
/**
@@ -167,7 +176,8 @@ export function createMarkdownRoute(
GET: async (_req, { params }) => {
try {
const { slug, locale } = await params
return markdownResponse(await render({ slug, locale, payload: await getCachedPayload() }))
const md = await render({ slug, locale, payload: await getCachedPayload() })
return markdownResponse(md, { canonical: canonicalOf(rendererArgs.baseUrl, rendererArgs.config, locale, slug) })
} catch (err) {
console.warn('[ipal] createMarkdownRoute: render failed:', err)
return new Response('Service unavailable', { headers: { 'content-type': 'text/plain' }, status: 503 })
@@ -1,3 +1,5 @@
import { isSiteNoindex } from '../seo/siteNoindex.js'
/**
* A single HTTP header, in the shape Next.js next.config headers() expects.
*/
@@ -116,6 +118,11 @@ export function buildSecurityHeaders(args: BuildSecurityHeadersArgs = {}): Secur
headers.push({ key: 'Cross-Origin-Opener-Policy', value: coop })
}
// Staging / preview (IPAL_NOINDEX=1): keep every response out of search engines.
if (isSiteNoindex()) {
headers.push({ key: 'X-Robots-Tag', value: 'noindex, nofollow' })
}
// Merge additional: same-key entries override the defaults above.
for (const extra of additional) {
const i = headers.findIndex((h) => h.key.toLowerCase() === extra.key.toLowerCase())
+4 -1
View File
@@ -1,3 +1,4 @@
import { isSiteNoindex } from './siteNoindex.js'
import type { I18nConfig, LocalizedSlugs } from '../i18n/index.js'
import type { TitleOrder } from './composeTitle.js'
import type { SeoMeta } from './types.js'
@@ -205,7 +206,9 @@ export function buildMetadata({
// robots: noindex pages are excluded (follow keeps link authority). Indexed
// pages get generous snippet/preview limits so Google can show rich results
// (long snippets, large image previews, full video previews).
...(noindex || meta?.noindex
...(isSiteNoindex()
? { robots: { follow: false, index: false } }
: noindex || meta?.noindex
? { robots: { follow: true, index: false } }
: {
robots: {
+30
View File
@@ -9,8 +9,17 @@ type BuildNoindexFieldArgs = {
name?: string
/** Extend/override the generated checkbox (position, access, etc.). */
overrides?: Partial<CheckboxField>
/**
* Refuse noindex on the homepage and on archive pages (blog, offers…) — it
* would drop the whole site or the whole section from Google. Default true.
*/
protectSystemPages?: boolean
/** SiteSettings global read for that check. Default 'site-settings'. */
settingsSlug?: string
}
const idOf = (rel: unknown): unknown => (rel && typeof rel === 'object' ? (rel as { id?: unknown }).id : rel)
/**
* A top-level sidebar `noindex` checkbox. When ticked, the page is excluded from
* `sitemap.xml`, `llms.txt`, site search, and gets `robots: noindex, follow` —
@@ -35,8 +44,28 @@ export function buildNoindexField(args: BuildNoindexFieldArgs = {}): Field {
description = 'Check to exclude this page from indexing (robots: noindex, follow), the sitemap, llms.txt and site search.',
label = 'Exclude from indexing (noindex)',
overrides = {},
protectSystemPages = true,
settingsSlug = 'site-settings',
} = args
const validate: CheckboxField['validate'] = async (value, { id, req }) => {
if (!protectSystemPages || value !== true || id === undefined) {return true}
try {
const settings = (await req.payload.findGlobal({ slug: settingsSlug as never, depth: 0, req })) as Record<string, unknown>
if (idOf(settings.homepage) === id) {
return 'This page is the homepage (Site Settings → System Pages). noindex would remove the whole site from Google.'
}
for (const [key, rel] of Object.entries(settings)) {
if (key.endsWith('Archive') && idOf(rel) === id) {
return 'This page is an archive (Site Settings → System Pages). noindex would hide the page that lists all its entries.'
}
}
} catch {
// settings unreadable (fresh DB) — nothing to protect yet
}
return true
}
const { admin: adminOverrides, ...restOverrides } = overrides
return {
@@ -49,6 +78,7 @@ export function buildNoindexField(args: BuildNoindexFieldArgs = {}): Field {
},
defaultValue: false,
label,
validate,
...restOverrides,
} as CheckboxField
}
+4
View File
@@ -1,3 +1,5 @@
import { isSiteNoindex } from './siteNoindex.js'
type RobotRule = { allow?: string; disallow?: string[]; userAgent: string | string[] }
/**
@@ -125,6 +127,8 @@ export function buildRobots({
sitemap = true,
}: BuildRobotsArgs): RobotsRules {
const origin = baseUrl.replace(/\/$/, '')
// Staging / preview (IPAL_NOINDEX=1): nothing may be crawled.
if (isSiteNoindex()) {return { rules: { disallow: ['/'], userAgent: '*' } }}
const defaults = [...(adminRoute ? [adminRoute] : []), '/api']
const paramRules = disallowParams
+3 -1
View File
@@ -54,7 +54,9 @@ export function createLlmsTxtRoute(opts: {
summaryField: opts.summaryField,
})
return new Response(body, {
headers: { 'Content-Type': 'text/plain; charset=utf-8' },
// For AI agents, not a search result: keep it (and the full-content
// copy, a duplicate of every page) out of search indexes.
headers: { 'Content-Type': 'text/plain; charset=utf-8', 'X-Robots-Tag': 'noindex' },
})
} catch (err) {
// DB unreachable at build (container) — return a minimal valid file so the
+14
View File
@@ -0,0 +1,14 @@
/**
* Whole-site noindex for staging, previews and test copies: set IPAL_NOINDEX=1
* in that environment's env. Then robots.txt disallows everything, every page
* gets `robots: noindex, nofollow`, and buildSecurityHeaders adds
* `X-Robots-Tag: noindex, nofollow` to every response (files and API too).
* Production never sets it — a forgotten staging copy indexed by Google is a
* duplicate of the real site.
*/
export const SITE_NOINDEX_ENV = 'IPAL_NOINDEX'
export function isSiteNoindex(): boolean {
const v = process.env[SITE_NOINDEX_ENV]?.trim().toLowerCase()
return v === '1' || v === 'true' || v === 'yes'
}
+13
View File
@@ -9,6 +9,7 @@ import { buildConfig, getPayload } from 'payload'
import { afterAll, beforeAll, describe, expect, test } from 'vitest'
import { resolveRoute } from '../src/modules/content/resolveRoute.js'
import { buildNoindexField } from '../src/modules/seo/buildNoindexField.js'
import { ipalKit } from '../src/plugin.js'
let payload: Payload
@@ -21,6 +22,7 @@ beforeAll(async () => {
fields: [
{ name: 'title', type: 'text' },
{ name: 'slug', type: 'text', localized: true },
buildNoindexField(),
],
versions: { drafts: true },
},
@@ -74,3 +76,14 @@ describe('archive listing', () => {
expect(preview.totalDocs).toBe(2)
})
})
describe('noindex protection', () => {
test('the homepage cannot be set to noindex; an ordinary page can', async () => {
const home = await payload.create({ collection: 'pages' as never, data: { _status: 'published', slug: 'start', title: 'Start' } as never })
const other = await payload.create({ collection: 'pages' as never, data: { _status: 'published', slug: 'dziekujemy', title: 'Dziękujemy' } as never })
await payload.updateGlobal({ slug: 'site-settings' as never, data: { homepage: home.id, siteName: 'Acme' } as never })
await expect(payload.update({ collection: 'pages' as never, data: { noindex: true } as never, id: home.id })).rejects.toThrow(/Exclude from indexing/)
const updated = (await payload.update({ collection: 'pages' as never, data: { noindex: true } as never, id: other.id })) as { noindex?: boolean }
expect(updated.noindex).toBe(true)
})
})
+23
View File
@@ -236,3 +236,26 @@ describe('buildUploadSecurityHeaders', () => {
expect(csp).not.toContain('script-src')
})
})
describe('site-wide noindex (IPAL_NOINDEX) and Markdown headers', () => {
test('staging blocks crawling everywhere', async () => {
const { vi } = await import('vitest')
vi.stubEnv('IPAL_NOINDEX', '1')
try {
expect(buildRobots({ baseUrl: 'https://staging.acme.pl' })).toEqual({ rules: { disallow: ['/'], userAgent: '*' } })
expect(buildSecurityHeaders().find((h) => h.key === 'X-Robots-Tag')?.value).toBe('noindex, nofollow')
const { buildMetadata } = await import('../src/modules/seo/buildMetadata.js')
expect(buildMetadata({ config, locale: 'pl', slugs: { pl: 'x' } }).robots).toEqual({ follow: false, index: false })
} finally {
vi.unstubAllEnvs()
}
expect(buildSecurityHeaders().some((h) => h.key === 'X-Robots-Tag')).toBe(false)
})
test('Markdown mirrors are noindex with a canonical link to the HTML page', async () => {
const { markdownResponse } = await import('../src/modules/content/createMarkdownRenderer.js')
const res = markdownResponse('# x', { canonical: 'https://acme.pl/pl/o-nas' })
expect(res.headers.get('x-robots-tag')).toBe('noindex')
expect(res.headers.get('link')).toBe('<https://acme.pl/pl/o-nas>; rel="canonical"')
})
})