Skip to content

Commit

Permalink
Add CSP nonce to Vite reactRefresh inline script (#44816)
Browse files Browse the repository at this point in the history
  • Loading branch information
andyvenus authored Nov 4, 2022
1 parent 0702f55 commit 6a72083
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 1 deletion.
7 changes: 6 additions & 1 deletion src/Illuminate/Foundation/Vite.php
Original file line number Diff line number Diff line change
Expand Up @@ -575,17 +575,22 @@ public function reactRefresh()
return;
}

$attributes = $this->parseAttributes([
'nonce' => $this->cspNonce()
]);

return new HtmlString(
sprintf(
<<<'HTML'
<script type="module">
<script type="module" %s>
import RefreshRuntime from '%s'
RefreshRuntime.injectIntoGlobalHook(window)
window.$RefreshReg$ = () => {}
window.$RefreshSig$ = () => (type) => type
window.__vite_plugin_react_preamble_installed__ = true
</script>
HTML,
implode(' ', $attributes),
$this->hotAsset('@react-refresh')
)
);
Expand Down
19 changes: 19 additions & 0 deletions tests/Foundation/FoundationViteTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,25 @@ public function testItCanSpecifyCspNonceWithManifest()
);
}

public function testReactRefreshWithNoNonce()
{
$this->makeViteHotFile();

$result = app(Vite::class)->reactRefresh();

$this->assertStringNotContainsString('nonce', $result);
}

public function testReactRefreshNonce()
{
$this->makeViteHotFile();

$nonce = ViteFacade::useCspNonce('expected-nonce');
$result = app(Vite::class)->reactRefresh();

$this->assertStringContainsString(sprintf('nonce="%s"', $nonce), $result);
}

public function testItCanInjectIntegrityWhenPresentInManifest()
{
$buildDir = Str::random();
Expand Down

0 comments on commit 6a72083

Please sign in to comment.