Skip to content

Commit

Permalink
Bug: escape XML-entities in codeSyntaxHighlight plugin when language …
Browse files Browse the repository at this point in the history
…is unspecified (fix nhn#3220)
  • Loading branch information
hexwayteam committed Jan 25, 2024
1 parent 0c5c11b commit 3dc4ab7
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import type { MdNode, CodeBlockMdNode } from '@toast-ui/editor';
import type { HTMLToken } from '@toast-ui/toastmark';
import { PrismJs } from '@t/index';
import { escapeXml } from '@/utils/common';

const BACKTICK_COUNT = 3;

Expand All @@ -17,6 +18,7 @@ export function getHTMLRenderers(prism: PrismJs) {
}

let content = node.literal!;
let contentEscaped = false;

if (infoWords.length && infoWords[0].length) {
const [lang] = infoWords;
Expand All @@ -28,9 +30,12 @@ export function getHTMLRenderers(prism: PrismJs) {

if (registeredLang) {
content = prism.highlight(node.literal!, registeredLang, lang);
contentEscaped = true;
}
}

content = contentEscaped ? content : escapeXml(content);

return [
{ type: 'openTag', tagName: 'pre', classNames: preClasses },
{ type: 'openTag', tagName: 'code', attributes: codeAttrs },
Expand Down
25 changes: 25 additions & 0 deletions plugins/code-syntax-highlight/src/utils/common.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,28 @@
export function flatten<T>(arr: T[]): T[] {
return arr.reduce<T[]>((a, b) => a.concat(Array.isArray(b) ? flatten(b) : b), []);
}

const XMLSPECIAL = '[&<>"]';
const reXmlSpecial = new RegExp(XMLSPECIAL, 'g');

function replaceUnsafeChar(char: string) {
switch (char) {
case '&':
return '&amp;';
case '<':
return '&lt;';
case '>':
return '&gt;';
case '"':
return '&quot;';
default:
return char;
}
}

export function escapeXml(text: string) {
if (reXmlSpecial.test(text)) {
return text.replace(reXmlSpecial, replaceUnsafeChar);
}
return text;
}

0 comments on commit 3dc4ab7

Please sign in to comment.