Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/sanitize-document-renderer-links.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@keystatic/core': patch
---

Sanitize link URLs in `DocumentRenderer`. Links with `javascript:`, `data:` or `vbscript:` URLs now render with `about:blank`, including when a custom `link` renderer is used.
52 changes: 52 additions & 0 deletions packages/keystatic/src/renderer.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
/** @vitest-environment node */
import { ReactElement, ReactNode } from 'react';
import { renderToStaticMarkup } from 'react-dom/server';
import { expect, test } from 'vitest';
import { DocumentRenderer } from './renderer';

function renderLink(
href: string,
link?: (props: { children: ReactNode; href: string }) => ReactElement | null
) {
return renderToStaticMarkup(
<DocumentRenderer
document={[
{
type: 'paragraph',
children: [{ type: 'link', href, children: [{ text: 'x' }] }],
},
]}
renderers={link ? { inline: { link } } : undefined}
/>
);
}

test.each([
'javascript:alert(1)',
'JaVaScRiPt:alert(1)',
'\tjavascript:alert(1)',
'java\nscript:alert(1)',
'data:text/html,<script>alert(1)</script>',
'vbscript:msgbox(1)',
])('unsafe link href %j is replaced', href => {
expect(renderLink(href)).toBe('<p><a href="about:blank">x</a></p>');
});

test.each([
'https://example.com/a?b=c#d',
'http://example.com',
'/relative/path',
'#heading',
'mailto:someone@example.com',
])('safe link href %j is kept', href => {
expect(renderLink(href)).toBe(`<p><a href="${href}">x</a></p>`);
});

test('custom link renderers receive the sanitized href', () => {
const hrefs: string[] = [];
renderLink('javascript:alert(1)', ({ children, href }) => {
hrefs.push(href);
return <>{children}</>;
});
expect(hrefs).toEqual(['about:blank']);
});
3 changes: 2 additions & 1 deletion packages/keystatic/src/renderer.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { sanitizeUrl } from '@braintree/sanitize-url';
import { Fragment, ReactElement, ReactNode, type JSX } from 'react';

type Node = Element | Text;
Expand Down Expand Up @@ -260,7 +261,7 @@ function DocumentNode({
}
case 'link': {
return (
<renderers.inline.link href={node.href as string}>
<renderers.inline.link href={sanitizeUrl(node.href as string)}>
{children}
</renderers.inline.link>
);
Expand Down