Skip to content

Commit

Permalink
Content Security Policy Support (#98)
Browse files Browse the repository at this point in the history
  • Loading branch information
rawilk authored Apr 13, 2023
1 parent bf5951f commit 83595c6
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 1 deletion.
28 changes: 27 additions & 1 deletion src/FormComponents.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@

namespace Rawilk\FormComponents;

use Illuminate\Support\Facades\Vite;

final class FormComponents
{
/**
Expand All @@ -22,14 +24,38 @@ public function javaScript(array $options = []): string
private function javaScriptAssets(array $options = []): string
{
$assetsUrl = config('form-components.asset_url') ?: rtrim($options['asset_url'] ?? '', '/');
$nonce = $this->getNonce($options);

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

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

return <<<HTML
<script src="{$fullAssetPath}" data-turbo-eval="false" data-turbolinks-eval="false"></script>
<script src="{$fullAssetPath}" data-turbo-eval="false" data-turbolinks-eval="false" {$nonce}></script>
HTML;
}

private function getNonce(array $options): string
{
if (isset($options['nonce'])) {
return "nonce=\"{$options['nonce']}\"";
}

// If there is a csp package installed, i.e. spatie/laravel-csp, we'll check for the existence of the helper function.
if (function_exists('csp_nonce') && $nonce = csp_nonce()) {
return "nonce=\"{$nonce}\"";
}

if (function_exists('cspNonce') && $nonce = cspNonce()) {
return "nonce=\"{$nonce}\"";
}

// Lastly, we'll check for the existence of a csp nonce from Vite.
if (class_exists(Vite::class) && $nonce = Vite::cspNonce()) {
return "nonce=\"{$nonce}\"";
}

return '';
}
}
10 changes: 10 additions & 0 deletions tests/Unit/AssetsDirectiveTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

declare(strict_types=1);

use Illuminate\Support\Str;
use Rawilk\FormComponents\Facades\FormComponents;

it('outputs the script source', function () {
Expand Down Expand Up @@ -44,3 +45,12 @@
FormComponents::javaScript(['asset_url' => 'https://example.com']),
);
});

it('can output a nonce on the script tag', function () {
$nonce = Str::random(32);

$this->assertStringContainsString(
"nonce=\"{$nonce}\"",
FormComponents::javaScript(['nonce' => $nonce]),
);
});

0 comments on commit 83595c6

Please sign in to comment.