Skip to content

Commit

Permalink
Merge pull request #47 from Laravel-Backpack/csp-nonce-support
Browse files Browse the repository at this point in the history
Added csp nonce support
  • Loading branch information
tabacitu authored Jun 24, 2023
2 parents 3baed54 + 806ac54 commit d0e968a
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 6 deletions.
30 changes: 24 additions & 6 deletions src/BassetManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ class BassetManager
private array $loaded;
private string $basePath;
private string $cachebusting;
private string|null $nonce;
private bool $dev = false;

public CacheMap $cacheMap;
Expand All @@ -40,6 +41,7 @@ public function __construct()
$this->cachebusting = '?'.substr(md5(base_path('composer.lock')), 0, 12);
$this->basePath = (string) Str::of(config('backpack.basset.path'))->finish('/');
$this->dev = config('backpack.basset.dev_mode', false);
$this->nonce = config('backpack.basset.nonce', null);

$this->cacheMap = new CacheMap($this->disk, $this->basePath);
$this->loader = new LoadingTime();
Expand Down Expand Up @@ -110,12 +112,10 @@ public function echoFile(string $path, array $attributes = []): void
*/
public function echoCss(string $path, array $attributes = []): void
{
$args = '';
foreach ($attributes as $key => $value) {
$args .= " $key".($value === true || empty($value) ? '' : "=\"$value\"");
}
$href = asset($path.$this->cachebusting);
$args = $this->prepareAttributes($attributes);

echo '<link href="'.asset($path.$this->cachebusting).'"'.$args.' rel="stylesheet" type="text/css" />'.PHP_EOL;
echo '<link href="'.$href.'"'.$args.' rel="stylesheet" type="text/css" />'.PHP_EOL;
}

/**
Expand All @@ -126,12 +126,30 @@ public function echoCss(string $path, array $attributes = []): void
*/
public function echoJs(string $path, array $attributes = []): void
{
$src = asset($path.$this->cachebusting);
$args = $this->prepareAttributes($attributes);

echo '<script src="'.$src.'"'.$args.'></script>'.PHP_EOL;
}

/**
* Prepares attributes to be added to the script/style dom element.
*
* @param array $attributes
* @return string
*/
private function prepareAttributes(array $attributes = []): string
{
if ($this->nonce) {
$attributes['nonce'] ??= $this->nonce;
}

$args = '';
foreach ($attributes as $key => $value) {
$args .= " $key".($value === true || empty($value) ? '' : "=\"$value\"");
}

echo '<script src="'.asset($path.$this->cachebusting).'"'.$args.'></script>'.PHP_EOL;
return $args;
}

/**
Expand Down
3 changes: 3 additions & 0 deletions src/config/backpack/basset.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,7 @@
'view_paths' => [
resource_path('views'),
],

// content security policy nonce
'nonce' => null,
];

0 comments on commit d0e968a

Please sign in to comment.