Still getting inline script CSP violation after disabling optimization of scripts in Angular...

Discussão em 'Angular' iniciado por Ben Reeves, Outubro 20, 2024.

  1. Ben Reeves

    Ben Reeves Guest

    I am in the early stages of setting up an Angular project. From previous experience with other projects, I'm implementing a content security policy early so we can find violations during development and handle them as they come up. Angular seems to like to inline a lot of things and makes it difficult to have a restricted content policy for styling and scripts. I'm not too worried about styling but I really don't want to have 'unsafe-inline' for script-src.

    Everything I have read seems to indicate that I should be able to prevent inline scripts by setting the optimization for scripts to false in the angular.json file. However, when I do that, I'm still receiving an exception to the policy.

    VM974:1 Refused to execute inline script because it violates the following Content Security Policy directive: "script-src 'self'". Either the 'unsafe-inline' keyword, a hash ('sha256-lAv2mkGJp6SGGEBjSBtNofGW0z9UbIkFVrzyccLfMb0='), or a nonce ('nonce-...') is required to enable inline execution.


    My optimization code, which is located in projects > projectName > architect > build

    "optimization": {
    "fonts": true,
    "scripts": false,
    "styles": {
    "inlineCritical": false,
    "minify": true,
    "removeSpecialComments": true
    }
    }


    I have also tried just setting all optimization to false. The strange thing is that the site seems to work the same either way. I'm unable to find the script that's referenced and it doesn't seem to do anything. When I use dev tools to look at the actual code being executed where the violation occurred it looks like this:

    (e=>{
    const t = document.createElement("script");
    t.setAttribute("type", "text/javascript"),
    t.textContent = e,
    (document.head || document.documentElement).appendChild(t),
    t.parentNode && t.parentNode.removeChild(t)
    }
    )("\n (function () {\n try {\n


    Which makes it seem like something is being appended to the page head. When I compare the page heads with the policy on and off, the contents are exactly the same. I am currently only running this on my machine at localhost.

    Someone asked in the comments and I am also running server side rendering. I'm guessing that's a big piece of this but still seem unable to figure out how to disable the inline scripts.

    Does anyone know how to prevent an Angular 18 SSR project from running any inline scripts?

    Continue reading...

Compartilhe esta Página