From 2e5a0f8541421ff8f87e40762b2fe8408d6c518b Mon Sep 17 00:00:00 2001 From: Vincent Pietri Date: Thu, 15 May 2025 22:29:51 +0200 Subject: [PATCH] Draft with cspNonceProvider --- Block/Tab/Panel.php | 26 +++++++++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) diff --git a/Block/Tab/Panel.php b/Block/Tab/Panel.php index d933395..35e7a5e 100644 --- a/Block/Tab/Panel.php +++ b/Block/Tab/Panel.php @@ -15,6 +15,8 @@ class Panel extends \Magento\Framework\View\Element\Template protected $qdbHelperRegister; + private $cspNonceProvider; + public function __construct( \Magento\Framework\View\Element\Template\Context $context, @@ -27,6 +29,10 @@ public function __construct( $this->helper = $helper; $this->qdbHelperRegister = $qdbHelperRegister; + + if(class_exists(\Magento\Csp\Helper\CspNonceProvider::class)) { + $this->cspNonceProvider = ObjectManager::getInstance()->get(\Magento\Csp\Helper\CspNonceProvider::class); + } } /** @@ -190,7 +196,9 @@ protected function _toHtml() { try { $buffer = parent::_toHtml(); - return $this->sanitizeOutput($buffer); + $buffer = $this->sanitizeOutput($buffer); + $buffer = $this->addNonceOnScript($buffer); + return $buffer; } catch (\Exception $e) { return $e->getMessage(); } @@ -225,6 +233,20 @@ protected function sanitizeOutput($buffer) return $buffer; } + private function addNonceOnScript($buffer) + { + //$this->setAutoNonceOnSrciptTag(true); + if($this->getAutoNonceOnSrciptTag() && $this->cspNonceProvider) { + $openscriptPattern = '/<(script)(.*)>/'; + $nonceTiInject = 'nonce="' . $this->cspNonceProvider->generateNonce() .'"'; + if(preg_match($openscriptPattern, $buffer, $matches) ) { + $buffer = preg_replace($openscriptPattern, '<${1} ' . $nonceTiInject . '${2}>', $buffer); + } + } + + return $buffer; + } + public function htmlFormatClass($class) { return $this->helper->getIDELinkForClass($class); @@ -245,4 +267,6 @@ public function getQdbConfig($key, $scopeType = ScopeConfigInterface::SCOPE_TYPE return $this->helper->getQdbConfig($key, $scopeType, $scopeCode); } + + }