Skip to content

Commit 2794f81

Browse files
[9.x] Add nonce for preloaded assets (#44747)
* fix: add nonce for preloaded assets * formatting * add tests Co-authored-by: Tim MacDonald <[email protected]>
1 parent aaac47f commit 2794f81

File tree

2 files changed

+44
-0
lines changed

2 files changed

+44
-0
lines changed

src/Illuminate/Foundation/Vite.php

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -438,9 +438,11 @@ protected function resolvePreloadTagAttributes($src, $url, $chunk, $manifest)
438438
'rel' => 'preload',
439439
'as' => 'style',
440440
'href' => $url,
441+
'nonce' => $this->nonce ?? false,
441442
] : [
442443
'rel' => 'modulepreload',
443444
'href' => $url,
445+
'nonce' => $this->nonce ?? false,
444446
];
445447

446448
$attributes = $this->integrityKey !== false

tests/Foundation/FoundationViteTest.php

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -846,6 +846,48 @@ public function testItCanSpecifyAttributesForPreloadedAssets()
846846
$this->cleanViteManifest($buildDir);
847847
}
848848

849+
public function testPreloadAssetsGetAssetNonce()
850+
{
851+
$buildDir = Str::random();
852+
$this->makeViteManifest([
853+
'resources/js/app.js' => [
854+
'src' => 'resources/js/app.js',
855+
'file' => 'assets/app.versioned.js',
856+
'css' => [
857+
'assets/app.versioned.css',
858+
],
859+
],
860+
'resources/css/app.css' => [
861+
'src' => 'resources/css/app.css',
862+
'file' => 'assets/app.versioned.css',
863+
],
864+
], $buildDir);
865+
ViteFacade::useCspNonce('expected-nonce');
866+
867+
$result = app(Vite::class)(['resources/js/app.js'], $buildDir);
868+
869+
$this->assertSame(
870+
'<link rel="preload" as="style" href="https://example.com/'.$buildDir.'/assets/app.versioned.css" nonce="expected-nonce" />'
871+
.'<link rel="modulepreload" href="https://example.com/'.$buildDir.'/assets/app.versioned.js" nonce="expected-nonce" />'
872+
.'<link rel="stylesheet" href="https://example.com/'.$buildDir.'/assets/app.versioned.css" nonce="expected-nonce" />'
873+
.'<script type="module" src="https://example.com/'.$buildDir.'/assets/app.versioned.js" nonce="expected-nonce"></script>',
874+
$result->toHtml());
875+
876+
$this->assertSame([
877+
"https://example.com/$buildDir/assets/app.versioned.css" => [
878+
'rel="preload"',
879+
'as="style"',
880+
'nonce="expected-nonce"',
881+
],
882+
"https://example.com/$buildDir/assets/app.versioned.js" => [
883+
'rel="modulepreload"',
884+
'nonce="expected-nonce"',
885+
],
886+
], ViteFacade::preloadedAssets());
887+
888+
$this->cleanViteManifest($buildDir);
889+
}
890+
849891
protected function makeViteManifest($contents = null, $path = 'build')
850892
{
851893
app()->singleton('path.public', fn () => __DIR__);

0 commit comments

Comments
 (0)