3 namespace BookStack\Util;
5 use Illuminate\Support\Str;
6 use Symfony\Component\HttpFoundation\Response;
13 public function __construct(string $nonce = '')
15 $this->nonce = $nonce ?: Str::random(24);
19 * Get the nonce value for CSP.
21 public function getNonce(): string
27 * Sets CSP 'script-src' headers to restrict the forms of script that can
30 public function setScriptSrc(Response $response)
32 if (config('app.allow_content_scripts')) {
39 '\'nonce-' . $this->nonce . '\'',
43 $value = 'script-src ' . implode(' ', $parts);
44 $response->headers->set('Content-Security-Policy', $value, false);
48 * Sets CSP "frame-ancestors" headers to restrict the hosts that BookStack can be
49 * iframed within. Also adjusts the cookie samesite options so that cookies will
50 * operate in the third-party context.
52 public function setFrameAncestors(Response $response)
54 $iframeHosts = $this->getAllowedIframeHosts();
55 array_unshift($iframeHosts, "'self'");
56 $cspValue = 'frame-ancestors ' . implode(' ', $iframeHosts);
57 $response->headers->set('Content-Security-Policy', $cspValue, false);
61 * Check if the user has configured some allowed iframe hosts.
63 public function allowedIFrameHostsConfigured(): bool
65 return count($this->getAllowedIframeHosts()) > 0;
69 * Sets CSP 'object-src' headers to restrict the types of dynamic content
70 * that can be embedded on the page.
72 public function setObjectSrc(Response $response)
74 if (config('app.allow_content_scripts')) {
78 $response->headers->set('Content-Security-Policy', 'object-src \'self\'', false);
82 * Sets CSP 'base-uri' headers to restrict what base tags can be set on
83 * the page to prevent manipulation of relative links.
85 public function setBaseUri(Response $response)
87 $response->headers->set('Content-Security-Policy', 'base-uri \'self\'', false);
90 protected function getAllowedIframeHosts(): array
92 $hosts = config('app.iframe_hosts', '');
94 return array_filter(explode(' ', $hosts));