开发者

Safe JavaScript Templates

开发者 https://www.devze.com 2023-01-05 20:02 出处:网络
I am looking to allow users to create templates to display their data, and these templates are to be rendered using JavaScript. I was wondering if it was possible to开发者_StackOverflow社区 safely do

I am looking to allow users to create templates to display their data, and these templates are to be rendered using JavaScript. I was wondering if it was possible to开发者_StackOverflow社区 safely do this? I just need simple things like loops and if-else statements and of course accessing and printing values of variables in a given object.

Are there any template libraries that allow this, or easy methods for accomplishing this task?


The following are considering possibly Node.js server-safe options (no arbitrary code execution / infinite loops). Browser safe (XSS) is hard / impossible.

Mustache appears to be explicitly designed to be safe for user consumption and prevent infinite loops to avoid server DoS: https://github.com/janl/mustache.js/

You can also look for JavaScript Liquid ports: Liquid templating for Node.js such as https://github.com/liquid-lang/liquid-node since Liquid is the default GitHub pages choice, so it should be safe to run on the server.

Options which are known not to be safe:

  • https://mozilla.github.io/nunjucks/templating.html "nunjucks does not sandbox execution so it is not safe to run user-defined templates or inject user-defined content into template definitions."


You can't run something safe in the browser.

What you can do is to sandbox potentially unsafe content in an IFRAME with a src slightly different from your main page. eg:

  • your page is on www.example.com
  • and your iframe is on something like: sandbox.example.com , www.example.com:8080, ...

The IFRAME will not be able to access the parent page resources. That does not prevent XSS, but this is another issue you have to care anyway.

And if you look about a templating engine, have a look at PURE, it separates well HTML and JS.

You could then give the option to people build the HTML only of the templates and leave the JS code on your side. And if necessary, build a cleaning function to insure the HTML contains no JS.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号