I need to place the 'style-src 'self' security directive in my application's csp.
But this directive blocks styles defined by the external Mantine-UI style library. I can't use 'unsafe-inline' to enable styles, because it goes against security.
I create the settings in vite.config and assign the csp settings in index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<%- csp %>
<title>Vite + React + TS</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
If you remove the 'style-src 'self' directive in vite.config you will see that styles will be enabled:
createHtmlPlugin({
minify: true,
inject: {
data: {
csp: `<meta http-equiv="Content-Security-Policy" content="img-src 'self' blob: data: ;
style-src 'self';
object-src 'none';
upgrade-insecure-requests;
block-all-mixed-content;
form-action 'self';
script-src 'self' 'unsafe-inline' 'unsafe-eval';
worker-src 'self' blob:;">`,
viteDev: `<script type="module" src="http://localhost:3000/@vite/client"></script>`,
},
},
}),
One of the easiest ways to allow style tags when using CSP is to use a nonce, example:
<script nonce="rAnd0m">
doWhatever();
</script>
The Mantine-UI style library that I use has the getStyleNonce function, which creates a nonce for each style tag dynamically. You can use devtools to inspect the html:
import { SHA256 } from "crypto-js";
function generateRandomHash() {
const randomString =
Math.random().toString(36).substring(2, 15) +
Math.random().toString(36).substring(2, 15);
return SHA256(randomString).toString();
}
<MantineProvider getStyleNonce={generateRandomHash}>
...
Even using the nonce, I was unable to enable my styles. Can you help me find a way to enable them?
Codesandbox: https://codesandbox.io/p/devbox/staging-dew-jwcfw4?file=%2Fsrc%2FApp.tsx%3A26%2C5-26%2C57