From 6c589a20eb4670fb0d7749f2c341cbdd315a84f2 Mon Sep 17 00:00:00 2001 From: "Edward Tirado Jr." Date: Sun, 14 Dec 2025 13:38:12 -0600 Subject: [PATCH] fixed nonce --- .../Middleware/AddContentSecurityPolicy.php | 46 +++++++++++++++++++ bootstrap/app.php | 4 +- config/livewire.php | 13 ++++++ 3 files changed, 62 insertions(+), 1 deletion(-) create mode 100644 app/Http/Middleware/AddContentSecurityPolicy.php diff --git a/app/Http/Middleware/AddContentSecurityPolicy.php b/app/Http/Middleware/AddContentSecurityPolicy.php new file mode 100644 index 0000000..df4bb98 --- /dev/null +++ b/app/Http/Middleware/AddContentSecurityPolicy.php @@ -0,0 +1,46 @@ +attributes->set('csp-nonce', $nonce); + + // Get the response + $response = $next($request); + + // Build CSP header + if (app()->environment('local')) { + // Relaxed CSP for local development with Vite + $csp = "script-src 'self' 'unsafe-inline' 'unsafe-eval' http: https:; " . + "style-src 'self' 'unsafe-inline' http: https:; " . + "connect-src 'self' ws: http: https:;"; + } else { + // Strict CSP for production with nonces + $scriptSrc = "'self' 'nonce-{$nonce}' https:"; + $styleSrc = "'self' 'unsafe-inline' https:"; + $connectSrc = "'self' https:"; + + $csp = "script-src {$scriptSrc}; style-src {$styleSrc}; connect-src {$connectSrc};"; + } + + $response->headers->set('Content-Security-Policy', $csp); + + return $response; + } +} diff --git a/bootstrap/app.php b/bootstrap/app.php index c183276..4cd7d29 100644 --- a/bootstrap/app.php +++ b/bootstrap/app.php @@ -11,7 +11,9 @@ return Application::configure(basePath: dirname(__DIR__)) health: '/up', ) ->withMiddleware(function (Middleware $middleware): void { - // + $middleware->web(append: [ + \App\Http\Middleware\AddContentSecurityPolicy::class, + ]); }) ->withExceptions(function (Exceptions $exceptions): void { // diff --git a/config/livewire.php b/config/livewire.php index 8a4be98..be8b103 100644 --- a/config/livewire.php +++ b/config/livewire.php @@ -170,4 +170,17 @@ return [ */ 'pagination_theme' => 'tailwind', + + /* + |--------------------------------------------------------------------------- + | Content Security Policy Nonce + |--------------------------------------------------------------------------- + | + | When using Content-Security-Policy headers, Livewire can automatically + | apply nonces to its injected scripts. Provide a closure that returns + | the nonce value for the current request, or null to disable. + | + */ + + 'nonce' => fn () => request()->attributes->get('csp-nonce'), ];