From c5eedebc617960140efe9d6d8c3b63b2af766b93 Mon Sep 17 00:00:00 2001 From: Brandon Shipley Date: Sat, 14 Nov 2026 01:54:14 -0800 Subject: [PATCH] turnstile helper --- config/app.example.php | 13 +- src/CakeContactUsPlugin.php | 10 ++ .../Component/ContactUsComponent.php | 12 +- src/View/Helper/TurnstileHelper.php | 152 ++++++++++++++++++ .../View/Helper/TurnstileHelperTest.php | 100 ++++++++++++ 5 files changed, 281 insertions(+), 6 deletions(-) create mode 100644 src/View/Helper/TurnstileHelper.php create mode 100644 tests/TestCase/View/Helper/TurnstileHelperTest.php diff --git a/config/app.example.php b/config/app.example.php index 5862ad9..6a2c6b6 100644 --- a/config/app.example.php +++ b/config/app.example.php @@ -26,9 +26,18 @@ return [ 'controller' => 'ContactUsFormSubmissions', 'action' => 'view', ], + /** + * @link https://developers.cloudflare.com/turnstile/troubleshooting/testing/ + * + * secretKeys for testing: + * always passes = 1x0000000000000000000000000000000AA + * always fails = 2x0000000000000000000000000000000AA + * token already spent error 3x0000000000000000000000000000000AA + */ 'turnstile' => [ - 'siteKey' => '{SITE_KEY_GOES_HERE}', // define in app_local or an .env variable - 'secretKey' => '{SECRET_GOES_HERE}', // define in app_local or an .env variable + 'enabled' => true, + 'siteKey' => '{SITE_KEY_GOES_HERE}', // define in app_local or an .env variable - CLOUDFLARE_TURNSTILE_SITE_KEY + 'secretKey' => '{SECRET_GOES_HERE}', // define in app_local or an .env variable - CLOUDFLARE_TURNSTILE_SECRET_KEY ], ], ]; diff --git a/src/CakeContactUsPlugin.php b/src/CakeContactUsPlugin.php index a8b60fe..f35aa30 100644 --- a/src/CakeContactUsPlugin.php +++ b/src/CakeContactUsPlugin.php @@ -30,6 +30,16 @@ class CakeContactUsPlugin extends BasePlugin { */ public const CAKE_CONTACT_US_MYSQL_DATETIME = 'Y-m-d H:i:s'; + /** + * @var string + */ + public const CAKE_CONTACT_US_CLOUDFLARE_TURNSTILE_SECRET_KEY = 'CLOUDFLARE_TURNSTILE_SECRET_KEY'; + + /** + * @var string + */ + public const CAKE_CONTACT_US_CLOUDFLARE_TURNSTILE_SITE_KEY = 'CLOUDFLARE_TURNSTILE_SITE_KEY'; + /** * Load all the plugin configuration and bootstrap logic. * diff --git a/src/Controller/Component/ContactUsComponent.php b/src/Controller/Component/ContactUsComponent.php index c6d5709..2195ada 100644 --- a/src/Controller/Component/ContactUsComponent.php +++ b/src/Controller/Component/ContactUsComponent.php @@ -81,7 +81,9 @@ class ContactUsComponent extends Component { $this->ContactUsFormSubmissions = TableRegistry::getTableLocator()->get('CakeContactUs.ContactUsFormSubmissions'); $requireCaptcha = Configure::readOrFail('ContactUs.fields.captcha'); - $useTurnstile = Configure::read('ContactUs.turnstile', []); + $useTurnstile = Configure::read('ContactUs.turnstile', [ + 'enabled' => false, + ]); $this->setConfig('redirectUrl', Configure::read('ContactUs.redirectUrl', '/')); $this->setConfig('addIdToRedirect', Configure::read('ContactUs.addIdToRedirect', false)); $this->setConfig('requireEmail', Configure::readOrFail('ContactUs.fields.email')); @@ -90,8 +92,8 @@ class ContactUsComponent extends Component { if ($requireCaptcha) { $this->getController()->viewBuilder()->addHelpers(['Captcha.Captcha']); } - if ($useTurnstile) { -// $this->getController()->viewBuilder()->addHelpers(['']); + if ($useTurnstile['enabled'] ?? false) { +// $this->getController()->viewBuilder()->addHelpers(['Turnstile']); } } @@ -194,7 +196,9 @@ class ContactUsComponent extends Component { if (!$this->getConfig('turnstile')) { return; } - if (!$this->getConfig('turnstile.siteKey') || !$this->getConfig('turnstile.secretKey')) { + $siteKey = getenv(CakeContactUsPlugin::CAKE_CONTACT_US_CLOUDFLARE_TURNSTILE_SITE_KEY) ?: $this->getConfig('turnstile.siteKey'); + $secretKey = getenv(CakeContactUsPlugin::CAKE_CONTACT_US_CLOUDFLARE_TURNSTILE_SECRET_KEY) ?: $this->getConfig('turnstile.secretKey'); + if (!$siteKey || !$secretKey) { $event->stopPropagation(); $event->setResult([ 'success' => false, diff --git a/src/View/Helper/TurnstileHelper.php b/src/View/Helper/TurnstileHelper.php new file mode 100644 index 0000000..cece4a0 --- /dev/null +++ b/src/View/Helper/TurnstileHelper.php @@ -0,0 +1,152 @@ + + */ + protected array $_defaultConfig = []; + + /** + * @var array|string[] + */ + protected array $helpers = ['Html']; + + /** + * @param \Cake\View\View $view + * @param array $config + */ + public function __construct(View $view, array $config = []) { + $config += (array)Configure::read('ContactUs.turnstile'); + + parent::__construct($view, $config); + } + + /** + * @return string + */ + public function preConnect() + { + return ''; + } + + /** + * @param array $options + * + * @return string|null + */ + public function script(array $options = []) + { + $options += [ + 'async' => true, + 'defer' => true, + ]; + $scriptOptions = $options; + unset($scriptOptions['eventListeners']); + + if ($options['eventListeners'] ?? false) { + return $this->Html->script('https://challenges.cloudflare.com/turnstile/v0/api.js', $scriptOptions) . $this->eventListener($options['eventListeners']); + } + return $this->Html->script('https://challenges.cloudflare.com/turnstile/v0/api.js', $scriptOptions); + } + + /** + * @param $options + * + * @return string + */ + public function eventListener($options) + { + $options += [ + 'dynamicButton' => $this->getConfig('dynamicButton', false), + 'log' => $this->getConfig('log', false), + 'submitButtonId' => $this->getConfig('submitButtonId', 'submit-btn') + ]; + $final = ''; + + return $final; + } + + /** + * @param $options + * + * @return string + */ + protected function _onTurnstileSuccess($options = []): string + { + $jsFunction = 'function onTurnstileSuccess(token) {'; + if ($options['log'] ?? false) { + $jsFunction .= 'console.log("Turnstile success:", token);'; + } + if ($options['dynamicButton'] ?? false) { + $jsFunction .= 'document.getElementById("' . + ($options['submitButtonId'] ?? 'submit-btn') . + '")?.disabled = false;'; + } + $jsFunction .= '}'; + + return $jsFunction; + } + + /** + * @param $options + * + * @return string + */ + protected function onTurnstileError($options = []): string + { + $jsFunction = 'function onTurnstileError(errorCode) {'; + if ($options['log'] ?? false) { + $jsFunction .= 'console.error("Turnstile error:", errorCode);'; + } + if ($options['dynamicButton'] ?? false) { + $jsFunction .= 'document.getElementById("' . + ($options['submitButtonId'] ?? 'submit-btn') . + '")?.disabled = true;'; + } + $jsFunction .= '}'; + + return $jsFunction; + } + + /** + * @param $options + * + * @return string + */ + protected function onTurnstileExpired($options = []): string + { + $jsFunction = 'function onTurnstileExpired(errorCode) {'; + if ($options['log'] ?? false) { + $jsFunction .= 'console.warn("Turnstile token expired");'; + } + if ($options['dynamicButton'] ?? false) { + $jsFunction .= 'document.getElementById("' . + ($options['submitButtonId'] ?? 'submit-btn') . + '")?.disabled = true;'; + } + + $jsFunction .= '}'; + + return $jsFunction; + } + +} diff --git a/tests/TestCase/View/Helper/TurnstileHelperTest.php b/tests/TestCase/View/Helper/TurnstileHelperTest.php new file mode 100644 index 0000000..b5690d0 --- /dev/null +++ b/tests/TestCase/View/Helper/TurnstileHelperTest.php @@ -0,0 +1,100 @@ +Turnstile = new TurnstileHelper($view); + } + + /** + * tearDown method + * + * @return void + */ + protected function tearDown(): void + { + unset($this->Turnstile); + + parent::tearDown(); + } + + /** + * @return void + */ + public function testPreConnect(): void + { + $this->assertStringContainsString( + '', + $this->Turnstile->preConnect() + ); + } + + /** + * @return void + */ + public function testScriptNoEventListener(): void + { + $result = $this->Turnstile->script(); + $this->assertStringContainsString( + '