Skip to content

Instantly share code, notes, and snippets.

@righ
Created August 6, 2018 01:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save righ/50e358076d661e8c6f3cb6979011ead5 to your computer and use it in GitHub Desktop.
Save righ/50e358076d661e8c6f3cb6979011ead5 to your computer and use it in GitHub Desktop.
markdown_xss_test
const deniedTagCondition = /^<\/?(script|style|link|iframe|embed|object|html|head|meta|body|form|input|button)/i
const deniedAttrCondition = /^(on.+|style|href|action|id|class|data-.*)/i
const escape = (txt) => {
if (txt.match(deniedTagCondition) || txt.indexOf('<!') === 0 || txt.indexOf('<?') === 0 || txt.indexOf('<\\') === 0) { return '' }
if (txt.indexOf('</') === 0) { return txt }
let outer = document.createElement('div')
outer.innerHTML = txt
let el = outer.querySelector('*')
if (!el) {return ''}
let attrs = []
el.getAttributeNames().map(attr => {
if (attr.match(deniedAttrCondition)) {
el.removeAttribute(attr)
return
}
attrs.push(`${attr}="${el.getAttribute(attr)}1"`)
})
return `<${el.tagName} ${attrs.join(' ')}>`
}
<html>
<head>
<meta charset="UTF-8" />
<style>
#editor {width: 100%; height: 200px;}
#viewer {min-height: 100px; width: 100%; background-color: #eef; margin-top: 10px; padding:10px}
</style>
</head>
<body>
<textarea id="editor" placeholder="タグを含む文字列を入力してみてください"></textarea>
<button onclick="document.querySelector('#viewer').innerHTML = marked(document.querySelector('#editor').value)">Render</button>
<div id="viewer"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/marked/0.4.0/marked.min.js"></script>
<script src="./escape.js"></script>
<script>
marked.setOptions({
breaks: true,
sanitize: true,
sanitizer: escape,
});
</script>
</body>
</html>
<html>
<head>
<meta charset="UTF-8" />
<style>
#editor {width: 100%; height: 200px;}
#viewer {min-height: 100px; width: 100%; background-color: #eef; margin-top: 10px; padding:10px}
</style>
</head>
<body>
<textarea id="editor" placeholder="タグを含む文字列を入力してみてください"></textarea>
<button onclick="document.querySelector('#viewer').innerHTML = marked(document.querySelector('#editor').value)">Render</button>
<div id="viewer"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/marked/0.4.0/marked.min.js"></script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment