From 90f21f4ed1213a1b5ff35b85ee0bb42c0ba2aca3 Mon Sep 17 00:00:00 2001 From: Nikolay Lopin Date: Sun, 25 Mar 2018 23:47:17 +0300 Subject: [PATCH] Escape html characters before convert to HTML --- browser/components/MarkdownPreview.js | 3 +- browser/lib/utils.js | 53 ++++++++++++++++++++++++++- 2 files changed, 53 insertions(+), 3 deletions(-) diff --git a/browser/components/MarkdownPreview.js b/browser/components/MarkdownPreview.js index bd5d3939..f3646f94 100755 --- a/browser/components/MarkdownPreview.js +++ b/browser/components/MarkdownPreview.js @@ -13,6 +13,7 @@ import htmlTextHelper from 'browser/lib/htmlTextHelper' import copy from 'copy-to-clipboard' import mdurl from 'mdurl' import exportNote from 'browser/main/lib/dataApi/exportNote' +import {escapeHtmlCharacters} from 'browser/lib/utils' const { remote } = require('electron') const { app } = remote @@ -208,7 +209,7 @@ export default class MarkdownPreview extends React.Component { const {fontFamily, fontSize, codeBlockFontFamily, lineNumber, codeBlockTheme} = this.getStyleParams() const inlineStyles = buildStyle(fontFamily, fontSize, codeBlockFontFamily, lineNumber, codeBlockTheme, lineNumber) - const body = this.markdown.render(noteContent) + const body = this.markdown.render(escapeHtmlCharacters(noteContent)) const files = [this.GetCodeThemeLink(codeBlockTheme), ...CSS_FILES] files.forEach((file) => { diff --git a/browser/lib/utils.js b/browser/lib/utils.js index be66f2ec..f67ca377 100644 --- a/browser/lib/utils.js +++ b/browser/lib/utils.js @@ -6,6 +6,55 @@ export function lastFindInArray (array, callback) { } } -export default { - lastFindInArray +export function escapeHtmlCharacters (text) { + const matchHtmlRegExp = /["'&<>]/ + const str = '' + text + const match = matchHtmlRegExp.exec(str) + + if (!match) { + return str + } + + let escape + let html = '' + let index = 0 + let lastIndex = 0 + + for (index = match.index; index < str.length; index++) { + switch (str.charCodeAt(index)) { + case 34: // " + escape = '"' + break + case 38: // & + escape = '&' + break + case 39: // ' + escape = ''' + break + case 60: // < + escape = '<' + break + case 62: // > + escape = '>' + break + default: + continue + } + + if (lastIndex !== index) { + html += str.substring(lastIndex, index) + } + + lastIndex = index + 1 + html += escape + } + + return lastIndex !== index + ? html + str.substring(lastIndex, index) + : html +} + +export default { + lastFindInArray, + escapeHtmlCharacters }