samrum / vite-plugin-web-extension

A vite plugin for generating cross browser platform, ES module based web extensions.
MIT License
325 stars 32 forks source link

Improve the way CSP is modified in HMR mode #54

Closed mdp closed 1 year ago

mdp commented 1 year ago

The reason for this PR is that we are passing in an already fairly defined CSP for our extension, but in HMR mode this plugin makes some breaking changes to the CSP definition.

Currently, anything we place in 'script-src' on the custom CSP gets overwritten by this plugins addition of HMR 'script-src' and 'object-src' settings.

Because the 'script-src' concatenation on https://github.com/samrum/vite-plugin-web-extension/blob/main/src/devBuilder/devBuilder.ts#L75 tacks on "; object-src 'self'" the following instruction

https://github.com/samrum/vite-plugin-web-extension/blob/main/src/devBuilder/devBuilder.ts#L82

replaces 'script-src' with script-src [hmrstuff]; object-src 'self' which ends up leading to some strange output if you actually had 'script-src' values you passed in:

script-src foo.com; img-src fooimage.com turns into script-src 'self' [hmrserver and inline hashes]; object-src 'self' foo.com; img-src fooimage.com

So you end up with object-src containing all the values you expected in script-src.

This proposed PR tries to do a couple things.

  1. Parses the CSP and make improvements to the HMR modifications on dev mode.
  2. Dedupes anything this plugin add, so object-src 'self' 'self' becomes object-src 'self' ( I ran into this with my current custom object-src which already had this set)

I also tried to add some basic tests to cover most of the use cases.

Happy to hear feedback and anything I can improve.