Construction mode hides pages from Markdown, MCP and search; MCP rejects non-object messages

createContentHelpers exposes isPathVisible (built from getConstructionMode)
and passes it to markdownRoute and mcpPOST; createSearchRoute,
createMcpRoute and createMarkdownRoute accept it. A null/number/string
JSON-RPC message now gets -32600 instead of crashing the route.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
Radosław Smoliński
2026-10-22 17:07:45 +02:00
co-authored by Claude Opus 5.5
parent 9a72ebfaff
commit 7c05a1dba9
11 changed files with 116 additions and 13 deletions
+4
View File
@@ -25,6 +25,10 @@ normalne działanie strony.
`next/link`) i pokazuje popup. Linki zewnętrzne, kotwice na tej samej stronie, `target="_blank"`
i kliknięcia z modyfikatorem (Ctrl/⌘) działają normalnie.
- Po przekierowaniu popup otwiera się raz, a parametr znika z paska adresu.
- **Markdown i MCP** z `createContentHelpers` (`markdownRoute`, `mcpPOST`) ukrywają te same strony:
`/md/…` → 404, `list_pages` / `search_content` ich nie pokazują, `get_page` → „No page found”.
Własny `createSearchRoute` / `createMcpRoute` / `createMarkdownRoute` → przekaż
`isPathVisible` z `lib/content` (`createSearchRoute({ …, isPathVisible })`).
- **Jedna reguła dla wszystkich odwiedzających** — strony zostają statyczne (ISR), bez sprawdzania
sesji. Po zmianie ustawień strony odświeżają się po rewalidacji (jak inne zmiany w Site Settings).
+2 -1
View File
@@ -330,7 +330,8 @@ Query: `?q=` (wymagane), `?locale=`, `?limit=`. Odpowiedź:
"results": [{ "title": "O nas", "url": "https://x/pl/o-nas", "description": "…", "slug": "o-nas" }] }
```
Brak `q` → 400. Tylko opublikowane, bez `noindex`, maks. 50 wyników. Błąd/baza
Brak `q` → 400. Tylko opublikowane, bez `noindex`, maks. 50 wyników. Tryb „w budowie”:
przekaż `isPathVisible` z `createContentHelpers`, a ukryte strony znikną z wyników. Błąd/baza
offline → pusty wynik (200), nie 500. **Limit zapytań:** 120/min na IP (w pamięci,
per instancja) → `429` z `Retry-After`; zmiana: `rateLimit: { max, windowMs }`,
wyłączenie (limiter z przodu, np. Cloudflare WAF): `rateLimit: false`.
+2 -1
View File
@@ -85,6 +85,7 @@ wykona `initialize` → `tools/list` → i będzie mógł wołać `get_site_info
Pojedynczy obiekt JSON-RPC albo batch (tablica). Notyfikacje (`notifications/*`,
bez `id`) → HTTP 202 bez ciała. Żądania → `{ jsonrpc:'2.0', id, result }` albo
`error` (`-32601` nieznana metoda, `-32700` parse error, `-32600` batch za duży,
`error` (`-32601` nieznana metoda, `-32700` parse error, `-32600` batch za duży albo wiadomość,
która nie jest obiektem — `null`, liczba, tekst;
`-32000` limit zapytań). `initialize` odbija
`protocolVersion` klienta (fallback `2025-06-18`).
+10
View File
@@ -0,0 +1,10 @@
/**
* Is this public page path served right now? createContentHelpers builds it from
* Site Settings → Under construction (`isPathVisible`), so the Markdown, MCP and
* search routes hide exactly what the page route hides. Paths are page paths as
* a visitor sees them ('/pl/o-nas', or '/o-nas' on a single-language site).
*/
export type PathVisibility = (path: string, locale: string) => boolean | Promise<boolean>
/** Pathname of a result URL (absolute or relative), for a PathVisibility check. */
export const pathOf = (url: string): string => new URL(url, 'http://localhost').pathname
+12 -2
View File
@@ -1,5 +1,6 @@
import type { BasePayload } from 'payload'
import type { PathVisibility } from '../construction/visibility.js'
import type { ContentOption } from './types.js'
import { blocksToMarkdown } from './blocksToMarkdown.js'
@@ -187,14 +188,23 @@ function routeOf(
* (details only in the server log).
*/
export function createMarkdownRoute(
args: { getCachedPayload: () => Promise<BasePayload> } & CreateMarkdownRendererArgs,
args: {
getCachedPayload: () => Promise<BasePayload>
/** Hide pages the site hides (construction mode) — 404 like an unknown page. */
isPathVisible?: PathVisibility
} & CreateMarkdownRendererArgs,
): { GET: (req: Request, ctx: MarkdownRouteContext) => Promise<Response> } {
const { getCachedPayload, ...rendererArgs } = args
const { getCachedPayload, isPathVisible, ...rendererArgs } = args
const render = createMarkdownRenderer(rendererArgs)
return {
GET: async (_req, { params }) => {
try {
const { slug, locale } = routeOf(await params, rendererArgs.config)
if (isPathVisible) {
const multilingual = (rendererArgs.config?.locales.length ?? 0) > 1
const path = `/${[...(multilingual ? [locale] : []), ...(slug ?? [])].join('/')}`
if (!(await isPathVisible(path, locale))) {return markdownResponse(null, {})}
}
const md = await render({ slug, locale, payload: await getCachedPayload() })
return markdownResponse(md, { canonical: canonicalOf(rendererArgs.baseUrl, rendererArgs.config, locale, slug) })
} catch (err) {
+8 -2
View File
@@ -3,6 +3,7 @@ import type { BasePayload } from 'payload'
import type { I18nConfig } from '../i18n/index.js'
import type { ClientIpOptions } from '../shared/rateLimit.js'
import { type PathVisibility, pathOf } from '../construction/visibility.js'
import { clientIp, consumeRateLimit, tooManyRequests } from '../shared/rateLimit.js'
import { searchContent } from './searchContent.js'
@@ -26,6 +27,8 @@ type CreateSearchRouteArgs = {
rateLimit?: { max?: number; windowMs?: number } | false
/** Field holding a richer AI summary (buildSummaryField) to prefer as description. */
summaryField?: string
/** Hide pages the site hides (construction mode) — pass `isPathVisible` from createContentHelpers. */
isPathVisible?: PathVisibility
}
/**
@@ -47,7 +50,7 @@ type CreateSearchRouteArgs = {
* Uses the global Request/Response — no next/server import.
*/
export function createSearchRoute(args: CreateSearchRouteArgs): (req: Request) => Promise<Response> {
const { baseUrl, collection = 'pages', config, defaultLimit = 10, getCachedPayload, homeSlug, summaryField } = args
const { baseUrl, collection = 'pages', config, defaultLimit = 10, getCachedPayload, homeSlug, isPathVisible, summaryField } = args
// 120/min: a debounced search-as-you-type box stays well under it; a scraper doesn't.
const rl = args.rateLimit === false ? null : { max: 120, windowMs: 60_000, ...args.rateLimit }
@@ -73,7 +76,7 @@ export function createSearchRoute(args: CreateSearchRouteArgs): (req: Request) =
try {
const payload = await getCachedPayload()
const results = await searchContent({
const found = await searchContent({
baseUrl,
collection,
config,
@@ -84,6 +87,9 @@ export function createSearchRoute(args: CreateSearchRouteArgs): (req: Request) =
query,
summaryField,
})
const shownLocale = locale ?? config.defaultLocale
const keep = isPathVisible ? await Promise.all(found.map((r) => isPathVisible(pathOf(r.url), shownLocale))) : null
const results = keep ? found.filter((_, i) => keep[i]) : found
return Response.json(
{ count: results.length, locale: locale ?? config.defaultLocale, query, results },
{ headers: { 'cache-control': 'public, max-age=0, s-maxage=60, stale-while-revalidate=600' } },
+1 -1
View File
@@ -110,7 +110,7 @@ export async function submitForm({
// 1. Rate limit — cheapest gate, drops a flood before any real work.
// No IP → the limiter's shared "unknown" bucket, never a free pass.
if (maxPerMinute > 0) {
if (!(await consumeRateLimit({ key: ip, max: maxPerMinute })).ok) {
if (!(await consumeRateLimit({ key: ip ?? '', max: maxPerMinute })).ok) {
return { reason: 'rate_limited', success: false }
}
}
+14 -2
View File
@@ -6,6 +6,7 @@ import { cache } from 'react'
import type { AnalyticsConfig } from '../analytics/types.js'
import type { ConsentTexts } from '../consent/texts.js'
import type { ConstructionMode } from '../construction/types.js'
import type { PathVisibility } from '../construction/visibility.js'
import type { ArchiveEntries, ContentOption, ResolvedRoute } from '../content/index.js'
import type { I18nConfig } from '../i18n/index.js'
import type { LinkValue, NavItem, ResolvedLink, ResolveLinkHrefOptions, SystemLink } from '../links/index.js'
@@ -15,6 +16,7 @@ import type { PageMetadata, RobotsOptions, RobotsRules, SitemapEntry, SitemapSty
import { getAnalyticsConfig } from '../analytics/getAnalyticsConfig.js'
import { getConsentTexts } from '../consent/getConsentTexts.js'
import { isPathAllowed } from '../construction/logic.js'
import { createMarkdownRoute } from '../content/createMarkdownRenderer.js'
import { getArchiveEntries, resolveRoute as resolveRouteRaw } from '../content/index.js'
import { MARKDOWN_PREFIX, markdownHref } from '../content/markdownNegotiation.js'
@@ -685,6 +687,15 @@ export function createContentHelpers({
}
})
/**
* Is this page path public right now? False for pages construction mode
* hides. The Markdown and MCP routes use it; pass it to createSearchRoute.
*/
const isPathVisible: PathVisibility = async (path, locale) => {
const construction = await getConstructionMode(locale)
return !construction.enabled || isPathAllowed(path, construction.allowedPaths)
}
// ── Layout ────────────────────────────────────────────────────────────────
/** Notifications → form texts in this locale (BuilderForm / RenderForm `texts`). */
const getFormTexts = cache(async (locale: string): Promise<FormNotificationTexts> =>
@@ -737,8 +748,8 @@ export function createContentHelpers({
}
const llms = lazy(() => createLlmsTxtRoute({ baseUrl: origin, config: needI18n('llmsRoute'), content, getCachedPayload, pagesSlug, settingsSlug, summaryField }))
const llmsFull = lazy(() => createLlmsTxtRoute({ baseUrl: origin, config: needI18n('llmsFullRoute'), content, full: true, getCachedPayload, pagesSlug, settingsSlug, summaryField }))
const md = lazy(() => createMarkdownRoute({ baseUrl: origin || undefined, collection: pagesSlug, config: i18n, content, getCachedPayload, settingsSlug, ...markdownOptions }))
const mcp = lazy(() => createMcpRoute({ baseUrl: origin, collection: pagesSlug, config: needI18n('mcpRoute'), content, getCachedPayload, settingsSlug, summaryField, ...mcpOptions }))
const md = lazy(() => createMarkdownRoute({ baseUrl: origin || undefined, collection: pagesSlug, config: i18n, content, getCachedPayload, isPathVisible, settingsSlug, ...markdownOptions }))
const mcp = lazy(() => createMcpRoute({ baseUrl: origin, collection: pagesSlug, config: needI18n('mcpRoute'), content, getCachedPayload, isPathVisible, settingsSlug, summaryField, ...mcpOptions }))
const health = lazy(() => createHealthRoute({ collection: pagesSlug, getCachedPayload }))
const indexNowKey = lazy(() => createIndexNowKeyRoute({ getCachedPayload }))
const manifestHandler = lazy(() => createManifestHandler({ config: needI18n('manifest'), getCachedPayload, settingsSlug }))
@@ -765,6 +776,7 @@ export function createContentHelpers({
getCachedPayload,
getConfiguredLocales,
getConstructionMode,
isPathVisible,
getEntries,
getFormTexts,
getHomeSlug,
+25 -4
View File
@@ -1,9 +1,11 @@
import type { BasePayload } from 'payload'
import type { PathVisibility } from '../construction/visibility.js'
import type { ContentOption } from '../content/index.js'
import type { I18nConfig } from '../i18n/index.js'
import type { ClientIpOptions } from '../shared/rateLimit.js'
import { pathOf } from '../construction/visibility.js'
import { createMarkdownRenderer, searchContent } from '../content/index.js'
import { getDefaultLocale, isValidLocale } from '../i18n/index.js'
import { readSiteMetaConfig } from '../seo/readSiteMetaConfig.js'
@@ -72,6 +74,11 @@ export type CreateMcpRouteArgs = {
settingsSlug?: string
/** Field holding a richer AI summary (buildSummaryField) to prefer in search results. */
summaryField?: string
/**
* Hide pages the site hides (construction mode): filtered out of list_pages
* and search_content, "not found" in get_page. createContentHelpers passes it.
*/
isPathVisible?: PathVisibility
}
type JsonRpcId = null | number | string
@@ -95,6 +102,7 @@ export function createMcpRoute(args: CreateMcpRouteArgs) {
config,
content,
getCachedPayload,
isPathVisible,
maxBatch = 10,
serverName = 'ipal-site',
serverVersion = '1.0.0',
@@ -160,6 +168,13 @@ export function createMcpRoute(args: CreateMcpRouteArgs) {
? params.locale
: getDefaultLocale(config)
/** Drops results whose page is hidden right now (construction mode). */
async function visible<T extends { url: string }>(items: T[], locale: string): Promise<T[]> {
if (!isPathVisible) {return items}
const keep = await Promise.all(items.map((item) => isPathVisible(pathOf(item.url), locale)))
return items.filter((_, i) => keep[i])
}
const formatResults = (results: { description?: string; title: string; url: string }[]) =>
results.map((r) => `- ${r.title} (${r.url})${r.description ? ` — ${r.description}` : ''}`).join('\n')
@@ -193,7 +208,7 @@ export function createMcpRoute(args: CreateMcpRouteArgs) {
const limit = Math.min(Math.max(Math.trunc(typeof params.limit === 'number' ? params.limit : 50) || 50, 1), 200)
const payload = await getCachedPayload()
// Same index as llms.txt and the sitemap rules: pages AND archive entries (blog…).
const index = await collectSiteIndex({
const index = await visible(await collectSiteIndex({
baseUrl: origin,
config,
content,
@@ -202,7 +217,7 @@ export function createMcpRoute(args: CreateMcpRouteArgs) {
payload,
settingsSlug,
summaryField,
})
}), locale)
if (index.length === 0) {return 'No published pages.'}
const shown = index.slice(0, limit)
const lines = shown.map(
@@ -221,7 +236,7 @@ export function createMcpRoute(args: CreateMcpRouteArgs) {
const payload = await getCachedPayload()
const meta = await siteMeta(payload, locale)
// Shared with the JSON search route — one ranking everywhere.
const results = await searchContent({
const results = await visible(await searchContent({
baseUrl: origin,
collection,
config,
@@ -231,7 +246,7 @@ export function createMcpRoute(args: CreateMcpRouteArgs) {
payload,
query,
summaryField,
})
}), locale)
if (results.length === 0) {return `No pages matched "${query}".`}
return formatResults(results)
}
@@ -246,12 +261,18 @@ export function createMcpRoute(args: CreateMcpRouteArgs) {
locale = segments[0]
slug = segments.slice(1)
}
if (isPathVisible) {
const path = `/${[...(config.locales.length > 1 ? [locale] : []), ...slug].join('/')}`
if (!(await isPathVisible(path, locale))) {return `No page found at ${raw}.`}
}
const payload = await getCachedPayload()
const md = await renderMarkdown({ slug, locale, payload })
return md ?? `No page found at ${raw}.`
}
async function handleOne(msg: JsonRpcRequest): Promise<null | object> {
// `null`, a number, a string… is not a JSON-RPC request — answer, don't crash.
if (!msg || typeof msg !== 'object' || Array.isArray(msg)) {return rpcError(null, -32600, 'Invalid Request')}
const { id = null, method, params } = msg
// Notifications (no id) get no response body.
+28
View File
@@ -87,4 +87,32 @@ describe('under construction — Site Settings → createPageRoute', () => {
await expect(open('pl', ['o-nas'])).rejects.toThrow('REDIRECT /pl?notice=construction')
await expect(open('pl', ['nie-ma'])).rejects.toThrow('REDIRECT /pl?notice=construction')
})
test('on: Markdown, MCP and search hide the same pages the page route hides', async () => {
const helpers = createContentHelpers({ baseUrl: 'https://acme.pl', config: configPromise, i18n })
expect((await helpers.getConstructionMode('pl')).enabled).toBe(true)
const md = (slug: string[]) => helpers.markdownRoute(new Request('https://acme.pl/md'), { params: Promise.resolve({ locale: 'pl', slug }) })
expect((await md(['o-nas'])).status).toBe(404)
expect((await md(['brief'])).status).toBe(200)
const rpc = async (name: string, args: Record<string, unknown>) => {
const res = await helpers.mcpPOST(
new Request('https://acme.pl/api/mcp', {
body: JSON.stringify({ id: 1, jsonrpc: '2.0', method: 'tools/call', params: { arguments: args, name } }),
headers: { 'content-type': 'application/json', 'x-real-ip': '198.51.100.4' },
method: 'POST',
}),
)
return ((await res.json()) as { result: { content: { text: string }[] } }).result.content[0].text
}
const list = await rpc('list_pages', { locale: 'pl' })
expect(list).toContain('/pl/brief')
expect(list).not.toContain('/pl/o-nas')
expect(await rpc('get_page', { path: '/pl/o-nas' })).toMatch(/No page found/)
expect(await rpc('search_content', { locale: 'pl', query: 'nas' })).not.toContain('/pl/o-nas')
expect(await helpers.isPathVisible('/pl/o-nas', 'pl')).toBe(false)
expect(await helpers.isPathVisible('/pl/brief', 'pl')).toBe(true)
})
})
+10
View File
@@ -104,6 +104,16 @@ describe('createMcpRoute', () => {
expect((await mcp.GET()).status).toBe(405)
})
test('a null, number or string message gets Invalid Request, not a 500', async () => {
for (const body of [null, 42, 'x']) {
const res = await rpc(body)
expect(res.status).toBe(200)
expect(res.body.error.code).toBe(-32600)
}
const batch = await rpc([null, { id: 2, jsonrpc: '2.0', method: 'ping' }])
expect(batch.body.map((m: { error?: { code: number } }) => m.error?.code ?? 'ok')).toEqual([-32600, 'ok'])
})
test('rate limit counts every message in a batch', async () => {
const ip = '10.9.9.9'
const batch = Array.from({ length: 10 }, (_, i) => ({ id: i, jsonrpc: '2.0', method: 'ping' }))