fix: Handle unsanitized markup in DOM (#4110)

This commit is contained in:
Fayaz Ahmed 2022-03-14 18:13:21 +05:30 committed by GitHub
parent e730804b48
commit dd1fe4f93a
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 18 additions and 3 deletions

View file

@ -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() {

View file

@ -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>'
);
});
});
@ -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>'
);
});
});
});