Skip to content

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

TypeScript

fix(Markdown): read angle-bracket link destinations to their closing bracket (#7078)

Cindy Zhang4501743a699e
diff --git a/.changeset/markdown-angle-destination-edges.md b/.changeset/markdown-angle-destination-edges.md
new file mode 100644
index 0000000000..3cd1948df6
--- /dev/null
+++ b/.changeset/markdown-angle-destination-edges.md
@@ -0,0 +1,8 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] Markdown: read angle-bracket link destinations to their closing bracket
+@cixzhang
+
+`Markdown` now reads an angle-bracket destination as CommonMark specifies: parentheses inside the brackets are part of the address, so `[a](<b(c>)` links to `b(c)`; an escaped bracket inside is part of it too, so `<b\>c>` is `b>c`; and a line ending inside the brackets makes the text no link. Unsafe schemes are refused as before.
diff --git a/packages/core/src/Markdown/angleDestinations.test.tsx b/packages/core/src/Markdown/angleDestinations.test.tsx
new file mode 100644
index 0000000000..175e615678
--- /dev/null
+++ b/packages/core/src/Markdown/angleDestinations.test.tsx
@@ -0,0 +1,86 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import {describe, expect, it} from 'vitest';
+import {parseInlineAst} from './parser';
+import {isSafeMarkdownParserUrl} from './url';
+
+type Json = {type: string; url?: string; value?: string; children?: Json[]};
+
+/** Each link or image as `type(url)`, in order. */
+function targets(markdown: string): string[] {
+ const found: string[] = [];
+ const visit = (node: Json) => {
+ if (node.type === 'link' || node.type === 'image') {
+ found.push(`${node.type}(${node.url})`);
+ }
+ (node.children ?? []).forEach(visit);
+ };
+ (parseInlineAst(markdown) as unknown as Json[]).forEach(visit);
+ return found;
+}
+
+describe('angle-bracket destinations (CommonMark 0.31 §6.3)', () => {
+ it.each([
+ ['[a](<b(c>)', ['link(b(c)']],
+ ['[a](<b(c> "t")', ['link(b(c)']],
+ ['[a](< b(c) d >)', ['link( b(c) d )']],
+ ['![i](<b(c>)', ['image(b(c)']],
+ ['[a](<b\\>c>)', ['link(b>c)']],
+ ['[a](<b\\<c>)', ['link(b<c)']],
+ ['[a](<>)', ['link()']],
+ ['[a](<b\nc>)', []],
+ ['[a](<b>c>)', ['link(<b>c>)']],
+ ['[a](b c)', ['link(b c)']],
+ ['[a](<b(c>) and [d](e)', ['link(b(c)', 'link(e)']],
+ ])('reads %j', (markdown, expected) => {
+ expect(targets(markdown)).toEqual(expected);
+ });
+
+ it('refuses every unsafe scheme, however its angle destination is written', () => {
+ let state = 31;
+ const random = () => {
+ state = (state * 1103515245 + 12345) % 2147483648;
+ return state / 2147483648;
+ };
+ const pick = <T,>(items: ReadonlyArray<T>): T =>
+ items[Math.floor(random() * items.length)];
+ const schemes = [
+ 'javascript:',
+ 'JaVaScRiPt:',
+ '&#106;avascript:',
+ '&#x6A;avascript:',
+ 'java\\script:',
+ 'vbscript:',
+ 'data:text/html,',
+ 'data: text/html,',
+ 'data:&#32;text/html,',
+ ];
+ for (let round = 0; round < 500; round++) {
+ const body = pick(['x', 'a(b)', 'a(b', 'a\\>b', 'a\\<b', ' x ', '']);
+ const title = pick(['', ' "t"', " 't'", ' (t)']);
+ const markdown = `${pick(['[a]', '![a]'])}(${pick(['', ' '])}<${pick(schemes)}${body}>${title})`;
+ for (const target of targets(markdown)) {
+ const url = target.slice(target.indexOf('(') + 1, -1);
+ expect(isSafeMarkdownParserUrl(url), markdown).toBe(true);
+ }
+ }
+ });
+
+ it('finds angle destinations in linear time', () => {
+ for (const markdown of [
+ '[a](<b '.repeat(20_000),
+ '[a](<b> ('.repeat(20_000),
+ '[a](<b> "'.repeat(20_000),
+ ]) {
+ parseInlineAst(markdown);
+ let fastest = Number.POSITIVE_INFINITY;
+ for (let round = 0; round < 3; round++) {
+ const started = performance.now();
+ parseInlineAst(markdown);
+ fastest = Math.min(fastest, performance.now() - started);
+ }
+ // The budget leaves room for a loaded test machine.
+ expect(fastest, markdown.slice(0, 12)).toBeLessThan(1000);
+ }
+ });
+});
diff --git a/packages/core/src/Markdown/parser.ts b/packages/core/src/Markdown/parser.ts
index 49fb510779..bcd9df6e59 100644
--- a/packages/core/src/Markdown/parser.ts
+++ b/packages/core/src/Markdown/parser.ts
@@ -1085,7 +1085,66 @@ function matchReferenceImage(
// destination or one without spaces, then an optional `"…"`, `'…'`, or `(…)`
// title after whitespace (CommonMark 0.31, link destinations and titles).
const INLINE_DESTINATION_WITH_TITLE =
- /^\s*(?:<([^<>\n]*)>|([^\s<]\S*?))(?:\s+(?:"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|\((?:[^()\\]|\\.)*\)))?\s*$/s;
+ /^\s*(?:<((?:[^<>\n\\]|\\.)*)>|([^\s<]\S*?))(?:\s+(?:"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|\((?:[^()\\]|\\.)*\)))?\s*$/s;
+
+/**
+ * Where an inline link's or image's destination ends when it is written in
+ * angle brackets — the index of the `)` that closes the link — or null when
+ * the content after `open` (the `(`) is not an angle-bracket destination.
+ * Inside the brackets parentheses are plain characters, so `<b(c>` is the
+ * destination `b(c`; a line ending or unescaped `<` there makes it no
+ * destination at all, so the link is text (CommonMark 0.31 §6.3).
+ */
+function angleDestinationClose(
+ text: string,
+ open: number,
+): number | 'refused' | null {
+ let index = open + 1;
+ while (text[index] === ' ' || text[index] === '\t') {
+ index++;
+ }
+ if (text[index] !== '<') {
+ return null;
+ }
+ for (index++; index < text.length; index++) {
+ const character = text[index];
+ if (character === '\\') {
+ index++;
+ } else if (character === '\n' || character === '\r') {
+ return 'refused';
+ } else if (character === '<') {
+ return null;
+ } else if (character === '>') {
+ break;
+ }
+ }
+ if (index >= text.length) {
+ return null;
+ }
+ // After the brackets: spaces, an optional title, spaces, and the `)`.
+ index++;
+ while (/\s/.test(text[index] ?? '')) {
+ index++;
+ }
+ const quote = text[index];
+ if (quote === '"' || quote === "'" || quote === '(') {
+ const closer = quote === '(' ? ')' : quote;
+ for (index++; index < text.length && text[index] !== closer; index++) {
+ if (text[index] === '\\') {
+ index++;
+ } else if (quote === '(' && text[index] === '(') {
+ // A title in parentheses holds no unescaped `(`; stopping here
+ // also keeps every search short.
+ return null;
+ }
+ }
+ index++;
+ while (/\s/.test(text[index] ?? '')) {
+ index++;
+ }
+ }
+ return text[index] === ')' ? index : null;
+}
/**
* The destination of an inline link or image, without its title. Content in
@@ -2073,7 +2132,11 @@ function parseInlineImpl(
if (text[i] === '!' && text[i + 1] === '[') {
const altClose = inlineIndex.closingBracket(i + 2);
if (altClose !== -1 && text[altClose + 1] === '(') {
- const srcClose = inlineIndex.closingParen(altClose + 1);
+ const angleClose = angleDestinationClose(text, altClose + 1);
+ const srcClose =
+ angleClose === 'refused'
+ ? -1
+ : (angleClose ?? inlineIndex.closingParen(altClose + 1));
if (srcClose !== -1) {
const src = decodeLinkDestination(
inlineDestination(text.slice(altClose + 2, srcClose)),
@@ -2118,7 +2181,11 @@ function parseInlineImpl(
if (text[i] === '[') {
const textClose = inlineIndex.closingBracket(i + 1);
if (textClose !== -1 && text[textClose + 1] === '(') {
- const urlClose = inlineIndex.closingParen(textClose + 1);
+ const angleClose = angleDestinationClose(text, textClose + 1);
+ const urlClose =
+ angleClose === 'refused'
+ ? -1
+ : (angleClose ?? inlineIndex.closingParen(textClose + 1));
if (urlClose !== -1) {
const href = decodeLinkDestination(
inlineDestination(text.slice(textClose + 2, urlClose)),