Skip to content

Commit 4bd1692

Browse files
authored
Merge pull request #142 from nckrtl/patch-1
Add support for Vite CSP nonce
2 parents 842e755 + 15f655a commit 4bd1692

File tree

2 files changed

+40
-1
lines changed

2 files changed

+40
-1
lines changed

src/Services/BrowserLogger.php

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@
55
namespace Laravel\Boost\Services;
66

77
use Illuminate\Support\Facades\Route;
8+
use Illuminate\Support\Facades\Vite;
9+
use Illuminate\View\ComponentAttributeBag;
810

911
class BrowserLogger
1012
{
@@ -14,8 +16,16 @@ public static function getScript(): string
1416
? route('boost.browser-logs')
1517
: '/_boost/browser-logs';
1618

19+
$attributes = new ComponentAttributeBag([
20+
'id' => 'browser-logger-active',
21+
]);
22+
23+
if ($nonce = Vite::cspNonce()) {
24+
$attributes = $attributes->merge(['nonce' => $nonce]);
25+
}
26+
1727
return <<<HTML
18-
<script id="browser-logger-active">
28+
<script {$attributes->toHtml()}>
1929
(function() {
2030
const ENDPOINT = '{$endpoint}';
2131
const logQueue = [];

tests/Feature/Middleware/InjectBoostTest.php

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@
55
use Illuminate\Http\Request;
66
use Illuminate\Http\Response;
77
use Illuminate\Support\Facades\Route;
8+
use Illuminate\Support\Facades\Vite;
9+
use Illuminate\Testing\TestResponse;
810
use Laravel\Boost\Middleware\InjectBoost;
911
use Symfony\Component\HttpFoundation\BinaryFileResponse;
1012
use Symfony\Component\HttpFoundation\JsonResponse;
@@ -89,3 +91,30 @@ function createMiddlewareResponse($response): SymfonyResponse
8991
'with head and body tags' => '<html><head><title>Test</title></head><body></body></html>',
9092
'without head/body tags' => '<html>Test</html>',
9193
]);
94+
95+
it('handles CSP nonce attribute correctly', function ($nonce, $assertions) {
96+
if ($nonce) {
97+
Vite::useCspNonce($nonce);
98+
}
99+
100+
Route::get('injection-test', fn () => view('test::injection-test'))
101+
->middleware(InjectBoost::class);
102+
103+
$response = $this->get('injection-test')->assertViewIs('test::injection-test');
104+
105+
$assertions($response);
106+
})->with([
107+
'with CSP nonce configured' => [
108+
'test-nonce',
109+
fn (TestResponse $response) => $response
110+
->assertSee('nonce="test-nonce"', false)
111+
->assertSee('id="browser-logger-active"', false),
112+
],
113+
'without CSP nonce configured' => [
114+
null,
115+
fn (TestResponse $response) => $response
116+
->assertSee('<script id="browser-logger-active">', false)
117+
->assertDontSee('nonce=', false)
118+
->assertDontSee('test-nonce', false),
119+
],
120+
]);

0 commit comments

Comments
 (0)