Opt-outs for the secure defaults; isPathVisibleIn in construction/logic

- setUnknownIpFactor (0 = old free pass), UNKNOWN_IP_FACTOR exported
- createContentHelpers({ settingsDepth }) and markdown/mcp isPathVisible overrides
- <RenderRichText safeLinks={false}>
- resolveRedirect({ draft: true }) for preview
- isPathVisibleIn(mode, path), pathOf, PathVisibility exported; page route uses it

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
Radosław Smoliński
2026-10-22 17:35:08 +02:00
co-authored by Claude Opus 5.5
parent 4585e0fc69
commit 0fd57c1d6a
13 changed files with 144 additions and 24 deletions
+7 -5
View File
@@ -1,3 +1,5 @@
export { applyGlobalOverrides } from './globals/overrides.js'
export type { GlobalOverride, GlobalOverrides, IpalGlobalSlug } from './globals/overrides.js'
export type { AccessOption, Role } from './modules/access/index.js'
export {
adminOnly,
@@ -46,9 +48,11 @@ export {
updateConsent,
} from './modules/consent/index.js'
export type { ConsentCategory, ConsentLogOptions, ConsentState, ConsentTexts, CookieTableRow } from './modules/consent/index.js'
export { constructionNoticeHref, isPathAllowed } from './modules/construction/logic.js'
export { constructionNoticeHref, isPathAllowed, isPathVisibleIn } from './modules/construction/logic.js'
export type { ConstructionMode } from './modules/construction/types.js'
export { CONSTRUCTION_NOTICE_PARAM } from './modules/construction/types.js'
export { pathOf } from './modules/construction/visibility.js'
export type { PathVisibility } from './modules/construction/visibility.js'
export type { ContentCollectionOption, ContentOption, ResolvedRoute } from './modules/content/index.js'
export {
archiveFieldName,
@@ -170,9 +174,9 @@ export type { ExtractHeadingsOptions, HeadingItem, HeadingLevel } from './module
// Lexical → Markdown (pure, no React) — for AI-readable output.
export { lexicalToMarkdown } from './modules/richtext/index.js'
export { buildSecurityHeaders, buildUploadSecurityHeaders } from './modules/security/index.js'
export { buildCsp } from './modules/security/index.js'
export type { BuildCspArgs } from './modules/security/index.js'
export type { BuildSecurityHeadersArgs, SecurityHeader } from './modules/security/index.js'
export type { OgImage } from './modules/seo/buildMetadata.js'
export type { PageMetadata, SeoMeta, SeoOption } from './modules/seo/index.js'
@@ -217,7 +221,7 @@ export { buildArticleJsonLd, buildProductJsonLd, buildWebPageJsonLd, formatOpeni
export { buildLlmsTxt } from './modules/seo/index.js'
export { buildSitemapCss, buildSitemapXml, DEFAULT_SITEMAP_CREDIT, SITEMAP_STYLE_PARAM } from './modules/seo/index.js'
export type { SitemapRouteOptions, SitemapStyleOptions } from './modules/seo/index.js'
export { clientIp, setRateLimitStore } from './modules/shared/rateLimit.js'
export { clientIp, setRateLimitStore, setUnknownIpFactor, UNKNOWN_IP_FACTOR } from './modules/shared/rateLimit.js'
export type { ClientIpOptions, RateLimitStore } from './modules/shared/rateLimit.js'
export { buildSlugField, toSlug } from './modules/slug/index.js'
export { STATS_SLUG } from './modules/stats/index.js'
@@ -233,5 +237,3 @@ export { getTurnstileConfig } from './modules/turnstile/config.js'
export type { TurnstileConfig } from './modules/turnstile/config.js'
export { ipalKit } from './plugin.js'
export type { IpalOptions } from './types.js'
export { applyGlobalOverrides } from './globals/overrides.js'
export type { GlobalOverride, GlobalOverrides, IpalGlobalSlug } from './globals/overrides.js'
+11
View File
@@ -1,3 +1,5 @@
import type { ConstructionMode } from './types.js'
import { CONSTRUCTION_NOTICE_PARAM, CONSTRUCTION_NOTICE_VALUE } from './types.js'
/** `/pl/` → `/pl`, `` → `/` — paths compare without a trailing slash. */
@@ -15,3 +17,12 @@ export function isPathAllowed(pathname: string, allowedPaths: readonly string[])
/** Where a blocked address goes: the homepage with the notice parameter. */
export const constructionNoticeHref = (homePath: string): string =>
`${homePath}?${CONSTRUCTION_NOTICE_PARAM}=${CONSTRUCTION_NOTICE_VALUE}`
/**
* Is this public page path served under this construction mode? True when the
* mode is off or the path is allowed. One rule for the page route, Markdown,
* MCP, search, the sitemap and llms.txt — feed it getConstructionMode(locale).
*/
export function isPathVisibleIn(mode: Pick<ConstructionMode, 'allowedPaths' | 'enabled'>, pathname: string): boolean {
return !mode.enabled || isPathAllowed(pathname, mode.allowedPaths)
}
+7 -1
View File
@@ -25,6 +25,11 @@ type ResolveRedirectArgs = {
*/
collections?: RedirectCollection[]
config: I18nConfig
/**
* Preview (draftMode): also redirect from a never-published draft's old
* slug. Default false — public redirects never reveal a draft's new slug.
*/
draft?: boolean
/** Home slug map/string, so a renamed homepage still collapses to the root. */
homeSlug?: Record<string, string> | string
/** Active locale (the request's locale). */
@@ -66,6 +71,7 @@ type DocShape = { _status?: unknown; slug?: unknown }
export async function resolveRedirect({
collections = [{ slug: 'pages' }],
config,
draft = false,
homeSlug,
locale,
payload,
@@ -93,7 +99,7 @@ export async function resolveRedirect({
// A never-published draft must not be reachable — nor its new slug
// revealed — through a redirect (same rule as resolveRoute).
const status = doc?._status
if (doc && status !== undefined && status !== null && status !== 'published') {continue}
if (!draft && doc && status !== undefined && status !== null && status !== 'published') {continue}
if (doc && typeof doc[slugField as keyof DocShape] === 'string') {
currentSlug = doc[slugField as keyof DocShape] as string
}
+1
View File
@@ -5,6 +5,7 @@ export {
consumeRateLimit,
retryAfterSeconds,
setRateLimitStore,
setUnknownIpFactor,
tooManyRequests,
} from '../shared/rateLimit.js'
export type { ClientIpOptions, RateLimitArgs, RateLimitStore } from '../shared/rateLimit.js'
+12 -8
View File
@@ -16,7 +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 { isPathVisibleIn } 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'
@@ -55,7 +55,7 @@ type CreateContentHelpersArgs = {
*/
i18n?: I18nConfig
/** Markdown route (`markdownRoute`): per-block overrides, frontmatter, layout field. */
markdown?: { frontmatter?: boolean; layoutField?: string; overrides?: Record<string, (block: Record<string, unknown>) => string> }
markdown?: { frontmatter?: boolean; isPathVisible?: PathVisibility; layoutField?: string; overrides?: Record<string, (block: Record<string, unknown>) => string> }
/**
* Advertise each page's Markdown version from generatePageMetadata:
* `<link rel="alternate" type="text/markdown" href="/md/pl/o-nas">` (GEO —
@@ -65,7 +65,7 @@ type CreateContentHelpersArgs = {
*/
markdownAlternate?: boolean | string
/** MCP route (`mcpRoute`): server name/version, rate limit, batch size. */
mcp?: Pick<CreateMcpRouteArgs, 'clientIp' | 'maxBatch' | 'rateLimit' | 'serverName' | 'serverVersion'>
mcp?: Pick<CreateMcpRouteArgs, 'clientIp' | 'isPathVisible' | 'maxBatch' | 'rateLimit' | 'serverName' | 'serverVersion'>
/** Defaults for getPageJsonLd — each call can override them. */
pageJsonLd?: PageJsonLdOptions
/** Pages collection slug. Defaults to 'pages'. */
@@ -78,6 +78,12 @@ type CreateContentHelpersArgs = {
* `{ adminRoute: false }` when the admin path is hidden (ipalKit adminRoute).
*/
robots?: RobotsOptions
/**
* Depth of the Site Settings read behind getSettings / getSiteShell. Default
* 1 (relations as documents, their relations as ids). Raise it only if your
* layout reads deeper — every request pays for it.
*/
settingsDepth?: number
/** SiteSettings global slug. Defaults to 'site-settings'. */
settingsSlug?: string
/**
@@ -171,6 +177,7 @@ export function createContentHelpers({
pagesSlug = 'pages',
redirectCollections,
robots: robotsOptions,
settingsDepth = 1,
settingsSlug = 'site-settings',
siteJsonLd,
sitemapImages,
@@ -198,7 +205,7 @@ export function createContentHelpers({
*/
const getSettings = cache(async (locale: string) => {
const payload = await getCachedPayload()
return payload.findGlobal({ slug: settingsSlug as never, depth: 1, locale: locale as never })
return payload.findGlobal({ slug: settingsSlug as never, depth: settingsDepth, locale: locale as never })
})
/** What does this URL point at? Routing only — no listing data. */
@@ -691,10 +698,7 @@ 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)
}
const isPathVisible: PathVisibility = async (path, locale) => isPathVisibleIn(await getConstructionMode(locale), path)
// ── Layout ────────────────────────────────────────────────────────────────
/** Notifications → form texts in this locale (BuilderForm / RenderForm `texts`). */
+2 -2
View File
@@ -5,7 +5,7 @@ import type { ResolvedRoute } from '../content/index.js'
import type { ContentHelpers, PageJsonLdOptions } from './createContentHelpers.js'
import { RenderBlocks } from '../blocks/RenderBlocks.js'
import { constructionNoticeHref, isPathAllowed } from '../construction/logic.js'
import { constructionNoticeHref, isPathVisibleIn } from '../construction/logic.js'
import { LocaleView } from '../pages/LocaleView.js'
import { NotFoundLoader } from '../pages/NotFoundLoader.js'
import { JsonLdGraph } from '../seo/JsonLdGraph.js'
@@ -116,7 +116,7 @@ export function createPageRoute(helpers: Helpers, options: PageRouteOptions) {
const construction = await helpers.getConstructionMode(locale)
const multilingual = (helpers.i18n?.locales.length ?? 0) > 1
const path = `/${[...(multilingual ? [locale] : []), ...segments].join('/')}`
if (construction.enabled && !isPathAllowed(path, construction.allowedPaths)) {return redirect(constructionNoticeHref(construction.homePath))}
if (!isPathVisibleIn(construction, path)) {return redirect(constructionNoticeHref(construction.homePath))}
}
const route = await helpers.resolveRoute(locale, segments, 1)
if (!route) {
+8 -2
View File
@@ -31,6 +31,12 @@ export type RenderRichTextProps = {
* converter still renders the heading; the id is added to what it returns.
*/
headingIds?: { className?: string; levels?: readonly HeadingLevel[] } | boolean
/**
* Links whose URL isn't a safe target (`javascript:`, `data:`…) render as
* '#'. Default true; `false` renders stored URLs as they are (only for
* content you fully trust).
*/
safeLinks?: boolean
}
type HeadingNode = { children?: unknown[]; tag: HeadingLevel }
@@ -97,10 +103,10 @@ function withHeadingIds(
* <TableOfContents items={extractHeadings(page.content)} label={toc.label} /> // /client
* <RenderRichText data={page.content} headingIds={{ className: 'scroll-mt-24' }} />
*/
export function RenderRichText({ className, converters, data: raw, headingIds }: RenderRichTextProps) {
export function RenderRichText({ className, converters, data: raw, headingIds, safeLinks = true }: RenderRichTextProps) {
if (!raw) {return null}
// javascript:/data: link URLs from stored content never reach an href
const data = sanitizeRichTextLinks(raw)
const data = safeLinks ? sanitizeRichTextLinks(raw) : raw
if (headingIds) {
const opts = headingIds === true ? {} : headingIds
const ids = computeHeadingIds(data, opts.levels ? { levels: opts.levels } : {})
+23 -5
View File
@@ -77,10 +77,24 @@ type CheckArgs = { cost?: number } & RateLimitArgs
* capping the flood.
*/
export const UNKNOWN_IP_KEY = 'unknown-ip'
/** Default multiplier for the shared no-IP bucket. */
export const UNKNOWN_IP_FACTOR = 20
function resolveKey(key: string, max: number): { key: string; max: number } {
return key ? { key, max } : { key: UNKNOWN_IP_KEY, max: max * UNKNOWN_IP_FACTOR }
let unknownIpFactor = UNKNOWN_IP_FACTOR
/**
* How requests with no client IP are limited, for every limiter in the plugin:
* the shared bucket's limit is `factor` × max. `0` = let them through
* unlimited (the behaviour before 1.13 — only when a limiter in front, e.g.
* Cloudflare, already covers them). Default UNKNOWN_IP_FACTOR.
*/
export function setUnknownIpFactor(factor: number): void {
unknownIpFactor = Math.max(0, factor)
}
function resolveKey(key: string, max: number): { key: string; max: number } | null {
if (key) {return { key, max }}
return unknownIpFactor > 0 ? { key: UNKNOWN_IP_KEY, max: max * unknownIpFactor } : null
}
function hitMemory(id: string, cost: number, windowMs: number): Bucket {
@@ -102,10 +116,12 @@ function hitMemory(id: string, cost: number, windowMs: number): Bucket {
*
* Returns true when the request is within the limit, false when it should be
* rejected. A missing key (no IP) counts against one shared bucket with
* UNKNOWN_IP_FACTOR × max.
* UNKNOWN_IP_FACTOR × max (setUnknownIpFactor).
*/
export function checkRateLimit({ cost = 1, key: rawKey, max: rawMax = 5, scope = 'form', windowMs = 60_000 }: CheckArgs): boolean {
const { key, max } = resolveKey(rawKey, rawMax)
const resolved = resolveKey(rawKey, rawMax)
if (!resolved) {return true}
const { key, max } = resolved
const id = `${scope}:${key}`
const current = buckets.get(id)
const used = current && current.resetAt > Date.now() ? current.count : 0
@@ -127,7 +143,9 @@ export async function consumeRateLimit({
scope = 'form',
windowMs = 60_000,
}: CheckArgs): Promise<{ ok: boolean; retryAfter: number }> {
const { key, max } = resolveKey(rawKey, rawMax)
const resolved = resolveKey(rawKey, rawMax)
if (!resolved) {return { ok: true, retryAfter: 0 }}
const { key, max } = resolved
const id = `${scope}:${key}`
let bucket: Bucket
+31 -1
View File
@@ -7,7 +7,7 @@ import path from 'node:path'
import { buildConfig, getPayload } from 'payload'
import { afterAll, beforeAll, describe, expect, test, vi } from 'vitest'
import { constructionNoticeHref, isPathAllowed, normalizePath } from '../src/modules/construction/logic.js'
import { constructionNoticeHref, isPathAllowed, isPathVisibleIn, normalizePath } from '../src/modules/construction/logic.js'
import { createContentHelpers } from '../src/modules/frontend/createContentHelpers.js'
import { createPageRoute } from '../src/modules/frontend/pageRoute.js'
import { ipalKit } from '../src/plugin.js'
@@ -22,6 +22,12 @@ describe('under construction — path logic', () => {
expect(isPathAllowed('/pl/o-nas', ['/pl', '/pl/brief'])).toBe(false)
expect(constructionNoticeHref('/pl')).toBe('/pl?notice=construction')
})
test('isPathVisibleIn: off → everything; on → allowed paths only', () => {
expect(isPathVisibleIn({ allowedPaths: [], enabled: false }, '/pl/o-nas')).toBe(true)
expect(isPathVisibleIn({ allowedPaths: ['/pl', '/pl/brief'], enabled: true }, '/pl/brief/')).toBe(true)
expect(isPathVisibleIn({ allowedPaths: ['/pl', '/pl/brief'], enabled: true }, '/pl/o-nas')).toBe(false)
})
})
describe('under construction — Site Settings → createPageRoute', () => {
@@ -116,3 +122,27 @@ describe('under construction — Site Settings → createPageRoute', () => {
expect(await helpers.isPathVisible('/pl/brief', 'pl')).toBe(true)
})
})
describe('under construction — opting out per route', () => {
test('a project can pass its own isPathVisible to Markdown / MCP', async () => {
const { createMcpRoute } = await import('../src/modules/mcp/createMcpRoute.js')
const seen: string[] = []
const mcp = createMcpRoute({
config: { defaultLocale: 'pl', locales: [{ code: 'pl', label: 'PL' }, { code: 'en', label: 'EN' }] },
getCachedPayload: async () => ({}) as never,
isPathVisible: (path) => {
seen.push(path)
return false
},
rateLimit: false,
})
const res = await mcp.POST(
new Request('https://x/api/mcp', {
body: JSON.stringify({ id: 1, jsonrpc: '2.0', method: 'tools/call', params: { name: 'get_page', arguments: { path: '/pl/o-nas' } } }),
method: 'POST',
}),
)
expect(JSON.stringify(await res.json())).toContain('No page found')
expect(seen).toEqual(['/pl/o-nas'])
})
})
+8
View File
@@ -5,6 +5,7 @@ import {
clientIp,
consumeRateLimit,
setRateLimitStore,
setUnknownIpFactor,
UNKNOWN_IP_FACTOR,
} from '../src/modules/shared/rateLimit.js'
@@ -65,6 +66,13 @@ describe('checkRateLimit (in memory)', () => {
expect(checkRateLimit({ cost: 4, key: `k-${Math.random()}`, max: 3 })).toBe(false)
})
test('setUnknownIpFactor(0) restores the old free pass; the default comes back', () => {
setUnknownIpFactor(0)
expect(checkRateLimit({ key: '', max: 0, scope: `z-${Math.random()}` })).toBe(true)
setUnknownIpFactor(UNKNOWN_IP_FACTOR)
expect(checkRateLimit({ key: '', max: 0, scope: `z-${Math.random()}` })).toBe(false)
})
test('no key → one shared bucket with a roomier limit, not a free pass', () => {
const scope = `s-${Math.random()}`
for (let i = 0; i < 2 * UNKNOWN_IP_FACTOR; i++) {expect(checkRateLimit({ key: '', max: 2, scope })).toBe(true)}
+5
View File
@@ -18,6 +18,11 @@ describe('old-slug redirects and drafts', () => {
expect(await resolveRedirect({ config, locale: 'pl', payload, segments: ['oferta'] })).toBeNull()
})
test('draft: true (preview) redirects drafts too', async () => {
const payload = payloadWith({ slug: 'tajny-projekt', _status: 'draft' })
expect(await resolveRedirect({ config, draft: true, locale: 'pl', payload, segments: ['oferta'] })).toBe('/tajny-projekt')
})
test('collections without drafts still redirect', async () => {
const payload = payloadWith({ slug: 'kontakt-2' })
expect(await resolveRedirect({ config, locale: 'pl', payload, segments: ['kontakt'] })).toBe('/kontakt-2')
+21
View File
@@ -28,3 +28,24 @@ describe('rich text links', () => {
expect(out.root.children[0].children[0]).toBe(d.root.children[0].children[0])
})
})
describe('RenderRichText', () => {
const state = {
root: {
type: 'root', children: [{ type: 'paragraph', children: [{ type: 'link', children: [{ type: 'text', detail: 0, format: 0, mode: 'normal', style: '', text: 'klik', version: 1 }], fields: { linkType: 'custom', url: 'data:text/html,<script>alert(1)</script>' }, version: 3 }], version: 1 }],
direction: null, format: '', indent: 0, version: 1,
},
}
// React 19 already blocks javascript: hrefs; data: URLs it renders as is.
test('renders unsafe links as # by default; safeLinks={false} keeps them', async () => {
const { renderToStaticMarkup } = await import('react-dom/server')
const { createElement } = await import('react')
const { RenderRichText } = await import('../src/modules/richtext/RenderRichText.js')
const html = renderToStaticMarkup(createElement(RenderRichText, { data: state as never }))
expect(html).toContain('href="#"')
expect(html).not.toContain('data:')
const raw = renderToStaticMarkup(createElement(RenderRichText, { data: state as never, safeLinks: false }))
expect(raw).toContain('href="data:text/html')
})
})
+8
View File
@@ -82,3 +82,11 @@ describe('Site Settings depth', () => {
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' })
})
})