Problem while loading CSP nonce in System.config.ts file

18 Views Asked by At

I am using an application where I want to load csp nonce in System.config.ts file. I am using Spring application on backend and thymeleaf for template.

The nonce is created on the server and passed on as request.parameter This is the HTML code:

...
<head>
... 
<script th:src="@{/lib/system/system.js}" th:nonce="${scriptNonce}"></script>
<script th:src="@{/client/system.config.js}" th:nonce="${scriptNonce}"></script>
...
</head>

scriptNonce is getting applied properly. I want this scriptNonce to be accessible from system.config.ts file as well

The file looks like this

SystemJS.config({
    baseURL: '/',
    warnings: true,
    meta: {
        '*' : {
            nonce: document.getElementsByTagName('script')[0].nonce,
        },
      ...
    }
}

the nonce for '*' means it gets applied for every dependency and I do not have to use usafe-eval in my CSP for script-src directive.

When I compile the project npm run gulp local-ts then it works fine. But when I use npm run gulp server-ts, it gives following error

evalmachine.<anonymous>:6
            nonce: document.getElementsByTagName('script')[0].nonce
                   ^

ReferenceError: document is not defined
    at evalmachine.<anonymous>:6:20
    at Script.runInContext (node:vm:141:12)
    at Script.runInNewContext (node:vm:146:17)
    at Object.runInNewContext (node:vm:306:38)


My question - is there a proper way to include the nonce in the system.config.ts file?

0

There are 0 best solutions below