RenderRichText neutralises unsafe link URLs (safeHref)

Payload's link converter rendered fields.url as is; javascript:/data: URLs
stored via import or API reached the href. They now become '#'.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
Radosław Smoliński
2026-10-22 17:09:44 +02:00
co-authored by Claude Opus 5.5
parent 7967453f57
commit 1beb0edb7f
5 changed files with 84 additions and 3 deletions
+4
View File
@@ -53,6 +53,10 @@ const converters: JSXConvertersFunction = ({ defaultConverters }) => ({
Spread `defaultConverters` — nadpisujesz tylko te węzły, które chcesz. Reszta
(listy, tabele, obrazy, linki) działa z oficjalnej obsługi Payload.
**Linki są filtrowane jak w `<CMSLink>` (`safeHref`).** Własny link z adresem spoza `http(s)`,
`mailto`, `tel`, `sms`, `#`, `/` (np. `javascript:`, `data:`) dostaje `href="#"` — także gdy trafił
do bazy importem, seedem albo przez API, z pominięciem pola w panelu.
## Spis treści i kotwice nagłówków (1.11.1)
Długie dokumenty (polityka prywatności, regulamin) — spis treści z linkami do sekcji.
+2 -1
View File
@@ -329,7 +329,8 @@ dostęp do danych, nie tylko UI.
- Drafty nigdy nieopublikowane nie są już dostępne publicznie (`resolveRoute`, Markdown, MCP,
metadata) ani na listach archiwów (`getArchiveEntries`). Podgląd: `resolveRoute({ draft: true })`,
`getArchiveEntries({ draft: true })` w trybie `draftMode()`.
- Linki z CMS: tylko `http(s)`, `mailto`, `tel`, `sms`, `#`, `/` (`safeHref`); `javascript:` i `data:` odrzucane.
- Linki z CMS: tylko `http(s)`, `mailto`, `tel`, `sms`, `#`, `/` (`safeHref`); `javascript:` i `data:` odrzucane —
także w rich text (`RenderRichText` zamienia je na `#`).
- ID analityki walidowane (panel i przed wysłaniem do przeglądarki).
- Zgłoszenia formularzy: odczyt `editor+`; adresy z zakładki Emails niewidoczne publicznie.
- Uploady: `buildUploadSecurityHeaders()` w `next.config.ts` (SVG nie uruchomi skryptu na domenie strony).
+5 -2
View File
@@ -5,6 +5,7 @@ import { RichText as PayloadRichText } from '@payloadcms/richtext-lexical/react'
import { cloneElement, isValidElement, type ReactElement, type ReactNode } from 'react'
import { headingIds as computeHeadingIds, type HeadingLevel } from './headings.js'
import { sanitizeRichTextLinks } from './sanitizeLinks.js'
export type RenderRichTextProps = {
/** Wrapper class (e.g. Tailwind prose classes). */
@@ -96,8 +97,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, headingIds }: RenderRichTextProps) {
if (!data) {return null}
export function RenderRichText({ className, converters, data: raw, headingIds }: RenderRichTextProps) {
if (!raw) {return null}
// javascript:/data: link URLs from stored content never reach an href
const data = sanitizeRichTextLinks(raw)
if (headingIds) {
const opts = headingIds === true ? {} : headingIds
const ids = computeHeadingIds(data, opts.levels ? { levels: opts.levels } : {})
+43
View File
@@ -0,0 +1,43 @@
import { safeHref } from '../links/resolveLinkHref.js'
type LexicalNode = { [key: string]: unknown; children?: unknown[]; fields?: { [key: string]: unknown; url?: unknown }; type?: string }
/**
* Rich text with custom links whose URL isn't a safe target (`javascript:`,
* `data:`, "java\tscript:") gets them neutralised to '#' — the same rule as
* <CMSLink> (safeHref). Payload's link converter renders `fields.url` as is,
* and stored content can come from imports, seeds or the API, not only the
* editor's link drawer.
*
* Returns the SAME object when nothing needed changing (no copy per render);
* otherwise only the path to each unsafe link is copied.
*/
export function sanitizeRichTextLinks<T>(data: T): T {
return walk(data) as T
}
function walk(value: unknown): unknown {
if (Array.isArray(value)) {
let changed = false
const next = value.map((item) => {
const out = walk(item)
if (out !== item) {changed = true}
return out
})
return changed ? next : value
}
if (!value || typeof value !== 'object') {return value}
const node = value as LexicalNode
let result: LexicalNode = node
if ((node.type === 'link' || node.type === 'autolink') && node.fields && node.fields.linkType !== 'internal') {
const url = typeof node.fields.url === 'string' ? node.fields.url : ''
if (url && safeHref(url) === null) {result = { ...node, fields: { ...node.fields, url: '#' } }}
}
for (const key of ['root', 'children'] as const) {
if (!(key in result)) {continue}
const out = walk(result[key])
if (out !== result[key]) {result = { ...result, [key]: out }}
}
return result
}
+30
View File
@@ -0,0 +1,30 @@
import { describe, expect, test } from 'vitest'
import { sanitizeRichTextLinks } from '../src/modules/richtext/sanitizeLinks.js'
const link = (url: string, type = 'link', linkType = 'custom') => ({ type, children: [{ type: 'text', text: 'x' }], fields: { linkType, url } })
const doc = (...nodes: object[]) => ({ root: { type: 'root', children: [{ type: 'paragraph', children: nodes }] } })
const urls = (d: ReturnType<typeof doc>) =>
(d.root.children[0].children as { fields: { url: string } }[]).map((n) => n.fields.url)
describe('rich text links', () => {
test.each(['javascript:alert(1)', ' JaVaScRiPt:alert(1)', 'java\tscript:alert(1)', 'data:text/html,<script>alert(1)</script>', 'vbscript:x'])(
'%j is neutralised to #',
(bad) => {
expect(urls(sanitizeRichTextLinks(doc(link(bad), link(bad, 'autolink'))))).toEqual(['#', '#'])
},
)
test('safe links are kept and an untouched document is returned as is', () => {
const d = doc(link('https://acme.pl'), link('/pl/kontakt'), link('mailto:[email protected]'), link('tel:+48123'), link('#faq'))
expect(sanitizeRichTextLinks(d)).toBe(d)
})
test('only the path to an unsafe link is copied; the input is not mutated', () => {
const d = doc(link('https://acme.pl'), link('javascript:alert(1)'))
const out = sanitizeRichTextLinks(d)
expect(urls(d)).toEqual(['https://acme.pl', 'javascript:alert(1)'])
expect(urls(out)).toEqual(['https://acme.pl', '#'])
expect(out.root.children[0].children[0]).toBe(d.root.children[0].children[0])
})
})