onionhammer / nim-templates

A simple string templating library for Nim
BSD 3-Clause "New" or "Revised" License
94 stars 9 forks source link

xmlEncode #11

Open itsumura-h opened 2 years ago

itsumura-h commented 2 years ago

Variable should be xml encoded to prevent XSS https://nim-lang.org/docs/cgi.html#xmlEncode%2Cstring

import templates

let x = "<script>alert("hello")</script>"

let dom = tmpli html"""
<p>$x</p>
"""   ↑Dainger

so I propose a new syntax if possible

then it shoud be like this

import templates

let x = "<script>alert("hello")</script>"

let dom = tmpli html"""
<p>${{x}}</p>
"""
assert dom == "<p>&lt;script&gt;alert(&quot;hello&quot;)&lt;/script&gt;</p>"
onionhammer commented 2 years ago

Interesting idea - My only concern would be it interfering with some other nim syntax. What about adding another prefix to indicate escape; like '$!' instead of just '$' ?

i..e.

import templates

let x = "<script>alert("hello")</script>"

let dom = tmpli html"""
<p>$!x</p>
"""
assert dom == "<p>&lt;script&gt;alert(&quot;hello&quot;)&lt;/script&gt;</p>"
itsumura-h commented 2 years ago

@onionhammer "!" means destructive change or doing something that should not be used but is unavoidably dangerous in other programming languages. so "$!x" prefers be like dangerouslySetInnerHTML in react, and if "$x" is escaped by default, it is safe.

onionhammer commented 2 years ago

Yeah good point. I wouldn't want to issue a breaking change for this, but syntactic sugar for escaping the HTML would be nice.