diff --git a/docs/richtext.md b/docs/richtext.md index a4a9fd6..e40e821 100644 --- a/docs/richtext.md +++ b/docs/richtext.md @@ -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 `` (`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. diff --git a/docs/security.md b/docs/security.md index d0cafbb..fc23772 100644 --- a/docs/security.md +++ b/docs/security.md @@ -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). diff --git a/src/modules/richtext/RenderRichText.tsx b/src/modules/richtext/RenderRichText.tsx index 709be2b..e29cf16 100644 --- a/src/modules/richtext/RenderRichText.tsx +++ b/src/modules/richtext/RenderRichText.tsx @@ -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( * // /client * */ -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 } : {}) diff --git a/src/modules/richtext/sanitizeLinks.ts b/src/modules/richtext/sanitizeLinks.ts new file mode 100644 index 0000000..2efef1b --- /dev/null +++ b/src/modules/richtext/sanitizeLinks.ts @@ -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 + * (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(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 +} diff --git a/test/richTextLinks.test.ts b/test/richTextLinks.test.ts new file mode 100644 index 0000000..9329d1a --- /dev/null +++ b/test/richTextLinks.test.ts @@ -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) => + (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,', '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:a@acme.pl'), 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]) + }) +})