danharper / Handlebars-Helpers

A small collection of useful helpers for Handlebars.js
Do What The F*ck You Want To Public License
274 stars 55 forks source link

String escaping in nl2br #7

Closed mirozoo closed 11 years ago

mirozoo commented 11 years ago

I discovered that the nl2br helper function returns a Handlebars.SafeString which isn't being escaped during rendering. While this is necessary to leave the inserted br-Tags untouched, it can cause security issues (e. g. XSS) if the INPUT string is not escaped. In my opinion this should be done before the replacement is performed:

Handlebars.registerHelper('nl2br', function(text) {
    text = Handlebars.Utils.escapeExpression(text);
    var nl2br = (text + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1' + '<br>' + '$2');
    return new Handlebars.SafeString(nl2br);
});
danharper commented 11 years ago

Yeah, that makes sense. Would you mind submitting a PR for this? If not, I'll get to it at some point later.

It's a shame Handlebars offers no way to know if a helper was called with a double or triple stash (to determine if the input should be escaped or not) - there's an open issue for this here.

danharper commented 11 years ago

Merged with #8.