Skip to content

Instantly share code, notes, and snippets.

@whump
Last active December 12, 2015 00:08
Show Gist options
  • Save whump/4681137 to your computer and use it in GitHub Desktop.
Save whump/4681137 to your computer and use it in GitHub Desktop.
A quick note on bootstrapping Backbone models without XSSing yourself.

Writing out the initial model data as a JSON object in a SCRIPT literal can leave you open to a cross-site scripting/injection attack.

To mitigate against this risk, use the OWASP guideline for bootstrapping an application with JSON data.

Write the HTML-escaped JSON inside of a hidden div, then fetch the contents of the div and parse it using JSON.parse.

<div style="display: none;">
!= $data
</div>

var accountsData = [];
var Accounts = new Backbone.Collection;

// we will do the parsing in a try block to catch the 
// case when we do get invalid JSON from the server 
// (which may or may not contain an injection 
try {
    accountsData = JSON.parse($('div#Accounts-Data').text());
    Accounts.reset(accountsData);
}
catch(err) {
    console.log('error parsing accounts data');
    // try Accounts.fetch() to load the model
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment