Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

fix(richtext): import a link core refuses as its source text, never a link (#7065)

Cindy Zhang0d7197d7e9a1
diff --git a/packages/richtext/src/markdownCharacterReferences.ts b/packages/richtext/src/markdownCharacterReferences.ts
index c58792d241..6a81c4ff47 100644
--- a/packages/richtext/src/markdownCharacterReferences.ts
+++ b/packages/richtext/src/markdownCharacterReferences.ts
@@ -4,10 +4,11 @@
* @file markdownCharacterReferences.ts
* @input Uses lexical, @lexical/link, @lexical/code, and core Markdown's
* decodeMarkdownCharacterReferences.
- * @output Exports protectBackslashEscapes, protectLinkDestinationParentheses,
- * and protectCharacterReferences, which swap every backslash escape, every
- * parenthesis inside a link destination, and every character reference in
- * Markdown source for a private-use stand-in before Lexical imports it, and
+ * @output Exports protectRefusedLinks, protectBackslashEscapes,
+ * protectLinkDestinationParentheses, and protectCharacterReferences, which
+ * swap every link core refuses, every backslash escape, every parenthesis
+ * inside a link destination, and every character reference in Markdown
+ * source for a private-use stand-in before Lexical imports it, and
* $restoreCharacterReferences, which puts the literal or decoded text in
* place of the stand-ins afterwards.
* @position Used by importMarkdownKeepingSource (markdownSource.ts), so every
@@ -28,13 +29,17 @@
import {$isCodeNode} from '@lexical/code';
import {$isLinkNode} from '@lexical/link';
+import {$dfs} from '@lexical/utils';
import {
$isElementNode,
$isTextNode,
type ElementNode,
type LexicalNode,
} from 'lexical';
-import {decodeMarkdownCharacterReferences} from '@astryxdesign/core/Markdown/parser';
+import {
+ decodeMarkdownCharacterReferences,
+ parseInlineAst,
+} from '@astryxdesign/core/Markdown/parser';
/**
* What a stand-in replaced: a reference as written, an escaped `&`, or a
@@ -44,7 +49,8 @@ type StandIn =
| {readonly kind: 'reference'; readonly source: string}
| {readonly kind: 'ampersand'}
| {readonly kind: 'escape'; readonly character: string}
- | {readonly kind: 'backslash'};
+ | {readonly kind: 'backslash'}
+ | {readonly kind: 'literal'; readonly text: string};
export interface ProtectedMarkdown {
/** The source with stand-ins in place of references. */
@@ -260,6 +266,161 @@ export function protectBackslashEscapes(markdown: string): ProtectedMarkdown {
return {markdown: output + markdown.slice(copied), standIns};
}
+/**
+ * For each `[`, `]`, `(`, and `)` in `text` outside code and not escaped,
+ * the index of the bracket or parenthesis it pairs with by nesting; -1 for
+ * the rest. One pass, so a candidate never rescans the text.
+ */
+function pairedDelimiters(
+ text: string,
+ code: ReadonlyArray<readonly [number, number]>,
+): Int32Array {
+ const pair = new Int32Array(text.length).fill(-1);
+ const brackets: number[] = [];
+ const parentheses: number[] = [];
+ let codeIndex = 0;
+ for (let index = 0; index < text.length; index++) {
+ while (codeIndex < code.length && code[codeIndex][1] <= index) {
+ codeIndex++;
+ }
+ if (codeIndex < code.length && code[codeIndex][0] <= index) {
+ index = code[codeIndex][1] - 1;
+ continue;
+ }
+ const character = text[index];
+ const open =
+ character === ']'
+ ? brackets.pop()
+ : character === ')'
+ ? parentheses.pop()
+ : undefined;
+ if (character === '\\') {
+ index++;
+ } else if (character === '[') {
+ brackets.push(index);
+ } else if (character === '(') {
+ parentheses.push(index);
+ } else if (open !== undefined) {
+ pair[index] = open;
+ pair[open] = index;
+ }
+ }
+ return pair;
+}
+
+/**
+ * Whether core Markdown refuses a link to `destination`, as written in the
+ * source: its own parser decides, so both surfaces refuse the same
+ * destinations by one policy.
+ */
+function coreRefusesDestination(destination: string): boolean {
+ const probe = `[x](${destination})`;
+ const [only, ...rest] = parseInlineAst(probe);
+ return rest.length === 0 && only?.type === 'text' && only.value === probe;
+}
+
+/**
+ * Whether core Markdown refuses a link to `url`, a destination already
+ * decoded: the probe writes it back with every special character escaped.
+ * A URL that cannot be written back is refused.
+ */
+export function coreRefusesUrl(url: string): boolean {
+ if (/[<>\n\r]/.test(url) && /\s/.test(url)) {
+ return true;
+ }
+ const escaped = url.replace(/[\\()<>&[\]"']/g, character => `\\${character}`);
+ return coreRefusesDestination(/\s/.test(url) ? `<${escaped}>` : escaped);
+}
+
+/**
+ * Returns `markdown` with each inline link whose destination core Markdown
+ * refuses — `javascript:` and the like — kept from becoming a link
+ * (spec:AST-061 FR7). Where core shows the link as its source text, exactly
+ * as written, the whole source becomes one stand-in that comes back as that
+ * text. Where core reads no link there at all (its link text holds brackets
+ * of its own), only the `(` that opens the destination becomes a stand-in,
+ * so the text around it reads as core reads it, marks included. Brackets and
+ * parentheses pair by nesting, so link text holding brackets is found whole.
+ * Linear in the source: pairs come from one pass, and a destination inside a
+ * found link is not probed again. Run first, on the source as written;
+ * `$unwrapRefusedLinks` catches any link the editor still makes.
+ */
+export function protectRefusedLinks(markdown: string): ProtectedMarkdown {
+ const standIns = new Map<string, StandIn>();
+ if (!markdown.includes('](')) {
+ return {markdown, standIns};
+ }
+ const pair = pairedDelimiters(markdown, codeRanges(markdown));
+ // Ranges to replace, in order: a whole link, or the `(` that opens its
+ // destination.
+ const refused: Array<{start: number; end: number; whole: boolean}> = [];
+ // Where the last probed destination ends: a link cannot sit inside one.
+ let probedTo = -1;
+ for (
+ let index = markdown.indexOf('](');
+ index !== -1;
+ index = markdown.indexOf('](', index + 1)
+ ) {
+ const open = pair[index];
+ const close = pair[index + 1];
+ if (index < probedTo || open === -1 || close === -1) {
+ continue;
+ }
+ probedTo = close;
+ if (!coreRefusesDestination(markdown.slice(index + 2, close))) {
+ continue;
+ }
+ const source = markdown.slice(open, close + 1);
+ const [only, ...rest] = parseInlineAst(source);
+ if (rest.length === 0 && only?.type === 'text' && only.value === source) {
+ // A whole link stands for the refused links found inside it.
+ while (refused.length > 0 && refused[refused.length - 1].start >= open) {
+ refused.pop();
+ }
+ refused.push({start: open, end: close + 1, whole: true});
+ } else {
+ refused.push({start: index + 1, end: index + 2, whole: false});
+ }
+ }
+ if (refused.length === 0) {
+ return {markdown, standIns};
+ }
+ const available = absentCharacters(markdown);
+ let output = '';
+ let copied = 0;
+ for (const {start, end, whole} of refused) {
+ const next = available.next();
+ if (next.done === true || start < copied) {
+ break;
+ }
+ standIns.set(
+ next.value,
+ whole
+ ? {kind: 'literal', text: markdown.slice(start, end)}
+ : {kind: 'escape', character: '('},
+ );
+ output += markdown.slice(copied, start) + next.value;
+ copied = end;
+ }
+ return {markdown: output + markdown.slice(copied), standIns};
+}
+
+/**
+ * Takes every link under `node` whose URL core Markdown refuses out of its
+ * link, leaving its text in place, so no form of link text or destination
+ * the source pass did not find can store or draw an unsafe URL.
+ */
+export function $unwrapRefusedLinks(node: ElementNode): void {
+ for (const {node: descendant} of $dfs(node)) {
+ if ($isLinkNode(descendant) && coreRefusesUrl(descendant.getURL())) {
+ for (const child of descendant.getChildren()) {
+ descendant.insertBefore(child);
+ }
+ descendant.remove();
+ }
+ }
+}
+
/**
* Returns `markdown` with every parenthesis inside an inline link
* destination — between the destination's own parentheses, balanced, as core
@@ -457,6 +618,8 @@ function restored(
const decoded = (standIn: StandIn): string => {
switch (standIn.kind) {
+ case 'literal':
+ return standIn.text;
case 'ampersand':
return '&';
case 'backslash':
@@ -469,6 +632,8 @@ const decoded = (standIn: StandIn): string => {
};
const asWritten = (standIn: StandIn): string => {
switch (standIn.kind) {
+ case 'literal':
+ return standIn.text;
case 'ampersand':
return '&';
case 'backslash':
diff --git a/packages/richtext/src/markdownRefusedLinks.test.tsx b/packages/richtext/src/markdownRefusedLinks.test.tsx
new file mode 100644
index 0000000000..4dd597164d
--- /dev/null
+++ b/packages/richtext/src/markdownRefusedLinks.test.tsx
@@ -0,0 +1,193 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import {describe, expect, it} from 'vitest';
+import {render, waitFor} from '@testing-library/react';
+import {createHeadlessEditor} from '@lexical/headless';
+import {$getRoot, $isTextNode} from 'lexical';
+import {parseInlineAst} from '@astryxdesign/core/Markdown/parser';
+import {DEFAULT_NODES} from './editorNodes';
+import {DEFAULT_TRANSFORMERS} from './markdownTable';
+import {
+ $exportMarkdownKeepingSource,
+ importMarkdownKeepingSource,
+} from './markdownSource';
+import {
+ editorStateJSONToMarkdown,
+ markdownToEditorStateJSON,
+} from './markdownSerializers';
+import {RichTextView} from './RichTextView';
+import {
+ coreRefusesUrl,
+ protectRefusedLinks,
+} from './markdownCharacterReferences';
+
+type Json = Record<string, unknown>;
+
+/** The paragraph's links and its text, as RichText imports it. */
+function imported(markdown: string): {links: string[]; text: string} {
+ const links: string[] = [];
+ let text = '';
+ const visit = (node: Json) => {
+ if (node.type === 'link' || node.type === 'autolink') {
+ links.push(node.url as string);
+ }
+ if (node.type === 'text') {
+ text += node.text as string;
+ }
+ ((node.children as Json[]) ?? []).forEach(visit);
+ };
+ visit((JSON.parse(markdownToEditorStateJSON(markdown)) as {root: Json}).root);
+ return {links, text};
+}
+
+/** The text core Markdown shows for an inline line. */
+function coreText(markdown: string): string {
+ const flat = (node: Json): string =>
+ node.type === 'text'
+ ? (node.value as string)
+ : ((node.children as Json[]) ?? []).map(flat).join('');
+ return (parseInlineAst(markdown) as unknown as Json[]).map(flat).join('');
+}
+
+describe('links core refuses (spec:AST-061 FR7)', () => {
+ it.each([
+ 'Go [here](javascript:alert(1)) now',
+ 'Go [here](JavaScript:alert(1)) now',
+ 'Go [here](&#106;avascript:alert(1)) now',
+ 'Go [here](vbscript:msgbox) now',
+ 'Go [here](data:text/html,hi) now',
+ 'Go **[here](javascript:alert(1))** now',
+ // Link text holding brackets of its own.
+ '[a [b] c](javascript:alert(1))',
+ '[[b]](vbscript:msgbox)',
+ '[**a [b]**](javascript:alert(1))',
+ '[a [b] c](&#106;avascript:alert(1))',
+ '[[b]](&#x76;bscript:msgbox)',
+ 'See [**a [b]**](JaVaScRiPt:alert(1)) now',
+ ])('imports %j as its source text, as core shows it', markdown => {
+ const {links, text} = imported(markdown);
+ expect(links).toEqual([]);
+ expect(text).toBe(coreText(markdown));
+ });
+
+ it('still links a safe destination beside a refused one', () => {
+ const {links, text} = imported(
+ '[bad](javascript:x) and [good](https://example.com)',
+ );
+ expect(links).toEqual(['https://example.com']);
+ expect(text).toBe('[bad](javascript:x) and good');
+ });
+
+ it('round-trips a refused link byte for byte, and keeps it text through an edit', () => {
+ const markdown = 'Go [here](javascript:alert(1)) now\n';
+ expect(editorStateJSONToMarkdown(markdownToEditorStateJSON(markdown))).toBe(
+ markdown,
+ );
+ const editor = createHeadlessEditor({
+ nodes: [...DEFAULT_NODES],
+ onError(error) {
+ throw error;
+ },
+ });
+ importMarkdownKeepingSource(editor, markdown, [...DEFAULT_TRANSFORMERS]);
+ editor.update(
+ () => {
+ const last = $getRoot().getAllTextNodes().at(-1);
+ if (!$isTextNode(last)) {
+ throw new Error('No text');
+ }
+ last.setTextContent(`${last.getTextContent()}!`);
+ },
+ {discrete: true},
+ );
+ const exported = editor
+ .getEditorState()
+ .read(() => $exportMarkdownKeepingSource([...DEFAULT_TRANSFORMERS]));
+ expect(imported(exported)).toEqual({
+ links: [],
+ text: 'Go [here](javascript:alert(1)) now!',
+ });
+ });
+
+ it('renders no anchor for it', async () => {
+ const {container} = render(
+ <RichTextView
+ value={markdownToEditorStateJSON('Go [here](javascript:alert(1)) now')}
+ />,
+ );
+ await waitFor(() =>
+ expect(container.textContent).toContain('[here](javascript:alert(1))'),
+ );
+ expect(container.querySelector('a')).toBeNull();
+ });
+});
+
+/** A small deterministic generator, so the fuzz is the same every run. */
+function generator(seed: number): () => number {
+ let state = seed;
+ return () => {
+ state = (state * 1103515245 + 12345) % 2147483648;
+ return state / 2147483648;
+ };
+}
+
+describe('no unsafe URL is ever stored', () => {
+ const unsafe = [
+ 'javascript:alert(1)',
+ 'JaVaScRiPt:alert(1)',
+ '&#106;avascript:alert(1)',
+ '&#x6A;avascript:alert(1)',
+ 'vbscript:msgbox',
+ 'data:text/html,hi',
+ '\\javascript:alert(1)',
+ ];
+
+ it('for link text with random nested brackets and marks', () => {
+ const random = generator(7);
+ const pick = <T,>(items: ReadonlyArray<T>): T =>
+ items[Math.floor(random() * items.length)];
+ const text = (depth: number): string =>
+ Array.from({length: 1 + Math.floor(random() * 3)}, () =>
+ depth < 3 && random() < 0.4
+ ? `${pick(['[', '[', '**[', '\\['])}${text(depth + 1)}${pick([']', ']', ']**', ''])}`
+ : pick(['a', 'b c', '*d*', '`e`', ' ']),
+ ).join('');
+ for (let round = 0; round < 300; round++) {
+ const markdown = `${pick(['', 'x ', '[', '] '])}[${text(0)}](${pick(unsafe)})${pick(['', ' y', ')', ']'])}`;
+ const {links} = imported(markdown);
+ expect(
+ links.filter(url => coreRefusesUrl(url)),
+ markdown,
+ ).toEqual([]);
+ }
+ });
+
+ it('for a link the editor makes that the source pass leaves', () => {
+ // An unclosed inner bracket: the editor's own link rule reads the link
+ // text from the first `[`.
+ const {links} = imported('[a [b](javascript:alert(1))');
+ expect(links).toEqual([]);
+ });
+
+ it('finds refused links in linear time, even in bracket-dense text', () => {
+ const time = (markdown: string): number => {
+ protectRefusedLinks(markdown);
+ let fastest = Number.POSITIVE_INFINITY;
+ for (let round = 0; round < 3; round++) {
+ const started = performance.now();
+ protectRefusedLinks(markdown);
+ fastest = Math.min(fastest, performance.now() - started);
+ }
+ return fastest;
+ };
+ // Alone, each takes a few milliseconds; the budget leaves room for a
+ // loaded test machine. A rescan per candidate takes seconds.
+ for (const markdown of [
+ '[a]('.repeat(20_000),
+ `${'['.repeat(20_000)}${'](x'.repeat(20_000)}`,
+ `${'[a]('.repeat(10_000)}${')'.repeat(10_000)}`,
+ ]) {
+ expect(time(markdown)).toBeLessThan(2000);
+ }
+ });
+});
diff --git a/packages/richtext/src/markdownSource.ts b/packages/richtext/src/markdownSource.ts
index 6ab5e3509d..960f0b4481 100644
--- a/packages/richtext/src/markdownSource.ts
+++ b/packages/richtext/src/markdownSource.ts
@@ -56,6 +56,8 @@ import {
protectBackslashEscapes,
protectCharacterReferences,
protectLinkDestinationParentheses,
+ protectRefusedLinks,
+ $unwrapRefusedLinks,
} from './markdownCharacterReferences';
import {
$restoreExtensionSources,
@@ -363,7 +365,8 @@ export function importMarkdownKeepingSource(
const holder = $createParagraphNode();
root.append(holder);
// Lexical imports LF lines; the record keeps the authored endings.
- // Adopted plugins' nodes, then backslash escapes and parentheses in
+ // Adopted plugins' nodes, links core refuses (as their source text),
+ // then backslash escapes and parentheses in
// link destinations, then character references go through as
// stand-ins: plugin nodes come back as extension nodes holding their
// source, escapes and parentheses as the literal characters,
@@ -372,7 +375,8 @@ export function importMarkdownKeepingSource(
withoutCarriageReturns(importChunks[index]?.content ?? chunk.content),
plugins,
);
- const escaped = protectBackslashEscapes(shielded.markdown);
+ const refused = protectRefusedLinks(shielded.markdown);
+ const escaped = protectBackslashEscapes(refused.markdown);
const destinations = protectLinkDestinationParentheses(
escaped.markdown,
);
@@ -381,11 +385,13 @@ export function importMarkdownKeepingSource(
$restoreCharacterReferences(
holder,
new Map([
+ ...refused.standIns,
...escaped.standIns,
...destinations.standIns,
...referenced.standIns,
]),
);
+ $unwrapRefusedLinks(holder);
$restoreExtensionSources(holder, shielded.standIns);
$joinSoftLineBreaks(holder);
for (const node of holder.getChildren()) {