A platform for community discussion. Free, open, simple.
FEATURE: Allow admins to test CAPTCHA keys (#44178)
Natalie Tayd8d59f720e4d
diff --git a/plugins/discourse-captcha/README.md b/plugins/discourse-captcha/README.mdindex af093d5103a..94489d450da 100644--- a/plugins/discourse-captcha/README.md+++ b/plugins/discourse-captcha/README.md@@ -35,6 +35,18 @@ You can enable either provider based on your preference and requirements.- Select `recaptcha` in the `discourse_captcha_provider` setting.- Add the site key and secret key you obtained from reCaptcha.+## 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 NotesIf you were using this plugin when it was named "discourse-hcaptcha", your existing settings have been automatically migrated.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.gjsnew file mode 100644index 00000000000..7de257874d5--- /dev/null+++ b/plugins/discourse-captcha/admin/assets/javascripts/discourse/components/captcha-configuration-test.gjs@@ -0,0 +1,160 @@+import Component from "@glimmer/component";+import { tracked } from "@glimmer/tracking";+import { array } from "@ember/helper";+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 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";++export default class CaptchaConfigurationTest extends Component {+ @service a11y;++ @tracked attempt = 0;+ @tracked challengeVisible = false;+ @tracked result;+ @tracked verifying = false;++ @action+ start() {+ this.attempt++;+ this.result = null;+ this.challengeVisible = true;+ }++ @action+ challengeFailed() {+ this.#showResult(+ {+ success: false,+ message: i18n("discourse_captcha.configuration_test.challenge_failed"),+ },+ false+ );+ }++ @action+ async verify(token) {+ if (this.verifying) {+ return;+ }++ if (!token) {+ this.#showResult({+ success: false,+ message: i18n("discourse_captcha.configuration_test.expired"),+ });+ return;+ }++ this.verifying = true;+ try {+ const result = await ajax("/admin/plugins/discourse-captcha/test.json", {+ type: "POST",+ data: {+ token,+ provider: this.args.configuration.provider,+ site_key: this.args.configuration.site_key,+ },+ });+ this.#showResult(result);+ } catch (error) {+ this.#showResult({ success: false, message: extractError(error) });+ } finally {+ if (!this.isDestroying) {+ this.verifying = false;+ }+ }+ }++ #showResult(result, hideChallenge = true) {+ if (this.isDestroying) {+ return;+ }+ if (hideChallenge) {+ this.challengeVisible = false;+ }+ this.result = result;+ this.a11y.announce(result.message);+ }++ <template>+ <div class="captcha-configuration-test" ...attributes>+ <DPageSubheader+ @descriptionLabel={{i18n+ "discourse_captcha.configuration_test.description"+ }}+ @titleLabel={{i18n "discourse_captcha.configuration_test.title"}}+ />++ {{#if @configuration.configured}}+ {{#if this.result}}+ <p+ class={{if+ this.result.success+ "alert alert-success"+ "alert alert-error"+ }}+ >+ {{this.result.message}}+ </p>+ {{/if}}+ {{#if this.challengeVisible}}+ {{#unless this.result}}+ <p>{{i18n+ "discourse_captcha.configuration_test.complete_challenge"+ }}</p>+ {{/unless}}+ {{#each (array this.attempt) key="@identity"}}+ {{#if (eq @configuration.provider "recaptcha")}}+ <ReCaptcha+ @errorMessage={{i18n+ "discourse_captcha.configuration_test.challenge_failed"+ }}+ @onError={{this.challengeFailed}}+ @onResponse={{this.verify}}+ @siteKey={{@configuration.site_key}}+ />+ {{else}}+ <HCaptcha+ @errorMessage={{i18n+ "discourse_captcha.configuration_test.challenge_failed"+ }}+ @onError={{this.challengeFailed}}+ @onResponse={{this.verify}}+ @siteKey={{@configuration.site_key}}+ />+ {{/if}}+ {{/each}}+ {{#if this.verifying}}+ <p>{{i18n "discourse_captcha.configuration_test.verifying"}}</p>+ {{/if}}+ {{/if}}+ {{#if this.result}}+ <DButton+ class="btn-primary captcha-configuration-test__retry"+ @action={{this.start}}+ @label="discourse_captcha.configuration_test.retry"+ />+ {{else}}+ {{#unless this.challengeVisible}}+ <DButton+ class="btn-primary"+ @action={{this.start}}+ @label="discourse_captcha.configuration_test.start"+ />+ {{/unless}}+ {{/if}}+ {{else}}+ <p class="alert alert-info">+ {{i18n "discourse_captcha.configuration_test.not_configured"}}+ </p>+ {{/if}}+ </div>+ </template>+}diff --git a/plugins/discourse-captcha/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-captcha-test.js b/plugins/discourse-captcha/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-captcha-test.jsnew file mode 100644index 00000000000..816e0e2bca0--- /dev/null+++ b/plugins/discourse-captcha/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-captcha-test.js@@ -0,0 +1,8 @@+import { ajax } from "discourse/lib/ajax";+import DiscourseRoute from "discourse/routes/discourse";++export default class DiscourseCaptchaTestRoute extends DiscourseRoute {+ model() {+ return ajax("/admin/plugins/discourse-captcha/test.json");+ }+}diff --git a/plugins/discourse-captcha/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-captcha-test.gjs b/plugins/discourse-captcha/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-captcha-test.gjsnew file mode 100644index 00000000000..a590e8221df--- /dev/null+++ b/plugins/discourse-captcha/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-captcha-test.gjs@@ -0,0 +1,5 @@+import CaptchaConfigurationTest from "discourse/plugins/discourse-captcha/discourse/components/captcha-configuration-test";++export default <template>+ <CaptchaConfigurationTest @configuration={{@model}} />+</template>diff --git a/plugins/discourse-captcha/app/controllers/discourse_captcha/admin_captcha_controller.rb b/plugins/discourse-captcha/app/controllers/discourse_captcha/admin_captcha_controller.rbnew file mode 100644index 00000000000..8d302d8d0e2--- /dev/null+++ b/plugins/discourse-captcha/app/controllers/discourse_captcha/admin_captcha_controller.rb@@ -0,0 +1,30 @@+# frozen_string_literal: true++module DiscourseCaptcha+ # Configuration testing must remain available before CAPTCHA enforcement is enabled.+ class AdminCaptchaController < ::Admin::AdminController # rubocop:disable Discourse/Plugins/CallRequiresPlugin+ def show+ respond_to do |format|+ format.html { render body: nil }+ format.json { render json: ConfigurationTest.new.configuration }+ end+ end++ def verify+ token = params.require(:token)+ raise Discourse::InvalidParameters.new(:token) if !token.is_a?(String) || token.size > 16_384++ test = ConfigurationTest.new+ configuration = test.configuration+ if params[:provider] != configuration[:provider] ||+ params[:site_key].to_s != configuration[:site_key].to_s+ raise Discourse::InvalidParameters.new(+ I18n.t("discourse_captcha.configuration_test.errors.configuration_changed"),+ )+ end++ RateLimiter.new(current_user, "captcha_configuration_test", 10, 1.minute).performed!+ render json: test.verify(token)+ end+ end+enddiff --git a/plugins/discourse-captcha/assets/javascripts/discourse/admin-discourse-captcha-plugin-route-map.js b/plugins/discourse-captcha/assets/javascripts/discourse/admin-discourse-captcha-plugin-route-map.jsnew file mode 100644index 00000000000..e0e24807fe2--- /dev/null+++ b/plugins/discourse-captcha/assets/javascripts/discourse/admin-discourse-captcha-plugin-route-map.js@@ -0,0 +1,8 @@+export default {+ resource: "admin.adminPlugins.show",+ path: "/plugins",++ map() {+ this.route("discourse-captcha-test", { path: "test" });+ },+};diff --git a/plugins/discourse-captcha/assets/javascripts/discourse/components/base-captcha.gjs b/plugins/discourse-captcha/assets/javascripts/discourse/components/base-captcha.gjsindex 230fc0f204e..d0310c5e51e 100644--- a/plugins/discourse-captcha/assets/javascripts/discourse/components/base-captcha.gjs+++ b/plugins/discourse-captcha/assets/javascripts/discourse/components/base-captcha.gjs@@ -21,17 +21,53 @@ export default class BaseCaptcha extends Component {const renderOptions = {sitekey: this.siteKey,callback: (response) => {+ if (this.args.onResponse) {+ this.args.onResponse(response);+ return;+ }this.captchaService.token = response;this.captchaService.invalid = !response;},"expired-callback": () => {+ if (this.args.onResponse) {+ this.args.onResponse(null);+ return;+ }this.captchaService.invalid = true;},...this.additionalRenderOptions(),+ ...(this.args.onError && { "error-callback": this.args.onError }),};- this.widgetId = captchaApi.render(element, renderOptions);- this.captchaService.registerWidget(captchaApi, this.widgetId);+ let active = true;+ ["callback", "expired-callback", "error-callback"].forEach((name) => {+ const callback = renderOptions[name];+ if (callback) {+ renderOptions[name] = (...args) => {+ if (active) {+ return callback(...args);+ }+ };+ }+ });++ const widgetId = captchaApi.render(element, renderOptions);+ this.widgetId = widgetId;+ if (!this.args.onResponse) {+ this.captchaService.registerWidget(captchaApi, this.widgetId);+ }++ const standalone = Boolean(this.args.onResponse);+ return () => {+ active = false;+ if (standalone) {+ if (captchaApi.remove) {+ captchaApi.remove(widgetId);+ } else {+ captchaApi.reset?.(widgetId);+ }+ }+ };});get siteKey() {@@ -73,7 +109,12 @@ export default class BaseCaptcha extends Component {resolve(window[this.captchaApiName]);};- loadScript(this.scriptUrl).catch(reject);+ loadScript(this.scriptUrl).catch((error) => {+ if (!this.isDestroying) {+ this.args.onError?.();+ }+ reject(error);+ });});}@@ -97,14 +138,18 @@ export default class BaseCaptcha extends Component {></div></:content><:error>- <div class="alert alert-error">- {{i18n this.captchaErrorKey}}- </div>+ {{#unless @onError}}+ <div class="alert alert-error">+ {{if @errorMessage @errorMessage (i18n this.captchaErrorKey)}}+ </div>+ {{/unless}}</:error></DAsyncContent>- {{#if this.captchaService.submitFailed}}- <DInputTip @validation={{this.captchaService.inputValidation}} />- {{/if}}+ {{#unless @onResponse}}+ {{#if this.captchaService.submitFailed}}+ <DInputTip @validation={{this.captchaService.inputValidation}} />+ {{/if}}+ {{/unless}}</template>}diff --git a/plugins/discourse-captcha/assets/javascripts/discourse/initializers/hcaptcha-admin-plugin-configuration-nav.js b/plugins/discourse-captcha/assets/javascripts/discourse/initializers/hcaptcha-admin-plugin-configuration-nav.jsindex 120ce6879e7..7e2fc3a624b 100644--- a/plugins/discourse-captcha/assets/javascripts/discourse/initializers/hcaptcha-admin-plugin-configuration-nav.js+++ b/plugins/discourse-captcha/assets/javascripts/discourse/initializers/hcaptcha-admin-plugin-configuration-nav.js@@ -13,6 +13,13 @@ export default {withPluginApi((api) => {api.setAdminPluginIcon(PLUGIN_ID, "hand");+ api.addAdminPluginConfigurationNav(PLUGIN_ID, [+ {+ label: "discourse_captcha.configuration_test.tab_title",+ route: "adminPlugins.show.discourse-captcha-test",+ description: "discourse_captcha.configuration_test.description",+ },+ ]);});},};diff --git a/plugins/discourse-captcha/assets/stylesheets/common/captcha-configuration-test.scss b/plugins/discourse-captcha/assets/stylesheets/common/captcha-configuration-test.scssnew file mode 100644index 00000000000..4686fd83479--- /dev/null+++ b/plugins/discourse-captcha/assets/stylesheets/common/captcha-configuration-test.scss@@ -0,0 +1,3 @@+.captcha-configuration-test__retry {+ margin-block-start: 1em;+}diff --git a/plugins/discourse-captcha/config/locales/client.en.yml b/plugins/discourse-captcha/config/locales/client.en.ymlindex dad1b4157a5..9cc441c4da5 100644--- a/plugins/discourse-captcha/config/locales/client.en.yml+++ b/plugins/discourse-captcha/config/locales/client.en.yml@@ -1,6 +1,18 @@en:js:discourse_captcha:+ title: "Captcha"+ configuration_test:+ tab_title: "Test"+ title: "Configuration test"+ description: "Test your saved CAPTCHA keys."+ start: "Test configuration"+ retry: "Test again"+ complete_challenge: "Complete the challenge to verify your saved keys."+ verifying: "Verifying with your CAPTCHA provider…"+ not_configured: "Select a CAPTCHA provider and save both the site key and secret key in Settings before testing."+ challenge_failed: "Could not load CAPTCHA. Check your keys and provider settings."+ expired: "The challenge expired. Start a new test and complete it again."missing_token: "Please complete the captcha challenge."verification_failed: "Captcha verification failed. Please try again."placeholder: placeholderdiff --git a/plugins/discourse-captcha/config/locales/server.en.yml b/plugins/discourse-captcha/config/locales/server.en.ymlindex 8d9c02d25c6..c58b53c3aab 100644--- a/plugins/discourse-captcha/config/locales/server.en.yml+++ b/plugins/discourse-captcha/config/locales/server.en.yml@@ -1,4 +1,16 @@en:+ discourse_captcha:+ configuration_test:+ 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."+ configuration_changed: "The CAPTCHA configuration changed. Reload this page and try again."+ invalid_secret: "The CAPTCHA provider rejected the secret key. Check the saved secret key in Settings."+ key_mismatch: "The site key and secret key do not match. Check that both keys belong to the same configuration with your provider."+ invalid_response: "The CAPTCHA response was invalid. Start a new test and try again."+ expired: "The challenge expired or has already been verified. Start a new test and complete it again."+ unavailable: "Could not contact the CAPTCHA provider or it returned an unexpected response. Try again later."+ verification_failed: "The CAPTCHA provider rejected the challenge. Check your saved keys and provider configuration, then try again."dashboard:problem:hcaptcha_configuration: "There is a problem with your hCaptcha `site_key` or `secret_key` configuration"diff --git a/plugins/discourse-captcha/config/routes.rb b/plugins/discourse-captcha/config/routes.rbindex bcf293a4c80..4fc8d37fab4 100644--- a/plugins/discourse-captcha/config/routes.rb+++ b/plugins/discourse-captcha/config/routes.rb@@ -1,6 +1,13 @@# frozen_string_literal: true-Discourse::Application.routes.draw { mount DiscourseCaptcha::Engine, at: "captcha" }+Discourse::Application.routes.draw do+ mount DiscourseCaptcha::Engine, at: "captcha"++ scope "/admin/plugins/discourse-captcha", constraints: AdminConstraint.new do+ get "/test" => "discourse_captcha/admin_captcha#show"+ post "/test" => "discourse_captcha/admin_captcha#verify"+ end+endDiscourseCaptcha::Engine.routes.draw dopost "/hcaptcha/create", to: "hcaptcha#create"diff --git a/plugins/discourse-captcha/lib/discourse_captcha/configuration_test.rb b/plugins/discourse-captcha/lib/discourse_captcha/configuration_test.rbnew file mode 100644index 00000000000..5065baf2b1f--- /dev/null+++ b/plugins/discourse-captcha/lib/discourse_captcha/configuration_test.rb@@ -0,0 +1,66 @@+# frozen_string_literal: true++module DiscourseCaptcha+ class ConfigurationTest+ ERROR_MESSAGES = {+ "missing-input-secret" => "invalid_secret",+ "invalid-input-secret" => "invalid_secret",+ "sitekey-secret-mismatch" => "key_mismatch",+ "invalid-input-response" => "invalid_response",+ "missing-input-response" => "invalid_response",+ "invalid-or-already-seen-response" => "expired",+ "expired-input-response" => "expired",+ "timeout-or-duplicate" => "expired",+ "not-using-dummy-passcode" => "key_mismatch",+ }.freeze++ def initialize+ @provider = SiteSetting.discourse_captcha_provider+ case @provider+ when CaptchaProvider::RECAPTCHA+ @site_key = SiteSetting.recaptcha_site_key+ @secret_key = SiteSetting.recaptcha_secret_key+ @captcha_provider = RecaptchaProvider.new+ when CaptchaProvider::HCAPTCHA+ @site_key = SiteSetting.hcaptcha_site_key+ @secret_key = SiteSetting.hcaptcha_secret_key+ @captcha_provider = HcaptchaProvider.new+ end+ end++ def configuration+ {+ provider: @provider,+ site_key: @site_key,+ configured: @captcha_provider.present? && @site_key.present? && @secret_key.present?,+ }+ end++ def verify(token)+ return failure("not_configured") if !configuration[:configured]++ response = @captcha_provider.send_captcha_verification(token)+ return failure("unavailable") if response.code.to_i != 200++ result = JSON.parse(response.body)+ return failure("invalid_response") if !result.is_a?(Hash)++ if result["success"] == true+ { success: true, message: I18n.t("discourse_captcha.configuration_test.success") }+ else+ error = Array(result["error-codes"]).filter_map { |code| ERROR_MESSAGES[code] }.first+ failure(error || "verification_failed")+ end+ rescue JSON::ParserError+ failure("invalid_response")+ rescue Timeout::Error, SocketError, IOError, SystemCallError, OpenSSL::SSL::SSLError+ failure("unavailable")+ end++ private++ def failure(error)+ { success: false, message: I18n.t("discourse_captcha.configuration_test.errors.#{error}") }+ end+ end+enddiff --git a/plugins/discourse-captcha/plugin.rb b/plugins/discourse-captcha/plugin.rbindex 5ab6e2926aa..5bd70ba4a1c 100644--- a/plugins/discourse-captcha/plugin.rb+++ b/plugins/discourse-captcha/plugin.rb@@ -12,6 +12,7 @@enabled_site_setting :discourse_captcha_enabledregister_svg_icon "hand"+register_asset "stylesheets/common/captcha-configuration-test.scss", :adminmodule ::DiscourseCaptchaPLUGIN_NAME = "discourse-captcha"@@ -24,6 +25,8 @@ require_relative "lib/discourse_captcha/create_users_controller_patch"require_relative "lib/discourse_captcha/session_controller_patch"after_initialize do+ add_admin_route("discourse_captcha.title", "discourse-captcha", use_new_show_route: true)+reloadable_patch { UsersController.include(DiscourseCaptcha::CreateUsersControllerPatch) }reloadable_patch { SessionController.prepend(DiscourseCaptcha::SessionControllerPatch) }diff --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.rbnew file mode 100644index 00000000000..f70593acfff--- /dev/null+++ b/plugins/discourse-captcha/spec/requests/discourse_captcha/admin_captcha_controller_spec.rb@@ -0,0 +1,193 @@+# frozen_string_literal: true++RSpec.describe DiscourseCaptcha::AdminCaptchaController do+ fab!(:admin)+ fab!(:moderator)+ fab!(:user)++ before do+ SiteSetting.discourse_captcha_provider = "recaptcha"+ SiteSetting.recaptcha_site_key = "test-site-key"+ SiteSetting.recaptcha_secret_key = "test-secret-key"+ end++ describe "#show" do+ it "returns the public configuration while enforcement is disabled" do+ sign_in(admin)+ SiteSetting.discourse_captcha_enabled = false++ get "/admin/plugins/discourse-captcha/test.json"++ expect(response.status).to eq(200)+ expect(response.parsed_body).to eq(+ "provider" => "recaptcha",+ "site_key" => SiteSetting.recaptcha_site_key,+ "configured" => true,+ )+ expect(response.body).not_to include(SiteSetting.recaptcha_secret_key)+ end++ it "supports directly loading the test page" do+ sign_in(admin)++ get "/admin/plugins/discourse-captcha/test"++ expect(response.status).to eq(200)+ end++ it "identifies missing credentials" do+ sign_in(admin)+ SiteSetting.recaptcha_secret_key = ""++ get "/admin/plugins/discourse-captcha/test.json"++ expect(response.parsed_body["configured"]).to eq(false)+ end++ it "denies anonymous users, regular users, and moderators" do+ get "/admin/plugins/discourse-captcha/test.json"+ expect(response.status).to eq(404)++ [user, moderator].each do |actor|+ sign_in(actor)+ get "/admin/plugins/discourse-captcha/test.json"+ expect(response.status).to eq(404)+ end+ end+ end++ describe "#verify" do+ let(:params) { { token: "test-token", provider: "recaptcha", 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+ sign_in(admin)+ SiteSetting.discourse_captcha_enabled = false+ stub_request(:post, verification_url).with(+ body: {+ secret: "test-secret-key",+ response: "test-token",+ },+ ).to_return(status: 200, body: { success: true }.to_json)++ expect { post "/admin/plugins/discourse-captcha/test.json", params: params }.not_to change(+ User,+ :count,+ )++ expect(response.status).to eq(200)+ expect(response.parsed_body["success"]).to eq(true)+ expect(server_session["recaptcha_token"]).to be_nil+ expect(SiteSetting.discourse_captcha_enabled).to eq(false)+ end++ it "verifies hCaptcha with its saved secret" do+ sign_in(admin)+ SiteSetting.discourse_captcha_provider = "hcaptcha"+ SiteSetting.hcaptcha_site_key = "test-site-key"+ SiteSetting.hcaptcha_secret_key = "hcaptcha-secret"+ stub_request(:post, "https://hcaptcha.com/siteverify").with(+ body: {+ secret: "hcaptcha-secret",+ response: "test-token",+ },+ ).to_return(status: 200, body: { success: true }.to_json)++ post "/admin/plugins/discourse-captcha/test.json", params: params.merge(provider: "hcaptcha")++ expect(response.parsed_body["success"]).to eq(true)+ end++ it "explains a rejected secret without disclosing it" do+ sign_in(admin)+ stub_request(:post, verification_url).to_return(+ status: 200,+ body: { :success => false, "error-codes" => ["invalid-input-secret"] }.to_json,+ )++ post "/admin/plugins/discourse-captcha/test.json", params: params++ expect(response.parsed_body).to eq(+ "success" => false,+ "message" => I18n.t("discourse_captcha.configuration_test.errors.invalid_secret"),+ )+ expect(response.body).not_to include(SiteSetting.recaptcha_secret_key)+ end++ it "handles expired challenges" do+ sign_in(admin)+ stub_request(:post, verification_url).to_return(+ status: 200,+ body: { :success => false, "error-codes" => ["timeout-or-duplicate"] }.to_json,+ )++ post "/admin/plugins/discourse-captcha/test.json", params: params++ expect(response.parsed_body["message"]).to eq(+ I18n.t("discourse_captcha.configuration_test.errors.expired"),+ )+ end++ it "handles unavailable providers and malformed responses" do+ sign_in(admin)+ [+ { status: 503, body: "unavailable" },+ { status: 200, body: "invalid json" },+ { status: 200, body: "[]" },+ { status: 200, body: { success: "true" }.to_json },+ ].each do |provider_response|+ stub_request(:post, verification_url).to_return(**provider_response)++ post "/admin/plugins/discourse-captcha/test.json", params: params++ expect(response.parsed_body["success"]).to eq(false)+ end+ end++ it "handles a connection timeout" do+ sign_in(admin)+ stub_request(:post, verification_url).to_timeout++ post "/admin/plugins/discourse-captcha/test.json", params: params++ expect(response.parsed_body["message"]).to eq(+ I18n.t("discourse_captcha.configuration_test.errors.unavailable"),+ )+ end++ it "rejects missing tokens and changed configurations" do+ sign_in(admin)+ post "/admin/plugins/discourse-captcha/test.json", params: params.except(:token)+ expect(response.status).to eq(400)++ post "/admin/plugins/discourse-captcha/test.json", params: params.merge(provider: "hcaptcha")+ expect(response.status).to eq(400)++ post "/admin/plugins/discourse-captcha/test.json", params: params.merge(site_key: "old-key")+ expect(response.status).to eq(400)+ end++ it "reports missing credentials and no selected provider" do+ sign_in(admin)+ SiteSetting.recaptcha_secret_key = ""+ post "/admin/plugins/discourse-captcha/test.json", params: params+ expect(response.parsed_body["success"]).to eq(false)++ SiteSetting.discourse_captcha_provider = "none"+ post "/admin/plugins/discourse-captcha/test.json",+ params: params.merge(provider: "none", site_key: nil)+ expect(response.parsed_body["success"]).to eq(false)+ end++ it "denies anonymous users, regular users, and moderators" do+ post "/admin/plugins/discourse-captcha/test.json", params: params+ expect(response.status).to eq(404)++ [user, moderator].each do |actor|+ sign_in(actor)+ post "/admin/plugins/discourse-captcha/test.json", params: params+ expect(response.status).to eq(404)+ end+ end+ end+enddiff --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.gjsnew file mode 100644index 00000000000..1a0484c0f15--- /dev/null+++ b/plugins/discourse-captcha/test/javascripts/integration/components/captcha-configuration-test-test.gjs@@ -0,0 +1,293 @@+import { click, render, settled } from "@ember/test-helpers";+import { module, test } from "qunit";+import sinon from "sinon";+import { setupRenderingTest } from "discourse/tests/helpers/component-test";+import pretender, { response } from "discourse/tests/helpers/create-pretender";+import { i18n } from "discourse-i18n";+import CaptchaConfigurationTest from "discourse/plugins/discourse-captcha/discourse/components/captcha-configuration-test";++module("Integration | Component | CaptchaConfigurationTest", function (hooks) {+ setupRenderingTest(hooks);++ hooks.beforeEach(function () {+ this.configuration = {+ configured: true,+ provider: "recaptcha",+ site_key: "saved-site-key",+ };+ this.originalRecaptcha = window.grecaptcha;+ this.originalHcaptcha = window.hcaptcha;+ this.originalRecaptchaCallback = window.discourseReCaptchaCallback;+ window.grecaptcha = window.hcaptcha = {+ render: (element, options) => {+ this.widgetOptions = options;+ return 1;+ },+ };+ });++ hooks.afterEach(function () {+ this.scriptStub?.restore();+ window.discourseReCaptchaCallback = this.originalRecaptchaCallback;+ window.grecaptcha = this.originalRecaptcha;+ window.hcaptcha = this.originalHcaptcha;+ });++ test("verifies saved keys and keeps signup state separate", async function (assert) {+ const captchaService = this.owner.lookup("service:captcha-service");+ captchaService.token = "signup-token";+ captchaService.invalid = false;+ pretender.post("/admin/plugins/discourse-captcha/test.json", (request) => {+ const data = new URLSearchParams(request.requestBody);+ assert.strictEqual(+ data.get("token"),+ "test-token",+ "sends the challenge token"+ );+ assert.strictEqual(+ data.get("site_key"),+ "saved-site-key",+ "identifies the tested site key"+ );+ assert.strictEqual(+ data.get("provider"),+ "recaptcha",+ "identifies the tested provider"+ );+ return response({ success: true, message: "Verification succeeded." });+ });++ await render(+ <template>+ <CaptchaConfigurationTest @configuration={{this.configuration}} />+ </template>+ );+ assert+ .dom("#g-recaptcha")+ .doesNotExist("waits for an explicit test action");+ await click(".captcha-configuration-test .btn-primary");+ assert.strictEqual(+ this.widgetOptions.sitekey,+ "saved-site-key",+ "renders the saved site key"+ );++ this.widgetOptions.callback("test-token");+ await settled();++ assert+ .dom(".alert-success")+ .hasText("Verification succeeded.", "displays the verification result");+ assert.strictEqual(+ captchaService.token,+ "signup-token",+ "preserves the signup token"+ );+ assert.false(captchaService.invalid, "preserves signup validity");+ assert+ .dom(".captcha-configuration-test .btn-primary")+ .hasText(+ i18n("discourse_captcha.configuration_test.retry"),+ "offers another test"+ );+ });++ test("shows provider failures and allows a fresh challenge", async function (assert) {+ this.configuration.provider = "hcaptcha";+ pretender.post("/admin/plugins/discourse-captcha/test.json", () =>+ response({ success: false, message: "The secret key was rejected." })+ );++ await render(+ <template>+ <CaptchaConfigurationTest @configuration={{this.configuration}} />+ </template>+ );+ await click(".captcha-configuration-test .btn-primary");+ this.widgetOptions.callback("test-token");+ await settled();++ assert+ .dom(".alert-error")+ .hasText("The secret key was rejected.", "displays the provider failure");++ await click(".captcha-configuration-test .btn-primary");+ assert.dom("#h-captcha-field").exists("renders a new hCaptcha challenge");+ assert.dom(".alert-error").doesNotExist("clears the previous result");+ });++ test("handles expiration and widget errors", async function (assert) {+ await render(+ <template>+ <CaptchaConfigurationTest @configuration={{this.configuration}} />+ </template>+ );+ await click(".captcha-configuration-test .btn-primary");+ this.widgetOptions["expired-callback"]();+ await settled();++ assert+ .dom(".alert-error")+ .hasText(+ i18n("discourse_captcha.configuration_test.expired"),+ "explains expiration"+ );++ await click(".captcha-configuration-test .btn-primary");+ this.widgetOptions["error-callback"]();+ await settled();++ assert+ .dom(".alert-error")+ .hasText(+ i18n("discourse_captcha.configuration_test.challenge_failed"),+ "explains a widget failure"+ );+ assert.dom("#g-recaptcha").exists("keeps provider error details visible");+ assert+ .dom(".captcha-configuration-test")+ .doesNotIncludeText(+ i18n("discourse_captcha.configuration_test.complete_challenge"),+ "hides completion instructions after failure"+ );+ await click(".captcha-configuration-test .btn-primary");+ assert.dom(".alert-error").doesNotExist("clears the failed state on retry");+ });++ test("offers a retry when the provider script fails to load", async function (assert) {+ const captchaApi = window.grecaptcha;+ delete window.grecaptcha;+ const appendChild = document.head.appendChild;+ this.scriptStub = sinon+ .stub(document.head, "appendChild")+ .callsFake(function (element) {+ if (+ element.tagName === "SCRIPT" &&+ element.src.includes("/recaptcha/api.js")+ ) {+ queueMicrotask(() => element.dispatchEvent(new Event("error")));+ return element;+ }+ return appendChild.call(this, element);+ });++ await render(+ <template>+ <CaptchaConfigurationTest @configuration={{this.configuration}} />+ </template>+ );+ await click(".captcha-configuration-test .btn-primary");++ assert+ .dom(".alert-error")+ .exists({ count: 1 }, "shows a single failure message");+ assert+ .dom(".captcha-configuration-test")+ .doesNotIncludeText(+ i18n("discourse_captcha.configuration_test.complete_challenge"),+ "hides instructions for the unavailable challenge"+ );+ assert+ .dom(".captcha-configuration-test .btn-primary")+ .hasText(+ i18n("discourse_captcha.configuration_test.retry"),+ "offers a retry"+ );++ window.grecaptcha = captchaApi;+ await click(".captcha-configuration-test .btn-primary");+ assert.dom("#g-recaptcha").exists("loads the challenge after recovery");+ assert.dom(".alert-error").doesNotExist("clears the failure");+ });++ for (const provider of ["recaptcha", "hcaptcha"]) {+ test(`${provider} ignores callbacks from a replaced challenge`, async function (assert) {+ this.configuration.provider = provider;+ let verificationRequests = 0;+ pretender.post("/admin/plugins/discourse-captcha/test.json", () => {+ verificationRequests++;+ return response({ success: true, message: "Verified" });+ });++ await render(+ <template>+ <CaptchaConfigurationTest @configuration={{this.configuration}} />+ </template>+ );+ await click(".captcha-configuration-test .btn-primary");+ const previousWidget = this.widgetOptions;+ previousWidget["error-callback"]();+ await settled();+ await click(".captcha-configuration-test .btn-primary");++ previousWidget["expired-callback"]();+ previousWidget["error-callback"]();+ previousWidget.callback("old-token");+ await settled();++ assert+ .dom(".captcha-container")+ .exists("keeps the current challenge visible");+ assert+ .dom(".alert-error")+ .doesNotExist("ignores previous errors and expiration");+ assert.strictEqual(+ verificationRequests,+ 0,+ "does not verify an old challenge token"+ );++ this.widgetOptions.callback("current-token");+ await settled();+ assert+ .dom(".alert-success")+ .hasText("Verified", "the current challenge still works");+ assert.strictEqual(+ verificationRequests,+ 1,+ "verifies only the current challenge"+ );+ });+ }++ test("explains missing configuration before loading a challenge", async function (assert) {+ this.configuration.configured = false;++ await render(+ <template>+ <CaptchaConfigurationTest @configuration={{this.configuration}} />+ </template>+ );++ assert+ .dom(".alert-info")+ .hasText(+ i18n("discourse_captcha.configuration_test.not_configured"),+ "explains which settings are needed"+ );+ assert+ .dom(".captcha-configuration-test button")+ .doesNotExist("does not offer an unconfigured test");+ });++ test("displays request errors", async function (assert) {+ pretender.post("/admin/plugins/discourse-captcha/test.json", () =>+ response(429, { errors: ["Please wait before trying again."] })+ );+ await render(+ <template>+ <CaptchaConfigurationTest @configuration={{this.configuration}} />+ </template>+ );+ await click(".captcha-configuration-test .btn-primary");+ this.widgetOptions.callback("test-token");+ await settled();++ assert.dom(".alert-error").hasText(+ i18n("generic_error_with_reason", {+ error: "Please wait before trying again.",+ }),+ "displays the server error"+ );+ });+});