I'm using mustache to escape user data before displaying it in html via javascript.
However, when I use it to display their data in form input fields (pre populating the form after retrieving their user data from the server via AJAX), it displays entities instead.
eg
Shaun's place
displays as
Shaun's place
I'd use the three bracket trick in Mustache, but doesn't that mean the data won't be escaped, therefore making the page vulnerable?
the data stored in MySQL is user profiles.
when I get it back from the server, I run the data through the following mustache code before saving it in a local object - the idea being I don't have to keep running it through multiple lots of mustache each time I wasn to display it in various places on the site. So here's an example of one of the keys, location, being process :
var t="{{x}}",o={x:serverObjectReturn.location},x=Mustache.render(t, o); localUserDataObject.location=x;
not 100% sure what you mean by content-type - I'm using AJAX calls, and sending the data back as JSON. The AJAX function dataType is "json". Let me know if you needed something else and I'll edit
I update the form input field so they have their profile data loaded ready for editing like so:
$("#location").val(userData.location);
That's when I get:
Shaun's place
...whereas:
$("#testerDivLocation").html(userData.location);
shows
Shaun's place
Thank you.
Here is the documentation on the subject:
All variables are HTML escaped by default. If you want to return unescaped HTML, use the triple mustache: {{{name}}}.
So you're right that it may open you up to vulnerabilities (XSS in particular). This is useful for data that you already known is safe to render in HTML, perhaps because you've escaped and/or sanitized it elsewhere.
Since input
field values are a little different because they are more raw than plain HTML, you may need to do some custom escaping either on the server-side, or in javascript just prior to the render
call. This means figuring out the set of all possible characters that put an input field at risk (quotes are obvious, but what about angle brackets <
, >
?)
An alternative is to leave the form field values blank in HTML-land and use JavaScript up set their values through the DOM. That feels much safer to me since you are no longer trying to embed the raw data into HTML code.
var t="<input type='text' name='firstname' value=''>";
var x=Mustache.render(t);
$('input', x).val(serverObjectReturn.firstname);
(Assumes jQuery is loaded for the $
call).