From a7b77a1ced11407c218625fe4acd134ede85225c Mon Sep 17 00:00:00 2001 From: Yuriy Bakhtin Date: Thu, 16 Nov 2023 15:38:08 +0100 Subject: [PATCH] Add nonce attribute to all JavaScript tags in templates and HTML pages automatically --- docs/CHANGELOG.md | 2 +- helpers/Html.php | 32 +++++++++++++++++++ lib/templates/twig/TwigEngine.php | 9 +----- models/Page.php | 4 +-- .../template/components/TemplateRenderer.php | 10 +++--- 5 files changed, 40 insertions(+), 17 deletions(-) create mode 100644 helpers/Html.php diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 10768162..caf508c1 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -4,7 +4,7 @@ Changelog 1.9.5 (Unreleased) ------------------------ - Enh #303: Fix visibility of the method `Controller::getAccessRules()` -- Enh #305: JavaScript nonce placeholder for templates & HTML pages +- Enh #305: Add nonce attribute to all JavaScript tags in templates and HTML pages automatically 1.9.4 (October 24, 2023) ------------------------ diff --git a/helpers/Html.php b/helpers/Html.php new file mode 100644 index 00000000..f1ec5605 --- /dev/null +++ b/helpers/Html.php @@ -0,0 +1,32 @@ +)/i', [self::class, 'applyScriptNonceCallback'], $content); + } + + protected static function applyScriptNonceCallback(array $m): string + { + $attrs = str_replace([' nonce=""', " nonce=''", ' nonce'], '', $m[2]); + return $m[1] . ' ' . self::nonce() . $attrs; + } +} diff --git a/lib/templates/twig/TwigEngine.php b/lib/templates/twig/TwigEngine.php index 3d7ff6e0..7db73e5a 100644 --- a/lib/templates/twig/TwigEngine.php +++ b/lib/templates/twig/TwigEngine.php @@ -1,17 +1,14 @@ false, 'debug' => true]); - $twig->addFunction(new TwigFunction('nonce', function () { - return Html::nonce(); - })); - return $twig->render($template, $content); } diff --git a/models/Page.php b/models/Page.php index e7e507b1..4cc9ad10 100644 --- a/models/Page.php +++ b/models/Page.php @@ -2,8 +2,8 @@ namespace humhub\modules\custom_pages\models; -use humhub\libs\Html; use humhub\modules\content\models\Content; +use humhub\modules\custom_pages\helpers\Html; use humhub\modules\custom_pages\helpers\Url; use humhub\modules\custom_pages\models\forms\SettingsForm; use humhub\modules\custom_pages\modules\template\models\Template; @@ -188,7 +188,7 @@ public function getContentTypes() public function getPageContent() { if ($this->type == HtmlType::ID) { - return preg_replace('/()/i', '$1 ' . Html::nonce() . '$3', $this->page_content); + return Html::applyScriptNonce($this->page_content); } return $this->page_content; diff --git a/modules/template/components/TemplateRenderer.php b/modules/template/components/TemplateRenderer.php index 7123b910..20d3426e 100644 --- a/modules/template/components/TemplateRenderer.php +++ b/modules/template/components/TemplateRenderer.php @@ -1,9 +1,8 @@