Description
Describe the bug
In production code, Svelte may generate JS with innerHTML
assignments, which are disallowed by default by the Content Security Policy (CSP) rule "require-trusted-types-for 'script'"
.
I can workaround this by adding the elements using document.createElement()
. This way, Svelte obviously won't generate innerHTML
since I already added things using JS, but it's very costly.
Another workaround is to add the following to svelte/App.svelte
(see Reproduction for the repo). It seems ok to me since it's just escaping <
and >
, but I'm unsure about its security and performance.
<script>
if (
'trustedTypes' in window &&
window.trustedTypes !== null &&
typeof window.trustedTypes === 'object' &&
'createPolicy' in window.trustedTypes &&
window.trustedTypes.createPolicy !== null &&
window.trustedTypes.createPolicy instanceof Function
) {
window.trustedTypes.createPolicy('default', {
createHTML: (/** @type {string} */ string) => string.replace(/</g, '<').replace(/>/g, '>'),
})
}
</script>
This might be related at some level to #7943, #7908, and #8135
Reproduction
I created a minimal repo to reproduce the error. It uses NodeJS + Express and sets the CSP rules. The svelte code is under svelte
and is compiled to the directory svelte/dist
which is served by Express.
git clone git@github.com:planetsLightningArrester/svelte-csp-issue.git
cd svelte-csp-issue
# Build Svelte to `svelte/dist`
cd svelte
npm ci
npm run build
# Run the server
cd ..
npm ci
npm run start
Open http://localhost:3000. The page should be blank. Check the dev tools (tested on Chrome) and see the error This document requires 'TrustedHTML' assignment.
in the console pointing to the generated code.
To check the expected behavior, open ./app.js
, comment line 18, and re-start the server. The error should be gone and Hello
should show.
Logs
index-BP59ppMc.js:5 This document requires 'TrustedHTML' assignment.
index-BP59ppMc.js:5
Uncaught TypeError: Failed to set the 'innerHTML' property on 'Element': This document requires 'TrustedHTML' assignment.
at Object.c (index-BP59ppMc.js:5:78293)
at fe (index-BP59ppMc.js:1:6802)
at new qf (index-BP59ppMc.js:5:80408)
at index-BP59ppMc.js:5:80547
System Info
System:
OS: Linux 5.15 Ubuntu 22.04.4 LTS 22.04.4 LTS (Jammy Jellyfish)
CPU: (12) x64 AMD Ryzen 5 5600G with Radeon Graphics
Memory: 10.65 GB / 15.52 GB
Container: Yes
Shell: 5.1.16 - /bin/bash
Binaries:
Node: 20.10.0 - ~/.local/bin/node
npm: 10.2.3 - ~/.local/bin/npm
npmPackages:
svelte: ^4.2.12 => 4.2.12
Severity
annoyance