3 namespace BookStack\Util;
10 class HtmlNonceApplicator
12 protected static $placeholder = '[CSP_NONCE_VALUE]';
15 * Prepare the given HTML content with nonce attributes including a placeholder
16 * value which we can target later.
18 public static function prepare(string $html): string
24 $html = '<?xml encoding="utf-8" ?><body>' . $html . '</body>';
25 libxml_use_internal_errors(true);
26 $doc = new DOMDocument();
27 $doc->loadHTML($html, LIBXML_SCHEMA_CREATE);
28 $xPath = new DOMXPath($doc);
31 $scriptElems = $xPath->query('//script');
32 static::addNonceAttributes($scriptElems, static::$placeholder);
35 $styleElems = $xPath->query('//style');
36 static::addNonceAttributes($styleElems, static::$placeholder);
39 $topElems = $doc->documentElement->childNodes->item(0)->childNodes;
40 foreach ($topElems as $child) {
41 $content = $doc->saveHTML($child);
42 $returnHtml .= $content;
49 * Apply the give nonce value to the given prepared HTML.
51 public static function apply(string $html, string $nonce): string
53 return str_replace(static::$placeholder, $nonce, $html);
56 protected static function addNonceAttributes(DOMNodeList $nodes, string $attrValue): void
58 /** @var DOMElement $node */
59 foreach ($nodes as $node) {
60 $node->setAttribute('nonce', $attrValue);