Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript and CSP - best practices [closed]

I want to use Content Site Protection for my web application. If you haven't heard of it, in short: it will allow me to disable any embedded javascript into my web app, helping preventing XSS.

The result is, all my javascript code will have to be in external files.

Most javascript 'library/framework' code already is, but usually my pages will contain at least a few lines of JS code, instantiating components that are relevant to a specific page.

For example, I have a hypothetical registration page. On the bottom of the registration page, I have the following code:

var registrationForm = new MyApp.registrationValidator($('.regform'));
registrationForm.init();

This hypothetical code gets a reference to the registration form, and could register all the validation code.

Now I have to move this code to an external file. I could:

Option A: create a small .js file for every page, that only executes code specific for that page.

  • Pros - Simple and relatively fast
  • Cons - This an extra js file for every page, I'd much prefer to be able to minimize all my javascript into a single file to reduce requests.

Option B: Execute all my 'instantiating code' in a javascript file. I'll just detect if there's any '.regForm' css classes on the page and only instantiate my objects if they appear on the page.

  • Pros - Single place for instantiation. Components on the page will magically start working, if they have the correct css class.
  • Cons - If my application grows quite a bit, there will be a lot of initializing code that may be unneeded for a specific page.

Option C: Give my <body> tag an id or class, and execute the correct code based on a big switch.

  • Pros: Can still be a compressed to a single .js file and I don't need a .js file per page.
  • Cons: I suppose I feel this is a bit ugly.

All in all, Option B is the nicest, if it weren't for the fact that I feel it's a bad idea to have a ton of initializing code.

What I'm mainly wondering is, do you have experiences with this situation, and how did you solve it?

like image 706
Evert Avatar asked Oct 08 '22 19:10

Evert


2 Answers

Option D (Variant of A and B): Have a look at deployment systems which will compile (and minify) multiple javascript source files into one, taking only the required files for that page into account.

For PHP, Assetic is such a system.

like image 51
Christian Studer Avatar answered Oct 12 '22 01:10

Christian Studer


if you are willing to use a framework like jQuery (to dynamically load and execute external javascript), you could have the benefits of A and B combined. every page would load the same .js, which determines (by presence or absence of dom elements) which other .js files to load dynamically.

like image 38
maddrag0n Avatar answered Oct 12 '22 00:10

maddrag0n