A platform for community discussion. Free, open, simple.
FEATURE: Add reCAPTCHA v3 captcha provider (#44211)
jbrwc237680d280a
diff --git a/db/structure.sql b/db/structure.sqlindex f377367db97..00a213e60b7 100644--- a/db/structure.sql+++ b/db/structure.sql@@ -25544,6 +25544,7 @@ ALTER TABLE ONLY public.ad_plugin_house_ads_groupsSET search_path TO "$user", public;INSERT INTO "schema_migrations" (version) VALUES+('20261001073226'),('20260930114733'),('20260928103925'),('20260925054715'),diff --git a/plugins/discourse-captcha/README.md b/plugins/discourse-captcha/README.mdindex 94489d450da..f9ba0efa775 100644--- a/plugins/discourse-captcha/README.md+++ b/plugins/discourse-captcha/README.md@@ -2,12 +2,13 @@## Overview-This plugin integrates captcha verification into the sign-up form of Discourse forums to enhance security and bot protection. The plugin supports two captcha providers:+This plugin integrates captcha verification into the sign-up form of Discourse forums to enhance security and bot protection. The plugin supports three captcha providers:- **hCaptcha**: Privacy-centric captcha service-- **reCaptcha**: Google's captcha service+- **reCaptcha v2**: Google's visible captcha widget+- **reCaptcha v3**: Google's invisible, score-based captcha-You can enable either provider based on your preference and requirements.+You can enable one provider based on your preference and requirements.## Installation@@ -23,7 +24,7 @@ You can enable either provider based on your preference and requirements.- Select `hcaptcha` in the `discourse_captcha_provider` setting.- Add the site key and secret key you obtained from hCaptcha.-### For reCaptcha+### For reCaptcha v2 or v31. **Create a reCaptcha Account**:- Visit [Google reCaptcha](https://www.google.com/recaptcha) to register your site. After registering, you'll receive a site key and a secret key.@@ -32,21 +33,9 @@ You can enable either provider based on your preference and requirements.- Log into your Discourse admin panel.- Navigate to `Admin` > `Settings` > `Plugins` > `Captcha Plugin`.- Enable the master toggle: `discourse_captcha_enabled`- - Select `recaptcha` in the `discourse_captcha_provider` setting.- - Add the site key and secret key you obtained from reCaptcha.+ - Select `recaptcha_v2` (v2) or `recaptcha_v3` in the `discourse_captcha_provider` setting.+ - Add the site key and secret key you obtained from reCaptcha. For v3 you can also adjust the minimum accepted score with `recaptcha_v3_score_threshold`.## Testing saved keys-Admins can open **Test** on the CAPTCHA plugin's admin page to test-the selected provider with the saved site key and secret key. Click **Test configuration**, then complete the challenge-to verify the keys with the provider. The test works with registration enforcement-disabled and does not create an account or authorize a registration.--The test runs on the current site's domain, which must be allowed by the provider.-reCAPTCHA keys must support the v2 checkbox challenge. The secret key stays on the-server. Provider errors, expired challenges, and connection failures are displayed-in the test section; a successful test confirms the configuration at that moment.--## Migration Notes--If you were using this plugin when it was named "discourse-hcaptcha", your existing settings have been automatically migrated.+The plugin must be enabled to test saved keys from the **Test** tab on its admin page.diff --git a/plugins/discourse-captcha/admin/assets/javascripts/discourse/components/captcha-configuration-test.gjs b/plugins/discourse-captcha/admin/assets/javascripts/discourse/components/captcha-configuration-test.gjsindex 7de257874d5..5496f4d4008 100644--- a/plugins/discourse-captcha/admin/assets/javascripts/discourse/components/captcha-configuration-test.gjs+++ b/plugins/discourse-captcha/admin/assets/javascripts/discourse/components/captcha-configuration-test.gjs@@ -5,12 +5,13 @@ import { action } from "@ember/object";import { service } from "@ember/service";import { ajax } from "discourse/lib/ajax";import { extractError } from "discourse/lib/ajax-error";-import { eq } from "discourse/truth-helpers";+import { eq, or } from "discourse/truth-helpers";import DButton from "discourse/ui-kit/d-button";import DPageSubheader from "discourse/ui-kit/d-page-subheader";import { i18n } from "discourse-i18n";import HCaptcha from "discourse/plugins/discourse-captcha/discourse/components/h-captcha";import ReCaptcha from "discourse/plugins/discourse-captcha/discourse/components/re-captcha";+import ReCaptchaV3 from "discourse/plugins/discourse-captcha/discourse/components/re-captcha-v3";export default class CaptchaConfigurationTest extends Component {@service a11y;@@ -105,13 +106,15 @@ export default class CaptchaConfigurationTest extends Component {</p>{{/if}}{{#if this.challengeVisible}}- {{#unless this.result}}+ {{#if+ (not (or this.result (eq @configuration.provider "recaptcha_v3")))+ }}<p>{{i18n"discourse_captcha.configuration_test.complete_challenge"}}</p>- {{/unless}}+ {{/if}}{{#each (array this.attempt) key="@identity"}}- {{#if (eq @configuration.provider "recaptcha")}}+ {{#if (eq @configuration.provider "recaptcha_v2")}}<ReCaptcha@errorMessage={{i18n"discourse_captcha.configuration_test.challenge_failed"@@ -120,6 +123,12 @@ export default class CaptchaConfigurationTest extends Component {@onResponse={{this.verify}}@siteKey={{@configuration.site_key}}/>+ {{else if (eq @configuration.provider "recaptcha_v3")}}+ <ReCaptchaV3+ @onError={{this.challengeFailed}}+ @onResponse={{this.verify}}+ @siteKey={{@configuration.site_key}}+ />{{else}}<HCaptcha@errorMessage={{i18ndiff --git a/plugins/discourse-captcha/app/controllers/discourse_captcha/recaptcha_controller.rb b/plugins/discourse-captcha/app/controllers/discourse_captcha/recaptcha_controller.rbindex 97f90bee719..aea40ea1c9c 100644--- a/plugins/discourse-captcha/app/controllers/discourse_captcha/recaptcha_controller.rb+++ b/plugins/discourse-captcha/app/controllers/discourse_captcha/recaptcha_controller.rb@@ -7,7 +7,7 @@ module DiscourseCaptchaprivatedef ensure_config- if SiteSetting.discourse_captcha_provider != CaptchaProvider::RECAPTCHA+ if SiteSetting.discourse_captcha_provider != CaptchaProvider::RECAPTCHA_V2raise Discourse::NotFoundendraise Discourse::InvalidParameters.new(:token) if params[:token].blank?diff --git a/plugins/discourse-captcha/app/controllers/discourse_captcha/recaptcha_v3_controller.rb b/plugins/discourse-captcha/app/controllers/discourse_captcha/recaptcha_v3_controller.rbnew file mode 100644index 00000000000..14e1535a555--- /dev/null+++ b/plugins/discourse-captcha/app/controllers/discourse_captcha/recaptcha_v3_controller.rb@@ -0,0 +1,20 @@+# frozen_string_literal: true++module DiscourseCaptcha+ class RecaptchaV3Controller < DiscourseCaptcha::CaptchaController+ requires_plugin PLUGIN_NAME++ private++ def ensure_config+ if SiteSetting.discourse_captcha_provider != CaptchaProvider::RECAPTCHA_V3+ raise Discourse::NotFound+ end+ raise Discourse::InvalidParameters.new(:token) if params[:token].blank?+ end++ def token_key+ "recaptcha_v3_token"+ end+ end+enddiff --git a/plugins/discourse-captcha/app/services/problem_check/recaptcha_configuration.rb b/plugins/discourse-captcha/app/services/problem_check/recaptcha_configuration.rbindex 47dc65093db..8162077bc0b 100644--- a/plugins/discourse-captcha/app/services/problem_check/recaptcha_configuration.rb+++ b/plugins/discourse-captcha/app/services/problem_check/recaptcha_configuration.rb@@ -5,8 +5,8 @@ class ProblemCheck::RecaptchaConfiguration < ProblemCheckdef callif SiteSetting.discourse_captcha_enabled &&- SiteSetting.discourse_captcha_provider == DiscourseCaptcha::CaptchaProvider::RECAPTCHA &&- !recaptcha_credentials_present?+ SiteSetting.discourse_captcha_provider ==+ DiscourseCaptcha::CaptchaProvider::RECAPTCHA_V2 && !recaptcha_credentials_present?return problemendno_problem@@ -15,6 +15,6 @@ class ProblemCheck::RecaptchaConfiguration < ProblemCheckprivatedef recaptcha_credentials_present?- SiteSetting.recaptcha_site_key.present? && SiteSetting.recaptcha_secret_key.present?+ SiteSetting.recaptcha_v2_site_key.present? && SiteSetting.recaptcha_v2_secret_key.present?endenddiff --git a/plugins/discourse-captcha/app/services/problem_check/recaptcha_v3_configuration.rb b/plugins/discourse-captcha/app/services/problem_check/recaptcha_v3_configuration.rbnew file mode 100644index 00000000000..f89a8c7d47f--- /dev/null+++ b/plugins/discourse-captcha/app/services/problem_check/recaptcha_v3_configuration.rb@@ -0,0 +1,20 @@+# frozen_string_literal: true++class ProblemCheck::RecaptchaV3Configuration < ProblemCheck+ self.priority = "high"++ def call+ if SiteSetting.discourse_captcha_enabled &&+ SiteSetting.discourse_captcha_provider ==+ DiscourseCaptcha::CaptchaProvider::RECAPTCHA_V3 && !recaptcha_v3_credentials_present?+ return problem+ end+ no_problem+ end++ private++ def recaptcha_v3_credentials_present?+ SiteSetting.recaptcha_v3_site_key.present? && SiteSetting.recaptcha_v3_secret_key.present?+ end+enddiff --git a/plugins/discourse-captcha/assets/javascripts/discourse/components/re-captcha-v3.gjs b/plugins/discourse-captcha/assets/javascripts/discourse/components/re-captcha-v3.gjsnew file mode 100644index 00000000000..68af3ee535b--- /dev/null+++ b/plugins/discourse-captcha/assets/javascripts/discourse/components/re-captcha-v3.gjs@@ -0,0 +1,104 @@+import { modifier as modifierFn } from "ember-modifier";+import DAsyncContent from "discourse/ui-kit/d-async-content";+import DInputTip from "discourse/ui-kit/d-input-tip";+import { i18n } from "discourse-i18n";+import BaseCaptcha from "./base-captcha";++export default class ReCaptchaV3 extends BaseCaptcha {+ registerCaptcha = modifierFn((_element, _args, { captchaApi }) => {+ let active = true;+ if (this.args.onResponse) {+ captchaApi.execute(this.siteKey, { action: "configuration_test" }).then(+ (token) => {+ if (active) {+ this.args.onResponse(token);+ }+ },+ () => {+ if (active) {+ this.args.onError?.();+ }+ }+ );+ return () => {+ active = false;+ };+ }++ const refresh = async () => {+ this.captchaService.token = null;+ this.captchaService.invalid = true;++ try {+ const token = await captchaApi.execute(this.siteKey, {+ action: "signup",+ });+ if (active) {+ this.captchaService.token = token || null;+ this.captchaService.invalid = !token;+ }+ } catch {+ // Leave verification invalid so the user can retry submission.+ }+ };++ this.captchaService.refreshToken = refresh;+ return () => {+ active = false;+ if (this.captchaService.refreshToken === refresh) {+ this.captchaService.refreshToken = null;+ this.captchaService.reset();+ }+ };+ });++ get scriptUrl() {+ return `https://www.google.com/recaptcha/api.js?onload=${this.callbackName}&render=${this.siteKey}`;+ }++ get callbackName() {+ return "discourseReCaptchaV3Callback";+ }++ get captchaApiName() {+ return "grecaptcha";+ }++ get providerName() {+ return "reCaptcha v3";+ }++ get containerId() {+ return "g-recaptcha-v3";+ }++ <template>+ <DAsyncContent @asyncData={{this.loadCaptchaScript}}>+ <:loading>+ <div class="captcha-container captcha-loading">+ {{i18n "loading"}}+ </div>+ </:loading>+ <:content as |captchaApi|>+ <div+ class="captcha-container re-captcha-v3"+ id={{this.containerId}}+ {{this.registerCaptcha captchaApi=captchaApi}}+ ></div>+ </:content>+ <:error>+ {{#unless @onError}}+ <div class="alert alert-error">+ {{i18n this.captchaErrorKey}}+ </div>+ {{/unless}}+ </:error>+ </DAsyncContent>++ {{#unless @onResponse}}+ {{#if this.captchaService.submitFailed}}+ <DInputTip @validation={{this.captchaService.inputValidation}} />+ {{/if}}+ {{/unless}}+ </template>+}diff --git a/plugins/discourse-captcha/assets/javascripts/discourse/connectors/code-login-after-code/captcha-fields-connector.gjs b/plugins/discourse-captcha/assets/javascripts/discourse/connectors/code-login-after-code/captcha-fields-connector.gjsindex ca62c62c504..f99b0f94be0 100644--- a/plugins/discourse-captcha/assets/javascripts/discourse/connectors/code-login-after-code/captcha-fields-connector.gjs+++ b/plugins/discourse-captcha/assets/javascripts/discourse/connectors/code-login-after-code/captcha-fields-connector.gjs@@ -3,6 +3,7 @@ import { service } from "@ember/service";import { eq } from "discourse/truth-helpers";import HCaptcha from "../../components/h-captcha";import ReCaptcha from "../../components/re-captcha";+import ReCaptchaV3 from "../../components/re-captcha-v3";export default class CaptchaFieldsConnector extends Component {@service siteSettings;@@ -13,9 +14,13 @@ export default class CaptchaFieldsConnector extends Component {{{#if (eq this.siteSettings.discourse_captcha_provider "hcaptcha")}}<HCaptcha @siteKey={{this.siteSettings.hcaptcha_site_key}} />{{else if- (eq this.siteSettings.discourse_captcha_provider "recaptcha")+ (eq this.siteSettings.discourse_captcha_provider "recaptcha_v2")}}- <ReCaptcha @siteKey={{this.siteSettings.recaptcha_site_key}} />+ <ReCaptcha @siteKey={{this.siteSettings.recaptcha_v2_site_key}} />+ {{else if+ (eq this.siteSettings.discourse_captcha_provider "recaptcha_v3")+ }}+ <ReCaptchaV3 @siteKey={{this.siteSettings.recaptcha_v3_site_key}} />{{/if}}</div></div>diff --git a/plugins/discourse-captcha/assets/javascripts/discourse/connectors/create-account-after-user-fields/captcha-fields-connector.gjs b/plugins/discourse-captcha/assets/javascripts/discourse/connectors/create-account-after-user-fields/captcha-fields-connector.gjsindex 521371ba8b5..87e2460b0a1 100644--- a/plugins/discourse-captcha/assets/javascripts/discourse/connectors/create-account-after-user-fields/captcha-fields-connector.gjs+++ b/plugins/discourse-captcha/assets/javascripts/discourse/connectors/create-account-after-user-fields/captcha-fields-connector.gjs@@ -5,6 +5,7 @@ import { tagName } from "@ember-decorators/component";import { eq } from "discourse/truth-helpers";import HCaptcha from "../../components/h-captcha";import ReCaptcha from "../../components/re-captcha";+import ReCaptchaV3 from "../../components/re-captcha-v3";@tagName("")export default class CaptchaFieldsConnector extends Component {@@ -19,9 +20,13 @@ export default class CaptchaFieldsConnector extends Component {{{#if (eq this.siteSettings.discourse_captcha_provider "hcaptcha")}}<HCaptcha @siteKey={{this.siteSettings.hcaptcha_site_key}} />{{else if- (eq this.siteSettings.discourse_captcha_provider "recaptcha")+ (eq this.siteSettings.discourse_captcha_provider "recaptcha_v2")}}- <ReCaptcha @siteKey={{this.siteSettings.recaptcha_site_key}} />+ <ReCaptcha @siteKey={{this.siteSettings.recaptcha_v2_site_key}} />+ {{else if+ (eq this.siteSettings.discourse_captcha_provider "recaptcha_v3")+ }}+ <ReCaptchaV3 @siteKey={{this.siteSettings.recaptcha_v3_site_key}} />{{/if}}</div></div>diff --git a/plugins/discourse-captcha/assets/javascripts/discourse/services/captcha-service.js b/plugins/discourse-captcha/assets/javascripts/discourse/services/captcha-service.jsindex d28c01f0335..251e8432ee5 100644--- a/plugins/discourse-captcha/assets/javascripts/discourse/services/captcha-service.js+++ b/plugins/discourse-captcha/assets/javascripts/discourse/services/captcha-service.js@@ -11,6 +11,7 @@ export default class CaptchaService extends Service {@tracked token = null;widgetId = null;captcha = null;+ refreshToken = null;get submitFailed() {return this.submitted && this.invalid;@@ -32,6 +33,6 @@ export default class CaptchaService extends Service {this.invalid = true;this.submitted = false;this.token = null;- this.captcha.reset(this.widgetId);+ this.captcha?.reset(this.widgetId);}}diff --git a/plugins/discourse-captcha/assets/javascripts/pre-initializers/h-captcha.js b/plugins/discourse-captcha/assets/javascripts/pre-initializers/h-captcha.jsindex 5f09c5977f1..d056d500228 100644--- a/plugins/discourse-captcha/assets/javascripts/pre-initializers/h-captcha.js+++ b/plugins/discourse-captcha/assets/javascripts/pre-initializers/h-captcha.js@@ -26,6 +26,10 @@ function initializeHCaptcha(api, container) {const captchaService = container.lookup("service:captcha-service");captchaService.submitted = true;+ if (captchaService.refreshToken) {+ await captchaService.refreshToken();+ }+if (captchaService.invalid) {return {success: false,diff --git a/plugins/discourse-captcha/config/locales/server.en.yml b/plugins/discourse-captcha/config/locales/server.en.ymlindex c58b53c3aab..4da86c36f5d 100644--- a/plugins/discourse-captcha/config/locales/server.en.yml+++ b/plugins/discourse-captcha/config/locales/server.en.yml@@ -1,6 +1,8 @@en:discourse_captcha:configuration_test:+ v3_success: "Your reCAPTCHA v3 keys work. This test scored %{score}, meeting the signup threshold of %{threshold}."+ v3_low_score: "Your reCAPTCHA v3 keys work, but this test scored %{score}, below the signup threshold of %{threshold}."success: "Verification succeeded. Your saved CAPTCHA keys work on this site."errors:not_configured: "Select a CAPTCHA provider and save both keys in Settings before testing."@@ -15,6 +17,7 @@ en:problem:hcaptcha_configuration: "There is a problem with your hCaptcha `site_key` or `secret_key` configuration"recaptcha_configuration: "There is a problem with your ReCaptcha `site_key` or `secret_key` configuration"+ recaptcha_v3_configuration: "There is a problem with your ReCaptcha v3 `site_key` or `secret_key` configuration"admin:site_settings:@@ -26,8 +29,11 @@ en:discourse_captcha_provider: "Choose a Captcha provider. This requires you to own an account of the chosen provider"hcaptcha_site_key: "hCaptcha Site Key from your <a target='blank' href='https://hcaptcha.com'>hcaptcha.com</a> account"hcaptcha_secret_key: "hCaptcha Secret Key from your <a target='blank' href='https://hcaptcha.com'>hcaptcha.com</a> account"- recaptcha_site_key: "ReCaptcha Site Key from your <a target='blank' href='https://www.google.com/recaptcha'>ReCaptcha</a> account"- recaptcha_secret_key: "ReCaptcha Secret Key from your <a target='blank' href='https://www.google.com/recaptcha'>ReCaptcha</a> account"+ recaptcha_v2_site_key: "ReCaptcha v2 Site Key from your <a target='blank' href='https://www.google.com/recaptcha'>ReCaptcha</a> account. Used only when the captcha provider is set to reCaptcha v2."+ recaptcha_v2_secret_key: "ReCaptcha v2 Secret Key from your <a target='blank' href='https://www.google.com/recaptcha'>ReCaptcha</a> account. Used only when the captcha provider is set to reCaptcha v2."+ recaptcha_v3_site_key: "ReCaptcha v3 Site Key from your <a target='blank' href='https://www.google.com/recaptcha'>ReCaptcha</a> account"+ recaptcha_v3_secret_key: "ReCaptcha v3 Secret Key from your <a target='blank' href='https://www.google.com/recaptcha'>ReCaptcha</a> account"+ recaptcha_v3_score_threshold: "The minimum score a reCaptcha v3 challenge must reach for a signup to be accepted. Lower values are more permissive, higher values provide stronger bot protection."captcha_verification_failed: "Captcha verification failed"captcha_not_configured: "Captcha is enabled but not properly configured. Please contact the site administrator."diff --git a/plugins/discourse-captcha/config/routes.rb b/plugins/discourse-captcha/config/routes.rbindex 4fc8d37fab4..fdbdb3983c1 100644--- a/plugins/discourse-captcha/config/routes.rb+++ b/plugins/discourse-captcha/config/routes.rb@@ -12,4 +12,6 @@ endDiscourseCaptcha::Engine.routes.draw dopost "/hcaptcha/create", to: "hcaptcha#create"post "/recaptcha/create", to: "recaptcha#create"+ post "/recaptcha_v2/create", to: "recaptcha#create"+ post "/recaptcha_v3/create", to: "recaptcha_v3#create"enddiff --git a/plugins/discourse-captcha/config/settings.yml b/plugins/discourse-captcha/config/settings.ymlindex fd641aada45..c54d96b4e29 100644--- a/plugins/discourse-captcha/config/settings.yml+++ b/plugins/discourse-captcha/config/settings.yml@@ -8,7 +8,8 @@ discourse_captcha:type: enumchoices:- hcaptcha- - recaptcha+ - recaptcha_v2+ - recaptcha_v3- nonehcaptcha_site_key:default: ''@@ -17,10 +18,23 @@ discourse_captcha:default: ''client: falsesecret: true- recaptcha_site_key:+ recaptcha_v2_site_key:default: ''client: true- recaptcha_secret_key:+ recaptcha_v2_secret_key:default: ''client: falsesecret: true+ recaptcha_v3_site_key:+ default: ''+ client: true+ recaptcha_v3_secret_key:+ default: ''+ client: false+ secret: true+ recaptcha_v3_score_threshold:+ default: 0.5+ type: float+ min: 0.0+ max: 1.0+ client: falsediff --git a/plugins/discourse-captcha/db/migrate/20261001073226_rename_recaptcha_v2_settings.rb b/plugins/discourse-captcha/db/migrate/20261001073226_rename_recaptcha_v2_settings.rbnew file mode 100644index 00000000000..666d6aef598--- /dev/null+++ b/plugins/discourse-captcha/db/migrate/20261001073226_rename_recaptcha_v2_settings.rb@@ -0,0 +1,27 @@+# frozen_string_literal: true++class RenameRecaptchaV2Settings < ActiveRecord::Migration[8.1]+ def up+ execute <<~SQL+ UPDATE site_settings+ SET value = 'recaptcha_v2'+ WHERE name = 'discourse_captcha_provider' AND value = 'recaptcha'+ SQL++ execute <<~SQL+ UPDATE site_settings+ SET name = 'recaptcha_v2_site_key'+ WHERE name = 'recaptcha_site_key'+ SQL++ execute <<~SQL+ UPDATE site_settings+ SET name = 'recaptcha_v2_secret_key'+ WHERE name = 'recaptcha_secret_key'+ SQL+ end++ def down+ raise ActiveRecord::IrreversibleMigration+ end+enddiff --git a/plugins/discourse-captcha/lib/discourse_captcha/captcha_provider.rb b/plugins/discourse-captcha/lib/discourse_captcha/captcha_provider.rbindex 94a85f4c074..64d7cdfbb3a 100644--- a/plugins/discourse-captcha/lib/discourse_captcha/captcha_provider.rb+++ b/plugins/discourse-captcha/lib/discourse_captcha/captcha_provider.rb@@ -3,7 +3,8 @@module DiscourseCaptchaclass CaptchaProviderHCAPTCHA = "hcaptcha"- RECAPTCHA = "recaptcha"+ RECAPTCHA_V2 = "recaptcha_v2"+ RECAPTCHA_V3 = "recaptcha_v3"NONE = "none"def fetch_captcha_token(server_session)@@ -18,6 +19,17 @@ module DiscourseCaptcharaise NotImplementedErrorend+ def validate_captcha_response(response)+ raise Discourse::InvalidAccess if response.code.to_i >= 500++ response_json = JSON.parse(response.body)+ if response_json["success"].nil? || response_json["success"] == false+ raise Discourse::InvalidAccess+ end++ response_json+ end+protecteddef send_verification(captcha_token, captcha_verification_url, secret_key)diff --git a/plugins/discourse-captcha/lib/discourse_captcha/captcha_verification.rb b/plugins/discourse-captcha/lib/discourse_captcha/captcha_verification.rbindex 2d4e7d8a32c..9c8dbfcbc16 100644--- a/plugins/discourse-captcha/lib/discourse_captcha/captcha_verification.rb+++ b/plugins/discourse-captcha/lib/discourse_captcha/captcha_verification.rb@@ -14,7 +14,9 @@ module DiscourseCaptchacaptcha_token = captcha_provider.fetch_captcha_token(server_session)return :captcha_verification_failed if captcha_token.blank?- validate_captcha_response(captcha_provider.send_captcha_verification(captcha_token))+ captcha_provider.validate_captcha_response(+ captcha_provider.send_captcha_verification(captcha_token),+ )nilrescue StandardError => eRails.logger.warn("Captcha verification error: #{e.class} - #{e.message}")@@ -27,19 +29,16 @@ module DiscourseCaptchaif SiteSetting.hcaptcha_site_key.present? && SiteSetting.hcaptcha_secret_key.present?DiscourseCaptcha::HcaptchaProvider.newend- when CaptchaProvider::RECAPTCHA- if SiteSetting.recaptcha_site_key.present? && SiteSetting.recaptcha_secret_key.present?+ when CaptchaProvider::RECAPTCHA_V2+ if SiteSetting.recaptcha_v2_site_key.present? &&+ SiteSetting.recaptcha_v2_secret_key.present?DiscourseCaptcha::RecaptchaProvider.newend- end- end-- def validate_captcha_response(response)- raise Discourse::InvalidAccess if response.code.to_i >= 500-- response_json = JSON.parse(response.body)- if response_json["success"].nil? || response_json["success"] == false- raise Discourse::InvalidAccess+ when CaptchaProvider::RECAPTCHA_V3+ if SiteSetting.recaptcha_v3_site_key.present? &&+ SiteSetting.recaptcha_v3_secret_key.present?+ DiscourseCaptcha::RecaptchaV3Provider.new+ endendendenddiff --git a/plugins/discourse-captcha/lib/discourse_captcha/configuration_test.rb b/plugins/discourse-captcha/lib/discourse_captcha/configuration_test.rbindex 5065baf2b1f..3c2e1bff437 100644--- a/plugins/discourse-captcha/lib/discourse_captcha/configuration_test.rb+++ b/plugins/discourse-captcha/lib/discourse_captcha/configuration_test.rb@@ -17,14 +17,18 @@ module DiscourseCaptchadef initialize@provider = SiteSetting.discourse_captcha_providercase @provider- when CaptchaProvider::RECAPTCHA- @site_key = SiteSetting.recaptcha_site_key- @secret_key = SiteSetting.recaptcha_secret_key+ when CaptchaProvider::RECAPTCHA_V2+ @site_key = SiteSetting.recaptcha_v2_site_key+ @secret_key = SiteSetting.recaptcha_v2_secret_key@captcha_provider = RecaptchaProvider.newwhen CaptchaProvider::HCAPTCHA@site_key = SiteSetting.hcaptcha_site_key@secret_key = SiteSetting.hcaptcha_secret_key@captcha_provider = HcaptchaProvider.new+ when CaptchaProvider::RECAPTCHA_V3+ @site_key = SiteSetting.recaptcha_v3_site_key+ @secret_key = SiteSetting.recaptcha_v3_secret_key+ @captcha_provider = RecaptchaV3Provider.newendend@@ -46,6 +50,8 @@ module DiscourseCaptchareturn failure("invalid_response") if !result.is_a?(Hash)if result["success"] == true+ return verify_v3(response) if @provider == CaptchaProvider::RECAPTCHA_V3+{ success: true, message: I18n.t("discourse_captcha.configuration_test.success") }elseerror = Array(result["error-codes"]).filter_map { |code| ERROR_MESSAGES[code] }.first@@ -59,6 +65,32 @@ module DiscourseCaptchaprivate+ def verify_v3(response)+ result =+ @captcha_provider.validate_captcha_response(+ response,+ action: "configuration_test",+ score_threshold: 0,+ )+ score = result["score"]+ threshold = SiteSetting.recaptcha_v3_score_threshold+ meets_threshold = score >= threshold+ message_key = meets_threshold ? "v3_success" : "v3_low_score"+ {+ success: true,+ score: score,+ meets_threshold: meets_threshold,+ message:+ I18n.t(+ "discourse_captcha.configuration_test.#{message_key}",+ score: score,+ threshold: threshold,+ ),+ }+ rescue Discourse::InvalidAccess+ failure("invalid_response")+ end+def failure(error){ success: false, message: I18n.t("discourse_captcha.configuration_test.errors.#{error}") }enddiff --git a/plugins/discourse-captcha/lib/discourse_captcha/recaptcha_provider.rb b/plugins/discourse-captcha/lib/discourse_captcha/recaptcha_provider.rbindex a7896a160bd..e7611b71996 100644--- a/plugins/discourse-captcha/lib/discourse_captcha/recaptcha_provider.rb+++ b/plugins/discourse-captcha/lib/discourse_captcha/recaptcha_provider.rb@@ -15,7 +15,11 @@ module DiscourseCaptchaenddef send_captcha_verification(captcha_token)- send_verification(captcha_token, CAPTCHA_VERIFICATION_URL, SiteSetting.recaptcha_secret_key)+ send_verification(+ captcha_token,+ CAPTCHA_VERIFICATION_URL,+ SiteSetting.recaptcha_v2_secret_key,+ )endendenddiff --git a/plugins/discourse-captcha/lib/discourse_captcha/recaptcha_v3_provider.rb b/plugins/discourse-captcha/lib/discourse_captcha/recaptcha_v3_provider.rbnew file mode 100644index 00000000000..afae91fb70b--- /dev/null+++ b/plugins/discourse-captcha/lib/discourse_captcha/recaptcha_v3_provider.rb@@ -0,0 +1,36 @@+# frozen_string_literal: true++module DiscourseCaptcha+ class RecaptchaV3Provider < RecaptchaProvider+ CAPTCHA_VERIFICATION_URL = "https://www.google.com/recaptcha/api/siteverify"+ CAPTCHA_ACTION = "signup"++ def fetch_captcha_token(server_session)+ token = server_session["recaptcha_v3_token"]+ server_session.delete("recaptcha_v3_token")+ token+ end++ def send_captcha_verification(captcha_token)+ send_verification(+ captcha_token,+ CAPTCHA_VERIFICATION_URL,+ SiteSetting.recaptcha_v3_secret_key,+ )+ end++ def validate_captcha_response(+ response,+ action: CAPTCHA_ACTION,+ score_threshold: SiteSetting.recaptcha_v3_score_threshold+ )+ response_json = super(response)+ raise Discourse::InvalidAccess if response_json["action"] != action++ score = response_json["score"]+ raise Discourse::InvalidAccess if !score.is_a?(Numeric) || score < score_threshold++ response_json+ end+ end+enddiff --git a/plugins/discourse-captcha/plugin.rb b/plugins/discourse-captcha/plugin.rbindex 5bd70ba4a1c..4e6c8e43433 100644--- a/plugins/discourse-captcha/plugin.rb+++ b/plugins/discourse-captcha/plugin.rb@@ -23,6 +23,9 @@ require_relative "lib/discourse_captcha/captcha_provider"require_relative "lib/discourse_captcha/captcha_verification"require_relative "lib/discourse_captcha/create_users_controller_patch"require_relative "lib/discourse_captcha/session_controller_patch"+require_relative "lib/discourse_captcha/hcaptcha_provider"+require_relative "lib/discourse_captcha/recaptcha_provider"+require_relative "lib/discourse_captcha/recaptcha_v3_provider"after_initialize doadd_admin_route("discourse_captcha.title", "discourse-captcha", use_new_show_route: true)@@ -32,6 +35,8 @@ after_initialize dorequire_relative "app/services/problem_check/hcaptcha_configuration"require_relative "app/services/problem_check/recaptcha_configuration"+ require_relative "app/services/problem_check/recaptcha_v3_configuration"register_problem_check ProblemCheck::HcaptchaConfigurationregister_problem_check ProblemCheck::RecaptchaConfiguration+ register_problem_check ProblemCheck::RecaptchaV3Configurationenddiff --git a/plugins/discourse-captcha/spec/lib/discourse_captcha/create_users_controller_patch_spec.rb b/plugins/discourse-captcha/spec/lib/discourse_captcha/create_users_controller_patch_spec.rbindex 4d1c2842c05..f505ecc2797 100644--- a/plugins/discourse-captcha/spec/lib/discourse_captcha/create_users_controller_patch_spec.rb+++ b/plugins/discourse-captcha/spec/lib/discourse_captcha/create_users_controller_patch_spec.rb@@ -22,8 +22,11 @@ RSpec.describe "Users", type: :request doSiteSetting.hcaptcha_site_key = "site-key"SiteSetting.hcaptcha_secret_key = "secret-key"- SiteSetting.recaptcha_site_key = "site-key"- SiteSetting.recaptcha_secret_key = "secret-key"+ SiteSetting.recaptcha_v2_site_key = "site-key"+ SiteSetting.recaptcha_v2_secret_key = "secret-key"++ SiteSetting.recaptcha_v3_site_key = "site-key"+ SiteSetting.recaptcha_v3_secret_key = "secret-key"stub_request(:post, DiscourseCaptcha::HcaptchaProvider::CAPTCHA_VERIFICATION_URL).with(body: {@@ -54,18 +57,37 @@ RSpec.describe "Users", type: :request docontext "when using reCaptcha" dobefore do- SiteSetting.discourse_captcha_provider = DiscourseCaptcha::CaptchaProvider::RECAPTCHA+ SiteSetting.discourse_captcha_provider = DiscourseCaptcha::CaptchaProvider::RECAPTCHA_V2stub_request(:post, DiscourseCaptcha::RecaptchaProvider::CAPTCHA_VERIFICATION_URL).with(body: {- secret: SiteSetting.recaptcha_secret_key,+ secret: SiteSetting.recaptcha_v2_secret_key,response: "token-from-reCaptcha",},).to_return(status: 200, body: '{"success":false}', headers: {})endit "fails registration" do- post "/captcha/recaptcha/create.json", params: { token: "token-from-reCaptcha" }+ post "/captcha/recaptcha_v2/create.json", params: { token: "token-from-reCaptcha" }+ post "/u.json", params: user_params+ expect(JSON.parse(response.body)["success"]).to be(false)+ end+ end++ context "when using reCaptcha v3" do+ before do+ SiteSetting.discourse_captcha_provider = DiscourseCaptcha::CaptchaProvider::RECAPTCHA_V3++ stub_request(:post, DiscourseCaptcha::RecaptchaV3Provider::CAPTCHA_VERIFICATION_URL).with(+ body: {+ secret: SiteSetting.recaptcha_v3_secret_key,+ response: "token-from-reCaptchaV3",+ },+ ).to_return(status: 200, body: '{"success":false}', headers: {})+ end++ it "fails registration" do+ post "/captcha/recaptcha_v3/create.json", params: { token: "token-from-reCaptchaV3" }post "/u.json", params: user_paramsexpect(JSON.parse(response.body)["success"]).to be(false)end@@ -86,7 +108,18 @@ RSpec.describe "Users", type: :request docontext "when using reCaptcha" dobefore do- SiteSetting.discourse_captcha_provider = DiscourseCaptcha::CaptchaProvider::RECAPTCHA+ SiteSetting.discourse_captcha_provider = DiscourseCaptcha::CaptchaProvider::RECAPTCHA_V2+ end++ it "fails registration" do+ post "/u.json", params: user_params+ expect(JSON.parse(response.body)["success"]).to be(false)+ end+ end++ context "when using reCaptcha v3" do+ before do+ SiteSetting.discourse_captcha_provider = DiscourseCaptcha::CaptchaProvider::RECAPTCHA_V3endit "fails registration" do@@ -119,18 +152,43 @@ RSpec.describe "Users", type: :request docontext "when using reCaptcha" dobefore do- SiteSetting.discourse_captcha_provider = DiscourseCaptcha::CaptchaProvider::RECAPTCHA+ SiteSetting.discourse_captcha_provider = DiscourseCaptcha::CaptchaProvider::RECAPTCHA_V2stub_request(:post, DiscourseCaptcha::RecaptchaProvider::CAPTCHA_VERIFICATION_URL).with(body: {"response" => "token-from-reCaptcha",- "secret" => SiteSetting.recaptcha_secret_key,+ "secret" => SiteSetting.recaptcha_v2_secret_key,},).to_return(status: 200, body: '{"success":true}', headers: {})endit "succeeds in registration" do- post "/captcha/recaptcha/create.json", params: { token: "token-from-reCaptcha" }+ post "/captcha/recaptcha_v2/create.json", params: { token: "token-from-reCaptcha" }+ post "/u.json", params: user_params++ expect(JSON.parse(response.body)["success"]).to be(true)+ end+ end++ context "when using reCaptcha v3" do+ before do+ SiteSetting.discourse_captcha_provider = DiscourseCaptcha::CaptchaProvider::RECAPTCHA_V3++ stub_request(:post, DiscourseCaptcha::RecaptchaV3Provider::CAPTCHA_VERIFICATION_URL).with(+ body: {+ "response" => "token-from-reCaptchaV3",+ "secret" => SiteSetting.recaptcha_v3_secret_key,+ },+ ).to_return(+ status: 200,+ body: '{"success":true,"score":0.9,"action":"signup"}',+ headers: {+ },+ )+ end++ it "succeeds in registration" do+ post "/captcha/recaptcha_v3/create.json", params: { token: "token-from-reCaptchaV3" }post "/u.json", params: user_paramsexpect(JSON.parse(response.body)["success"]).to be(true)@@ -187,9 +245,23 @@ RSpec.describe "Users", type: :request docontext "when reCaptcha is selected but keys are missing" dobefore do- SiteSetting.discourse_captcha_provider = DiscourseCaptcha::CaptchaProvider::RECAPTCHA- SiteSetting.recaptcha_site_key = ""- SiteSetting.recaptcha_secret_key = ""+ SiteSetting.discourse_captcha_provider = DiscourseCaptcha::CaptchaProvider::RECAPTCHA_V2+ SiteSetting.recaptcha_v2_site_key = ""+ SiteSetting.recaptcha_v2_secret_key = ""+ end++ it "blocks registration" do+ post "/u.json", params: user_params+ expect(JSON.parse(response.body)["success"]).to be(false)+ expect(JSON.parse(response.body)["message"]).to include("not properly configured")+ end+ end++ context "when reCaptcha v3 is selected but keys are missing" do+ before do+ SiteSetting.discourse_captcha_provider = DiscourseCaptcha::CaptchaProvider::RECAPTCHA_V3+ SiteSetting.recaptcha_v3_site_key = ""+ SiteSetting.recaptcha_v3_secret_key = ""endit "blocks registration" do@@ -222,18 +294,18 @@ RSpec.describe "Users", type: :request docontext "when using reCaptcha" dobefore do- SiteSetting.discourse_captcha_provider = DiscourseCaptcha::CaptchaProvider::RECAPTCHA+ SiteSetting.discourse_captcha_provider = DiscourseCaptcha::CaptchaProvider::RECAPTCHA_V2stub_request(:post, DiscourseCaptcha::RecaptchaProvider::CAPTCHA_VERIFICATION_URL).with(body: {- secret: SiteSetting.recaptcha_secret_key,+ secret: SiteSetting.recaptcha_v2_secret_key,response: "token-from-reCaptcha",},).to_return(status: 503, body: "Service Unavailable")endit "fails registration" do- post "/captcha/recaptcha/create.json", params: { token: "token-from-reCaptcha" }+ post "/captcha/recaptcha_v2/create.json", params: { token: "token-from-reCaptcha" }post "/u.json", params: user_paramsexpect(JSON.parse(response.body)["success"]).to be(false)end@@ -262,18 +334,18 @@ RSpec.describe "Users", type: :request docontext "when using reCaptcha" dobefore do- SiteSetting.discourse_captcha_provider = DiscourseCaptcha::CaptchaProvider::RECAPTCHA+ SiteSetting.discourse_captcha_provider = DiscourseCaptcha::CaptchaProvider::RECAPTCHA_V2stub_request(:post, DiscourseCaptcha::RecaptchaProvider::CAPTCHA_VERIFICATION_URL).with(body: {- secret: SiteSetting.recaptcha_secret_key,+ secret: SiteSetting.recaptcha_v2_secret_key,response: "token-from-reCaptcha",},).to_return(status: 200, body: "not valid json")endit "fails registration" do- post "/captcha/recaptcha/create.json", params: { token: "token-from-reCaptcha" }+ post "/captcha/recaptcha_v2/create.json", params: { token: "token-from-reCaptcha" }post "/u.json", params: user_paramsexpect(JSON.parse(response.body)["success"]).to be(false)enddiff --git a/plugins/discourse-captcha/spec/lib/discourse_captcha/recaptcha_provider_spec.rb b/plugins/discourse-captcha/spec/lib/discourse_captcha/recaptcha_provider_spec.rbindex 4c1cdcbe2bc..16ca53b47eb 100644--- a/plugins/discourse-captcha/spec/lib/discourse_captcha/recaptcha_provider_spec.rb+++ b/plugins/discourse-captcha/spec/lib/discourse_captcha/recaptcha_provider_spec.rb@@ -43,10 +43,10 @@ RSpec.describe DiscourseCaptcha::RecaptchaProvider dobefore doSiteSetting.enable_local_logins = trueSiteSetting.discourse_captcha_enabled = true- SiteSetting.discourse_captcha_provider = DiscourseCaptcha::CaptchaProvider::RECAPTCHA+ SiteSetting.discourse_captcha_provider = DiscourseCaptcha::CaptchaProvider::RECAPTCHA_V2- SiteSetting.recaptcha_site_key = "site-key"- SiteSetting.recaptcha_secret_key = "secret-key"+ SiteSetting.recaptcha_v2_site_key = "site-key"+ SiteSetting.recaptcha_v2_secret_key = "secret-key"endit "returns the response from reCAPTCHA" dodiff --git a/plugins/discourse-captcha/spec/lib/discourse_captcha/recaptcha_v3_provider_spec.rb b/plugins/discourse-captcha/spec/lib/discourse_captcha/recaptcha_v3_provider_spec.rbnew file mode 100644index 00000000000..aeb3355f3db--- /dev/null+++ b/plugins/discourse-captcha/spec/lib/discourse_captcha/recaptcha_v3_provider_spec.rb@@ -0,0 +1,130 @@+# frozen_string_literal: true++RSpec.describe DiscourseCaptcha::RecaptchaV3Provider do+ subject(:provider) { described_class.new }++ let(:captcha_response) { Struct.new(:code, :body) }++ before do+ SiteSetting.discourse_captcha_enabled = true+ SiteSetting.discourse_captcha_provider = DiscourseCaptcha::CaptchaProvider::RECAPTCHA_V3+ SiteSetting.recaptcha_v3_site_key = "site-key"+ SiteSetting.recaptcha_v3_secret_key = "secret-key"+ SiteSetting.recaptcha_v3_score_threshold = 0.5+ end++ describe "#captcha_verification_url" do+ it "returns the reCAPTCHA verification URL" do+ expect(provider.captcha_verification_url).to eq(+ "https://www.google.com/recaptcha/api/siteverify",+ )+ end+ end++ describe "#fetch_captcha_token" do+ let(:token) { "test-recaptcha-v3-token" }+ let(:server_session) { ServerSession.new(SecureRandom.hex) }++ before { server_session["recaptcha_v3_token"] = token }++ it "retrieves token from server session" do+ expect(provider.fetch_captcha_token(server_session)).to eq(token)+ end++ it "deletes the token from server session after fetching" do+ provider.fetch_captcha_token(server_session)+ expect(server_session["recaptcha_v3_token"]).to be_nil+ end++ context "when no token is present" do+ let(:empty_session) { ServerSession.new(SecureRandom.hex) }++ it "returns nil" do+ expect(provider.fetch_captcha_token(empty_session)).to be_nil+ end+ end+ end++ describe "#send_captcha_verification" do+ let(:token) { "test-recaptcha-v3-token" }++ it "returns the response from reCAPTCHA" do+ stub =+ stub_request(+ :post,+ DiscourseCaptcha::RecaptchaV3Provider::CAPTCHA_VERIFICATION_URL,+ ).to_return(status: 200, body: '{"success":true,"score":0.9,"action":"signup"}')++ response = provider.send_captcha_verification(token)++ expect(stub).to have_been_requested+ expect(response.code.to_i).to eq(200)+ expect(JSON.parse(response.body)["success"]).to be(true)+ end+ end++ describe "#validate_captcha_response" do+ it "accepts a response meeting the score threshold and action" do+ response = captcha_response.new(200, '{"success":true,"score":0.9,"action":"signup"}')++ expect { provider.validate_captcha_response(response) }.not_to raise_error+ end++ it "rejects a response without an action" do+ response = captcha_response.new(200, '{"success":true,"score":0.9}')++ expect { provider.validate_captcha_response(response) }.to raise_error(+ Discourse::InvalidAccess,+ )+ end++ it "rejects a response without a score" do+ response = captcha_response.new(200, '{"success":true,"action":"signup"}')++ expect { provider.validate_captcha_response(response) }.to raise_error(+ Discourse::InvalidAccess,+ )+ end++ it "rejects a nonnumeric score even when the threshold is zero" do+ SiteSetting.recaptcha_v3_score_threshold = 0+ response = captcha_response.new(200, '{"success":true,"score":"invalid","action":"signup"}')++ expect { provider.validate_captcha_response(response) }.to raise_error(+ Discourse::InvalidAccess,+ )+ end++ it "rejects a response whose score is below the threshold" do+ response = captcha_response.new(200, '{"success":true,"score":0.2,"action":"signup"}')++ expect { provider.validate_captcha_response(response) }.to raise_error(+ Discourse::InvalidAccess,+ )+ end++ it "rejects a response with a mismatched action" do+ response = captcha_response.new(200, '{"success":true,"score":0.9,"action":"login"}')++ expect { provider.validate_captcha_response(response) }.to raise_error(+ Discourse::InvalidAccess,+ )+ end++ it "rejects an unsuccessful response" do+ response = captcha_response.new(200, '{"success":false}')++ expect { provider.validate_captcha_response(response) }.to raise_error(+ Discourse::InvalidAccess,+ )+ end++ it "rejects a response returning a server error" do+ response = captcha_response.new(503, "Service Unavailable")++ expect { provider.validate_captcha_response(response) }.to raise_error(+ Discourse::InvalidAccess,+ )+ end+ end+enddiff --git a/plugins/discourse-captcha/spec/requests/discourse_captcha/admin_captcha_controller_spec.rb b/plugins/discourse-captcha/spec/requests/discourse_captcha/admin_captcha_controller_spec.rbindex f70593acfff..9b8a8307bfb 100644--- a/plugins/discourse-captcha/spec/requests/discourse_captcha/admin_captcha_controller_spec.rb+++ b/plugins/discourse-captcha/spec/requests/discourse_captcha/admin_captcha_controller_spec.rb@@ -6,9 +6,9 @@ RSpec.describe DiscourseCaptcha::AdminCaptchaController dofab!(:user)before do- SiteSetting.discourse_captcha_provider = "recaptcha"- SiteSetting.recaptcha_site_key = "test-site-key"- SiteSetting.recaptcha_secret_key = "test-secret-key"+ SiteSetting.discourse_captcha_provider = "recaptcha_v2"+ SiteSetting.recaptcha_v2_site_key = "test-site-key"+ SiteSetting.recaptcha_v2_secret_key = "test-secret-key"enddescribe "#show" do@@ -20,11 +20,11 @@ RSpec.describe DiscourseCaptcha::AdminCaptchaController doexpect(response.status).to eq(200)expect(response.parsed_body).to eq(- "provider" => "recaptcha",- "site_key" => SiteSetting.recaptcha_site_key,+ "provider" => "recaptcha_v2",+ "site_key" => SiteSetting.recaptcha_v2_site_key,"configured" => true,)- expect(response.body).not_to include(SiteSetting.recaptcha_secret_key)+ expect(response.body).not_to include(SiteSetting.recaptcha_v2_secret_key)endit "supports directly loading the test page" do@@ -37,7 +37,7 @@ RSpec.describe DiscourseCaptcha::AdminCaptchaController doit "identifies missing credentials" dosign_in(admin)- SiteSetting.recaptcha_secret_key = ""+ SiteSetting.recaptcha_v2_secret_key = ""get "/admin/plugins/discourse-captcha/test.json"@@ -56,8 +56,72 @@ RSpec.describe DiscourseCaptcha::AdminCaptchaController doendend+ describe "reCAPTCHA v3 configuration" do+ before do+ sign_in(admin)+ SiteSetting.discourse_captcha_provider = "recaptcha_v3"+ SiteSetting.recaptcha_v3_site_key = "v3-site-key"+ SiteSetting.recaptcha_v3_secret_key = "v3-secret-key"+ SiteSetting.recaptcha_v3_score_threshold = 0.5+ end++ it "recognizes the saved v3 configuration" do+ get "/admin/plugins/discourse-captcha/test.json"++ expect(response.parsed_body).to eq(+ "provider" => "recaptcha_v3",+ "site_key" => "v3-site-key",+ "configured" => true,+ )+ end++ it "reports the score separately from whether the keys work" do+ [0.9, 0.1].each do |score|+ stub_request(:post, "https://www.google.com/recaptcha/api/siteverify").with(+ body: {+ secret: "v3-secret-key",+ response: "test-token",+ },+ ).to_return(+ status: 200,+ body: { success: true, score: score, action: "configuration_test" }.to_json,+ )++ post "/admin/plugins/discourse-captcha/test.json",+ params: {+ provider: "recaptcha_v3",+ site_key: "v3-site-key",+ token: "test-token",+ }++ expect(response.parsed_body["success"]).to eq(true)+ expect(response.parsed_body["score"]).to eq(score)+ expect(response.parsed_body["meets_threshold"]).to eq(score >= 0.5)+ expect(server_session["recaptcha_v3_token"]).to be_nil+ end+ end++ it "rejects a response with the signup action" do+ stub_request(:post, "https://www.google.com/recaptcha/api/siteverify").to_return(+ status: 200,+ body: { success: true, score: 0.9, action: "signup" }.to_json,+ )++ post "/admin/plugins/discourse-captcha/test.json",+ params: {+ provider: "recaptcha_v3",+ site_key: "v3-site-key",+ token: "test-token",+ }++ expect(response.parsed_body["message"]).to eq(+ I18n.t("discourse_captcha.configuration_test.errors.invalid_response"),+ )+ end+ end+describe "#verify" do- let(:params) { { token: "test-token", provider: "recaptcha", site_key: "test-site-key" } }+ let(:params) { { token: "test-token", provider: "recaptcha_v2", site_key: "test-site-key" } }let(:verification_url) { "https://www.google.com/recaptcha/api/siteverify" }it "verifies the saved keys without creating an account or storing a signup token" do@@ -111,7 +175,7 @@ RSpec.describe DiscourseCaptcha::AdminCaptchaController do"success" => false,"message" => I18n.t("discourse_captcha.configuration_test.errors.invalid_secret"),)- expect(response.body).not_to include(SiteSetting.recaptcha_secret_key)+ expect(response.body).not_to include(SiteSetting.recaptcha_v2_secret_key)endit "handles expired challenges" do@@ -169,7 +233,7 @@ RSpec.describe DiscourseCaptcha::AdminCaptchaController doit "reports missing credentials and no selected provider" dosign_in(admin)- SiteSetting.recaptcha_secret_key = ""+ SiteSetting.recaptcha_v2_secret_key = ""post "/admin/plugins/discourse-captcha/test.json", params: paramsexpect(response.parsed_body["success"]).to eq(false)diff --git a/plugins/discourse-captcha/spec/requests/discourse_captcha/hcaptcha_controller_spec.rb b/plugins/discourse-captcha/spec/requests/discourse_captcha/hcaptcha_controller_spec.rbindex 717007e4009..b8cd522f5f2 100644--- a/plugins/discourse-captcha/spec/requests/discourse_captcha/hcaptcha_controller_spec.rb+++ b/plugins/discourse-captcha/spec/requests/discourse_captcha/hcaptcha_controller_spec.rb@@ -36,9 +36,9 @@ RSpec.describe DiscourseCaptcha::HcaptchaController docontext "when hCaptcha is not the selected provider" dobefore do- SiteSetting.discourse_captcha_provider = DiscourseCaptcha::CaptchaProvider::RECAPTCHA- SiteSetting.recaptcha_site_key = "test-site-key"- SiteSetting.recaptcha_secret_key = "test-secret-key"+ SiteSetting.discourse_captcha_provider = DiscourseCaptcha::CaptchaProvider::RECAPTCHA_V2+ SiteSetting.recaptcha_v2_site_key = "test-site-key"+ SiteSetting.recaptcha_v2_secret_key = "test-secret-key"endit "returns 404 error" dodiff --git a/plugins/discourse-captcha/spec/requests/discourse_captcha/recaptcha_controller_spec.rb b/plugins/discourse-captcha/spec/requests/discourse_captcha/recaptcha_controller_spec.rbindex 809bca83b4d..67162638767 100644--- a/plugins/discourse-captcha/spec/requests/discourse_captcha/recaptcha_controller_spec.rb+++ b/plugins/discourse-captcha/spec/requests/discourse_captcha/recaptcha_controller_spec.rb@@ -1,17 +1,17 @@# frozen_string_literal: trueRSpec.describe DiscourseCaptcha::RecaptchaController do- describe "POST /captcha/recaptcha/create" do+ describe "POST /captcha/recaptcha_v2/create" dobefore doSiteSetting.discourse_captcha_enabled = true- SiteSetting.discourse_captcha_provider = DiscourseCaptcha::CaptchaProvider::RECAPTCHA- SiteSetting.recaptcha_site_key = "test-site-key"- SiteSetting.recaptcha_secret_key = "test-secret-key"+ SiteSetting.discourse_captcha_provider = DiscourseCaptcha::CaptchaProvider::RECAPTCHA_V2+ SiteSetting.recaptcha_v2_site_key = "test-site-key"+ SiteSetting.recaptcha_v2_secret_key = "test-secret-key"endcontext "when reCaptcha is enabled and configured" doit "stores token in server session with 2 minute TTL" do- post "/captcha/recaptcha/create.json", params: { token: "test-token" }+ post "/captcha/recaptcha_v2/create.json", params: { token: "test-token" }expect(response.status).to eq(200)expect(response.parsed_body["success"]).to eq("OK")@@ -22,18 +22,25 @@ RSpec.describe DiscourseCaptcha::RecaptchaController docontext "when token is missing" doit "returns 400 error" do- post "/captcha/recaptcha/create.json", params: {}+ post "/captcha/recaptcha_v2/create.json", params: {}expect(response.status).to eq(400)endit "returns 400 error when token is blank" do- post "/captcha/recaptcha/create.json", params: { token: "" }+ post "/captcha/recaptcha_v2/create.json", params: { token: "" }expect(response.status).to eq(400)endend+ it "accepts tokens from signup pages opened before the provider rename" do+ post "/captcha/recaptcha/create.json", params: { token: "existing-page-token" }++ expect(response.status).to eq(200)+ expect(server_session["recaptcha_token"]).to eq("existing-page-token")+ end+context "when reCaptcha is not the selected provider" dobefore doSiteSetting.discourse_captcha_provider = DiscourseCaptcha::CaptchaProvider::HCAPTCHA@@ -42,7 +49,7 @@ RSpec.describe DiscourseCaptcha::RecaptchaController doendit "returns 404 error" do- post "/captcha/recaptcha/create.json", params: { token: "test-token" }+ post "/captcha/recaptcha_v2/create.json", params: { token: "test-token" }expect(response.status).to eq(404)end@@ -52,7 +59,7 @@ RSpec.describe DiscourseCaptcha::RecaptchaController dobefore { SiteSetting.discourse_captcha_provider = DiscourseCaptcha::CaptchaProvider::NONE }it "returns 404 error" do- post "/captcha/recaptcha/create.json", params: { token: "test-token" }+ post "/captcha/recaptcha_v2/create.json", params: { token: "test-token" }expect(response.status).to eq(404)enddiff --git a/plugins/discourse-captcha/spec/requests/discourse_captcha/recaptcha_v3_controller_spec.rb b/plugins/discourse-captcha/spec/requests/discourse_captcha/recaptcha_v3_controller_spec.rbnew file mode 100644index 00000000000..f03127f1055--- /dev/null+++ b/plugins/discourse-captcha/spec/requests/discourse_captcha/recaptcha_v3_controller_spec.rb@@ -0,0 +1,61 @@+# frozen_string_literal: true++RSpec.describe DiscourseCaptcha::RecaptchaV3Controller do+ describe "POST /captcha/recaptcha_v3/create" do+ before do+ SiteSetting.discourse_captcha_enabled = true+ SiteSetting.discourse_captcha_provider = DiscourseCaptcha::CaptchaProvider::RECAPTCHA_V3+ SiteSetting.recaptcha_v3_site_key = "test-site-key"+ SiteSetting.recaptcha_v3_secret_key = "test-secret-key"+ end++ context "when reCaptcha v3 is enabled and configured" do+ it "stores token in server session with 2 minute TTL" do+ post "/captcha/recaptcha_v3/create.json", params: { token: "test-token" }++ expect(response.status).to eq(200)+ expect(response.parsed_body["success"]).to eq("OK")+ expect(server_session["recaptcha_v3_token"]).to eq("test-token")+ expect(server_session.ttl("recaptcha_v3_token")).to be_between(1, 120)+ end+ end++ context "when token is missing" do+ it "returns 400 error" do+ post "/captcha/recaptcha_v3/create.json", params: {}++ expect(response.status).to eq(400)+ end++ it "returns 400 error when token is blank" do+ post "/captcha/recaptcha_v3/create.json", params: { token: "" }++ expect(response.status).to eq(400)+ end+ end++ context "when reCaptcha v3 is not the selected provider" do+ before do+ SiteSetting.discourse_captcha_provider = DiscourseCaptcha::CaptchaProvider::HCAPTCHA+ SiteSetting.hcaptcha_site_key = "test-site-key"+ SiteSetting.hcaptcha_secret_key = "test-secret-key"+ end++ it "returns 404 error" do+ post "/captcha/recaptcha_v3/create.json", params: { token: "test-token" }++ expect(response.status).to eq(404)+ end+ end++ context "when captcha provider is none" do+ before { SiteSetting.discourse_captcha_provider = DiscourseCaptcha::CaptchaProvider::NONE }++ it "returns 404 error" do+ post "/captcha/recaptcha_v3/create.json", params: { token: "test-token" }++ expect(response.status).to eq(404)+ end+ end+ end+enddiff --git a/plugins/discourse-captcha/spec/services/problem_check/recaptcha_configuration_spec.rb b/plugins/discourse-captcha/spec/services/problem_check/recaptcha_configuration_spec.rbindex eea3c8df3f5..574dbceeb0d 100644--- a/plugins/discourse-captcha/spec/services/problem_check/recaptcha_configuration_spec.rb+++ b/plugins/discourse-captcha/spec/services/problem_check/recaptcha_configuration_spec.rb@@ -18,29 +18,29 @@ RSpec.describe ProblemCheck::RecaptchaConfiguration docontext "when discourse_captcha_provider siteSetting is ReCaptcha" dobefore doSiteSetting.discourse_captcha_enabled = true- SiteSetting.discourse_captcha_provider = DiscourseCaptcha::CaptchaProvider::RECAPTCHA+ SiteSetting.discourse_captcha_provider = DiscourseCaptcha::CaptchaProvider::RECAPTCHA_V2end- describe "`recaptcha_site_key` is not set" do- before { SiteSetting.recaptcha_secret_key = "just a string" }+ describe "`recaptcha_v2_site_key` is not set" do+ before { SiteSetting.recaptcha_v2_secret_key = "just a string" }include_examples "fails_problem_check"end- describe "`recaptcha_secret_key` is not set" do- before { SiteSetting.recaptcha_site_key = "just a string" }+ describe "`recaptcha_v2_secret_key` is not set" do+ before { SiteSetting.recaptcha_v2_site_key = "just a string" }include_examples "fails_problem_check"end- describe "`recaptcha_secret_key` and `recaptcha_site_key` are not set" do+ describe "`recaptcha_v2_secret_key` and `recaptcha_v2_site_key` are not set" doinclude_examples "fails_problem_check"end- describe "`recaptcha_secret_key` and `recaptcha_site_key` are set" do+ describe "`recaptcha_v2_secret_key` and `recaptcha_v2_site_key` are set" dobefore do- SiteSetting.recaptcha_secret_key = "just a string"- SiteSetting.recaptcha_site_key = "just a string"+ SiteSetting.recaptcha_v2_secret_key = "just a string"+ SiteSetting.recaptcha_v2_site_key = "just a string"endinclude_examples "passes_problem_check"@@ -50,26 +50,26 @@ RSpec.describe ProblemCheck::RecaptchaConfiguration docontext "when discourse_captcha_provider siteSetting is none" dobefore { SiteSetting.discourse_captcha_provider = DiscourseCaptcha::CaptchaProvider::NONE }- describe "`recaptcha_site_key` is not set" do- before { SiteSetting.recaptcha_secret_key = "just a string" }+ describe "`recaptcha_v2_site_key` is not set" do+ before { SiteSetting.recaptcha_v2_secret_key = "just a string" }include_examples "passes_problem_check"end- describe "`recaptcha_secret_key` is not set" do- before { SiteSetting.recaptcha_site_key = "just a string" }+ describe "`recaptcha_v2_secret_key` is not set" do+ before { SiteSetting.recaptcha_v2_site_key = "just a string" }include_examples "passes_problem_check"end- describe "`recaptcha_secret_key` and `recaptcha_site_key` are not set" do+ describe "`recaptcha_v2_secret_key` and `recaptcha_v2_site_key` are not set" doinclude_examples "passes_problem_check"end- describe "`recaptcha_secret_key` and `recaptcha_site_key` are set" do+ describe "`recaptcha_v2_secret_key` and `recaptcha_v2_site_key` are set" dobefore do- SiteSetting.recaptcha_secret_key = "just a string"- SiteSetting.recaptcha_site_key = "just a string"+ SiteSetting.recaptcha_v2_secret_key = "just a string"+ SiteSetting.recaptcha_v2_site_key = "just a string"endinclude_examples "passes_problem_check"diff --git a/plugins/discourse-captcha/spec/services/problem_check/recaptcha_v3_configuration_spec.rb b/plugins/discourse-captcha/spec/services/problem_check/recaptcha_v3_configuration_spec.rbnew file mode 100644index 00000000000..f44662c7e28--- /dev/null+++ b/plugins/discourse-captcha/spec/services/problem_check/recaptcha_v3_configuration_spec.rb@@ -0,0 +1,74 @@+# frozen_string_literal: true++RSpec.describe ProblemCheck::RecaptchaV3Configuration do+ subject(:check) { described_class.new }++ shared_examples "fails_problem_check" do+ it do+ expect(check).to have_a_problem.with_priority("high").with_message(+ "There is a problem with your ReCaptcha v3 `site_key` or `secret_key` configuration",+ )+ end+ end++ shared_examples "passes_problem_check" do+ it { expect(check).to be_chill_about_it }+ end++ context "when discourse_captcha_provider siteSetting is ReCaptcha v3" do+ before do+ SiteSetting.discourse_captcha_enabled = true+ SiteSetting.discourse_captcha_provider = DiscourseCaptcha::CaptchaProvider::RECAPTCHA_V3+ end++ describe "`recaptcha_v3_site_key` is not set" do+ before { SiteSetting.recaptcha_v3_secret_key = "just a string" }++ include_examples "fails_problem_check"+ end++ describe "`recaptcha_v3_secret_key` is not set" do+ before { SiteSetting.recaptcha_v3_site_key = "just a string" }++ include_examples "fails_problem_check"+ end++ describe "`recaptcha_v3_secret_key` and `recaptcha_v3_site_key` are not set" do+ include_examples "fails_problem_check"+ end++ describe "`recaptcha_v3_secret_key` and `recaptcha_v3_site_key` are set" do+ before do+ SiteSetting.recaptcha_v3_secret_key = "just a string"+ SiteSetting.recaptcha_v3_site_key = "just a string"+ end++ include_examples "passes_problem_check"+ end+ end++ context "when discourse_captcha_provider siteSetting is none" do+ before { SiteSetting.discourse_captcha_provider = DiscourseCaptcha::CaptchaProvider::NONE }++ describe "`recaptcha_v3_site_key` is not set" do+ before { SiteSetting.recaptcha_v3_secret_key = "just a string" }++ include_examples "passes_problem_check"+ end++ describe "`recaptcha_v3_secret_key` is not set" do+ before { SiteSetting.recaptcha_v3_site_key = "just a string" }++ include_examples "passes_problem_check"+ end++ describe "`recaptcha_v3_secret_key` and `recaptcha_v3_site_key` are set" do+ before do+ SiteSetting.recaptcha_v3_secret_key = "just a string"+ SiteSetting.recaptcha_v3_site_key = "just a string"+ end++ include_examples "passes_problem_check"+ end+ end+enddiff --git a/plugins/discourse-captcha/spec/system/captcha_configuration_test_spec.rb b/plugins/discourse-captcha/spec/system/captcha_configuration_test_spec.rbnew file mode 100644index 00000000000..eb728410476--- /dev/null+++ b/plugins/discourse-captcha/spec/system/captcha_configuration_test_spec.rb@@ -0,0 +1,62 @@+# frozen_string_literal: true++describe "CAPTCHA admin configuration" do+ fab!(:admin)++ it "labels the v2 key settings explicitly" do+ SiteSetting.discourse_captcha_enabled = true+ sign_in(admin)++ visit "/admin/plugins/discourse-captcha/settings"++ expect(page).to have_css(+ '[data-setting="recaptcha_v2_site_key"] .setting-label',+ text: "Recaptcha v2 site key",+ )+ expect(page).to have_css(+ '[data-setting="recaptcha_v2_secret_key"] .setting-label',+ text: "Recaptcha v2 secret key",+ )+ end++ it "reports working keys and a low score without asking the admin to solve a challenge" do+ SiteSetting.discourse_captcha_enabled = true+ SiteSetting.discourse_captcha_provider = "recaptcha_v3"+ SiteSetting.recaptcha_v3_site_key = "v3-site-key"+ SiteSetting.recaptcha_v3_secret_key = "v3-secret-key"+ SiteSetting.recaptcha_v3_score_threshold = 0.5+ sign_in(admin)++ page.driver.with_playwright_page { |pw_page| pw_page.add_init_script(script: <<~JS) }+ window.grecaptcha = {+ execute: (siteKey, { action }) => {+ if (siteKey !== "v3-site-key" || action !== "configuration_test") {+ return Promise.reject(new Error("Unexpected test configuration"));+ }+ return Promise.resolve("admin-test-token");+ }+ };+ JS++ stub_request(:post, "https://www.google.com/recaptcha/api/siteverify").with(+ body: {+ secret: "v3-secret-key",+ response: "admin-test-token",+ },+ ).to_return(+ status: 200,+ body: { success: true, action: "configuration_test", score: 0.1 }.to_json,+ )++ visit "/admin/plugins/discourse-captcha/test"+ find(".captcha-configuration-test .btn-primary").click++ expect(page).to have_css(+ ".captcha-configuration-test .alert-success",+ text: I18n.t("discourse_captcha.configuration_test.v3_low_score", score: 0.1, threshold: 0.5),+ )+ expect(page).to have_no_text(+ I18n.t("js.discourse_captcha.configuration_test.complete_challenge"),+ )+ end+enddiff --git a/plugins/discourse-captcha/spec/system/page_objects/components/captcha.rb b/plugins/discourse-captcha/spec/system/page_objects/components/captcha.rbindex 02c730ce8a9..be66ca8115b 100644--- a/plugins/discourse-captcha/spec/system/page_objects/components/captcha.rb+++ b/plugins/discourse-captcha/spec/system/page_objects/components/captcha.rb@@ -25,6 +25,14 @@ module PageObjectspage.has_no_css?("#g-recaptcha")end+ def has_recaptcha_v3_container?+ page.has_css?("#g-recaptcha-v3")+ end++ def has_no_recaptcha_v3_container?+ page.has_no_css?("#g-recaptcha-v3")+ end+def has_captcha_error?page.has_css?(".captcha-container + .alert-error") ||page.has_css?(".captcha-service-tip .bad")diff --git a/plugins/discourse-captcha/spec/system/signup_with_captcha_spec.rb b/plugins/discourse-captcha/spec/system/signup_with_captcha_spec.rbindex 2f6fa372c59..6d73afeb1c3 100644--- a/plugins/discourse-captcha/spec/system/signup_with_captcha_spec.rb+++ b/plugins/discourse-captcha/spec/system/signup_with_captcha_spec.rb@@ -125,15 +125,16 @@ RSpec.describe "Signup with captcha" dosignup_page.openexpect(captcha).to have_no_hcaptcha_containerexpect(captcha).to have_no_recaptcha_container+ expect(captcha).to have_no_recaptcha_v3_containerendendendcontext "with reCaptcha", allow_network: %w[www.google.com www.gstatic.com] dobefore do- SiteSetting.discourse_captcha_provider = DiscourseCaptcha::CaptchaProvider::RECAPTCHA- SiteSetting.recaptcha_site_key = "6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI"- SiteSetting.recaptcha_secret_key = "6LeIxAcTAAAAAGG-vFI1TnRWxMZNFuojJ4WifJWe"+ SiteSetting.discourse_captcha_provider = DiscourseCaptcha::CaptchaProvider::RECAPTCHA_V2+ SiteSetting.recaptcha_v2_site_key = "6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI"+ SiteSetting.recaptcha_v2_secret_key = "6LeIxAcTAAAAAGG-vFI1TnRWxMZNFuojJ4WifJWe"endit "displays the reCaptcha widget on signup page" do@@ -141,6 +142,34 @@ RSpec.describe "Signup with captcha" doexpect(captcha).to have_recaptcha_containerend+ it "completes signup using the renamed v2 provider and keys" do+ page.driver.with_playwright_page { |pw_page| pw_page.add_init_script(script: <<~JS) }+ window.grecaptcha = {+ render: (_element, options) => {+ setTimeout(() => options.callback("v2-token"), 0);+ return 1;+ },+ reset: () => {}+ };+ JS+ stub_request(:post, DiscourseCaptcha::RecaptchaProvider::CAPTCHA_VERIFICATION_URL).with(+ body: {+ secret: SiteSetting.recaptcha_v2_secret_key,+ response: "v2-token",+ },+ ).to_return(status: 200, body: { success: true }.to_json)++ signup_page+ .open+ .fill_email("[email protected]")+ .fill_username("testuser")+ .fill_password("supersecurepassword")+ expect(signup_page).to have_valid_fields+ signup_page.click_create_account++ expect(page).to have_current_path("/u/account-created")+ end+it "loads the reCaptcha iframe" dosignup_page.openexpect(captcha).to have_recaptcha_widget@@ -152,6 +181,110 @@ RSpec.describe "Signup with captcha" doendend+ context "with reCaptcha v3" do+ before do+ SiteSetting.discourse_captcha_provider = DiscourseCaptcha::CaptchaProvider::RECAPTCHA_V3+ SiteSetting.recaptcha_v3_site_key = "v3-site-key"+ SiteSetting.recaptcha_v3_secret_key = "v3-secret-key"++ page.driver.with_playwright_page { |pw_page| pw_page.add_init_script(script: <<~JS) }+ window.captchaExecutions = 0;+ window.grecaptcha = {+ execute: () => Promise.resolve(`v3-token-${++window.captchaExecutions}`)+ };+ JS++ stub_request(:post, DiscourseCaptcha::RecaptchaV3Provider::CAPTCHA_VERIFICATION_URL).with(+ body: {+ secret: "v3-secret-key",+ response: "v3-token-1",+ },+ ).to_return(status: 200, body: { success: true, action: "signup", score: 0.9 }.to_json)+ end++ it "fetches a fresh token after the signup form has been open for three minutes" do+ page.driver.with_playwright_page { |pw_page| pw_page.clock.install }+ signup_page+ .open+ .fill_email("[email protected]")+ .fill_username("testuser")+ .fill_password("supersecurepassword")+ expect(captcha).to have_no_hcaptcha_container+ expect(captcha).to have_no_recaptcha_container+ expect(signup_page).to have_valid_fields+ page.driver.with_playwright_page { |pw_page| pw_page.clock.fast_forward(180_000) }+ expect(page.evaluate_script("window.captchaExecutions")).to eq(0)++ signup_page.click_create_account++ expect(page).to have_current_path("/u/account-created")+ end+ end++ context "with reCaptcha v3 signup retries" do+ before do+ SiteSetting.discourse_captcha_provider = DiscourseCaptcha::CaptchaProvider::RECAPTCHA_V3+ SiteSetting.recaptcha_v3_site_key = "v3-site-key"+ SiteSetting.recaptcha_v3_secret_key = "v3-secret-key"++ page.driver.with_playwright_page { |pw_page| pw_page.add_init_script(script: <<~JS) }+ window.captchaExecutions = 0;+ window.grecaptcha = {+ execute: () => Promise.resolve(`v3-token-${++window.captchaExecutions}`)+ };+ JS++ stub_request(:post, DiscourseCaptcha::RecaptchaV3Provider::CAPTCHA_VERIFICATION_URL).with(+ body: {+ secret: "v3-secret-key",+ response: "v3-token-1",+ },+ ).to_return(status: 200, body: { success: true, action: "signup", score: 0.1 }.to_json)+ stub_request(:post, DiscourseCaptcha::RecaptchaV3Provider::CAPTCHA_VERIFICATION_URL).with(+ body: {+ secret: "v3-secret-key",+ response: "v3-token-2",+ },+ ).to_return(status: 200, body: { success: true, action: "signup", score: 0.9 }.to_json)+ end++ it "fetches a new token when retrying after verification fails" do+ signup_page+ .open+ .fill_email("[email protected]")+ .fill_username("testuser")+ .fill_password("supersecurepassword")+ expect(signup_page).to have_valid_fields++ signup_page.click_create_account+ expect(signup_page).to have_flash_message(I18n.t("captcha_verification_failed"))+ signup_page.click_create_account++ expect(page).to have_current_path("/u/account-created")+ end++ it "lets the user retry signup for approval after verifying a login code" do+ SiteSetting.enable_local_logins_via_email = true+ SiteSetting.enable_local_logins_via_code = true+ SiteSetting.must_approve_users = true+ Jobs.run_immediately!++ code_signup.open.submit_email("[email protected]")+ wait_for { ActionMailer::Base.deliveries.any? }+ code = ActionMailer::Base.deliveries.last.subject[/(\d{6})/, 1]+ code_signup.submit_code(code)++ expect(code_signup).to have_account_details+ code_signup.fill_username("approval-user")+ expect(page.evaluate_script("window.captchaExecutions")).to eq(0)+ code_signup.submit_for_approval+ expect(code_signup).to have_error(I18n.t("captcha_verification_failed"))+ code_signup.submit_for_approval++ expect(code_signup).to have_pending_approval+ end+ end+context "when captcha provider is none" dobefore { SiteSetting.discourse_captcha_provider = DiscourseCaptcha::CaptchaProvider::NONE }@@ -159,6 +292,7 @@ RSpec.describe "Signup with captcha" dosignup_page.openexpect(captcha).to have_no_hcaptcha_containerexpect(captcha).to have_no_recaptcha_container+ expect(captcha).to have_no_recaptcha_v3_containerendendenddiff --git a/plugins/discourse-captcha/test/javascripts/integration/components/captcha-configuration-test-test.gjs b/plugins/discourse-captcha/test/javascripts/integration/components/captcha-configuration-test-test.gjsindex 1a0484c0f15..00b33a26a18 100644--- a/plugins/discourse-captcha/test/javascripts/integration/components/captcha-configuration-test-test.gjs+++ b/plugins/discourse-captcha/test/javascripts/integration/components/captcha-configuration-test-test.gjs@@ -12,7 +12,7 @@ module("Integration | Component | CaptchaConfigurationTest", function (hooks) {hooks.beforeEach(function () {this.configuration = {configured: true,- provider: "recaptcha",+ provider: "recaptcha_v2",site_key: "saved-site-key",};this.originalRecaptcha = window.grecaptcha;@@ -33,6 +33,93 @@ module("Integration | Component | CaptchaConfigurationTest", function (hooks) {window.hcaptcha = this.originalHcaptcha;});+ test("tests v3 only after clicking and keeps signup state separate", async function (assert) {+ this.configuration.provider = "recaptcha_v3";+ const captchaService = this.owner.lookup("service:captcha-service");+ captchaService.token = "signup-token";+ captchaService.invalid = false;+ const refreshToken = () => {};+ captchaService.refreshToken = refreshToken;+ const execute = sinon.stub().resolves("v3-test-token");+ window.grecaptcha = { execute };+ pretender.post("/admin/plugins/discourse-captcha/test.json", (request) => {+ const data = new URLSearchParams(request.requestBody);+ assert.strictEqual(+ data.get("provider"),+ "recaptcha_v3",+ "tests the v3 provider"+ );+ assert.strictEqual(+ data.get("token"),+ "v3-test-token",+ "sends the test token"+ );+ return response({+ success: true,+ message: "Keys work; score is below the signup threshold.",+ });+ });++ await render(+ <template>+ <CaptchaConfigurationTest @configuration={{this.configuration}} />+ </template>+ );+ assert.false(execute.called, "does not execute before clicking Test");+ await click(".captcha-configuration-test .btn-primary");++ assert.true(+ execute.calledOnceWithExactly("saved-site-key", {+ action: "configuration_test",+ }),+ "uses a separate test action"+ );+ assert+ .dom(".alert-success")+ .hasText(+ "Keys work; score is below the signup threshold.",+ "displays the score result"+ );+ assert.strictEqual(+ captchaService.token,+ "signup-token",+ "preserves the signup token"+ );+ assert.false(captchaService.invalid, "preserves signup validity");+ assert.strictEqual(+ captchaService.refreshToken,+ refreshToken,+ "preserves the signup callback"+ );+ });++ test("allows retrying a failed v3 token request", async function (assert) {+ this.configuration.provider = "recaptcha_v3";+ window.grecaptcha = {+ execute: sinon.stub().rejects(new Error("unavailable")),+ };++ await render(+ <template>+ <CaptchaConfigurationTest @configuration={{this.configuration}} />+ </template>+ );+ await click(".captcha-configuration-test .btn-primary");++ assert+ .dom(".alert-error")+ .hasText(+ i18n("discourse_captcha.configuration_test.challenge_failed"),+ "shows the failure"+ );+ assert+ .dom(".captcha-configuration-test .btn-primary")+ .hasText(+ i18n("discourse_captcha.configuration_test.retry"),+ "offers another attempt"+ );+ });+test("verifies saved keys and keeps signup state separate", async function (assert) {const captchaService = this.owner.lookup("service:captcha-service");captchaService.token = "signup-token";@@ -51,7 +138,7 @@ module("Integration | Component | CaptchaConfigurationTest", function (hooks) {);assert.strictEqual(data.get("provider"),- "recaptcha",+ "recaptcha_v2","identifies the tested provider");return response({ success: true, message: "Verification succeeded." });@@ -200,7 +287,7 @@ module("Integration | Component | CaptchaConfigurationTest", function (hooks) {assert.dom(".alert-error").doesNotExist("clears the failure");});- for (const provider of ["recaptcha", "hcaptcha"]) {+ for (const provider of ["recaptcha_v2", "hcaptcha"]) {test(`${provider} ignores callbacks from a replaced challenge`, async function (assert) {this.configuration.provider = provider;let verificationRequests = 0;