CVE-2023-34245 (published 2023-06-09T18:15Z)

@udecode/plate-link is the link handler for the udecode/plate rich-text editor plugin system for Slate & React. Affected versions of the link plugin and link UI component do not sanitize URLs to prevent use of the `javascript:` scheme. As a result, links with JavaScript URLs can be inserted into the Plate editor through various means, including opening or pasting malicious content. `@udecode/plate-link` 20.0.0 resolves this issue by introducing an `allowedSchemes` option to the link plugin, defaulting to `['http', 'https', 'mailto', 'tel']`. URLs using a scheme that isn't in this list will not be rendered to the DOM. Users are advised to upgrade. Users unable to upgrade are advised to override the `LinkElement` and `PlateFloatingLink` components with implementations that explicitly check the URL scheme before rendering any anchor elements.

CVSS v3 base score: 6.1, MEDIUM (CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N)

Weakness information:
cwe_id: CWE-79
cwe_name: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
description: The product does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.
extended_description: 
            Cross-site scripting (XSS) vulnerabilities occur when:
            
               Untrusted data enters a web application, typically from a web request.
               The web application dynamically generates a web page that contains this untrusted data.
               During page generation, the application does not prevent the data from containing content that is executable by a web browser, such as JavaScript, HTML tags, HTML attributes, mouse events, Flash, ActiveX, etc.
               A victim visits the generated web page through a web browser, which contains malicious script that was injected using the untrusted data.
               Since the script comes from a web page that was sent by the web server, the victim's web browser executes the malicious script in the context of the web server's domain.
               This effectively violates the intention of the web browser's same-origin policy, which states that scripts in one domain should not be able to access resources or run code in a different domain.
            
            There are three main kinds of XSS:
            
               
                  Type 1: Reflected XSS (or Non-Persistent) - 
         			The server reads data directly from the HTTP request and reflects it back in the HTTP response. Reflected XSS exploits occur when an attacker causes a victim to supply dangerous content to a vulnerable web application, which is then reflected back to the victim and executed by the web browser. The most common mechanism for delivering malicious content is to include it as a parameter in a URL that is posted publicly or e-mailed directly to the victim. URLs constructed in this manner constitute the core of many phishing schemes, whereby an attacker convinces a victim to visit a URL that refers to a vulnerable site. After the site reflects the attacker's content back to the victim, the content is executed by the victim's browser.
               
                  Type 2: Stored XSS (or Persistent) - 
               The application stores dangerous data in a database, message forum, visitor log, or other trusted data store. At a later time, the dangerous data is subsequently read back into the application and included in dynamic content. From an attacker's perspective, the optimal place to inject malicious content is in an area that is displayed to either many users or particularly interesting users. Interesting users typically have elevated privileges in the application or interact with sensitive data that is valuable to the attacker. If one of these users executes malicious content, the attacker may be able to perform privileged operations on behalf of the user or gain access to sensitive data belonging to the user. For example, the attacker might inject XSS into a log message, which might not be handled properly when an administrator views the logs.
            
               
                  Type 0: DOM-Based XSS - 
               In DOM-based XSS, the client performs the injection of XSS into the page; in the other types, the server performs the injection. DOM-based XSS generally involves server-controlled, trusted script that is sent to the client, such as Javascript that performs sanity checks on a form before the user submits it. If the server-supplied script processes user-supplied data and then injects it back into the web page (such as with dynamic HTML), then DOM-based XSS is possible.
            
            
            Once the malicious script is injected, the attacker can perform a variety of malicious activities. The attacker could transfer private information, such as cookies that may include session information, from the victim's machine to the attacker. The attacker could send malicious requests to a web site on behalf of the victim, which could be especially dangerous to the site if the victim has administrator privileges to manage that site. Phishing attacks could be used to emulate trusted web sites and trick the victim into entering a password, allowing the attacker to compromise the victim's account on that web site. Finally, the script could exploit a vulnerability in the web browser itself possibly taking over the victim's machine, sometimes referred to as "drive-by hacking."
            In many cases, the attack can be launched without the victim even being aware of it. Even with careful users, attackers frequently use a variety of methods to encode the malicious portion of the attack, such as URL encoding or Unicode, so the request looks less suspicious.
         
         

Fix information:
repo_url: https://github.com/udecode/plate
commit_details: repo_url: https://github.com/udecode/plate
author: Oli
author_date: 2023-02-28 14:26:56+00:00
msg: Apply isUrl option to pasted links #2239 (#2240)

* Apply isUrl option to pasted links #2239

* Sanitize link URLs

* Sanitize link URLs before rendering

* Fix broken tests

* Separate changesets

* Separate changeset for breaking change

---------

Co-authored-by: Joe Anderson <joe@mousetrapped.co.uk>
repository: repo_url: https://github.com/udecode/plate
repo_name: udecode/plate
description: The rich-text editor for React.
repo_language: TypeScript
owner: udecode
file_changes: filename: great-actors-work-core.md
change_type: ModificationType.ADD
diff: @@ -0,0 +1,5 @@
+---
+'@udecode/plate-core': minor
+---
+
+- Add `sanitizeUrl` util to check if URL has an allowed scheme

programming_language: SQL
filename: great-actors-work.md
change_type: ModificationType.ADD
diff: @@ -0,0 +1,12 @@
+---
+'@udecode/plate-link': minor
+---
+
+- `upsertLink`:
+  - Removed `isUrl`
+  - Added `skipValidation`
+- Check that URL scheme is valid when:
+  - Upserting links
+  - Deserializing links from HTL
+  - Passing `href` to `nodeProps`
+  - Rendering the `OpenLinkButton` in `FloatingLink`

programming_language: Markdown
filename: quiet-wombats-hug.md
change_type: ModificationType.ADD
diff: @@ -0,0 +1,6 @@
+---
+'@udecode/plate-link': major
+---
+
+- Add `allowedSchemes` plugin option
+  - Any URL schemes other than `http(s)`, `mailto` and `tel` must be added to `allowedSchemes`, otherwise they will not be included in links

programming_language: SQL
filename: link.mdx
change_type: ModificationType.MODIFY
diff: @@ -47,6 +47,12 @@ interface LinkPlugin {
    */
   triggerFloatingLinkHotkeys?: string | string[];
 
+  /**
+   * List of allowed URL schemes.
+   * @default ['http', 'https', 'mailto', 'tel']
+   */
+  allowedSchemes?: string[];
+
   /**
    * Callback to validate an url.
    * @default isUrl

programming_language: Markdown
filename: index.ts
change_type: ModificationType.MODIFY
diff: @@ -15,5 +15,6 @@ export * from './jotai';
 export * from './mergeProps';
 export * from './nanoid';
 export * from './react-hotkeys-hook';
+export * from './sanitizeUrl';
 export * from './type-utils';
 export * from './zustood';

programming_language: TypeScript
filename: sanitizeUrl.spec.ts
change_type: ModificationType.ADD
diff: @@ -0,0 +1,47 @@
+import { sanitizeUrl } from './sanitizeUrl';
+
+describe('sanitizeUrl', () => {
+  describe('when permitInvalid is false', () => {
+    const options = {
+      allowedSchemes: ['http'],
+      permitInvalid: false,
+    };
+
+    it('should return null when url is invalid', () => {
+      expect(sanitizeUrl('invalid', options)).toBeNull();
+    });
+
+    it('should return null when url has disallowed scheme', () => {
+      // eslint-disable-next-line no-script-url
+      expect(sanitizeUrl('javascript://example.com/', options)).toBeNull();
+    });
+
+    it('should return url when url is valid', () => {
+      expect(sanitizeUrl('http://example.com/', options)).toBe(
+        'http://example.com/'
+      );
+    });
+  });
+
+  describe('when permitInvalid is true', () => {
+    const options = {
+      allowedSchemes: ['http'],
+      permitInvalid: true,
+    };
+
+    it('should return url when url is invalid', () => {
+      expect(sanitizeUrl('invalid', options)).toBe('invalid');
+    });
+
+    it('should return null when url has disallowed scheme', () => {
+      // eslint-disable-next-line no-script-url
+      expect(sanitizeUrl('javascript://example.com/', options)).toBeNull();
+    });
+
+    it('should return url when url is valid', () => {
+      expect(sanitizeUrl('http://example.com/', options)).toBe(
+        'http://example.com/'
+      );
+    });
+  });
+});

programming_language: TypeScript
filename: sanitizeUrl.ts
change_type: ModificationType.ADD
diff: @@ -0,0 +1,28 @@
+export interface SanitizeUrlOptions {
+  allowedSchemes?: string[];
+  permitInvalid?: boolean;
+}
+
+export const sanitizeUrl = (
+  url: string | undefined,
+  { allowedSchemes, permitInvalid = false }: SanitizeUrlOptions
+): string | null => {
+  if (!url) return null;
+
+  let parsedUrl: URL | null = null;
+
+  try {
+    parsedUrl = new URL(url);
+  } catch (error) {
+    return permitInvalid ? url : null;
+  }
+
+  if (
+    allowedSchemes &&
+    !allowedSchemes.includes(parsedUrl.protocol.slice(0, -1))
+  ) {
+    return null;
+  }
+
+  return parsedUrl.href;
+};

programming_language: TypeScript
filename: OpenLinkButton.tsx
change_type: ModificationType.MODIFY
diff: @@ -11,6 +11,7 @@ import {
 } from '@udecode/plate-core';
 import { ELEMENT_LINK } from '../../createLinkPlugin';
 import { TLinkElement } from '../../types';
+import { getLinkAttributes } from '../../utils/index';
 
 export const useOpenLinkButton = (
   props: HTMLPropsAs<'a'>
@@ -31,12 +32,13 @@ export const useOpenLinkButton = (
     return {};
   }
 
-  const [link] = entry;
+  const [element] = entry;
+  const linkAttributes = getLinkAttributes(editor, element);
 
   return {
-    'aria-label': 'Open link in a new tab',
+    ...linkAttributes,
     target: '_blank',
-    href: link.url,
+    'aria-label': 'Open link in a new tab',
     onMouseOver: (e) => {
       e.stopPropagation();
     },

programming_language: TypeScript
filename: Link.tsx
change_type: ModificationType.MODIFY
diff: @@ -7,17 +7,17 @@ import {
   Value,
 } from '@udecode/plate-core';
 import { TLinkElement } from '../types';
+import { getLinkAttributes } from '../utils/index';
 
 export type LinkRootProps = PlateRenderElementProps<Value, TLinkElement> &
   HTMLPropsAs<'a'>;
 
 export const useLink = (props: LinkRootProps): HTMLPropsAs<'a'> => {
+  const { editor } = props;
+
   const _props = useElementProps<TLinkElement, 'a'>({
     ...props,
-    elementToAttributes: (element) => ({
-      href: element.url,
-      target: element.target,
-    }),
+    elementToAttributes: (element) => getLinkAttributes(editor, element),
   });
 
   return {

programming_language: TypeScript
filename: createLinkPlugin.ts
change_type: ModificationType.MODIFY
diff: @@ -1,8 +1,10 @@
 import {
   createPluginFactory,
-  isUrl as isUrlProtocol,
+  isUrl,
   RangeBeforeOptions,
 } from '@udecode/plate-core';
+import { getLinkAttributes, validateUrl } from './utils/index';
+import { TLinkElement } from './types';
 import { withLink } from './withLink';
 
 export const ELEMENT_LINK = 'a';
@@ -27,6 +29,12 @@ export interface LinkPlugin {
    */
   triggerFloatingLinkHotkeys?: string | string[];
 
+  /**
+   * List of allowed URL schemes.
+   * @default ['http', 'https', 'mailto', 'tel']
+   */
+  allowedSchemes?: string[];
+
   /**
    * Callback to validate an url.
    * @default isUrl
@@ -53,12 +61,10 @@ export const createLinkPlugin = createPluginFactory<LinkPlugin>({
   key: ELEMENT_LINK,
   isElement: true,
   isInline: true,
-  props: ({ element }) => ({
-    nodeProps: { href: element?.url, target: element?.target },
-  }),
   withOverrides: withLink,
   options: {
-    isUrl: isUrlProtocol,
+    allowedSchemes: ['http', 'https', 'mailto', 'tel'],
+    isUrl,
     rangeBeforeOptions: {
       matchString: ' ',
       skipInvalid: true,
@@ -67,17 +73,28 @@ export const createLinkPlugin = createPluginFactory<LinkPlugin>({
     triggerFloatingLinkHotkeys: 'meta+k, ctrl+k',
   },
   then: (editor, { type }) => ({
+    props: ({ element }) => ({
+      nodeProps: getLinkAttributes(editor, element as TLinkElement),
+    }),
     deserializeHtml: {
       rules: [
         {
           validNodeName: 'A',
         },
       ],
-      getNode: (el) => ({
-        type,
-        url: el.getAttribute('href'),
-        target: el.getAttribute('target') || '_blank',
-      }),
+      getNode: (el) => {
+        const url = el.getAttribute('href');
+
+        if (url && validateUrl(editor, url)) {
+          return {
+            type,
+            url,
+            target: el.getAttribute('target') || '_blank',
+          };
+        }
+
+        return undefined;
+      },
     },
   }),
 });

programming_language: TypeScript
filename: submitFloatingLink.ts
change_type: ModificationType.MODIFY
diff: @@ -9,6 +9,7 @@ import {
   floatingLinkSelectors,
 } from '../components/FloatingLink/floatingLinkStore';
 import { ELEMENT_LINK, LinkPlugin } from '../createLinkPlugin';
+import { validateUrl } from '../utils/index';
 import { upsertLink } from './index';
 
 /**
@@ -20,14 +21,10 @@ import { upsertLink } from './index';
 export const submitFloatingLink = <V extends Value>(editor: PlateEditor<V>) => {
   if (!editor.selection) return;
 
-  const { isUrl, forceSubmit } = getPluginOptions<LinkPlugin, V>(
-    editor,
-    ELEMENT_LINK
-  );
+  const { forceSubmit } = getPluginOptions<LinkPlugin, V>(editor, ELEMENT_LINK);
 
   const url = floatingLinkSelectors.url();
-  const isValid = isUrl?.(url) || forceSubmit;
-  if (!isValid) return;
+  if (!forceSubmit && !validateUrl(editor, url)) return;
 
   const text = floatingLinkSelectors.text();
   const target = floatingLinkSelectors.newTab() ? undefined : '_self';
@@ -38,7 +35,7 @@ export const submitFloatingLink = <V extends Value>(editor: PlateEditor<V>) => {
     url,
     text,
     target,
-    isUrl: (_url) => (forceSubmit || !isUrl ? true : isUrl(_url)),
+    skipValidation: true,
   });
 
   setTimeout(() => {

programming_language: TypeScript
filename: upsertLink.spec.tsx
change_type: ModificationType.MODIFY
diff: @@ -415,7 +415,7 @@ describe('upsertLink', () => {
     });
   });
 
-  describe('when isUrl always true', () => {
+  describe('when skipValidation is false and url is invalid', () => {
     const input = (
       <editor>
         <hp>
@@ -426,16 +426,46 @@ describe('upsertLink', () => {
     ) as any;
 
     const output = (
+      <editor>
+        <hp>insert link.</hp>
+      </editor>
+    ) as any;
+
+    it('should do nothing', () => {
+      const editor = createEditor(input);
+      upsertLink(editor, {
+        url: 'invalid',
+        skipValidation: false,
+      });
+
+      expect(input.children).toEqual(output.children);
+    });
+  });
+
+  describe('when skipValidation is true and url is invalid', () => {
+    const input = (
       <editor>
         <hp>
-          insert link<ha url="test">test</ha>.
+          insert link
+          <cursor />.
+        </hp>
+      </editor>
+    ) as any;
+
+    const output = (
+      <editor>
+        <hp>
+          insert link<ha url="invalid">invalid</ha>.
         </hp>
       </editor>
     ) as any;
 
     it('should insert', () => {
       const editor = createEditor(input);
-      upsertLink(editor, { url: 'test', isUrl: (_url) => true });
+      upsertLink(editor, {
+        url: 'invalid',
+        skipValidation: true,
+      });
 
       expect(input.children).toEqual(output.children);
     });

programming_language: TypeScript
filename: upsertLink.ts
change_type: ModificationType.MODIFY
diff: @@ -4,7 +4,6 @@ import {
   getEditorString,
   getNodeLeaf,
   getNodeProps,
-  getPluginOptions,
   getPluginType,
   InsertNodesOptions,
   isDefined,
@@ -16,9 +15,9 @@ import {
   Value,
   WrapNodesOptions,
 } from '@udecode/plate-core';
-import { ELEMENT_LINK, LinkPlugin } from '../createLinkPlugin';
+import { ELEMENT_LINK } from '../createLinkPlugin';
 import { TLinkElement } from '../types';
-import { CreateLinkNodeOptions } from '../utils/index';
+import { CreateLinkNodeOptions, validateUrl } from '../utils/index';
 import { insertLink } from './insertLink';
 import { unwrapLink } from './unwrapLink';
 import { upsertLinkText } from './upsertLinkText';
@@ -34,7 +33,7 @@ export type UpsertLinkOptions<
   insertNodesOptions?: InsertNodesOptions<V>;
   unwrapNodesOptions?: UnwrapNodesOptions<V>;
   wrapNodesOptions?: WrapNodesOptions<V>;
-  isUrl?: (url: string) => boolean;
+  skipValidation?: boolean;
 };
 
 /**
@@ -53,7 +52,7 @@ export const upsertLink = <V extends Value>(
     target,
     insertTextInLink,
     insertNodesOptions,
-    isUrl = getPluginOptions<LinkPlugin, V>(editor, ELEMENT_LINK).isUrl,
+    skipValidation = false,
   }: UpsertLinkOptions<V>
 ) => {
   const at = editor.selection;
@@ -72,7 +71,7 @@ export const upsertLink = <V extends Value>(
     return true;
   }
 
-  if (!isUrl?.(url)) return;
+  if (!skipValidation && !validateUrl(editor, url)) return;
 
   if (isDefined(text) && !text.length) {
     text = url;

programming_language: TypeScript
filename: getLinkAttributes.spec.ts
change_type: ModificationType.ADD
diff: @@ -0,0 +1,60 @@
+import { createPlateEditor } from '@udecode/plate-core';
+import { createLinkPlugin, LinkPlugin } from '../createLinkPlugin';
+import { TLinkElement } from '../types';
+import { getLinkAttributes } from './getLinkAttributes';
+
+const baseLink = {
+  type: 'a',
+  children: [{ text: 'Link text' }],
+};
+
+describe('getLinkAttributes', () => {
+  const editor = createPlateEditor({
+    plugins: [createLinkPlugin()],
+  });
+
+  describe('when url is valid', () => {
+    const link: TLinkElement = {
+      ...baseLink,
+      url: 'https://example.com/',
+      target: '_self',
+    };
+
+    it('should return href and target', () => {
+      expect(getLinkAttributes(editor, link)).toEqual({
+        href: 'https://example.com/',
+        target: '_self',
+      });
+    });
+  });
+
+  describe('when url is invalid', () => {
+    const link: TLinkElement = {
+      ...baseLink,
+      // eslint-disable-next-line no-script-url
+      url: 'javascript://example.com/',
+      target: '_self',
+    };
+
+    it('href should be undefined', () => {
+      expect(getLinkAttributes(editor, link)).toEqual({
+        href: undefined,
+        target: '_self',
+      });
+    });
+  });
+
+  describe('when target is not set', () => {
+    const link: TLinkElement = {
+      ...baseLink,
+      url: 'https://example.com/',
+    };
+
+    it('target should be undefiend', () => {
+      expect(getLinkAttributes(editor, link)).toEqual({
+        href: 'https://example.com/',
+        target: undefined,
+      });
+    });
+  });
+});

programming_language: TypeScript
filename: getLinkAttributes.ts
change_type: ModificationType.ADD
diff: @@ -0,0 +1,23 @@
+import {
+  getPluginOptions,
+  PlateEditor,
+  sanitizeUrl,
+  Value,
+} from '@udecode/plate-core';
+import { ELEMENT_LINK, LinkPlugin } from '../createLinkPlugin';
+import { TLinkElement } from '../types';
+
+export const getLinkAttributes = <V extends Value>(
+  editor: PlateEditor<V>,
+  link: TLinkElement
+) => {
+  const { allowedSchemes } = getPluginOptions<LinkPlugin, V>(
+    editor,
+    ELEMENT_LINK
+  );
+
+  const href = sanitizeUrl(link.url, { allowedSchemes }) || undefined;
+  const { target } = link;
+
+  return { href, target };
+};

programming_language: TypeScript
filename: index.ts
change_type: ModificationType.MODIFY
diff: @@ -3,6 +3,8 @@
  */
 
 export * from './createLinkNode';
+export * from './getLinkAttributes';
 export * from './triggerFloatingLink';
 export * from './triggerFloatingLinkEdit';
 export * from './triggerFloatingLinkInsert';
+export * from './validateUrl';

programming_language: TypeScript
filename: validateUrl.ts
change_type: ModificationType.ADD
diff: @@ -0,0 +1,29 @@
+import {
+  getPluginOptions,
+  PlateEditor,
+  sanitizeUrl,
+  Value,
+} from '@udecode/plate-core';
+import { ELEMENT_LINK, LinkPlugin } from '../createLinkPlugin';
+
+export const validateUrl = <V extends Value>(
+  editor: PlateEditor<V>,
+  url: string
+): boolean => {
+  const { allowedSchemes, isUrl } = getPluginOptions<LinkPlugin, V>(
+    editor,
+    ELEMENT_LINK
+  );
+
+  if (isUrl && !isUrl(url)) return false;
+
+  if (
+    !sanitizeUrl(url, {
+      allowedSchemes,
+      permitInvalid: true,
+    })
+  )
+    return false;
+
+  return true;
+};

programming_language: TypeScript