Skip to content

Commit

Permalink
fix: Handle unsanitized markup in DOM (#4110)
Browse files Browse the repository at this point in the history
  • Loading branch information
fayazara committed Mar 14, 2022
1 parent e730804 commit dd1fe4f
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 3 deletions.
7 changes: 6 additions & 1 deletion app/javascript/shared/helpers/MessageFormatter.js
Expand Up @@ -47,7 +47,12 @@ class MessageFormatter {
const markedDownOutput = marked(withHash);
return markedDownOutput;
}
return marked(this.message, { breaks: true, gfm: true });
DOMPurify.addHook('afterSanitizeAttributes', node => {
if ('target' in node) node.setAttribute('target', '_blank');
});
return DOMPurify.sanitize(
marked(this.message, { breaks: true, gfm: true })
);
}

get formattedMessage() {
Expand Down
14 changes: 12 additions & 2 deletions app/javascript/shared/helpers/specs/MessageFormatter.spec.js
Expand Up @@ -6,14 +6,14 @@ describe('#MessageFormatter', () => {
const message =
'Chatwoot is an opensource tool. [Chatwoot](https://www.chatwoot.com)';
expect(new MessageFormatter(message).formattedMessage).toMatch(
'<p>Chatwoot is an opensource tool. <a rel="noreferrer noopener nofollow" href="https://www.chatwoot.com" class="link" title="" target="_blank">Chatwoot</a></p>'
'<p>Chatwoot is an opensource tool. <a title="" class="link" href="https://www.chatwoot.com" rel="noreferrer noopener nofollow" target="_blank">Chatwoot</a></p>'
);
});
it('should format correctly', () => {
const message =
'Chatwoot is an opensource tool. https://www.chatwoot.com';
expect(new MessageFormatter(message).formattedMessage).toMatch(
'<p>Chatwoot is an opensource tool. <a rel="noreferrer noopener nofollow" href="https://www.chatwoot.com" class="link" title="" target="_blank">https://www.chatwoot.com</a></p>'
'<p>Chatwoot is an opensource tool. <a title="" class="link" href="https://www.chatwoot.com" rel="noreferrer noopener nofollow" target="_blank">https://www.chatwoot.com</a></p>'
);
});
});
Expand Down Expand Up @@ -58,4 +58,14 @@ describe('#MessageFormatter', () => {
);
});
});

describe('#sanitize', () => {
it('sanitizes markup and removes all unnecessary elements', () => {
const message =
'[xssLink](javascript:alert(document.cookie))\n[normalLink](https://google.com)**I am a bold text paragraph**';
expect(new MessageFormatter(message).formattedMessage).toMatch(
'<p><a title="" class="link" rel="noreferrer noopener nofollow" target="_blank">xssLink</a><br><a title="" class="link" href="https://google.com" rel="noreferrer noopener nofollow" target="_blank">normalLink</a><strong>I am a bold text paragraph</strong></p>'
);
});
});
});

0 comments on commit dd1fe4f

Please sign in to comment.