#CSP + Vite build

5 messages · Page 1 of 1 (latest)

floral cedar
#

I'm having trouble implementing Content Security Policy (CSP) with nonces using Vite for asset building. Here's the situation:

I'm using the Spatie CSP package to set up my CSP. My policy is configured to use nonces for scripts and styles.

    public function configure(): void
    {
        $this
            ->addDirective(Directive::BASE, Keyword::SELF)
            ->addDirective(Directive::CONNECT, Keyword::SELF)
            ->addDirective(Directive::DEFAULT, Keyword::SELF)
            ->addDirective(Directive::FORM_ACTION, Keyword::SELF)
            ->addDirective(Directive::IMG, Keyword::SELF)
            ->addDirective(Directive::MEDIA, Keyword::SELF)
            ->addDirective(Directive::OBJECT, Keyword::NONE)
            ->addDirective(Directive::SCRIPT, [Keyword::SELF, 'https://app.domain.com', 'https://domain.com'])
            ->addDirective(Directive::STYLE, [Keyword::SELF, 'https://fonts.bunny.net'])
            ->addDirective(Directive::FONT, [Keyword::SELF, 'https://fonts.bunny.net'])
            ->addDirective(Directive::FRAME, Keyword::NONE)
            ->addDirective(Directive::WORKER, Keyword::SELF)
            ->addDirective(Directive::MANIFEST, Keyword::SELF)
            ->addNonceForDirective(Directive::SCRIPT)
            ->addNonceForDirective(Directive::STYLE);
    }

In development, everything works fine - a new nonce is generated for each request.
However, after building assets with Vite (npm run build), I get CSP errors in production.

The main issue seems to be that the nonce generated for the CSP header doesn't match the nonce in the built script tags. This is because Vite can't inject the dynamically generated nonce into the built files.

Has anyone successfully implemented CSP with nonces in a Laravel + Vite setup?

dawn pewter
floral cedar
#

I use a custom generator to return the same:

    public function generate(): string
    {
        return Vite::cspNonce();
    }
dawn pewter
#

Afaik that's all I do in my own apps. A custom generator, return the Vite nonce, and update the config
Can't look at the code right now, I'll get back to you tomorrow

floral cedar
#

Ok looks like I found the issue. It looks like few frontend component (vaul/Radix/shadcn) that adds stylesheet..can not do much with that other than not adding nonce to style at the moment. They have open issues for that.