I’m building an app using Electron and Vite but have run into an issue when specifying my Content Security Policy. I want to have a CSP as strict as possible (not specify unsafe-inline
) but Vite clashes with this be adding inline styles. The issue is the exact same as this github issue. A solution was made in this PR by supporting a nonce during the vite process.
This solution doesn’t work for me because I’m not loading my resources from a server, I need to create the nonce on the client and supply it to the process like so.
// electron.vite.config.ts
let nonce = crypto.randomBytes(16).toString('base64');
export default defineConfig({
renderer: {
plugins: [
transformHtmlPlugin({ nonce: nonce })
],
html: {
cspNonce: nonce
}
},
})
I then use the transformHtmlPlugin
to replace a template in the index.html with the nonce like so:
// electron.vite.config.ts
const transformHtmlPlugin = data => ({
name: 'transform-html',
transformIndexHtml: {
transform(html)
{
return html.replace(
/<%=s*(w+)s*%>/gi,
(match, p1) => data[p1] || ''
);
}
}
});
// index.html
<meta http-equiv="Content-Security-Policy"
content="default-src 'self'; style-src 'nonce-<%= nonce %>'" />
This works fine in development where I re run the entire process each time I build the the app, but after packaging the app, the nonce won’t be regenerated. This defeats the whole purpose of a nonce.
How can I use a strict CSP with vite without using a nonce or regenerate the nonce after packaging?