Although your script only displays to the current user, your page may be vulnerable to a Cross Site Scripting attack. The way to handle it in this case (as you are allowing scripts) is to use a similar mechanism to a Cross Site Request Forgery prevention (although CSRF and XSS are completely different).
e.g. if your page https://www.example.com/preview
displays all content (HTML and script) POSTed to it (for thie example assume the POSt parameter is called content
), an attacker may include the following code on their page and then entice the victim to visit it whilst logged into your website.
On www.evil.com
:-
<form method="post" action="https://www.example.com/preview">
<input type="hidden" name="content" value="<script>alert('foo');</script>" />
</form>
and this form could be submitted automatically via JavaScript (document.forms[0].submit()
).
This will cause the script in content
to be executed in the context of your site, possibly passing cookie values of the user's session to www.evil.com
rather than my benign example of an alert box.
However, as your are POSTing the content
value to your own site using AJAX, you can prevent this attack by checking that the X-Requested-With
request header is set to XMLHttpRequest
. This header cannot be POSTed cross domain (without your server agreeing to this using CORS).
Also, if your page is for a preview - what is the preview for if your preview cannot be saved? If this is related to your full save functionality, then it is possible to allow a user to save scripts safely by running the entered content within a sandbox.