xss – Prevent Cross Site Scripting but still support HTML file upload

I have a web application where user can upload and view files. The user has a link next to the file (s)he has uploaded. Clicking on the link will open the file in the browser (if possible) or show the download dialog (of the browser). Meaning that, if the user upload an html/pdf/txt file it will be rendered in the browser but if it is a word document, it will be downloaded. The file url is like https://mydoma.in/ran-dom-guid.

It is identified that rendering the HTML file in the browser could be a vulnerability – Cross Site Scripting. That is, since the file is executed under my domain, it is possible to attack if it contains a malicious script.

What is the right solution to this problem? The two options I am currently looking at are:

  1. to put Content-Disposition header in the response to make HTML files downloaded instead viewed in the browser.
  2. to find some html scrubbing/sanitizing library to remove any javascript from the file before I serve it.

Looking at the gmail, they do the second approach (of scrubbing) with having a separate domain for the file download – may be to minimize/distract the attack surface. However in this approach the receiver gets a different file than what was sent. Which is not ‘right’ in my opinion; may be I am biased. In my case, the first one is easy to fix. But I wonder if that is enough, or is there any thing that I overlook!

What are your thoughts on these approaches? Or do you have any other suggestions?