Compare commits

...
4 Commits
Author SHA1 Message Date
radoslaw.smolinski c852d7bdae 1.7.7 2026-10-12 14:47:59 +02:00
radoslaw.smolinski 24fa3fdcdf Security fix for MCP 2026-10-12 14:47:50 +02:00
radoslaw.smolinski 73eacb09c2 1.7.6 2026-10-12 14:35:58 +02:00
radoslaw.smolinski 2665cfa7b6 noindex fix 2026-10-12 14:35:51 +02:00
28 changed files with 130 additions and 151 deletions
+1 -1
View File
@@ -47,7 +47,7 @@ import { buildLocalizedPath, getDefaultLocale, isValidLocale } from '../i18n/ind
if (doc._status && doc._status !== 'published') {
continue;
}
if (doc.meta?.noindex) {
if (doc.noindex || doc.meta?.noindex) {
continue;
}
const title = typeof doc.title === 'string' ? doc.title : undefined;
File diff suppressed because one or more lines are too long
+4 -1
View File
@@ -41,9 +41,12 @@
status: 200
});
} catch (err) {
// Log the real error for ops; keep the PUBLIC body generic — a 503 with
// `db: 'down'` is all an orchestrator needs, and raw DB error text (host,
// credentials-in-URL, driver internals) must not leak on a public route.
console.warn('[ipal] createHealthRoute: database unreachable:', err);
const body = {
db: 'down',
error: err instanceof Error ? err.message : 'unknown',
status: 'error',
timestamp: new Date().toISOString(),
tookMs: Date.now() - startedAt
+1 -1
View File
@@ -1 +1 @@
{"version":3,"sources":["../../../src/modules/health/createHealthRoute.ts"],"sourcesContent":["import type { BasePayload } from 'payload'\n\ntype CreateHealthRouteArgs = {\n /**\n * Collection to ping for a real DB round-trip. Default 'pages'. Pick any\n * collection that always exists in the project.\n */\n collection?: string\n /**\n * Optional extra checks merged into the body (e.g. a cache or queue ping).\n * Throwing marks the whole healthcheck unhealthy.\n */\n extra?: () => Promise<Record<string, unknown>>\n /** Same cached accessor the rest of the app uses. */\n getCachedPayload: () => Promise<BasePayload>\n}\n\n/**\n * A liveness/readiness route for Coolify/Docker healthchecks and uptime\n * monitors. Does a real DB round-trip (not just \"process is up\") and returns\n * 200 when reachable, 503 when not — so an orchestrator can restart or hold\n * traffic off a container whose database is down.\n *\n * // app/api/health/route.ts\n * import { createHealthRoute } from '@intecion/ipal-kit'\n * import { getCachedPayload } from '@/lib/content'\n * export const dynamic = 'force-dynamic' // never prerender/cache a healthcheck\n * export const GET = createHealthRoute({ getCachedPayload })\n *\n * Point Coolify's healthcheck at /api/health. Uses the global `Response`\n * (standard in Next route handlers) — no next/server import, peer-dep clean.\n */\nexport function createHealthRoute(args: CreateHealthRouteArgs): () => Promise<Response> {\n const { collection = 'pages', extra, getCachedPayload } = args\n\n return async () => {\n const startedAt = Date.now()\n try {\n const payload = await getCachedPayload()\n // Cheapest real round-trip: ask for at most one row, no population.\n await payload.find({\n collection: collection as never,\n depth: 0,\n limit: 1,\n pagination: false,\n })\n\n const extraData = extra ? await extra() : {}\n const body = {\n db: 'up',\n status: 'ok',\n timestamp: new Date().toISOString(),\n tookMs: Date.now() - startedAt,\n ...extraData,\n }\n return new Response(JSON.stringify(body), {\n headers: { 'cache-control': 'no-store', 'content-type': 'application/json' },\n status: 200,\n })\n } catch (err) {\n const body = {\n db: 'down',\n error: err instanceof Error ? err.message : 'unknown',\n status: 'error',\n timestamp: new Date().toISOString(),\n tookMs: Date.now() - startedAt,\n }\n return new Response(JSON.stringify(body), {\n headers: { 'cache-control': 'no-store', 'content-type': 'application/json' },\n status: 503,\n })\n }\n }\n}\n"],"names":["createHealthRoute","args","collection","extra","getCachedPayload","startedAt","Date","now","payload","find","depth","limit","pagination","extraData","body","db","status","timestamp","toISOString","tookMs","Response","JSON","stringify","headers","err","error","Error","message"],"mappings":"AAiBA;;;;;;;;;;;;;;CAcC,GACD,OAAO,SAASA,kBAAkBC,IAA2B;IAC3D,MAAM,EAAEC,aAAa,OAAO,EAAEC,KAAK,EAAEC,gBAAgB,EAAE,GAAGH;IAE1D,OAAO;QACL,MAAMI,YAAYC,KAAKC,GAAG;QAC1B,IAAI;YACF,MAAMC,UAAU,MAAMJ;YACtB,oEAAoE;YACpE,MAAMI,QAAQC,IAAI,CAAC;gBACjBP,YAAYA;gBACZQ,OAAO;gBACPC,OAAO;gBACPC,YAAY;YACd;YAEA,MAAMC,YAAYV,QAAQ,MAAMA,UAAU,CAAC;YAC3C,MAAMW,OAAO;gBACXC,IAAI;gBACJC,QAAQ;gBACRC,WAAW,IAAIX,OAAOY,WAAW;gBACjCC,QAAQb,KAAKC,GAAG,KAAKF;gBACrB,GAAGQ,SAAS;YACd;YACA,OAAO,IAAIO,SAASC,KAAKC,SAAS,CAACR,OAAO;gBACxCS,SAAS;oBAAE,iBAAiB;oBAAY,gBAAgB;gBAAmB;gBAC3EP,QAAQ;YACV;QACF,EAAE,OAAOQ,KAAK;YACZ,MAAMV,OAAO;gBACXC,IAAI;gBACJU,OAAOD,eAAeE,QAAQF,IAAIG,OAAO,GAAG;gBAC5CX,QAAQ;gBACRC,WAAW,IAAIX,OAAOY,WAAW;gBACjCC,QAAQb,KAAKC,GAAG,KAAKF;YACvB;YACA,OAAO,IAAIe,SAASC,KAAKC,SAAS,CAACR,OAAO;gBACxCS,SAAS;oBAAE,iBAAiB;oBAAY,gBAAgB;gBAAmB;gBAC3EP,QAAQ;YACV;QACF;IACF;AACF"}
{"version":3,"sources":["../../../src/modules/health/createHealthRoute.ts"],"sourcesContent":["import type { BasePayload } from 'payload'\n\ntype CreateHealthRouteArgs = {\n /**\n * Collection to ping for a real DB round-trip. Default 'pages'. Pick any\n * collection that always exists in the project.\n */\n collection?: string\n /**\n * Optional extra checks merged into the body (e.g. a cache or queue ping).\n * Throwing marks the whole healthcheck unhealthy.\n */\n extra?: () => Promise<Record<string, unknown>>\n /** Same cached accessor the rest of the app uses. */\n getCachedPayload: () => Promise<BasePayload>\n}\n\n/**\n * A liveness/readiness route for Coolify/Docker healthchecks and uptime\n * monitors. Does a real DB round-trip (not just \"process is up\") and returns\n * 200 when reachable, 503 when not — so an orchestrator can restart or hold\n * traffic off a container whose database is down.\n *\n * // app/api/health/route.ts\n * import { createHealthRoute } from '@intecion/ipal-kit'\n * import { getCachedPayload } from '@/lib/content'\n * export const dynamic = 'force-dynamic' // never prerender/cache a healthcheck\n * export const GET = createHealthRoute({ getCachedPayload })\n *\n * Point Coolify's healthcheck at /api/health. Uses the global `Response`\n * (standard in Next route handlers) — no next/server import, peer-dep clean.\n */\nexport function createHealthRoute(args: CreateHealthRouteArgs): () => Promise<Response> {\n const { collection = 'pages', extra, getCachedPayload } = args\n\n return async () => {\n const startedAt = Date.now()\n try {\n const payload = await getCachedPayload()\n // Cheapest real round-trip: ask for at most one row, no population.\n await payload.find({\n collection: collection as never,\n depth: 0,\n limit: 1,\n pagination: false,\n })\n\n const extraData = extra ? await extra() : {}\n const body = {\n db: 'up',\n status: 'ok',\n timestamp: new Date().toISOString(),\n tookMs: Date.now() - startedAt,\n ...extraData,\n }\n return new Response(JSON.stringify(body), {\n headers: { 'cache-control': 'no-store', 'content-type': 'application/json' },\n status: 200,\n })\n } catch (err) {\n // Log the real error for ops; keep the PUBLIC body generic — a 503 with\n // `db: 'down'` is all an orchestrator needs, and raw DB error text (host,\n // credentials-in-URL, driver internals) must not leak on a public route.\n console.warn('[ipal] createHealthRoute: database unreachable:', err)\n const body = {\n db: 'down',\n status: 'error',\n timestamp: new Date().toISOString(),\n tookMs: Date.now() - startedAt,\n }\n return new Response(JSON.stringify(body), {\n headers: { 'cache-control': 'no-store', 'content-type': 'application/json' },\n status: 503,\n })\n }\n }\n}\n"],"names":["createHealthRoute","args","collection","extra","getCachedPayload","startedAt","Date","now","payload","find","depth","limit","pagination","extraData","body","db","status","timestamp","toISOString","tookMs","Response","JSON","stringify","headers","err","console","warn"],"mappings":"AAiBA;;;;;;;;;;;;;;CAcC,GACD,OAAO,SAASA,kBAAkBC,IAA2B;IAC3D,MAAM,EAAEC,aAAa,OAAO,EAAEC,KAAK,EAAEC,gBAAgB,EAAE,GAAGH;IAE1D,OAAO;QACL,MAAMI,YAAYC,KAAKC,GAAG;QAC1B,IAAI;YACF,MAAMC,UAAU,MAAMJ;YACtB,oEAAoE;YACpE,MAAMI,QAAQC,IAAI,CAAC;gBACjBP,YAAYA;gBACZQ,OAAO;gBACPC,OAAO;gBACPC,YAAY;YACd;YAEA,MAAMC,YAAYV,QAAQ,MAAMA,UAAU,CAAC;YAC3C,MAAMW,OAAO;gBACXC,IAAI;gBACJC,QAAQ;gBACRC,WAAW,IAAIX,OAAOY,WAAW;gBACjCC,QAAQb,KAAKC,GAAG,KAAKF;gBACrB,GAAGQ,SAAS;YACd;YACA,OAAO,IAAIO,SAASC,KAAKC,SAAS,CAACR,OAAO;gBACxCS,SAAS;oBAAE,iBAAiB;oBAAY,gBAAgB;gBAAmB;gBAC3EP,QAAQ;YACV;QACF,EAAE,OAAOQ,KAAK;YACZ,wEAAwE;YACxE,0EAA0E;YAC1E,yEAAyE;YACzEC,QAAQC,IAAI,CAAC,mDAAmDF;YAChE,MAAMV,OAAO;gBACXC,IAAI;gBACJC,QAAQ;gBACRC,WAAW,IAAIX,OAAOY,WAAW;gBACjCC,QAAQb,KAAKC,GAAG,KAAKF;YACvB;YACA,OAAO,IAAIe,SAASC,KAAKC,SAAS,CAACR,OAAO;gBACxCS,SAAS;oBAAE,iBAAiB;oBAAY,gBAAgB;gBAAmB;gBAC3EP,QAAQ;YACV;QACF;IACF;AACF"}
+5 -1
View File
@@ -190,7 +190,11 @@ export function createMcpRoute(args) {
}
return rpcResult(id, toolText(`Unknown tool: ${p.name}`, true));
} catch (err) {
return rpcResult(id, toolText(err instanceof Error ? err.message : 'Tool error', true));
// Log the real error server-side; return a GENERIC message to the
// (anonymous) caller so internal details — DB schema, host, stack —
// never leak over a public endpoint.
console.warn('[ipal] createMcpRoute: tool execution failed:', err);
return rpcResult(id, toolText('Tool execution failed.', true));
}
}
case 'tools/list':
File diff suppressed because one or more lines are too long
+2 -2
View File
@@ -70,7 +70,7 @@ import { buildLocalizedPath } from '../i18n/index.js';
if (raw._status && raw._status !== 'published') {
continue;
}
if (raw.meta?.noindex) {
if (raw.noindex || raw.meta?.noindex) {
continue;
}
const title = typeof raw.title === 'string' ? raw.title : undefined;
@@ -111,7 +111,7 @@ import { buildLocalizedPath } from '../i18n/index.js';
if (raw._status && raw._status !== 'published') {
continue;
}
if (raw.meta?.noindex) {
if (raw.noindex || raw.meta?.noindex) {
continue;
}
const title = typeof raw.title === 'string' ? raw.title : undefined;
File diff suppressed because one or more lines are too long
+8 -1
View File
@@ -53,6 +53,13 @@ type BuildMetadataArgs = {
locale: string;
/** SEO meta from the document (plugin-seo group). */
meta?: null | SeoMeta;
/**
* Top-level noindex flag (buildNoindexField). Checked alongside meta.noindex:
* plugin-seo's meta group doesn't declare noindex, so a mirror into
* meta.noindex is stripped on save — the top-level field is the one that
* persists. Either being true emits robots index:false.
*/
noindex?: boolean | null;
/** Page title or site name first. Defaults to 'page-first'. */
order?: TitleOrder;
/**
@@ -98,5 +105,5 @@ type BuildMetadataArgs = {
* pieces (meta group, site name, image URL, localized slugs) and passes them
* in — the plugin composes, it doesn't fetch.
*/
export declare function buildMetadata({ baseUrl, config, homeSlug, imageUrl, locale, meta, order, pageTitle, prefix, query, separator, siteDescription, siteName, slugs, }: BuildMetadataArgs): PageMetadata;
export declare function buildMetadata({ baseUrl, config, homeSlug, imageUrl, locale, meta, noindex, order, pageTitle, prefix, query, separator, siteDescription, siteName, slugs, }: BuildMetadataArgs): PageMetadata;
export {};
+2 -2
View File
@@ -9,7 +9,7 @@ import { buildHreflangAlternates } from './hreflang.js';
* Designed for use inside Next.js `generateMetadata`. The caller resolves the
* pieces (meta group, site name, image URL, localized slugs) and passes them
* in — the plugin composes, it doesn't fetch.
*/ export function buildMetadata({ baseUrl, config, homeSlug = 'home', imageUrl, locale, meta, order, pageTitle, prefix, query, separator, siteDescription, siteName, slugs }) {
*/ export function buildMetadata({ baseUrl, config, homeSlug = 'home', imageUrl, locale, meta, noindex, order, pageTitle, prefix, query, separator, siteDescription, siteName, slugs }) {
// Title source priority: titleOverride (exact, wins outright) > meta.title
// (SEO title an editor set) > pageTitle (the document's own name). This means
// a page with no SEO title still shows its name (e.g. 'Sprzątanie biur')
@@ -83,7 +83,7 @@ import { buildHreflangAlternates } from './hreflang.js';
// 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).
...meta?.noindex ? {
...noindex || meta?.noindex ? {
robots: {
follow: true,
index: false
File diff suppressed because one or more lines are too long
+12 -15
View File
@@ -2,29 +2,26 @@ import type { CheckboxField, Field } from 'payload';
type BuildNoindexFieldArgs = {
/** Help text under the checkbox. */
description?: string;
/** Sidebar label. Default 'Wyklucz z indeksowania (noindex)'. */
/** Sidebar label. Default 'Exclude from indexing (noindex)'. */
label?: string;
/**
* Dotted path, inside the document, that the SEO read path (metadata +
* sitemap) consumes. Default 'meta.noindex' — the plugin-seo `meta` group.
* The checkbox value is mirrored here on every save, so editors toggle one
* friendly switch and the machinery reads a stable location.
*/
metaPath?: string;
/** Field name for the editor-facing checkbox. Default 'noindex'. */
name?: string;
/** Extend/override the generated checkbox (position, access, etc.). */
overrides?: Partial<CheckboxField>;
};
/**
* A sidebar `noindex` checkbox that mirrors into `meta.noindex` (what the
* sitemap and metadata generators actually read). Replaces the hand-rolled
* checkbox + `beforeChange` hook with its `(data as any).meta.noindex = …`
* glue copied into every project — no `any`, one source of truth for editors,
* one stable read location for the engine.
* A top-level sidebar `noindex` checkbox. When ticked, the page is excluded from
* `sitemap.xml`, `llms.txt`, site search, and gets `robots: noindex, follow` —
* ALL automatically, no per-project filtering.
*
* Idempotent and order-independent: if either the checkbox OR an existing
* `meta.noindex` is set, the page ends up noindex; the two can't drift apart.
* Why top-level (not mirrored into `meta.noindex`): plugin-seo's `meta` group
* declares only title/description/image, so Payload silently strips any extra
* key (`meta.noindex`) during sanitization — an earlier version mirrored there
* and the value vanished, leaking noindex pages into the sitemap. The value now
* lives on this top-level field, which persists; every reader in the kit
* (buildSitemapEntries, buildMetadata/createPageMetadata, buildLlmsTxt,
* searchContent) checks `doc.noindex` (and still tolerates a legacy
* `meta.noindex`). One field, one source of truth, zero project glue.
*
* // collections/Pages.ts
* import { buildNoindexField } from '@intecion/ipal-kit'
+13 -47
View File
@@ -1,49 +1,23 @@
/** Read a dotted path (e.g. 'meta.noindex') off a loosely-typed object. */ function readPath(obj, path) {
let cur = obj;
for (const key of path){
if (cur == null || typeof cur !== 'object') {
return undefined;
}
cur = cur[key];
}
return cur;
}
/** Write a dotted path, creating intermediate objects as needed. */ function writePath(obj, path, value) {
let cur = obj;
for(let i = 0; i < path.length - 1; i++){
const key = path[i];
const next = cur[key];
if (next == null || typeof next !== 'object') {
cur[key] = {};
}
cur = cur[key];
}
cur[path[path.length - 1]] = value;
}
/**
* A sidebar `noindex` checkbox that mirrors into `meta.noindex` (what the
* sitemap and metadata generators actually read). Replaces the hand-rolled
* checkbox + `beforeChange` hook with its `(data as any).meta.noindex = …`
* glue copied into every project — no `any`, one source of truth for editors,
* one stable read location for the engine.
* A top-level sidebar `noindex` checkbox. When ticked, the page is excluded from
* `sitemap.xml`, `llms.txt`, site search, and gets `robots: noindex, follow` —
* ALL automatically, no per-project filtering.
*
* Idempotent and order-independent: if either the checkbox OR an existing
* `meta.noindex` is set, the page ends up noindex; the two can't drift apart.
* Why top-level (not mirrored into `meta.noindex`): plugin-seo's `meta` group
* declares only title/description/image, so Payload silently strips any extra
* key (`meta.noindex`) during sanitization — an earlier version mirrored there
* and the value vanished, leaking noindex pages into the sitemap. The value now
* lives on this top-level field, which persists; every reader in the kit
* (buildSitemapEntries, buildMetadata/createPageMetadata, buildLlmsTxt,
* searchContent) checks `doc.noindex` (and still tolerates a legacy
* `meta.noindex`). One field, one source of truth, zero project glue.
*
* // collections/Pages.ts
* import { buildNoindexField } from '@intecion/ipal-kit'
* fields: [ /* … *\/ buildNoindexField() ],
*/ export function buildNoindexField(args = {}) {
const { name = 'noindex', description = 'Check to exclude this page from indexing (robots: noindex, follow) and from sitemap.xml.', label = 'Exclude from indexing (noindex)', metaPath = 'meta.noindex', overrides = {} } = args;
const segments = metaPath.split('.');
const mirror = ({ data, value })=>{
const shouldNoindex = Boolean(value ?? readPath(data, segments));
if (data && typeof data === 'object') {
writePath(data, segments, shouldNoindex);
}
return shouldNoindex;
};
const { admin: adminOverrides, hooks: hooksOverrides, ...restOverrides } = overrides;
const { name = 'noindex', description = 'Check to exclude this page from indexing (robots: noindex, follow), the sitemap, llms.txt and site search.', label = 'Exclude from indexing (noindex)', overrides = {} } = args;
const { admin: adminOverrides, ...restOverrides } = overrides;
return {
name,
type: 'checkbox',
@@ -53,14 +27,6 @@
...adminOverrides
},
defaultValue: false,
hooks: {
...hooksOverrides,
// mirror runs first, then any project-supplied beforeChange hooks.
beforeChange: [
mirror,
...hooksOverrides?.beforeChange ?? []
]
},
label,
...restOverrides
};
File diff suppressed because one or more lines are too long
+5 -1
View File
@@ -29,7 +29,11 @@ import { buildHreflangAlternates } from './hreflang.js';
if (doc._status && doc._status !== 'published') {
return false;
}
if (doc.meta?.noindex) {
// Check BOTH the top-level checkbox (buildNoindexField, the field that
// persists) AND meta.noindex — plugin-seo's meta group doesn't declare
// noindex, so a mirror into meta.noindex is stripped on save. Reading both
// makes exclusion automatic regardless of where the flag ended up.
if (doc.noindex || doc.meta?.noindex) {
return false;
}
if (hasExcludedSlug(doc.slug)) {
File diff suppressed because one or more lines are too long
+1
View File
@@ -90,6 +90,7 @@ import { slugsAcrossLocales } from './slugsAcrossLocales.js';
...base,
imageUrl: resolveOgImage(doc),
meta: doc.meta,
noindex: doc.noindex,
pageTitle: doc.title,
prefix,
query,
File diff suppressed because one or more lines are too long
+20 -8
View File
@@ -731,9 +731,9 @@ Alternatywnie: dodaj `noindex` do System Pages o rolach prawnych automatycznie.
### buildNoindexField — przyjazny checkbox w sidebarze
Zamiast własnego checkboxa + hooka z `(data as any).meta.noindex = …` użyj
gotowego pola. Jeden przełącznik dla redaktora, zgrany z `meta.noindex` (to
czyta sitemap i metadata), bez `any`, bez rozjazdu między dwoma miejscami:
Jeden przełącznik w sidebarze. Zaznaczony → strona **automatycznie** wypada z:
`sitemap.xml`, `llms.txt`, wyszukiwarki, i dostaje `robots: noindex, follow` —
bez żadnego ręcznego filtrowania w projekcie.
```ts
import { buildNoindexField } from '@intecion/ipal-kit'
@@ -743,10 +743,22 @@ export const Pages: CollectionConfig = {
}
```
Idempotentne: jeśli ustawiony checkbox LUB istniejące `meta.noindex` — strona
wychodzi `noindex`; nie da się ich rozjechać. Opcje: `name` (domyślnie
`'noindex'`), `label`, `description`, `metaPath` (domyślnie `'meta.noindex'`),
`overrides` (pozycja, access itp.).
**Pole jest top-level (`doc.noindex`), NIE mirrorowane do `meta.noindex`.**
Dlaczego: grupa `meta` z plugin-seo deklaruje tylko title/description/image, więc
Payload przy sanityzacji **po cichu wycina** każdy dodatkowy klucz (`meta.noindex`)
— wcześniejsza wersja mirrorowała tam wartość i znikała, przez co strony noindex
trafiały do sitemapy. Teraz wartość żyje na polu top-level (które się zapisuje), a
wszystkie czytniki kitu (`buildSitemapEntries`, `buildMetadata`/
`createPageMetadata`, `buildLlmsTxt`, `searchContent`) sprawdzają `doc.noindex`
(oraz, dla zgodności wstecznej, ewentualne `meta.noindex`). Jedno pole, jedno
źródło prawdy, zero kleju w projekcie.
Opcje: `name` (domyślnie `'noindex'`), `label`, `description`, `overrides`
(pozycja, access itp.).
> Naprawione w 1.7.5 — wcześniej (mirror do `meta.noindex`) strony noindex
> potrafiły wyciekać do sitemapy. Po aktualizacji `app/sitemap.xml/route.ts`
> wraca do czystej jednolinijki, bez ręcznego filtrowania.
## robots.txt — blokada parametrów (crawl budget)
@@ -1129,4 +1141,4 @@ const speakable = buildSpeakableJsonLd({
W markupie projektu oznacz pasujące elementy (np. `className="speakable"` albo
sekcja `.lead` ze streszczeniem). Selektory nietrafiające w nic są ignorowane —
nie wskazuj nawigacji ani boilerplate'u, tylko samodzielny, czytelny tekst.
Dopełnia Markdown/llms: asystent łatwiej wyciąga kluczową treść strony.
Dopełnia Markdown/llms: asystent łatwiej wyciąga kluczową treść strony.
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@intecion/ipal-kit",
"version": "1.7.4",
"version": "1.7.7",
"description": "Intecion Payload Advanced Library — a Payload CMS 3 plugin: i18n, SEO, forms, consent, analytics, blog/archives.",
"license": "MIT",
"repository": {
+2 -1
View File
@@ -40,6 +40,7 @@ type PageRow = {
_status?: string
id: number | string
meta?: { description?: unknown; noindex?: boolean } | null
noindex?: boolean | null
slug?: unknown
title?: unknown
}
@@ -91,7 +92,7 @@ export async function searchContent({
const results: SearchResult[] = []
for (const doc of docs) {
if (doc._status && doc._status !== 'published') {continue}
if (doc.meta?.noindex) {continue}
if (doc.noindex || doc.meta?.noindex) {continue}
const title = typeof doc.title === 'string' ? doc.title : undefined
const slug = typeof doc.slug === 'string' ? doc.slug : undefined
if (!title || !slug) {continue}
+4 -1
View File
@@ -58,9 +58,12 @@ export function createHealthRoute(args: CreateHealthRouteArgs): () => Promise<Re
status: 200,
})
} catch (err) {
// Log the real error for ops; keep the PUBLIC body generic — a 503 with
// `db: 'down'` is all an orchestrator needs, and raw DB error text (host,
// credentials-in-URL, driver internals) must not leak on a public route.
console.warn('[ipal] createHealthRoute: database unreachable:', err)
const body = {
db: 'down',
error: err instanceof Error ? err.message : 'unknown',
status: 'error',
timestamp: new Date().toISOString(),
tookMs: Date.now() - startedAt,
+5 -1
View File
@@ -187,7 +187,11 @@ export function createMcpRoute(args: CreateMcpRouteArgs) {
if (p.name === 'get_page') {return rpcResult(id, toolText(await getPage(toolArgs)))}
return rpcResult(id, toolText(`Unknown tool: ${p.name}`, true))
} catch (err) {
return rpcResult(id, toolText(err instanceof Error ? err.message : 'Tool error', true))
// Log the real error server-side; return a GENERIC message to the
// (anonymous) caller so internal details — DB schema, host, stack —
// never leak over a public endpoint.
console.warn('[ipal] createMcpRoute: tool execution failed:', err)
return rpcResult(id, toolText('Tool execution failed.', true))
}
}
case 'tools/list':
+3 -2
View File
@@ -42,6 +42,7 @@ type PageRow = {
_status?: string
id: number | string
meta?: { description?: unknown; noindex?: boolean } | null
noindex?: boolean | null
slug?: unknown
title?: unknown
}
@@ -131,7 +132,7 @@ export async function buildLlmsTxt({
const sections: string[] = []
for (const raw of result.docs as PageRow[]) {
if (raw._status && raw._status !== 'published') {continue}
if (raw.meta?.noindex) {continue}
if (raw.noindex || raw.meta?.noindex) {continue}
const title = typeof raw.title === 'string' ? raw.title : undefined
const slug = typeof raw.slug === 'string' ? raw.slug : undefined
@@ -153,7 +154,7 @@ export async function buildLlmsTxt({
const pageLinks: string[] = []
for (const raw of result.docs as PageRow[]) {
if (raw._status && raw._status !== 'published') {continue}
if (raw.meta?.noindex) {continue}
if (raw.noindex || raw.meta?.noindex) {continue}
const title = typeof raw.title === 'string' ? raw.title : undefined
const slug = typeof raw.slug === 'string' ? raw.slug : undefined
+9 -1
View File
@@ -57,6 +57,13 @@ type BuildMetadataArgs = {
locale: string
/** SEO meta from the document (plugin-seo group). */
meta?: null | SeoMeta
/**
* Top-level noindex flag (buildNoindexField). Checked alongside meta.noindex:
* plugin-seo's meta group doesn't declare noindex, so a mirror into
* meta.noindex is stripped on save — the top-level field is the one that
* persists. Either being true emits robots index:false.
*/
noindex?: boolean | null
/** Page title or site name first. Defaults to 'page-first'. */
order?: TitleOrder
/**
@@ -110,6 +117,7 @@ export function buildMetadata({
imageUrl,
locale,
meta,
noindex,
order,
pageTitle,
prefix,
@@ -163,7 +171,7 @@ 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).
...(meta?.noindex
...(noindex || meta?.noindex
? { robots: { follow: true, index: false } }
: {
robots: {
+15 -56
View File
@@ -1,54 +1,29 @@
import type { CheckboxField, Field, FieldHook } from 'payload'
import type { CheckboxField, Field } from 'payload'
type BuildNoindexFieldArgs = {
/** Help text under the checkbox. */
description?: string
/** Sidebar label. Default 'Wyklucz z indeksowania (noindex)'. */
/** Sidebar label. Default 'Exclude from indexing (noindex)'. */
label?: string
/**
* Dotted path, inside the document, that the SEO read path (metadata +
* sitemap) consumes. Default 'meta.noindex' — the plugin-seo `meta` group.
* The checkbox value is mirrored here on every save, so editors toggle one
* friendly switch and the machinery reads a stable location.
*/
metaPath?: string
/** Field name for the editor-facing checkbox. Default 'noindex'. */
name?: string
/** Extend/override the generated checkbox (position, access, etc.). */
overrides?: Partial<CheckboxField>
}
/** Read a dotted path (e.g. 'meta.noindex') off a loosely-typed object. */
function readPath(obj: null | Record<string, unknown> | undefined, path: string[]): unknown {
let cur: unknown = obj
for (const key of path) {
if (cur == null || typeof cur !== 'object') {return undefined}
cur = (cur as Record<string, unknown>)[key]
}
return cur
}
/** Write a dotted path, creating intermediate objects as needed. */
function writePath(obj: Record<string, unknown>, path: string[], value: unknown): void {
let cur: Record<string, unknown> = obj
for (let i = 0; i < path.length - 1; i++) {
const key = path[i]
const next = cur[key]
if (next == null || typeof next !== 'object') {cur[key] = {}}
cur = cur[key] as Record<string, unknown>
}
cur[path[path.length - 1]] = value
}
/**
* A sidebar `noindex` checkbox that mirrors into `meta.noindex` (what the
* sitemap and metadata generators actually read). Replaces the hand-rolled
* checkbox + `beforeChange` hook with its `(data as any).meta.noindex = …`
* glue copied into every project — no `any`, one source of truth for editors,
* one stable read location for the engine.
* A top-level sidebar `noindex` checkbox. When ticked, the page is excluded from
* `sitemap.xml`, `llms.txt`, site search, and gets `robots: noindex, follow` —
* ALL automatically, no per-project filtering.
*
* Idempotent and order-independent: if either the checkbox OR an existing
* `meta.noindex` is set, the page ends up noindex; the two can't drift apart.
* Why top-level (not mirrored into `meta.noindex`): plugin-seo's `meta` group
* declares only title/description/image, so Payload silently strips any extra
* key (`meta.noindex`) during sanitization — an earlier version mirrored there
* and the value vanished, leaking noindex pages into the sitemap. The value now
* lives on this top-level field, which persists; every reader in the kit
* (buildSitemapEntries, buildMetadata/createPageMetadata, buildLlmsTxt,
* searchContent) checks `doc.noindex` (and still tolerates a legacy
* `meta.noindex`). One field, one source of truth, zero project glue.
*
* // collections/Pages.ts
* import { buildNoindexField } from '@intecion/ipal-kit'
@@ -57,23 +32,12 @@ function writePath(obj: Record<string, unknown>, path: string[], value: unknown)
export function buildNoindexField(args: BuildNoindexFieldArgs = {}): Field {
const {
name = 'noindex',
description = 'Check to exclude this page from indexing (robots: noindex, follow) and from sitemap.xml.',
description = 'Check to exclude this page from indexing (robots: noindex, follow), the sitemap, llms.txt and site search.',
label = 'Exclude from indexing (noindex)',
metaPath = 'meta.noindex',
overrides = {},
} = args
const segments = metaPath.split('.')
const mirror: FieldHook = ({ data, value }) => {
const shouldNoindex = Boolean(value ?? readPath(data as Record<string, unknown>, segments))
if (data && typeof data === 'object') {
writePath(data as Record<string, unknown>, segments, shouldNoindex)
}
return shouldNoindex
}
const { admin: adminOverrides, hooks: hooksOverrides, ...restOverrides } = overrides
const { admin: adminOverrides, ...restOverrides } = overrides
return {
name,
@@ -84,11 +48,6 @@ export function buildNoindexField(args: BuildNoindexFieldArgs = {}): Field {
...adminOverrides,
},
defaultValue: false,
hooks: {
...hooksOverrides,
// mirror runs first, then any project-supplied beforeChange hooks.
beforeChange: [mirror, ...(hooksOverrides?.beforeChange ?? [])],
},
label,
...restOverrides,
} as CheckboxField
+7 -1
View File
@@ -52,6 +52,8 @@ type DocRow = {
_status?: string
id: number | string
meta?: { noindex?: boolean } | null
/** Top-level checkbox (buildNoindexField) — the field that actually persists. */
noindex?: boolean | null
slug?: unknown
updatedAt?: string
}
@@ -78,7 +80,11 @@ function hasExcludedSlug(slug: unknown): boolean {
/** Skip drafts, noindex, and system/error pages (404 etc.). */
function isIndexable(doc: DocRow): boolean {
if (doc._status && doc._status !== 'published') {return false}
if (doc.meta?.noindex) {return false}
// Check BOTH the top-level checkbox (buildNoindexField, the field that
// persists) AND meta.noindex — plugin-seo's meta group doesn't declare
// noindex, so a mirror into meta.noindex is stripped on save. Reading both
// makes exclusion automatic regardless of where the flag ended up.
if (doc.noindex || doc.meta?.noindex) {return false}
if (hasExcludedSlug(doc.slug)) {return false}
return true
}
+3
View File
@@ -43,6 +43,8 @@ type PageMetadataContext = {
type DocShape = {
id: number | string
meta?: null | SeoMeta
/** Top-level noindex checkbox (buildNoindexField) — the field that persists. */
noindex?: boolean | null
/** The document's own title (page name), used as the fallback page title. */
title?: null | string
}
@@ -153,6 +155,7 @@ export function createPageMetadata(args: CreatePageMetadataArgs) {
...base,
imageUrl: resolveOgImage(doc),
meta: doc.meta,
noindex: doc.noindex,
pageTitle: doc.title,
prefix,
query,