Beautiful Open-Source Form Builder
Add reCAPTCHA support and update captcha provider handling (#647)
Chirag Chhatralad7ce8536c8f0
diff --git a/api/.env.example b/api/.env.exampleindex 31762cf80..445431f0c 100644--- a/api/.env.example+++ b/api/.env.example@@ -72,6 +72,9 @@ STRIPE_TEST_DEFAULT_PRICING_YEARLY=H_CAPTCHA_SITE_KEY=H_CAPTCHA_SECRET_KEY=+RE_CAPTCHA_SITE_KEY=+RE_CAPTCHA_SECRET_KEY=+MUX_WORKSPACE_ID=MUX_API_TOKEN=diff --git a/api/app/Http/Controllers/Auth/RegisterController.php b/api/app/Http/Controllers/Auth/RegisterController.phpindex 447689a1c..771d8cb63 100644--- a/api/app/Http/Controllers/Auth/RegisterController.php+++ b/api/app/Http/Controllers/Auth/RegisterController.php@@ -12,7 +12,7 @@ use Illuminate\Foundation\Auth\RegistersUsers;use Illuminate\Http\Request;use Illuminate\Support\Facades\Validator;use Illuminate\Validation\Rule;-use App\Rules\ValidHCaptcha;+use App\Rules\ValidReCaptcha;class RegisterController extends Controller{@@ -71,8 +71,8 @@ class RegisterController extends Controller'utm_data' => ['nullable', 'array'],];- if (config('services.h_captcha.secret_key')) {- $rules['h-captcha-response'] = [new ValidHCaptcha()];+ if (config('services.re_captcha.secret_key')) {+ $rules['g-recaptcha-response'] = [new ValidReCaptcha()];}return Validator::make($data, $rules, [diff --git a/api/app/Http/Requests/AnswerFormRequest.php b/api/app/Http/Requests/AnswerFormRequest.phpindex 0edc1989d..722f48fbd 100644--- a/api/app/Http/Requests/AnswerFormRequest.php+++ b/api/app/Http/Requests/AnswerFormRequest.php@@ -8,6 +8,7 @@ use App\Rules\MatrixValidationRule;use App\Rules\StorageFile;use App\Rules\ValidHCaptcha;use App\Rules\ValidPhoneInputRule;+use App\Rules\ValidReCaptcha;use App\Rules\ValidUrl;use App\Service\Forms\FormLogicPropertyResolver;use Illuminate\Foundation\Http\FormRequest;@@ -116,9 +117,13 @@ class AnswerFormRequest extends FormRequest$this->requestRules[$propertyId] = $rules;}- // Validate hCaptcha+ // Validate Captchaif ($this->form->use_captcha) {- $this->requestRules['h-captcha-response'] = [new ValidHCaptcha()];+ if ($this->form->captcha_provider === 'recaptcha') {+ $this->requestRules['g-recaptcha-response'] = [new ValidReCaptcha()];+ } elseif ($this->form->captcha_provider === 'hcaptcha') {+ $this->requestRules['h-captcha-response'] = [new ValidHCaptcha()];+ }}// Validate submission_id for edit modediff --git a/api/app/Http/Requests/UserFormRequest.php b/api/app/Http/Requests/UserFormRequest.phpindex cfaa84162..f8b8da295 100644--- a/api/app/Http/Requests/UserFormRequest.php+++ b/api/app/Http/Requests/UserFormRequest.php@@ -118,6 +118,7 @@ abstract class UserFormRequest extends \Illuminate\Foundation\Http\FormRequest'can_be_indexed' => 'boolean','password' => 'sometimes|nullable','use_captcha' => 'boolean',+ 'captcha_provider' => ['sometimes', Rule::in(['recaptcha', 'hcaptcha'])],// Custom SEO'seo_meta' => 'nullable|array',diff --git a/api/app/Models/Forms/Form.php b/api/app/Models/Forms/Form.phpindex f8769a2ee..541723710 100644--- a/api/app/Models/Forms/Form.php+++ b/api/app/Models/Forms/Form.php@@ -82,6 +82,7 @@ class Form extends Model implements CachableAttributes'submitted_text','redirect_url','use_captcha',+ 'captcha_provider','closes_at','closed_text','max_submissions_count',diff --git a/api/app/Rules/ValidHCaptcha.php b/api/app/Rules/ValidHCaptcha.phpindex b535690ce..b3ca00071 100644--- a/api/app/Rules/ValidHCaptcha.php+++ b/api/app/Rules/ValidHCaptcha.php@@ -10,7 +10,7 @@ class ValidHCaptcha implements ImplicitRule{public const H_CAPTCHA_VERIFY_URL = 'https://hcaptcha.com/siteverify';- private $error = 'Invalid CAPTCHA. Please prove you\'re not a bot.';+ private $error = 'validation.invalid_captcha';/*** Determine if the validation rule passes.@@ -22,7 +22,7 @@ class ValidHCaptcha implements ImplicitRulepublic function passes($attribute, $value){if (empty($value)) {- $this->error = 'Please complete the captcha.';+ $this->error = 'validation.complete_captcha';return false;}@@ -46,6 +46,6 @@ class ValidHCaptcha implements ImplicitRule*/public function message(){- return $this->error;+ return trans($this->error);}}diff --git a/api/app/Rules/ValidReCaptcha.php b/api/app/Rules/ValidReCaptcha.phpnew file mode 100644index 000000000..a889d423e--- /dev/null+++ b/api/app/Rules/ValidReCaptcha.php@@ -0,0 +1,51 @@+<?php++namespace App\Rules;++use Closure;+use Illuminate\Contracts\Validation\ImplicitRule;+use Illuminate\Support\Facades\Http;++class ValidReCaptcha implements ImplicitRule+{+ public const RECAPTCHA_VERIFY_URL = 'https://www.google.com/recaptcha/api/siteverify';++ private $error = 'validation.invalid_captcha';++ /**+ * Determine if the validation rule passes.+ *+ * @param string $attribute+ * @param mixed $value+ * @return bool+ */+ public function passes($attribute, $value)+ {+ if (empty($value)) {+ $this->error = 'validation.complete_captcha';++ return false;+ }++ return Http::asForm()->post(self::RECAPTCHA_VERIFY_URL, [+ 'secret' => config('services.re_captcha.secret_key'),+ 'response' => $value,+ ])->json('success');+ }+ public function validate(string $attribute, mixed $value, Closure $fail): void+ {+ if (!$this->passes($attribute, $value)) {+ $fail($this->message());+ }+ }++ /**+ * Get the validation error message.+ *+ * @return string+ */+ public function message()+ {+ return trans($this->error);+ }+}diff --git a/api/config/services.php b/api/config/services.phpindex 8076ef9a2..eda2e4708 100644--- a/api/config/services.php+++ b/api/config/services.php@@ -40,6 +40,11 @@ return ['secret_key' => env('H_CAPTCHA_SECRET_KEY'),],+ 're_captcha' => [+ 'site_key' => env('RE_CAPTCHA_SITE_KEY'),+ 'secret_key' => env('RE_CAPTCHA_SECRET_KEY'),+ ],+'canny' => ['api_key' => env('CANNY_API_KEY'),],diff --git a/api/database/migrations/2024_03_21_000000_add_captcha_provider_to_forms_table.php b/api/database/migrations/2024_03_21_000000_add_captcha_provider_to_forms_table.phpnew file mode 100644index 000000000..1e535425e--- /dev/null+++ b/api/database/migrations/2024_03_21_000000_add_captcha_provider_to_forms_table.php@@ -0,0 +1,21 @@+<?php++use Illuminate\Database\Migrations\Migration;+use Illuminate\Database\Schema\Blueprint;+use Illuminate\Support\Facades\Schema;++return new class () extends Migration {+ public function up()+ {+ Schema::table('forms', function (Blueprint $table) {+ $table->string('captcha_provider')->default('hcaptcha')->after('use_captcha');+ });+ }++ public function down()+ {+ Schema::table('forms', function (Blueprint $table) {+ $table->dropColumn('captcha_provider');+ });+ }+};diff --git a/api/resources/lang/ar/validation.php b/api/resources/lang/ar/validation.phpindex 1aa91cfec..8082e39ee 100644--- a/api/resources/lang/ar/validation.php+++ b/api/resources/lang/ar/validation.php@@ -116,4 +116,6 @@ return ['attributes' => [],'invalid_json' => 'إدخال غير صالح. يرجى التصحيح والمحاولة مرة أخرى.',+ 'invalid_captcha' => 'التحقق من صحة الحقل غير صحيح. يرجى التحقق من صحة الحقل والمحاولة مرة أخرى.',+ 'complete_captcha' => 'يرجى إكمال التحقق من صحة الحقل.',];diff --git a/api/resources/lang/bn/validation.php b/api/resources/lang/bn/validation.phpindex 8d942bcd6..61adf92ba 100644--- a/api/resources/lang/bn/validation.php+++ b/api/resources/lang/bn/validation.php@@ -116,4 +116,6 @@ return ['attributes' => [],'invalid_json' => 'অবৈধ ইনপুট। অনুগ্রহ করে সংশোধন করে আবার চেষ্টা করুন।',+ 'invalid_captcha' => 'অবৈধ টিপস। অনুগ্রহ করে টিপস টিপুন।',+ 'complete_captcha' => 'অনুগ্রহ করে টিপস টিপুন।',];diff --git a/api/resources/lang/de/validation.php b/api/resources/lang/de/validation.phpindex 7cca30856..43579ea1b 100644--- a/api/resources/lang/de/validation.php+++ b/api/resources/lang/de/validation.php@@ -116,4 +116,6 @@ return ['attributes' => [],'invalid_json' => 'Ungültige Eingabe. Bitte korrigieren Sie und versuchen Sie es erneut.',+ 'invalid_captcha' => 'Ungültige CAPTCHA. Bitte beweisen Sie, dass Sie kein Bot sind.',+ 'complete_captcha' => 'Bitte füllen Sie die CAPTCHA aus.',];diff --git a/api/resources/lang/en/validation.php b/api/resources/lang/en/validation.phpindex 0be387d3d..f6b59ed9a 100644--- a/api/resources/lang/en/validation.php+++ b/api/resources/lang/en/validation.php@@ -150,5 +150,7 @@ return ['attributes' => [],'invalid_json' => 'Invalid input. Please correct and try again.',+ 'invalid_captcha' => 'Invalid CAPTCHA. Please prove you\'re not a bot.',+ 'complete_captcha' => 'Please complete the captcha.',];diff --git a/api/resources/lang/es/validation.php b/api/resources/lang/es/validation.phpindex 342e3e26c..ef8dd31aa 100755--- a/api/resources/lang/es/validation.php+++ b/api/resources/lang/es/validation.php@@ -153,5 +153,7 @@ return [],'invalid_json' => 'Entrada no válida. Por favor, corrija e intente nuevamente.',+ 'invalid_captcha' => 'Captcha no válido. Por favor, demuestre que no es un bot.',+ 'complete_captcha' => 'Por favor, complete el captcha.',];diff --git a/api/resources/lang/fr/validation.php b/api/resources/lang/fr/validation.phpindex 561d001ed..868464fb4 100644--- a/api/resources/lang/fr/validation.php+++ b/api/resources/lang/fr/validation.php@@ -116,4 +116,6 @@ return ['attributes' => [],'invalid_json' => 'Entrée invalide. Veuillez corriger et réessayer.',+ 'invalid_captcha' => 'Captcha invalide. Veuillez prouver que vous n\'êtes pas un bot.',+ 'complete_captcha' => 'Veuillez compléter le captcha.',];diff --git a/api/resources/lang/hi/validation.php b/api/resources/lang/hi/validation.phpindex f0a575e46..a7322d01e 100644--- a/api/resources/lang/hi/validation.php+++ b/api/resources/lang/hi/validation.php@@ -116,4 +116,6 @@ return ['attributes' => [],'invalid_json' => 'अमान्य इनपुट। कृपया सुधारें और पुनः प्रयास करें।',+ 'invalid_captcha' => 'अमान्य कैप्चा। कृपया दिखाएं कि आप एक बॉट नहीं हैं।',+ 'complete_captcha' => 'कृपया कैप्चा भरें।',];diff --git a/api/resources/lang/ja/validation.php b/api/resources/lang/ja/validation.phpindex 29ebc92d9..bb945111d 100644--- a/api/resources/lang/ja/validation.php+++ b/api/resources/lang/ja/validation.php@@ -116,4 +116,6 @@ return ['attributes' => [],'invalid_json' => '無効な入力です。修正して再度お試しください。',+ 'invalid_captcha' => '無効なCAPTCHAです。ボットではないことを証明してください。',+ 'complete_captcha' => 'CAPTCHAを完了してください。',];diff --git a/api/resources/lang/jv/validation.php b/api/resources/lang/jv/validation.phpindex 0a6d62853..a859b10fe 100644--- a/api/resources/lang/jv/validation.php+++ b/api/resources/lang/jv/validation.php@@ -116,4 +116,6 @@ return ['attributes' => [],'invalid_json' => 'Input ora valid. Mangga dibenakake lan dicoba maneh.',+ 'invalid_captcha' => 'CAPTCHA ora valid. Mangga dibenakake lan dicoba maneh.',+ 'complete_captcha' => 'CAPTCHA kudu diisi.',];diff --git a/api/resources/lang/ko/validation.php b/api/resources/lang/ko/validation.phpindex 31166974b..c3117b424 100644--- a/api/resources/lang/ko/validation.php+++ b/api/resources/lang/ko/validation.php@@ -116,4 +116,6 @@ return ['attributes' => [],'invalid_json' => '잘못된 입력입니다. 수정 후 다시 시도해 주세요.',+ 'invalid_captcha' => '잘못된 캡차입니다. 봇이 아님을 증명해 주세요.',+ 'complete_captcha' => '캡차를 완료해 주세요.',];diff --git a/api/resources/lang/mr/validation.php b/api/resources/lang/mr/validation.phpindex 115ba5888..6024f8f85 100644--- a/api/resources/lang/mr/validation.php+++ b/api/resources/lang/mr/validation.php@@ -133,4 +133,6 @@ return ['attributes' => [],'invalid_json' => 'अवैध इनपुट. कृपया सुधारून पुन्हा प्रयत्न करा.',+ 'invalid_captcha' => 'अवैध कैप्चा। कृपया कैप्चा टिपला आणि पुन्हा प्रयत्न करा।',+ 'complete_captcha' => 'कृपया कैप्चा भरा.',];diff --git a/api/resources/lang/pa/validation.php b/api/resources/lang/pa/validation.phpindex f734589fc..e1c8dcc7c 100644--- a/api/resources/lang/pa/validation.php+++ b/api/resources/lang/pa/validation.php@@ -115,5 +115,7 @@ return ['attributes' => [],- 'invalid_json' => 'ਗਲਤ ਇਨਪੁਟ। ਕਿਰਪਾ ਕਰਕੇ ਸਹੀ ਕਰੋ ਅਤੇ ਦੁਬਾਰਾ ਕੋਸ਼ਿਸ਼ ਕਰੋ।',+ 'invalid_json' => 'ਗਲਤ ਇਨਪੁਟ। ਕਿਰਪਾ ਕਰਕਕੇ ਸਹੀ ਕਰੋ ਅਤੇ ਦੁਬਾਰਾ ਕੋਸ਼ਿਸ਼ ਕਰੋ।',+ 'invalid_captcha' => 'ਗਲਤ ਕੈਪਚਾ। ਕਿਰਪਾ ਕਰੋ ਕੈਪਚਾ ਟੀਪ ਅਤੇ ਦੁਬਾਰਾ ਕੋਸ਼ਿਸ਼ ਕਰੋ।',+ 'complete_captcha' => 'ਕਿਰਪਾ ਕਰੋ ਕੈਪਚਾ ਭਰੋ।',];diff --git a/api/resources/lang/pt-BR/validation.php b/api/resources/lang/pt-BR/validation.phpindex 9cc60a28f..1f523cf54 100644--- a/api/resources/lang/pt-BR/validation.php+++ b/api/resources/lang/pt-BR/validation.php@@ -180,4 +180,6 @@ return [],'invalid_json' => 'Entrada inválida. Por favor, corrija e tente novamente.',+ 'invalid_captcha' => 'Captcha inválido. Por favor, demonstre que não é um bot.',+ 'complete_captcha' => 'Por favor, complete o captcha.',];diff --git a/api/resources/lang/pt/validation.php b/api/resources/lang/pt/validation.phpindex cfcf6dd13..a03437234 100644--- a/api/resources/lang/pt/validation.php+++ b/api/resources/lang/pt/validation.php@@ -116,4 +116,6 @@ return ['attributes' => [],'invalid_json' => 'Entrada inválida. Por favor, corrija e tente novamente.',+ 'invalid_captcha' => 'Captcha inválido. Por favor, demonstre que não é um bot.',+ 'complete_captcha' => 'Por favor, complete o captcha.',];diff --git a/api/resources/lang/ru/validation.php b/api/resources/lang/ru/validation.phpindex af9a77670..b682c8c9d 100644--- a/api/resources/lang/ru/validation.php+++ b/api/resources/lang/ru/validation.php@@ -116,4 +116,6 @@ return ['attributes' => [],'invalid_json' => 'Неверный ввод. Пожалуйста, исправьте и попробуйте снова.',+ 'invalid_captcha' => 'Неверный CAPTCHA. Пожалуйста, докажите, что вы не бот.',+ 'complete_captcha' => 'Пожалуйста, заполните CAPTCHA.',];diff --git a/api/resources/lang/ta/validation.php b/api/resources/lang/ta/validation.phpindex 41c2bef29..1c44a5c28 100644--- a/api/resources/lang/ta/validation.php+++ b/api/resources/lang/ta/validation.php@@ -133,4 +133,6 @@ return ['attributes' => [],'invalid_json' => 'தவறான உள்ளீடு. சரிசெய்து மீண்டும் முயற்சிக்கவும்.',+ 'invalid_captcha' => 'தவறான கையால் வைத்த முறை. மீண்டும் முயற்சிக்கவும்.',+ 'complete_captcha' => 'கையால் வைத்த முறையை நிரப்பவும்.',];diff --git a/api/resources/lang/te/validation.php b/api/resources/lang/te/validation.phpindex 91883c1f8..6032afe69 100644--- a/api/resources/lang/te/validation.php+++ b/api/resources/lang/te/validation.php@@ -116,4 +116,6 @@ return ['attributes' => [],'invalid_json' => 'చెల్లని ఇన్పుట్. దయచేసి సరిచేసి మళ్లీ ప్రయత్నించండి.',+ 'invalid_captcha' => 'అవైధ క్యాప్చా. దయచేసి క్యాప్చా టైప్ మరియు మళ్లీ ప్రయత్నించండి.',+ 'complete_captcha' => 'దయచేసి క్యాప్చా భరించండి.',];diff --git a/api/resources/lang/tr/validation.php b/api/resources/lang/tr/validation.phpindex 3b77d4e24..bde699497 100644--- a/api/resources/lang/tr/validation.php+++ b/api/resources/lang/tr/validation.php@@ -133,4 +133,6 @@ return ['attributes' => [],'invalid_json' => 'Geçersiz girdi. Lütfen düzeltin ve tekrar deneyin.',+ 'invalid_captcha' => 'Geçersiz CAPTCHA. Lütfen bot olmadığınızı gösterin.',+ 'complete_captcha' => 'Lütfen CAPTCHA\'yı tamamlayın.',];diff --git a/api/resources/lang/ur/validation.php b/api/resources/lang/ur/validation.phpindex 87fe5ad97..f9c282387 100644--- a/api/resources/lang/ur/validation.php+++ b/api/resources/lang/ur/validation.php@@ -116,4 +116,6 @@ return ['attributes' => [],'invalid_json' => 'غلط ان پٹ۔ براہ کرم درست کریں اور دوبارہ کوشش کریں۔',+ 'invalid_captcha' => 'غلط کپچا۔ براہ کرم کپچا ٹائپ کریں اور دوبارہ کوشش کریں۔',+ 'complete_captcha' => 'براہ کرم کپچا پر کام کریں۔',];diff --git a/api/resources/lang/vi/validation.php b/api/resources/lang/vi/validation.phpindex 05c2ada83..df40ee2c2 100644--- a/api/resources/lang/vi/validation.php+++ b/api/resources/lang/vi/validation.php@@ -116,4 +116,6 @@ return ['attributes' => [],'invalid_json' => 'Dữ liệu không hợp lệ. Vui lòng sửa và thử lại.',+ 'invalid_captcha' => 'Mã bảo vệ không đúng. Vui lòng nhập lại và thử lại.',+ 'complete_captcha' => 'Vui lòng nhập mã bảo vệ.',];diff --git a/api/resources/lang/zh-CN/validation.php b/api/resources/lang/zh-CN/validation.phpindex f5e16a1b8..cd49c9978 100644--- a/api/resources/lang/zh-CN/validation.php+++ b/api/resources/lang/zh-CN/validation.php@@ -96,4 +96,6 @@ return ['attributes' => [],'invalid_json' => '输入无效。请修正后重试。',+ 'invalid_captcha' => '验证码错误。请重新输入并重试。',+ 'complete_captcha' => '请完成验证码。',];diff --git a/api/resources/lang/zh/validation.php b/api/resources/lang/zh/validation.phpindex 40934721a..5814a68c9 100644--- a/api/resources/lang/zh/validation.php+++ b/api/resources/lang/zh/validation.php@@ -116,4 +116,6 @@ return ['attributes' => [],'invalid_json' => '输入无效。请修正后重试。',+ 'invalid_captcha' => '验证码错误。请重新输入并重试。',+ 'complete_captcha' => '请完成验证码。',];diff --git a/api/tests/Feature/Forms/FormCaptchaTest.php b/api/tests/Feature/Forms/FormCaptchaTest.phpindex 7b3308259..84b74cbfc 100644--- a/api/tests/Feature/Forms/FormCaptchaTest.php+++ b/api/tests/Feature/Forms/FormCaptchaTest.php@@ -1,10 +1,11 @@<?php-it('create form with captcha and raise validation issue', function () {+it('create form with hcaptcha and raise validation issue', function () {$user = $this->actingAsUser();$workspace = $this->createUserWorkspace($user);$form = $this->createForm($user, $workspace, ['use_captcha' => true,+ 'captcha_provider' => 'hcaptcha',]);$this->postJson(route('forms.answer', $form->slug), [])@@ -18,3 +19,23 @@ it('create form with captcha and raise validation issue', function () {],]);});++it('create form with recaptcha and raise validation issue', function () {+ $user = $this->actingAsUser();+ $workspace = $this->createUserWorkspace($user);+ $form = $this->createForm($user, $workspace, [+ 'use_captcha' => true,+ 'captcha_provider' => 'recaptcha',+ ]);++ $this->postJson(route('forms.answer', $form->slug), [])+ ->assertStatus(422)+ ->assertJson([+ 'message' => 'Please complete the captcha.',+ 'errors' => [+ 'g-recaptcha-response' => [+ 'Please complete the captcha.',+ ],+ ],+ ]);+});diff --git a/api/tests/Feature/RegisterTest.php b/api/tests/Feature/RegisterTest.phpindex 598374cd4..95ecc6e7e 100644--- a/api/tests/Feature/RegisterTest.php+++ b/api/tests/Feature/RegisterTest.php@@ -1,13 +1,13 @@<?phpuse App\Models\User;-use App\Rules\ValidHCaptcha;+use App\Rules\ValidReCaptcha;use Illuminate\Support\Facades\Http;it('can register', function () {Http::fake([- ValidHCaptcha::H_CAPTCHA_VERIFY_URL => Http::response(['success' => true])+ ValidReCaptcha::RECAPTCHA_VERIFY_URL => Http::response(['success' => true])]);$this->postJson('/register', [@@ -17,7 +17,7 @@ it('can register', function () {'password' => 'secret','password_confirmation' => 'secret','agree_terms' => true,- 'h-captcha-response' => 'test-token', // Mock token for testing+ 'g-recaptcha-response' => 'test-token', // Mock token for testing])->assertSuccessful()->assertJsonStructure(['id', 'name', 'email']);@@ -36,7 +36,7 @@ it('cannot register with existing email', function () {'email' => '[email protected]','password' => 'secret','password_confirmation' => 'secret',- 'h-captcha-response' => 'test-token',+ 'g-recaptcha-response' => 'test-token',])->assertStatus(422)->assertJsonValidationErrors(['email']);@@ -44,7 +44,7 @@ it('cannot register with existing email', function () {it('cannot register with disposable email', function () {Http::fake([- ValidHCaptcha::H_CAPTCHA_VERIFY_URL => Http::response(['success' => true])+ ValidReCaptcha::RECAPTCHA_VERIFY_URL => Http::response(['success' => true])]);// Select random email@@ -62,7 +62,7 @@ it('cannot register with disposable email', function () {'password' => 'secret','password_confirmation' => 'secret','agree_terms' => true,- 'h-captcha-response' => 'test-token',+ 'g-recaptcha-response' => 'test-token',])->assertStatus(422)->assertJsonValidationErrors(['email'])@@ -77,10 +77,10 @@ it('cannot register with disposable email', function () {});it('requires hcaptcha token in production', function () {- config(['services.h_captcha.secret_key' => 'test-key']);+ config(['services.re_captcha.secret_key' => 'test-key']);Http::fake([- ValidHCaptcha::H_CAPTCHA_VERIFY_URL => Http::response(['success' => true])+ ValidReCaptcha::RECAPTCHA_VERIFY_URL => Http::response(['success' => true])]);$this->postJson('/register', [@@ -92,5 +92,5 @@ it('requires hcaptcha token in production', function () {'agree_terms' => true,])->assertStatus(422)- ->assertJsonValidationErrors(['h-captcha-response']);+ ->assertJsonValidationErrors(['g-recaptcha-response']);});diff --git a/client/.env.example b/client/.env.exampleindex 7fe5fcf22..261d3e267 100644--- a/client/.env.example+++ b/client/.env.example@@ -6,4 +6,5 @@ NUXT_PUBLIC_CRISP_WEBSITE_ID=NUXT_PUBLIC_ENV=NUXT_PUBLIC_GOOGLE_ANALYTICS_CODE=NUXT_PUBLIC_H_CAPTCHA_SITE_KEY=+NUXT_PUBLIC_RE_CAPTCHA_SITE_KEY=NUXT_API_SECRET=secretdiff --git a/client/components/forms/components/CaptchaInput.vue b/client/components/forms/components/CaptchaInput.vuenew file mode 100644index 000000000..d38647f3b--- /dev/null+++ b/client/components/forms/components/CaptchaInput.vue@@ -0,0 +1,179 @@+<template>+ <div>+ <div v-if="showCaptcha">+ <RecaptchaV2+ v-if="provider === 'recaptcha'"+ :key="`recaptcha-${componentKey}`"+ ref="captchaRef"+ :sitekey="recaptchaSiteKey"+ :theme="darkMode ? 'dark' : 'light'"+ :language="language"+ @verify="onCaptchaVerify"+ @expired="onCaptchaExpired"+ @opened="onCaptchaOpen"+ @closed="onCaptchaClose"+ />+ <HCaptchaV2+ v-else+ :key="`hcaptcha-${componentKey}`"+ ref="captchaRef"+ :sitekey="hCaptchaSiteKey"+ :theme="darkMode ? 'dark' : 'light'"+ :language="language"+ @verify="onCaptchaVerify"+ @expired="onCaptchaExpired"+ @opened="onCaptchaOpen"+ @closed="onCaptchaClose"+ />+ </div>+ <has-error+ :form="form"+ :field-id="formFieldName"+ />+ </div>+</template>++<script setup>+import HCaptchaV2 from './HCaptchaV2.vue'+import RecaptchaV2 from './RecaptchaV2.vue'++const props = defineProps({+ provider: {+ type: String,+ required: true,+ validator: (value) => ['recaptcha', 'hcaptcha'].includes(value)+ },+ form: {+ type: Object,+ required: true+ },+ language: {+ type: String,+ required: true+ },+ darkMode: {+ type: Boolean,+ default: false+ }+})++const config = useRuntimeConfig()+const recaptchaSiteKey = config.public.recaptchaSiteKey+const hCaptchaSiteKey = config.public.hCaptchaSiteKey++const captchaRef = ref(null)+const isIframe = ref(false)+const showCaptcha = ref(true)+const componentKey = ref(0)++const formFieldName = computed(() => props.provider === 'recaptcha' ? 'g-recaptcha-response' : 'h-captcha-response')++// Watch for provider changes to reset the form field+watch(() => props.provider, async (newProvider, oldProvider) => {+ if (newProvider !== oldProvider) {+ // Clear old provider's value+ if (oldProvider === 'recaptcha') {+ props.form['g-recaptcha-response'] = null+ } else if (oldProvider === 'hcaptcha') {+ props.form['h-captcha-response'] = null+ }++ // Force remount by toggling visibility and incrementing key+ showCaptcha.value = false++ // Wait longer to ensure complete cleanup+ await new Promise(resolve => setTimeout(resolve, 1000))++ componentKey.value+++ await nextTick()++ // Wait again before showing new captcha+ await new Promise(resolve => setTimeout(resolve, 1000))++ showCaptcha.value = true+ }+})++onMounted(() => {+ isIframe.value = window.self !== window.top+})++// Add a ref to track if captcha was completed+const wasCaptchaCompleted = ref(false)++// Handle captcha verification+const onCaptchaVerify = (token) => {+ wasCaptchaCompleted.value = true+ props.form[formFieldName.value] = token+ // Also set the DOM element value for compatibility with existing code+ if (import.meta.client) {+ const element = document.getElementsByName(formFieldName.value)[0]+ if (element) element.value = token+ }+}++// Handle captcha expiration+const onCaptchaExpired = () => {+ wasCaptchaCompleted.value = false+ props.form[formFieldName.value] = null+ // Also clear the DOM element value for compatibility with existing code+ if (import.meta.client) {+ const element = document.getElementsByName(formFieldName.value)[0]+ if (element) element.value = ''+ }+}++// Handle iframe resizing+const resizeIframe = (height) => {+ if (!isIframe.value) return++ try {+ window.parentIFrame?.size(height)+ } catch (e) {+ // Silently handle error+ }+}++// Handle captcha open/close for iframe resizing+const onCaptchaOpen = () => {+ resizeIframe(500)+ // Ensure the captcha is visible by scrolling to it+ if (import.meta.client) {+ nextTick(() => {+ const captchaElement = captchaRef.value?.$el+ if (captchaElement) {+ captchaElement.scrollIntoView({ behavior: 'smooth', block: 'center' })+ }+ })+ }+}++const onCaptchaClose = () => {+ resizeIframe(0)+}++// Method to reset captcha - can be called from parent+defineExpose({+ reset: () => {+ // Only do a full reset if the captcha was previously completed+ if (captchaRef.value) {+ if (wasCaptchaCompleted.value) {+ wasCaptchaCompleted.value = false+ captchaRef.value.reset()+ }+ }+ }+})+</script>++<style>+.fade-enter-active,+.fade-leave-active {+ transition: opacity 0.2s ease;+}++.fade-enter-from,+.fade-leave-to {+ opacity: 0;+}+</style>\ No newline at end of filediff --git a/client/components/forms/components/HCaptchaV2.vue b/client/components/forms/components/HCaptchaV2.vuenew file mode 100644index 000000000..18d2d4bf9--- /dev/null+++ b/client/components/forms/components/HCaptchaV2.vue@@ -0,0 +1,186 @@+<template>+ <div class="hcaptcha-container">+ <div ref="hcaptchaContainer" />+ </div>+</template>++<script setup>+const props = defineProps({+ sitekey: {+ type: String,+ required: true+ },+ theme: {+ type: String,+ default: 'light'+ },+ language: {+ type: String,+ default: 'en'+ }+})++const emit = defineEmits(['verify', 'expired', 'opened', 'closed'])+const hcaptchaContainer = ref(null)+let widgetId = null++// Global script loading state+const SCRIPT_ID = 'hcaptcha-script'+let scriptLoadPromise = null++// Add this cleanup function at the script level+const cleanupHcaptcha = () => {+ // Remove all hCaptcha iframes+ document.querySelectorAll('iframe[src*="hcaptcha.com"]').forEach(iframe => {+ iframe.remove()+ })++ // Remove all hCaptcha scripts+ document.querySelectorAll('script[src*="hcaptcha.com"]').forEach(script => {+ script.remove()+ })++ // Remove specific script+ const script = document.getElementById(SCRIPT_ID)+ if (script) {+ script.remove()+ }++ // Remove hCaptcha styles+ document.querySelectorAll('style[data-emotion]').forEach(style => {+ style.remove()+ })++ // Clean up global variables+ if (window.hcaptcha) {+ delete window.hcaptcha+ }++ // Clean up any potential callbacks+ Object.keys(window).forEach(key => {+ if (key.startsWith('hcaptchaOnLoad_')) {+ delete window[key]+ }+ })++ scriptLoadPromise = null+}++const loadHcaptchaScript = () => {+ if (scriptLoadPromise) return scriptLoadPromise++ // Clean up before loading new script+ cleanupHcaptcha()++ scriptLoadPromise = new Promise((resolve, reject) => {+ // If hcaptcha is already available and ready, use it+ if (window.hcaptcha?.render) {+ resolve(window.hcaptcha)+ return+ }++ // Create a unique callback name+ const callbackName = `hcaptchaOnLoad_${Date.now()}`++ // Create the script+ const script = document.createElement('script')+ script.id = SCRIPT_ID+ script.src = `https://js.hcaptcha.com/1/api.js?render=explicit&onload=${callbackName}&recaptchacompat=off`+ script.async = true+ script.defer = true++ let timeoutId = null++ // Set up the callback before adding the script+ window[callbackName] = () => {+ if (timeoutId) clearTimeout(timeoutId)+ if (window.hcaptcha?.render) {+ resolve(window.hcaptcha)+ delete window[callbackName]+ } else {+ reject(new Error('hCaptcha failed to initialize'))+ }+ }++ script.onerror = (error) => {+ if (timeoutId) clearTimeout(timeoutId)+ delete window[callbackName]+ scriptLoadPromise = null+ reject(error)+ }++ timeoutId = setTimeout(() => {+ delete window[callbackName]+ scriptLoadPromise = null+ reject(new Error('hCaptcha script load timeout'))+ }, 10000)++ document.head.appendChild(script)+ })++ return scriptLoadPromise+}++const renderHcaptcha = async () => {+ try {+ // Clear any existing content first+ if (hcaptchaContainer.value) {+ hcaptchaContainer.value.innerHTML = ''+ }++ const hcaptcha = await loadHcaptchaScript()++ // Double check container still exists after async operation+ if (!hcaptchaContainer.value) return++ // Render new widget+ widgetId = hcaptcha.render(hcaptchaContainer.value, {+ sitekey: props.sitekey,+ theme: props.theme,+ hl: props.language,+ 'callback': (token) => emit('verify', token),+ 'expired-callback': () => emit('expired'),+ 'error-callback': () => {+ if (widgetId !== null) {+ hcaptcha.reset(widgetId)+ }+ },+ 'open-callback': () => emit('opened'),+ 'close-callback': () => emit('closed')+ })+ } catch (error) {+ scriptLoadPromise = null // Reset promise on error+ }+}++onMounted(() => {+ renderHcaptcha()+})++onBeforeUnmount(() => {+ // Clean up widget and reset state+ if (window.hcaptcha && widgetId !== null) {+ try {+ window.hcaptcha.remove(widgetId)+ } catch (e) {+ // Silently handle error+ }+ }++ cleanupHcaptcha()++ if (hcaptchaContainer.value) {+ hcaptchaContainer.value.innerHTML = ''+ }++ widgetId = null+})++// Expose reset method that properly reloads the captcha+defineExpose({+ reset: async () => {+ cleanupHcaptcha()+ await renderHcaptcha()+ }+})+</script>\ No newline at end of filediff --git a/client/components/forms/components/RecaptchaV2.vue b/client/components/forms/components/RecaptchaV2.vuenew file mode 100644index 000000000..885077876--- /dev/null+++ b/client/components/forms/components/RecaptchaV2.vue@@ -0,0 +1,179 @@+<template>+ <div class="recaptcha-container">+ <div ref="recaptchaContainer" />+ </div>+</template>++<script setup>+const props = defineProps({+ sitekey: {+ type: String,+ required: true+ },+ theme: {+ type: String,+ default: 'light'+ },+ language: {+ type: String,+ default: 'en'+ }+})++const emit = defineEmits(['verify', 'expired', 'opened', 'closed'])+const recaptchaContainer = ref(null)+let widgetId = null++// Global script loading state+const SCRIPT_ID = 'recaptcha-script'+let scriptLoadPromise = null++// Add cleanup function similar to hCaptcha+const cleanupRecaptcha = () => {+ // Remove all reCAPTCHA iframes+ document.querySelectorAll('iframe[src*="google.com/recaptcha"]').forEach(iframe => {+ iframe.remove()+ })++ // Remove all reCAPTCHA scripts+ document.querySelectorAll('script[src*="google.com/recaptcha"]').forEach(script => {+ script.remove()+ })++ // Remove specific script+ const script = document.getElementById(SCRIPT_ID)+ if (script) {+ script.remove()+ }++ // Clean up global variables+ if (window.grecaptcha) {+ delete window.grecaptcha+ }++ scriptLoadPromise = null+}++const loadRecaptchaScript = () => {+ if (scriptLoadPromise) return scriptLoadPromise++ // Clean up before loading new script+ cleanupRecaptcha()++ scriptLoadPromise = new Promise((resolve, reject) => {+ // If grecaptcha is already available and ready, use it+ if (window.grecaptcha?.render) {+ resolve(window.grecaptcha)+ return+ }++ const script = document.createElement('script')+ script.id = SCRIPT_ID+ script.src = 'https://www.google.com/recaptcha/api.js?render=explicit'+ script.async = true+ script.defer = true++ let timeoutId = null++ script.onload = () => {+ const checkGrecaptcha = () => {+ if (window.grecaptcha?.render) {+ if (timeoutId) clearTimeout(timeoutId)+ resolve(window.grecaptcha)+ } else {+ setTimeout(checkGrecaptcha, 100)+ }+ }+ checkGrecaptcha()+ }++ script.onerror = (error) => {+ if (timeoutId) clearTimeout(timeoutId)+ scriptLoadPromise = null+ reject(error)+ }++ timeoutId = setTimeout(() => {+ scriptLoadPromise = null+ reject(new Error('reCAPTCHA script load timeout'))+ }, 10000)++ document.head.appendChild(script)+ })++ return scriptLoadPromise+}++const renderRecaptcha = async () => {+ try {+ // Clear any existing content first+ if (recaptchaContainer.value) {+ recaptchaContainer.value.innerHTML = ''+ }++ const grecaptcha = await loadRecaptchaScript()++ // Double check container still exists after async operation+ if (!recaptchaContainer.value) return++ // Render new widget+ widgetId = grecaptcha.render(recaptchaContainer.value, {+ sitekey: props.sitekey,+ theme: props.theme,+ hl: props.language,+ callback: (token) => emit('verify', token),+ 'expired-callback': () => emit('expired'),+ 'error-callback': () => {+ if (widgetId !== null) {+ grecaptcha.reset(widgetId)+ }+ }+ })+ } catch (error) {+ scriptLoadPromise = null // Reset promise on error+ }+}++onMounted(() => {+ renderRecaptcha()+})++onBeforeUnmount(() => {+ // Clean up widget and reset state+ if (window.grecaptcha && widgetId !== null) {+ try {+ window.grecaptcha.reset(widgetId)+ } catch (e) {+ // Silently handle error+ }+ }++ cleanupRecaptcha()++ if (recaptchaContainer.value) {+ recaptchaContainer.value.innerHTML = ''+ }++ widgetId = null+})++// Expose reset method that properly reloads the captcha+defineExpose({+ reset: async () => {+ if (window.grecaptcha && widgetId !== null) {+ try {+ // Try simple reset first+ window.grecaptcha.reset(widgetId)+ } catch (e) {+ // If simple reset fails, do a full cleanup and reload+ cleanupRecaptcha()+ await renderRecaptcha()+ }+ } else {+ // If no widget exists, do a full reload+ cleanupRecaptcha()+ await renderRecaptcha()+ }+ }+})+</script>\ No newline at end of filediff --git a/client/components/open/forms/OpenForm.vue b/client/components/open/forms/OpenForm.vueindex 4589bb71f..30caa001a 100644--- a/client/components/open/forms/OpenForm.vue+++ b/client/components/open/forms/OpenForm.vue@@ -76,21 +76,16 @@</transition><!-- Captcha -->- <template v-if="form.use_captcha && isLastPage">- <div class="mb-3 px-2 mt-2 mx-auto w-max">- <vue-hcaptcha- ref="hcaptcha"- :sitekey="hCaptchaSiteKey"- :theme="darkMode?'dark':'light'"- @opened="setMinHeight(500)"- @closed="setMinHeight(0)"- />- <has-error- :form="dataForm"- field-id="h-captcha-response"- />- </div>- </template>+ <div class="mb-3 px-2 mt-4 mx-auto w-max">+ <CaptchaInput+ v-if="form.use_captcha && isLastPage"+ ref="captcha"+ :provider="form.captcha_provider"+ :form="dataForm"+ :language="form.language"+ :dark-mode="darkMode"+ />+ </div><!-- Submit, Next and previous buttons --><div class="flex flex-wrap justify-center w-full">@@ -132,7 +127,7 @@import clonedeep from 'clone-deep'import draggable from 'vuedraggable'import OpenFormButton from './OpenFormButton.vue'-import VueHcaptcha from "@hcaptcha/vue3-hcaptcha"+import CaptchaInput from '~/components/forms/components/CaptchaInput.vue'import OpenFormField from './OpenFormField.vue'import {pendingSubmission} from "~/composables/forms/pendingSubmission.js"import FormLogicPropertyResolver from "~/lib/forms/FormLogicPropertyResolver.js"@@ -143,7 +138,7 @@ import { storeToRefs } from 'pinia'export default {name: 'OpenForm',- components: {draggable, OpenFormField, OpenFormButton, VueHcaptcha, FormTimer},+ components: {draggable, OpenFormField, OpenFormButton, CaptchaInput, FormTimer},props: {form: {type: Object,@@ -206,14 +201,10 @@ export default {* Used to force refresh components by changing their keys*/isAutoSubmit: false,- minHeight: 0}},computed: {- hCaptchaSiteKey() {- return useRuntimeConfig().public.hCaptchaSiteKey- },/*** Create field groups (or Page) using page breaks if any*/@@ -309,7 +300,6 @@ export default {},computedStyle() {return {- ...this.minHeight ? {minHeight: this.minHeight + 'px'} : {},'--form-color': this.form.color}}@@ -369,8 +359,7 @@ export default {if (!this.isAutoSubmit && this.formPageIndex !== this.fieldGroups.length - 1) returnif (this.form.use_captcha && import.meta.client) {- this.dataForm['h-captcha-response'] = document.getElementsByName('h-captcha-response')[0].value- this.$refs.hcaptcha.reset()+ this.$refs.captcha?.reset()}if (this.form.editable_submissions && this.form.submission_id) {@@ -584,16 +573,6 @@ export default {}this.formPageIndex = this.fieldGroups.length - 1},- setMinHeight(minHeight) {- if (!this.isIframe) return-- this.minHeight = minHeight- try {- window.parentIFrame.size()- } catch (e) {- console.error(e)- }- }}}</script>diff --git a/client/components/open/forms/components/form-components/FormSecurityAccess.vue b/client/components/open/forms/components/form-components/FormSecurityAccess.vueindex 8be4b9f77..2a5edea3b 100644--- a/client/components/open/forms/components/form-components/FormSecurityAccess.vue+++ b/client/components/open/forms/components/form-components/FormSecurityAccess.vue@@ -72,29 +72,32 @@<p class="text-gray-500 text-sm">Protect your form, and your sensitive files.</p>- <ToggleSwitchInput- name="use_captcha"- :form="form"- class="mt-4"- label="Bot Protection"- help="Protects your form from spam and abuse with a captcha"- />+ <div class="flex items-start gap-6 flex-wrap">+ <ToggleSwitchInput+ name="use_captcha"+ :form="form"+ class="mt-4"+ label="Bot Protection"+ help="Protects your form from spam and abuse with a captcha"+ />+ <FlatSelectInput+ v-if="form.use_captcha"+ name="captcha_provider"+ :form="form"+ :options="captchaOptions"+ class="mt-4 w-80"+ label="Select a captcha provider"+ />+ </div></SettingsSection></template>-<script>-import { useWorkingFormStore } from '../../../../../stores/working_form'+<script setup>+const workingFormStore = useWorkingFormStore()+const { content: form } = storeToRefs(workingFormStore)-export default {- components: { },- props: {},- setup () {- const workingFormStore = useWorkingFormStore()- return {- workingFormStore,- form: storeToRefs(workingFormStore).content,- crisp: useCrisp()- }- }-}+const captchaOptions = [+ { name: 'reCAPTCHA', value: 'recaptcha' },+ { name: 'hCaptcha', value: 'hcaptcha' },+]</script>diff --git a/client/components/pages/auth/components/RegisterForm.vue b/client/components/pages/auth/components/RegisterForm.vueindex 01dd3538c..a50da576b 100644--- a/client/components/pages/auth/components/RegisterForm.vue+++ b/client/components/pages/auth/components/RegisterForm.vue@@ -52,18 +52,16 @@label="Confirm Password"/>- <!-- hCaptcha -->+ <!-- Captcha --><div- v-if="hCaptchaSiteKey"- class="mb-3 px-2 mt-2 mx-auto w-max"+ v-if="recaptchaSiteKey"+ class="my-4 px-2 mx-auto w-max">- <vue-hcaptcha- ref="hcaptcha"- :sitekey="hCaptchaSiteKey"- />- <has-error+ <CaptchaInput+ ref="captcha"+ provider="recaptcha":form="form"- field-id="h-captcha-response"+ language="en"/></div>@@ -141,11 +139,10 @@<script>import {opnFetch} from "~/composables/useOpnApi.js"import { fetchAllWorkspaces } from "~/stores/workspaces.js"-import VueHcaptcha from '@hcaptcha/vue3-hcaptcha'export default {name: "RegisterForm",- components: {VueHcaptcha},+ components: {},props: {isQuick: {type: Boolean,@@ -177,15 +174,14 @@ export default {agree_terms: false,appsumo_license: null,utm_data: null,- 'h-captcha-response': null+ 'g-recaptcha-response': null}),disableEmail: false,- hcaptcha: null}),computed: {- hCaptchaSiteKey() {- return this.runtimeConfig.public.hCaptchaSiteKey+ recaptchaSiteKey() {+ return this.runtimeConfig.public.recaptchaSiteKey},hearAboutUsOptions() {const options = [@@ -209,10 +205,6 @@ export default {},mounted() {- if (this.hCaptchaSiteKey) {- this.hcaptcha = this.$refs.hcaptcha- }-// Set appsumo licenseif (this.$route.query.appsumo_license !== undefined &&@@ -234,9 +226,9 @@ export default {async register() {let datathis.form.utm_data = this.$utm.value- if (this.hCaptchaSiteKey) {- this.form['h-captcha-response'] = document.getElementsByName('h-captcha-response')[0].value- this.hcaptcha.reset()+ // Reset captcha after submission+ if (import.meta.client && this.recaptchaSiteKey) {+ this.$refs.captcha.reset()}try {// Register the user.diff --git a/client/composables/forms/initForm.js b/client/composables/forms/initForm.jsindex 477268497..869c3a21d 100644--- a/client/composables/forms/initForm.js+++ b/client/composables/forms/initForm.js@@ -36,6 +36,7 @@ export const initForm = (defaultValue = {}, withDefaultProperties = false) => {submitted_text:"Amazing, we saved your answers. Thank you for your time and have a great day!",use_captcha: false,+ captcha_provider: 'recaptcha',max_submissions_count: null,max_submissions_reached_text:"This form has now reached the maximum number of allowed submissions and is now closed.",@@ -105,6 +106,7 @@ export function setFormDefaults(formData) {bypass_success_page: false,can_be_indexed: true,use_captcha: false,+ captcha_provider: 'recaptcha',properties: [],}diff --git a/client/package.json b/client/package.jsonindex 9f9d62433..d39bcef8b 100644--- a/client/package.json+++ b/client/package.json@@ -36,7 +36,6 @@},"dependencies": {"@codemirror/lang-html": "^6.4.9",- "@hcaptcha/vue3-hcaptcha": "^1.3.0","@iconify-json/material-symbols": "^1.2.4","@nuxt/ui": "^2.19.2","@pinia/nuxt": "^0.5.5",diff --git a/client/runtimeConfig.js b/client/runtimeConfig.jsindex 968a5f5f1..d094fb68e 100644--- a/client/runtimeConfig.js+++ b/client/runtimeConfig.js@@ -19,6 +19,7 @@ export default {appUrl: process.env.NUXT_PUBLIC_APP_URL || '',env: process.env.NUXT_PUBLIC_ENV || 'local',hCaptchaSiteKey: process.env.NUXT_PUBLIC_H_CAPTCHA_SITE_KEY || null,+ recaptchaSiteKey: process.env.NUXT_PUBLIC_RE_CAPTCHA_SITE_KEY || null,gtmCode: process.env.NUXT_PUBLIC_GTM_CODE || null,amplitudeCode: process.env.NUXT_PUBLIC_AMPLITUDE_CODE || null,crispWebsiteId: process.env.NUXT_PUBLIC_CRISP_WEBSITE_ID || null,