From 0fd57c1d6a08d8a548a0abec400ad4cfe1c5dd61 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rados=C5=82aw=20Smoli=C5=84ski?= Date: Thu, 22 Oct 2026 17:35:08 +0200 Subject: [PATCH] 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 - - resolveRedirect({ draft: true }) for preview - isPathVisibleIn(mode, path), pathOf, PathVisibility exported; page route uses it Co-Authored-By: Claude Opus 5.5 --- src/index.ts | 12 +++++--- src/modules/construction/logic.ts | 11 +++++++ src/modules/content/resolveRedirect.ts | 8 ++++- src/modules/forms/rateLimit.ts | 1 + src/modules/frontend/createContentHelpers.ts | 20 +++++++----- src/modules/frontend/pageRoute.tsx | 4 +-- src/modules/richtext/RenderRichText.tsx | 10 ++++-- src/modules/shared/rateLimit.ts | 28 ++++++++++++++--- test/construction.test.ts | 32 +++++++++++++++++++- test/rateLimit.test.ts | 8 +++++ test/redirectDrafts.test.ts | 5 +++ test/richTextLinks.test.ts | 21 +++++++++++++ test/settingsDepth.test.ts | 8 +++++ 13 files changed, 144 insertions(+), 24 deletions(-) diff --git a/src/index.ts b/src/index.ts index 0659f34..be2efe6 100644 --- a/src/index.ts +++ b/src/index.ts @@ -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' diff --git a/src/modules/construction/logic.ts b/src/modules/construction/logic.ts index cd0a4cc..ebec881 100644 --- a/src/modules/construction/logic.ts +++ b/src/modules/construction/logic.ts @@ -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, pathname: string): boolean { + return !mode.enabled || isPathAllowed(pathname, mode.allowedPaths) +} diff --git a/src/modules/content/resolveRedirect.ts b/src/modules/content/resolveRedirect.ts index ac03f4b..653146d 100644 --- a/src/modules/content/resolveRedirect.ts +++ b/src/modules/content/resolveRedirect.ts @@ -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 /** 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 } diff --git a/src/modules/forms/rateLimit.ts b/src/modules/forms/rateLimit.ts index 9ac2d97..bb1505e 100644 --- a/src/modules/forms/rateLimit.ts +++ b/src/modules/forms/rateLimit.ts @@ -5,6 +5,7 @@ export { consumeRateLimit, retryAfterSeconds, setRateLimitStore, + setUnknownIpFactor, tooManyRequests, } from '../shared/rateLimit.js' export type { ClientIpOptions, RateLimitArgs, RateLimitStore } from '../shared/rateLimit.js' diff --git a/src/modules/frontend/createContentHelpers.ts b/src/modules/frontend/createContentHelpers.ts index 25094e7..12ac2a4 100644 --- a/src/modules/frontend/createContentHelpers.ts +++ b/src/modules/frontend/createContentHelpers.ts @@ -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> } + markdown?: { frontmatter?: boolean; isPathVisible?: PathVisibility; layoutField?: string; overrides?: Record) => string> } /** * Advertise each page's Markdown version from generatePageMetadata: * `` (GEO — @@ -65,7 +65,7 @@ type CreateContentHelpersArgs = { */ markdownAlternate?: boolean | string /** MCP route (`mcpRoute`): server name/version, rate limit, batch size. */ - mcp?: Pick + mcp?: Pick /** 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`). */ diff --git a/src/modules/frontend/pageRoute.tsx b/src/modules/frontend/pageRoute.tsx index 35120cb..9a64645 100644 --- a/src/modules/frontend/pageRoute.tsx +++ b/src/modules/frontend/pageRoute.tsx @@ -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) { diff --git a/src/modules/richtext/RenderRichText.tsx b/src/modules/richtext/RenderRichText.tsx index e29cf16..321fc84 100644 --- a/src/modules/richtext/RenderRichText.tsx +++ b/src/modules/richtext/RenderRichText.tsx @@ -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( * // /client * */ -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 } : {}) diff --git a/src/modules/shared/rateLimit.ts b/src/modules/shared/rateLimit.ts index 39c9fe8..ea1c202 100644 --- a/src/modules/shared/rateLimit.ts +++ b/src/modules/shared/rateLimit.ts @@ -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 diff --git a/test/construction.test.ts b/test/construction.test.ts index b1878c6..51ac158 100644 --- a/test/construction.test.ts +++ b/test/construction.test.ts @@ -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']) + }) +}) diff --git a/test/rateLimit.test.ts b/test/rateLimit.test.ts index d727618..afdf8dd 100644 --- a/test/rateLimit.test.ts +++ b/test/rateLimit.test.ts @@ -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)} diff --git a/test/redirectDrafts.test.ts b/test/redirectDrafts.test.ts index 79575ff..a420226 100644 --- a/test/redirectDrafts.test.ts +++ b/test/redirectDrafts.test.ts @@ -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') diff --git a/test/richTextLinks.test.ts b/test/richTextLinks.test.ts index 9329d1a..8d0b77e 100644 --- a/test/richTextLinks.test.ts +++ b/test/richTextLinks.test.ts @@ -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,' }, version: 3 }], version: 1 }], + direction: null, format: '', indent: 0, version: 1, + }, + } + + // React 19 already blocks javascript: hrefs; data: URLs it renders as is. + test('renders unsafe links as # by default; safeLinks={false} keeps them', async () => { + const { renderToStaticMarkup } = await import('react-dom/server') + const { createElement } = await import('react') + const { RenderRichText } = await import('../src/modules/richtext/RenderRichText.js') + const html = renderToStaticMarkup(createElement(RenderRichText, { data: state as never })) + expect(html).toContain('href="#"') + expect(html).not.toContain('data:') + const raw = renderToStaticMarkup(createElement(RenderRichText, { data: state as never, safeLinks: false })) + expect(raw).toContain('href="data:text/html') + }) +}) diff --git a/test/settingsDepth.test.ts b/test/settingsDepth.test.ts index fe6b392..d59dbd5 100644 --- a/test/settingsDepth.test.ts +++ b/test/settingsDepth.test.ts @@ -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' }) + }) +})