Skip to content
This repository was archived by the owner on Mar 18, 2025. It is now read-only.

Commit 83595c6

Browse files
authored
Content Security Policy Support (#98)
1 parent bf5951f commit 83595c6

File tree

2 files changed

+37
-1
lines changed

2 files changed

+37
-1
lines changed

src/FormComponents.php

+27-1
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@
44

55
namespace Rawilk\FormComponents;
66

7+
use Illuminate\Support\Facades\Vite;
8+
79
final class FormComponents
810
{
911
/**
@@ -22,14 +24,38 @@ public function javaScript(array $options = []): string
2224
private function javaScriptAssets(array $options = []): string
2325
{
2426
$assetsUrl = config('form-components.asset_url') ?: rtrim($options['asset_url'] ?? '', '/');
27+
$nonce = $this->getNonce($options);
2528

2629
$manifest = json_decode(file_get_contents(__DIR__ . '/../dist/manifest.json'), true);
2730
$versionedFileName = $manifest['/form-components.js'];
2831

2932
$fullAssetPath = "{$assetsUrl}/form-components{$versionedFileName}";
3033

3134
return <<<HTML
32-
<script src="{$fullAssetPath}" data-turbo-eval="false" data-turbolinks-eval="false"></script>
35+
<script src="{$fullAssetPath}" data-turbo-eval="false" data-turbolinks-eval="false" {$nonce}></script>
3336
HTML;
3437
}
38+
39+
private function getNonce(array $options): string
40+
{
41+
if (isset($options['nonce'])) {
42+
return "nonce=\"{$options['nonce']}\"";
43+
}
44+
45+
// If there is a csp package installed, i.e. spatie/laravel-csp, we'll check for the existence of the helper function.
46+
if (function_exists('csp_nonce') && $nonce = csp_nonce()) {
47+
return "nonce=\"{$nonce}\"";
48+
}
49+
50+
if (function_exists('cspNonce') && $nonce = cspNonce()) {
51+
return "nonce=\"{$nonce}\"";
52+
}
53+
54+
// Lastly, we'll check for the existence of a csp nonce from Vite.
55+
if (class_exists(Vite::class) && $nonce = Vite::cspNonce()) {
56+
return "nonce=\"{$nonce}\"";
57+
}
58+
59+
return '';
60+
}
3561
}

tests/Unit/AssetsDirectiveTest.php

+10
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
declare(strict_types=1);
44

5+
use Illuminate\Support\Str;
56
use Rawilk\FormComponents\Facades\FormComponents;
67

78
it('outputs the script source', function () {
@@ -44,3 +45,12 @@
4445
FormComponents::javaScript(['asset_url' => 'https://example.com']),
4546
);
4647
});
48+
49+
it('can output a nonce on the script tag', function () {
50+
$nonce = Str::random(32);
51+
52+
$this->assertStringContainsString(
53+
"nonce=\"{$nonce}\"",
54+
FormComponents::javaScript(['nonce' => $nonce]),
55+
);
56+
});

0 commit comments

Comments
 (0)