3 namespace BookStack\Util;
8 class HtmlNonceApplicator
10 protected static string $placeholder = '[CSP_NONCE_VALUE]';
13 * Prepare the given HTML content with nonce attributes including a placeholder
14 * value which we can target later.
16 public static function prepare(string $html): string
22 // LIBXML_SCHEMA_CREATE was found to be required here otherwise
23 // the PHP DOMDocument handling will attempt to format/close
24 // HTML tags within scripts and therefore change JS content.
25 $doc = new HtmlDocument($html, LIBXML_SCHEMA_CREATE);
28 $scriptElems = $doc->queryXPath('//script');
29 static::addNonceAttributes($scriptElems, static::$placeholder);
32 $styleElems = $doc->queryXPath('//style');
33 static::addNonceAttributes($styleElems, static::$placeholder);
35 return $doc->getBodyInnerHtml();
39 * Apply the give nonce value to the given prepared HTML.
41 public static function apply(string $html, string $nonce): string
43 return str_replace(static::$placeholder, $nonce, $html);
46 protected static function addNonceAttributes(DOMNodeList $nodes, string $attrValue): void
48 /** @var DOMElement $node */
49 foreach ($nodes as $node) {
50 $node->setAttribute('nonce', $attrValue);