AiDev
AiDev

Reputation: 1234

In Webpack and/or NextJS, how to disable eval-source-maps due to CSP issues

I'm trying to set a restrictive CSP for a secure application, and my use case not not allow for 'unsafe-eval'.

By default NextJS and Webpack use eval-source-maps that use eval() repeatedly, meaning this breaks my development environment. I understand these source maps are not used in production, but this means that I have to use different settings in my dev and prodction environments, which makes it very hard to debug CSP related issues.

I tried the solutions proposed by a few open issues on Github, listed below, but with no avail. NextJS simply overrides the source maps back to eval-source-maps when in dev, even when you explicitly add to the config to set devtool: false or devtool: source-map. It's wild to me that it automatically overrides the developer's manual override back to the default setting which is causing the problem, but thats where we're at!

Has anyone solved this? It would seem odd to me to intentionally use less secure settings for dev env when building an app that requires high levels of security.

Relevant github issues: https://github.com/vercel/next.js/discussions/20294 https://github.com/webpack/webpack/issues/4899 https://github.com/vercel/next.js/discussions/21425

Upvotes: 3

Views: 2064

Answers (1)

Vayne Valerius
Vayne Valerius

Reputation: 176

Not sure if this answer will help anyone but you have two options from my experience.

The first is to use report-only mode on the CSP configuration while in dev mode. This still flags all the errors and fixes in the inspector. There is nothing wrong with your local build using eval. Its only you that can do something funny with it. If not, you have a major security flaw on your local machine and CSP isn't going to fix that!

To actually test the configuration you can then run a local production build with report-mode off.

eval-source-map is slow though, and maybe you really want to test csp in local dev, and have your CSP on always. In that case switch to using pnpm and use its patch functionality to edit the internal webpack files. You can remove the restriction that way. Haven't used Next for a while but if its using TurboPack I'd guess it won't be too dissimilar.

  1. pnpm patch next@VERSION
  2. Click on the link returned in the terminal. It should open with $EDITOR
  3. Do a global search for devtoolRevertWarning
  4. There will be 4 files, ignore the two map files and comment out these 4 lines in the other 2
if (dev && originalDevtool !== webpackConfig.devtool) {
    webpackConfig.devtool = originalDevtool;
    devtoolRevertWarning(originalDevtool);
}
  1. Go back to the next project and run pnpm patch-commit <tmp-directory>. This is displayed in the original terminal output.

Unfortunately you have to do this with every update.

Upvotes: 0

Related Questions