An open source design system that's fully customizable and agent ready
TypeScript
fix: security — XSS in Markdown parser, ReDoS in ChatTokenizedText, dotfile creation in sanitizeName (#4330)
Sunilbb0706256176
diff --git a/.changeset/security-markdown-url-chat-regex.md b/.changeset/security-markdown-url-chat-regex.mdnew file mode 100644index 0000000000..407cfd79c9--- /dev/null+++ b/.changeset/security-markdown-url-chat-regex.md@@ -0,0 +1,6 @@+---+'@astryxdesign/core': patch+---++[fix] Security: reject `javascript:`, `vbscript:` and `data:text/html` URLs in the Markdown parser, so untrusted markdown can no longer produce an executable link href or image src; and fix `escapeRegExp` in `ChatTokenizedText`, whose character class closed early and left `]` and `\` unescaped, so token values containing them were injected raw into a `RegExp`+@Sunil56224972diff --git a/packages/cli/foundation/fs/path-safety.mjs b/packages/cli/foundation/fs/path-safety.mjsindex eaae1a3ed7..aab9d07015 100644--- a/packages/cli/foundation/fs/path-safety.mjs+++ b/packages/cli/foundation/fs/path-safety.mjs@@ -154,9 +154,9 @@ export function sanitizeName(name, options = {}) {);}- if (name === '.' || name === '..' || name.startsWith('..')) {+ if (name === '.' || name === '..' || name.startsWith('.')) {throw new PathSafetyError(- `Invalid ${label} "${name}": must not be '.' or start with '..'.`,+ `Invalid ${label} "${name}": must not start with '.'.`,'NAME_TRAVERSAL',);}diff --git a/packages/cli/foundation/fs/path-safety.test.mjs b/packages/cli/foundation/fs/path-safety.test.mjsindex 699963f3da..445a7c0f7c 100644--- a/packages/cli/foundation/fs/path-safety.test.mjs+++ b/packages/cli/foundation/fs/path-safety.test.mjs@@ -91,6 +91,13 @@ describe('sanitizeName', () => {expect(() => sanitizeName('.')).toThrow(PathSafetyError);});+ it('rejects dotfile names (.env, .htaccess) that could create hidden files', () => {+ expect(() => sanitizeName('.env')).toThrow(PathSafetyError);+ expect(() => sanitizeName('.htaccess')).toThrow(PathSafetyError);+ expect(() => sanitizeName('.bashrc')).toThrow(PathSafetyError);+ expect(() => sanitizeName('.gitignore')).toThrow(PathSafetyError);+ });+it('rejects NUL bytes', () => {expect(() => sanitizeName('foo\0bar')).toThrow(PathSafetyError);});diff --git a/packages/core/src/Chat/ChatTokenizedText.tsx b/packages/core/src/Chat/ChatTokenizedText.tsxindex c747085e8f..e696cc217a 100644--- a/packages/core/src/Chat/ChatTokenizedText.tsx+++ b/packages/core/src/Chat/ChatTokenizedText.tsx@@ -74,7 +74,7 @@ function isCustomToken(}function escapeRegExp(str: string): string {- return str.replace(/[.*+?^${}()|[\\]\\]/g, '\\$&');+ return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');}// =============================================================================diff --git a/packages/core/src/Markdown/parser.test.ts b/packages/core/src/Markdown/parser.test.tsindex b217b41515..38bb51996f 100644--- a/packages/core/src/Markdown/parser.test.ts+++ b/packages/core/src/Markdown/parser.test.ts@@ -51,6 +51,48 @@ describe('parseInline', () => {expect(result).toEqual([{type: 'image', src: 'img.png', alt: 'alt'}]);});+ it('rejects javascript: links as plain text (XSS prevention)', () => {+ const result = parseInline('[click](javascript:alert(1))');+ // Should be emitted as plain text, NOT as a link node+ expect(result).toEqual([+ {type: 'text', content: '[click](javascript:alert(1))'},+ ]);+ });++ it('rejects javascript: with mixed case and whitespace (XSS prevention)', () => {+ const result = parseInline('[click](JaVaScRiPt:alert(1))');+ expect(result).toEqual([+ {type: 'text', content: '[click](JaVaScRiPt:alert(1))'},+ ]);+ });++ it('rejects vbscript: links (XSS prevention)', () => {+ const result = parseInline('[click](vbscript:MsgBox(1))');+ expect(result).toEqual([+ {type: 'text', content: '[click](vbscript:MsgBox(1))'},+ ]);+ });++ it('rejects data:text/html image src (XSS prevention)', () => {+ const result = parseInline(+ '</script>)',+ );+ expect(result).toEqual([+ {+ type: 'text',+ content: '</script>)',+ },+ ]);+ });++ it('allows normal http/https links', () => {+ const result = parseInline('[safe](https://example.com)');+ expect(result[0].type).toBe('link');+ if (result[0].type === 'link') {+ expect(result[0].href).toBe('https://example.com');+ }+ });+it('parses strikethrough', () => {const result = parseInline('~~deleted~~');expect(result[0].type).toBe('strikethrough');@@ -727,6 +769,17 @@ describe('citation parsing', () => {});});+ it('rejects <javascript:...> angle-bracket autolinks (XSS prevention)', () => {+ const result = parseInline('see <javascript:alert(1)> ok', {+ autolink: 'gfm',+ });+ // Should NOT produce a link node with javascript: href+ const linkNodes = result.filter(+ (n): n is Extract<typeof n, {type: 'link'}> => n.type === 'link',+ );+ expect(linkNodes).toHaveLength(0);+ });+it('parses <email> angle-bracket autolinks', () => {const result = parseInline('mail <[email protected]> please', {autolink: 'gfm',diff --git a/packages/core/src/Markdown/parser.ts b/packages/core/src/Markdown/parser.tsindex 5583caa9f6..d4bd05799c 100644--- a/packages/core/src/Markdown/parser.ts+++ b/packages/core/src/Markdown/parser.ts@@ -275,7 +275,7 @@ function matchReferenceLink(// matches nothing.const label = rawLabel === '' ? linkText : rawLabel;const href = linkDefs.get(normalizeLinkLabel(label));- if (href != null) {+ if (href != null && isSafeUrl(href)) {return {node: {type: 'link', href, children: parseInlineImpl(linkText, opts)},end: labelClose + 1,@@ -290,7 +290,7 @@ function matchReferenceLink(return null;}const href = linkDefs.get(normalizeLinkLabel(linkText));- if (href == null) {+ if (href == null || !isSafeUrl(href)) {return null;}return {@@ -359,6 +359,31 @@ function isWordChar(ch: string | undefined): boolean {return /\w/.test(ch);}+// ---------------------------------------------------------------------------+// URL scheme sanitization+// ---------------------------------------------------------------------------++/**+ * Reject URLs with dangerous schemes (javascript:, vbscript:, data:) that+ * could execute arbitrary code when rendered as link hrefs or image srcs.+ * Returns true if the URL is safe to use, false otherwise.+ */+function isSafeUrl(url: string): boolean {+ // Trim and collapse whitespace/control chars that browsers tolerate but+ // could bypass a naive prefix check (e.g. "java\nscript:alert(1)").+ // eslint-disable-next-line no-control-regex -- control chars are the bypass+ const normalized = url.replace(/[\x00-\x1f\x7f]/g, '').trim();+ const lower = normalized.toLowerCase();+ if (+ lower.startsWith('javascript:') ||+ lower.startsWith('vbscript:') ||+ lower.startsWith('data:text/html')+ ) {+ return false;+ }+ return true;+}+// ---------------------------------------------------------------------------// Inline parser// ---------------------------------------------------------------------------@@ -478,11 +503,17 @@ function parseInlineImpl(text: string, opts: ResolvedOptions): InlineNode[] {if (altClose !== -1 && text[altClose + 1] === '(') {const srcClose = findClosingParen(text, altClose + 2);if (srcClose !== -1) {- nodes.push({- type: 'image',- src: text.slice(altClose + 2, srcClose),- alt: text.slice(i + 2, altClose),- });+ const src = text.slice(altClose + 2, srcClose);+ if (!isSafeUrl(src)) {+ // Dangerous scheme — emit as plain text.+ nodes.push({type: 'text', content: text.slice(i, srcClose + 1)});+ } else {+ nodes.push({+ type: 'image',+ src,+ alt: text.slice(i + 2, altClose),+ });+ }i = srcClose + 1;continue;}@@ -515,11 +546,17 @@ function parseInlineImpl(text: string, opts: ResolvedOptions): InlineNode[] {if (textClose !== -1 && text[textClose + 1] === '(') {const urlClose = findClosingParen(text, textClose + 2);if (urlClose !== -1) {- nodes.push({- type: 'link',- href: text.slice(textClose + 2, urlClose),- children: parseInlineImpl(text.slice(i + 1, textClose), opts),- });+ const href = text.slice(textClose + 2, urlClose);+ if (!isSafeUrl(href)) {+ // Dangerous scheme — emit as plain text instead of a link.+ nodes.push({type: 'text', content: text.slice(i, urlClose + 1)});+ } else {+ nodes.push({+ type: 'link',+ href,+ children: parseInlineImpl(text.slice(i + 1, textClose), opts),+ });+ }i = urlClose + 1;continue;}@@ -780,6 +817,10 @@ function scanAutolinksInText(text: string): AutolinkMatch[] {let m: RegExpExecArray | null;while ((m = re.exec(text)) !== null) {const url = m[1];+ // Skip dangerous URL schemes (javascript:, vbscript:, data:text/html)+ if (!isSafeUrl(url)) {+ continue;+ }matches.push({start: m.index,end: m.index + m[0].length,