是否可以在从另一个 js 文件导入的 js 脚本中应用内容安全随机数?

Is it possible to apply a Content Security nonce in a js script imported from another js file?

我的后端服务生成内容安全策略如下:

Content-Security-Policy
    default-src 'self'; frame-ancestors 'self'; form-action 'self'; script-src 'nonce-4VOtk0Uo1l7pwtC';

呈现的 HTML 在脚本标记中使用随机数以允许其执行:

<script nomodule src="https://xxx/build/script1.js" nonce="4VOtk0Uo1l7pwtC"></script>

<script type="module" src="https://xxx/build/script2.js" nonce="4VOtk0Uo1l7pwtC"></script>

这些脚本已正确加载。问题是 script2.js 包含一个导入语句来加载另一个脚本:

import{p as e,b as t}from"./p-cfa9fa8a.js";

这个被 csp 策略阻止了,因为它不包含 nonce 参数:

TypeError: error loading dynamically imported module undefined p-cfa9fa8a.js:1:12156

Content Security Policy: The page’s settings blocked the loading of a resource at inline (“default-src”). p-cfa9fa8a.js:1:12156

解决方案是添加 'strict-dynamic' 选项:

The strict-dynamic source expression specifies that the trust explicitly given to a script present in the markup, by accompanying it with a nonce or a hash, shall be propagated to all the scripts loaded by that root script. At the same time, any allow-list or source expressions such as 'self' or 'unsafe-inline' are ignored. See script-src for an example.

Content-Security-Policy
    default-src 'self'; frame-ancestors 'self'; form-action 'self'; script-src 'strict-dynamic' 'nonce-4VOtk0Uo1l7pwtC';