From 5db096942aeaa134e70b8a203350c062eb17104e Mon Sep 17 00:00:00 2001 From: Tessa Thornton Date: Fri, 27 Mar 2020 14:09:42 -0400 Subject: [PATCH] remove 'mailto:' prefix from links (#2914) Co-authored-by: Kim Gardner --- .../common/utils/__snapshots__/purify.spec.ts.snap | 2 +- src/core/common/utils/purify.spec.ts | 5 ++++- src/core/common/utils/purify.ts | 12 ++++++++++-- 3 files changed, 15 insertions(+), 4 deletions(-) diff --git a/src/core/common/utils/__snapshots__/purify.spec.ts.snap b/src/core/common/utils/__snapshots__/purify.spec.ts.snap index 39adb400a..657199578 100644 --- a/src/core/common/utils/__snapshots__/purify.spec.ts.snap +++ b/src/core/common/utils/__snapshots__/purify.spec.ts.snap @@ -2,7 +2,7 @@ exports[`allows anchor links 1`] = ` Object { - "body": "test", + "body": "http://test.com", "linkCount": 1, } `; diff --git a/src/core/common/utils/purify.spec.ts b/src/core/common/utils/purify.spec.ts index 94c1dac0a..df113cee7 100644 --- a/src/core/common/utils/purify.spec.ts +++ b/src/core/common/utils/purify.spec.ts @@ -26,7 +26,10 @@ it("sanitizes out attributes not allowed", () => { it("allows anchor links", () => { expect( - sanitizeCommentBody(DOMPurify, 'This is a link') + sanitizeCommentBody( + DOMPurify, + 'This is a link' + ) ).toMatchSnapshot(); }); diff --git a/src/core/common/utils/purify.ts b/src/core/common/utils/purify.ts index 0b2b4ee3e..897062ae1 100644 --- a/src/core/common/utils/purify.ts +++ b/src/core/common/utils/purify.ts @@ -1,6 +1,7 @@ import createDOMPurify from "dompurify"; type DOMPurify = ReturnType; +const MAILTO_PROTOCOL = "mailto:"; export function createPurify(window: Window, returnDOM = true) { // Initializing JSDOM and DOMPurify @@ -26,8 +27,15 @@ export function createPurify(window: Window, returnDOM = true) { node.setAttribute("rel", "noopener noreferrer"); // Ensure that all the links have the same link as they do text. - const href = node.getAttribute("href"); - if (node.textContent !== href) { + let href = node.getAttribute("href"); + if (href) { + if (node.textContent !== href) { + // remove "mailto:" prefix from link text + const url = new URL(href); + if (url.protocol === MAILTO_PROTOCOL) { + href = href.replace(url.protocol, ""); + } + } node.textContent = href; } } else {