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

Content Security Policy Support #98

Merged
merged 1 commit into from
Apr 13, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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]),
);
});