Files
ipal-kit/src/modules/content/resolveRoute.ts
T
radoslaw.smolinskiandClaude Opus 5.5 9e49856611 Security review: drafts no longer public, submissions staff-only, safe links, upload sandbox
- Fix: resolveRoute served never-published drafts by URL (Payload's find
  returns them with _status 'draft') — also via Markdown, MCP get_page and
  metadata. Drafts are dropped on every branch; `draft: true` for previews.
- Fix: getArchiveEntries listed drafts in archive pages despite its comment;
  `_status: published` is added automatically when the collection has drafts.
- form-submissions readable only by editor+ (form-builder default: any account
  of the admin collection, incl. plain users from an open sign-up); delete admin.
- Forms stay public for rendering, but the Emails tab (recipients) is hidden
  from anonymous REST reads.
- safeHref: CMS links only http(s), mailto, tel, sms, #, / — javascript:, data:
  and control-character tricks are dropped in resolveLinkHref.
- Analytics IDs validated in the panel and before reaching the browser.
- buildUploadSecurityHeaders: sandbox CSP for /api/<upload>/file/* so an
  uploaded SVG can't run script on the site's origin.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-16 03:06:26 +02:00

213 lines
7.3 KiB
TypeScript

import type { BasePayload } from 'payload'
import type { ContentOption } from './types.js'
import { archiveFieldName } from './types.js'
type ArchivePage = { id: number | string; slug?: unknown }
export type ResolvedRoute =
/** Locale root — the page assigned as Homepage in System Pages. */
| {
/** The archive page this entry lives under — its slug is the URL prefix. */
archive: Record<string, unknown>
collection: string
doc: Record<string, unknown>
type: 'entry'
}
/** An ordinary page. */
| {
collection: string
doc: Record<string, unknown>
/** 1-based, from ?page=. */
page: number
perPage: number
type: 'archive'
}
/** A collection's archive page, e.g. /pl/artykuly. */
| { doc: Record<string, unknown>; type: 'home' }
/** A single entry, e.g. /pl/artykuly/moj-post. */
| { doc: Record<string, unknown>; type: 'page' }
type ResolveRouteArgs = {
content?: ContentOption
/**
* Preview (Next draftMode): return the latest draft instead of the published
* version, and resolve never-published pages. Default false — public
* requests only ever see published content.
*/
draft?: boolean
locale: string
/** Page number from the query string (?page=2). Defaults to 1. */
page?: number
/** Client's Pages collection slug. Defaults to 'pages'. */
pagesSlug?: string
payload: BasePayload
/** Route segments after the locale, e.g. ['artykuly', 'moj-post']. */
segments?: string[]
/**
* SiteSettings already read for this locale (depth ≥ 1). Pass it to skip the
* read — createContentHelpers does, so layout, metadata and page share ONE
* settings query per request.
*/
settings?: null | Record<string, unknown>
/** SiteSettings global slug. Defaults to 'site-settings'. */
settingsSlug?: string
}
/**
* Works out what a URL points at: the home page, an ordinary page, a
* collection's archive, or a single entry.
*
* Routing only. An archive result says which collection to list and on which
* page, but doesn't fetch the entries — that's `getArchiveEntries`, called by
* whoever actually needs them. Keeping the two apart means listing changes
* (sorting, filtering, pagination) never touch routing rules, and metadata
* generation doesn't pay for a query it would discard.
*
* The trick is that archive prefixes aren't configured anywhere — they're the
* slug of whichever page an editor assigned as that collection's archive. So
* /pl/artykuly and /en/articles come from one assignment, and renaming the page
* moves the whole section.
*
* Resolution order matters: a first segment matching an archive's slug wins
* over an ordinary page of the same name, because an archive *is* a page and
* would otherwise shadow its own entries.
*
* Depth beyond {archive}/{entry} isn't supported — categories in the path would
* make canonical and hreflang ambiguous (the same entry reachable under several
* URLs).
*/
/**
* Payload's `find` returns never-published documents from the main collection
* (with `_status: 'draft'`) unless asked otherwise — public routing must drop
* them, or an unpublished page is reachable by its URL.
*/
function isPublic(doc: unknown, draft: boolean): boolean {
if (draft || !doc || typeof doc !== 'object') {return Boolean(doc)}
const status = (doc as { _status?: unknown })._status
return status === undefined || status === null || status === 'published'
}
export async function resolveRoute({
content,
draft = false,
locale,
page = 1,
pagesSlug = 'pages',
payload,
segments,
settings: preloaded,
settingsSlug = 'site-settings',
}: ResolveRouteArgs): Promise<null | ResolvedRoute> {
const settings =
preloaded ??
((await payload.findGlobal({
slug: settingsSlug,
depth: 1,
locale: locale as never,
})) as Record<string, unknown>)
// Locale root → Homepage from System Pages.
// settings.homepage is a shallow relation (depth: 1 above) — it identifies
// WHICH page is the homepage, but its nested block relations (e.g. Hero
// images) aren't populated. Re-fetch that page from the pages collection at
// the same depth as every other page, so the frontend gets one consistent
// shape. Uses pagesSlug/locale from args — no hard-coded collection or locale.
if (!segments?.length) {
const homepage = settings.homepage
if (!homepage || typeof homepage !== 'object') {
return null
}
const homepageId = (homepage as { id: number | string }).id
const doc = await payload.findByID({
id: homepageId,
collection: pagesSlug,
depth: 2,
draft,
locale: locale as never,
})
return doc && isPublic(doc, draft) ? { type: 'home', doc: doc as Record<string, unknown> } : null
}
const [first, ...rest] = segments
// Does the first segment name an archive page?
for (const collection of content?.collections ?? []) {
const archive = settings[archiveFieldName(collection.slug)]
if (!archive || typeof archive !== 'object') {continue}
const archiveDoc = archive as ArchivePage
if (archiveDoc.slug !== first) {continue}
if (!isPublic(archiveDoc, draft)) {return null}
// /pl/artykuly → the archive page itself.
if (rest.length === 0) {
return {
type: 'archive',
collection: collection.slug,
doc: archiveDoc as Record<string, unknown>,
page,
perPage: collection.perPage ?? 10,
}
}
// /pl/artykuly/moj-post → an entry.
if (rest.length === 1) {
const found = await payload.find({
collection: collection.slug as never,
depth: 2,
draft,
limit: 1,
locale: locale as never,
where: { slug: { equals: rest[0] } },
})
const entry = found.docs[0]
if (!entry || !isPublic(entry, draft)) {return null}
return {
type: 'entry',
archive: archiveDoc as Record<string, unknown>,
collection: collection.slug,
doc: entry as Record<string, unknown>,
}
}
// Deeper than {archive}/{entry}.
return null
}
// An ordinary page. Joined, so nested slugs ('a/b') keep working.
const found = await payload.find({
collection: pagesSlug as never,
depth: 2,
draft,
limit: 1,
locale: locale as never,
where: { slug: { equals: segments.join('/') } },
})
const doc = found.docs[0]
if (!doc || !isPublic(doc, draft)) {return null}
// The page assigned as 404 in System Pages must not be reachable as a normal
// 200 URL (/pl/strona-nie-znaleziona) — that's a soft-404 / duplicate. Treat
// it as not found, so the route calls notFound() and not-found.tsx renders
// that same page with a real 404 status. (If 404 = homepage, the homepage is
// served from the root branch above and never reaches here by its own slug
// in a way that matters — but guard anyway so we never hide the homepage.)
const notFound = settings.notFound
const homepage = settings.homepage
const notFoundId =
notFound && typeof notFound === 'object' ? (notFound as { id?: unknown }).id : notFound
const homepageId =
homepage && typeof homepage === 'object' ? (homepage as { id?: unknown }).id : homepage
const docId = (doc as { id?: unknown }).id
if (notFoundId != null && notFoundId === docId && notFoundId !== homepageId) {
return null
}
return { type: 'page', doc: doc as Record<string, unknown> }
}