A platform for community discussion. Free, open, simple.
FEATURE: Add recaptcha provider to hcaptcha plugin (#39018)
Gabriel Grubbaeccaa62a85ae
diff --git a/db/structure.sql b/db/structure.sqlindex 22823141632..b8766be32e6 100644--- a/db/structure.sql+++ b/db/structure.sql@@ -21953,6 +21953,7 @@ INSERT INTO "schema_migrations" (version) VALUES('20260422130653'),('20260422102523'),('20260422062938'),+('20260422000000'),('20260421061908'),('20260420014648'),('20260415082426'),diff --git a/frontend/discourse/app/lib/registry/transformers.js b/frontend/discourse/app/lib/registry/transformers.jsindex 955f0ed4cdf..5e717fe9735 100644--- a/frontend/discourse/app/lib/registry/transformers.js+++ b/frontend/discourse/app/lib/registry/transformers.js@@ -12,6 +12,7 @@ export const BEHAVIOR_TRANSFORMERS = Object.freeze(["composer-actions-on-select","composer-position:correct-scroll-position","composer-position:editor-touch-move",+ "create-account","custom-homepage-model","discovery-topic-list-load-more","full-page-search-load-more",diff --git a/frontend/discourse/app/models/user.js b/frontend/discourse/app/models/user.jsindex a45fd94d8c8..0fcc5f91c64 100644--- a/frontend/discourse/app/models/user.js+++ b/frontend/discourse/app/models/user.js@@ -34,6 +34,7 @@ import PreloadStore from "discourse/lib/preload-store";import singleton from "discourse/lib/singleton";import { emojiUnescape } from "discourse/lib/text";import { autoTrackedArray } from "discourse/lib/tracked-tools";+import { applyBehaviorTransformer } from "discourse/lib/transformer";import { userPath } from "discourse/lib/url";import { defaultHomepage, escapeExpression } from "discourse/lib/utilities";import Badge from "discourse/models/badge";@@ -1508,7 +1509,7 @@ User.reopenClass({return result;},- createAccount(attrs) {+ async createAccount(attrs) {let data = {name: attrs.accountName,email: attrs.accountEmail,@@ -1524,10 +1525,15 @@ User.reopenClass({data.invite_code = attrs.inviteCode;}- return ajax(userPath(), {- data,- type: "POST",- });+ return applyBehaviorTransformer(+ "create-account",+ () =>+ ajax(userPath(), {+ data,+ type: "POST",+ }),+ { data }+ );},_saveTimezone(user) {diff --git a/plugins/discourse-hcaptcha/app/controllers/discourse_hcaptcha/captcha_controller.rb b/plugins/discourse-hcaptcha/app/controllers/discourse_hcaptcha/captcha_controller.rbnew file mode 100644index 00000000000..715ff7a3935--- /dev/null+++ b/plugins/discourse-hcaptcha/app/controllers/discourse_hcaptcha/captcha_controller.rb@@ -0,0 +1,27 @@+# frozen_string_literal: true++module DiscourseHcaptcha+ class CaptchaController < ::ApplicationController+ requires_plugin PLUGIN_NAME++ before_action :ensure_config+ skip_before_action :redirect_to_login_if_required++ TOKEN_TTL = 2.minutes++ def create+ server_session.set(token_key, params[:token], expires: TOKEN_TTL)+ render json: { success: "OK" }+ end++ private++ def ensure_config+ raise NotImplementedError+ end++ def token_key+ raise NotImplementedError+ end+ end+enddiff --git a/plugins/discourse-hcaptcha/app/controllers/discourse_hcaptcha/hcaptcha_controller.rb b/plugins/discourse-hcaptcha/app/controllers/discourse_hcaptcha/hcaptcha_controller.rbindex 0c35a0266c6..6e17391e280 100644--- a/plugins/discourse-hcaptcha/app/controllers/discourse_hcaptcha/hcaptcha_controller.rb+++ b/plugins/discourse-hcaptcha/app/controllers/discourse_hcaptcha/hcaptcha_controller.rb@@ -1,46 +1,20 @@# frozen_string_literal: truemodule DiscourseHcaptcha- class HcaptchaController < ::ApplicationController+ class HcaptchaController < DiscourseHcaptcha::CaptchaControllerrequires_plugin PLUGIN_NAME- before_action :ensure_config- skip_before_action :redirect_to_login_if_required-- TOKEN_TTL = 2.minutes- protect_from_forgery except: [:create]-- def create- temp_id = SecureRandom.uuid- store_token_in_redis(temp_id)- set_encrypted_cookie(temp_id)-- render json: { success: "OK" }- end-privatedef ensure_config- raise "not enabled" unless SiteSetting.discourse_hcaptcha_enabled- raise "token is missing" if params[:token].blank?- end-- def store_token_in_redis(temp_id)- Discourse.redis.setex("hCaptchaToken_#{temp_id}", TOKEN_TTL.to_i, params[:token])- end-- def set_encrypted_cookie(temp_id)- cookies.encrypted[:h_captcha_temp_id] = cookie_options.merge({ value: temp_id })+ unless SiteSetting.discourse_captcha_provider == CaptchaProvider::HCAPTCHA+ raise Discourse::NotFound+ end+ raise Discourse::InvalidParameters.new(:token) if params[:token].blank?end- def cookie_options- same_site = SiteSetting.same_site_cookies == "Disabled" ? nil : SiteSetting.same_site_cookies- {- httponly: true,- secure: SiteSetting.force_https,- expires: TOKEN_TTL.from_now,- same_site: same_site,- }.compact+ def token_key+ "hcaptcha_token"endendenddiff --git a/plugins/discourse-hcaptcha/app/controllers/discourse_hcaptcha/recaptcha_controller.rb b/plugins/discourse-hcaptcha/app/controllers/discourse_hcaptcha/recaptcha_controller.rbnew file mode 100644index 00000000000..2ea11455c6d--- /dev/null+++ b/plugins/discourse-hcaptcha/app/controllers/discourse_hcaptcha/recaptcha_controller.rb@@ -0,0 +1,20 @@+# frozen_string_literal: true++module DiscourseHcaptcha+ class RecaptchaController < DiscourseHcaptcha::CaptchaController+ requires_plugin PLUGIN_NAME++ private++ def ensure_config+ unless SiteSetting.discourse_captcha_provider == CaptchaProvider::RECAPTCHA+ raise Discourse::NotFound+ end+ raise Discourse::InvalidParameters.new(:token) if params[:token].blank?+ end++ def token_key+ "recaptcha_token"+ end+ end+enddiff --git a/plugins/discourse-hcaptcha/app/services/problem_check/hcaptcha_configuration.rb b/plugins/discourse-hcaptcha/app/services/problem_check/hcaptcha_configuration.rbindex 2878b9185ad..06c607fec13 100644--- a/plugins/discourse-hcaptcha/app/services/problem_check/hcaptcha_configuration.rb+++ b/plugins/discourse-hcaptcha/app/services/problem_check/hcaptcha_configuration.rb@@ -4,14 +4,18 @@ class ProblemCheck::HcaptchaConfiguration < ProblemCheckself.priority = "high"def call- return problem if SiteSetting.discourse_hcaptcha_enabled && !hcaptcha_credentias_present?+ if SiteSetting.discourse_captcha_enabled &&+ SiteSetting.discourse_captcha_provider == DiscourseHcaptcha::CaptchaProvider::HCAPTCHA &&+ !hcaptcha_credentials_present?+ return problem+ endno_problemendprivate- def hcaptcha_credentias_present?+ def hcaptcha_credentials_present?SiteSetting.hcaptcha_site_key.present? && SiteSetting.hcaptcha_secret_key.present?endenddiff --git a/plugins/discourse-hcaptcha/app/services/problem_check/recaptcha_configuration.rb b/plugins/discourse-hcaptcha/app/services/problem_check/recaptcha_configuration.rbnew file mode 100644index 00000000000..11c90a20388--- /dev/null+++ b/plugins/discourse-hcaptcha/app/services/problem_check/recaptcha_configuration.rb@@ -0,0 +1,20 @@+# frozen_string_literal: true++class ProblemCheck::RecaptchaConfiguration < ProblemCheck+ self.priority = "high"++ def call+ if SiteSetting.discourse_captcha_enabled &&+ SiteSetting.discourse_captcha_provider == DiscourseHcaptcha::CaptchaProvider::RECAPTCHA &&+ !recaptcha_credentials_present?+ return problem+ end+ no_problem+ end++ private++ def recaptcha_credentials_present?+ SiteSetting.recaptcha_site_key.present? && SiteSetting.recaptcha_secret_key.present?+ end+enddiff --git a/plugins/discourse-hcaptcha/assets/javascripts/discourse/components/base-captcha.gjs b/plugins/discourse-hcaptcha/assets/javascripts/discourse/components/base-captcha.gjsnew file mode 100644index 00000000000..b943f0b44eb--- /dev/null+++ b/plugins/discourse-hcaptcha/assets/javascripts/discourse/components/base-captcha.gjs@@ -0,0 +1,110 @@+import Component from "@glimmer/component";+import { tracked } from "@glimmer/tracking";+import { service } from "@ember/service";+import { modifier as modifierFn } from "ember-modifier";+import { bind } from "discourse/lib/decorators";+import loadScript from "discourse/lib/load-script";+import DAsyncContent from "discourse/ui-kit/d-async-content";+import DInputTip from "discourse/ui-kit/d-input-tip";+import { i18n } from "discourse-i18n";++export default class BaseCaptcha extends Component {+ @service captchaService;++ @tracked widgetId;++ renderCaptcha = modifierFn((element, _, { captchaApi }) => {+ if (!captchaApi || !this.siteKey) {+ return;+ }++ const renderOptions = {+ sitekey: this.siteKey,+ callback: (response) => {+ this.captchaService.token = response;+ this.captchaService.invalid = !response;+ },+ "expired-callback": () => {+ this.captchaService.invalid = true;+ },+ ...this.additionalRenderOptions(),+ };++ this.widgetId = captchaApi.render(element, renderOptions);+ this.captchaService.registerWidget(captchaApi, this.widgetId);+ });++ get siteKey() {+ return this.args.siteKey;+ }++ get captchaErrorKey() {+ return "discourse_captcha.contact_system_administrator";+ }++ get scriptUrl() {+ throw new Error("Subclasses must implement 'scriptUrl'");+ }++ get callbackName() {+ throw new Error("Subclasses must implement 'callbackName'");+ }++ get captchaApiName() {+ throw new Error("Subclasses must implement 'captchaApiName'");+ }++ get providerName() {+ throw new Error("Subclasses must implement 'providerName'");+ }++ get containerId() {+ throw new Error("Subclasses must implement 'containerId'");+ }++ @bind+ async loadCaptchaScript() {+ if (window[this.captchaApiName]) {+ return window[this.captchaApiName];+ }++ return new Promise((resolve, reject) => {+ window[this.callbackName] = () => {+ resolve(window[this.captchaApiName]);+ };++ loadScript(this.scriptUrl).catch(reject);+ });+ }++ additionalRenderOptions() {+ return {};+ }++ <template>+ <DAsyncContent @asyncData={{this.loadCaptchaScript}}>+ <:loading>+ <div class="captcha-container captcha-loading">+ {{i18n "loading"}}+ </div>+ </:loading>+ <:content as |captchaApi|>+ <div+ id={{this.containerId}}+ class="captcha-container"+ data-sitekey={{@siteKey}}+ {{this.renderCaptcha captchaApi=captchaApi}}+ ></div>+ </:content>+ <:error>+ <div class="alert alert-error">+ {{i18n this.captchaErrorKey}}+ </div>+ </:error>+ </DAsyncContent>++ {{#if this.captchaService.submitFailed}}+ <DInputTip @validation={{this.captchaService.inputValidation}} />+ {{/if}}+ </template>+}diff --git a/plugins/discourse-hcaptcha/assets/javascripts/discourse/components/h-captcha.gjs b/plugins/discourse-hcaptcha/assets/javascripts/discourse/components/h-captcha.gjsindex e10f6b672cf..8956d8ceb25 100644--- a/plugins/discourse-hcaptcha/assets/javascripts/discourse/components/h-captcha.gjs+++ b/plugins/discourse-hcaptcha/assets/javascripts/discourse/components/h-captcha.gjs@@ -1,88 +1,33 @@-import Component from "@glimmer/component";-import { tracked } from "@glimmer/tracking";-import { next } from "@ember/runloop";-import { service } from "@ember/service";-import loadScript from "discourse/lib/load-script";-import DInputTip from "discourse/ui-kit/d-input-tip";-import { i18n } from "discourse-i18n";+import BaseCaptcha from "./base-captcha";-const HCAPTCHA_SCRIPT_URL = "https://hcaptcha.com/1/api.js?render=explicit";--export default class HCaptcha extends Component {- @service hCaptchaService;-- @tracked widgetId;- @tracked hCaptchaConfigError = "";- hCaptcha;-- constructor() {- super(...arguments);- this.initializeHCaptcha(this.args.siteKey);+export default class HCaptcha extends BaseCaptcha {+ get scriptUrl() {+ return "https://js.hcaptcha.com/1/api.js?onload=discourseHCaptchaCallback&render=explicit";}- willDestroy() {- super.willDestroy(...arguments);- if (this.isHCaptchaLoaded()) {- this.hCaptcha.reset(this.widgetId);- }+ get callbackName() {+ return "discourseHCaptchaCallback";}- initializeHCaptcha(siteKey) {- if (this.isHCaptchaLoaded()) {- next(() => {- if (document.getElementById("h-captcha-field")) {- this.renderHCaptcha(siteKey);- }- });- return;- }-- this.loadHCaptchaScript(siteKey);+ get captchaApiName() {+ return "hcaptcha";}- isHCaptchaLoaded() {- return typeof this.hCaptcha !== "undefined";+ get providerName() {+ return "hCaptcha";}- async loadHCaptchaScript(siteKey) {- await loadScript(HCAPTCHA_SCRIPT_URL);- this.hCaptcha = window.hcaptcha;- this.renderHCaptcha(siteKey);+ get containerId() {+ return "h-captcha-field";}- renderHCaptcha(siteKey) {- if (!this.isHCaptchaLoaded() || !this.args.siteKey) {- this.hCaptchaConfigError = i18n(- "discourse_hCaptcha.contact_system_administrator"- );- return;- }-- this.widgetId = this.hCaptcha.render("h-captcha-field", {- sitekey: siteKey,- callback: (response) => {- this.hCaptchaService.token = response;- this.hCaptchaService.invalid = !response;+ additionalRenderOptions() {+ return {+ "error-callback": (error) => {+ // eslint-disable-next-line no-console+ console.error("hCaptcha error:", error);+ this.captchaService.invalid = true;},- "expired-callback": () => {- this.hCaptchaService.invalid = true;- },- });-- this.hCaptchaService.registerWidget(this.hCaptcha, this.widgetId);+ };}-- <template>- <div id="h-captcha-field" class="h-captcha" data-sitekey={{@sitekey}}></div>-- {{#if this.hCaptchaConfigError}}- <div class="alert alert-error">- {{this.hCaptchaConfigError}}- </div>- {{/if}}-- {{#if this.hCaptchaService.submitFailed}}- <DInputTip @validation={{this.hCaptchaService.inputValidation}} />- {{/if}}- </template>}diff --git a/plugins/discourse-hcaptcha/assets/javascripts/discourse/components/re-captcha.gjs b/plugins/discourse-hcaptcha/assets/javascripts/discourse/components/re-captcha.gjsnew file mode 100644index 00000000000..7712ad82326--- /dev/null+++ b/plugins/discourse-hcaptcha/assets/javascripts/discourse/components/re-captcha.gjs@@ -0,0 +1,23 @@+import BaseCaptcha from "./base-captcha";++export default class ReCaptcha extends BaseCaptcha {+ get scriptUrl() {+ return "https://www.google.com/recaptcha/api.js?onload=discourseReCaptchaCallback&render=explicit";+ }++ get callbackName() {+ return "discourseReCaptchaCallback";+ }++ get captchaApiName() {+ return "grecaptcha";+ }++ get providerName() {+ return "reCaptcha";+ }++ get containerId() {+ return "g-recaptcha";+ }+}diff --git a/plugins/discourse-hcaptcha/assets/javascripts/discourse/connectors/create-account-after-user-fields/captcha-fields-connector.gjs b/plugins/discourse-hcaptcha/assets/javascripts/discourse/connectors/create-account-after-user-fields/captcha-fields-connector.gjsnew file mode 100644index 00000000000..521371ba8b5--- /dev/null+++ b/plugins/discourse-hcaptcha/assets/javascripts/discourse/connectors/create-account-after-user-fields/captcha-fields-connector.gjs@@ -0,0 +1,29 @@+/* eslint-disable ember/no-classic-components */+import Component from "@ember/component";+import { service } from "@ember/service";+import { tagName } from "@ember-decorators/component";+import { eq } from "discourse/truth-helpers";+import HCaptcha from "../../components/h-captcha";+import ReCaptcha from "../../components/re-captcha";++@tagName("")+export default class CaptchaFieldsConnector extends Component {+ @service siteSettings;++ <template>+ <div+ class="create-account-after-user-fields-outlet captcha-fields-connector"+ ...attributes+ >+ <div class="input-group">+ {{#if (eq this.siteSettings.discourse_captcha_provider "hcaptcha")}}+ <HCaptcha @siteKey={{this.siteSettings.hcaptcha_site_key}} />+ {{else if+ (eq this.siteSettings.discourse_captcha_provider "recaptcha")+ }}+ <ReCaptcha @siteKey={{this.siteSettings.recaptcha_site_key}} />+ {{/if}}+ </div>+ </div>+ </template>+}diff --git a/plugins/discourse-hcaptcha/assets/javascripts/discourse/connectors/create-account-after-user-fields/hcaptcha-fields-connector.gjs b/plugins/discourse-hcaptcha/assets/javascripts/discourse/connectors/create-account-after-user-fields/hcaptcha-fields-connector.gjsdeleted file mode 100644index b5bc2546bf8..00000000000--- a/plugins/discourse-hcaptcha/assets/javascripts/discourse/connectors/create-account-after-user-fields/hcaptcha-fields-connector.gjs+++ /dev/null@@ -1,18 +0,0 @@-/* eslint-disable ember/no-classic-components */-import Component from "@ember/component";-import { tagName } from "@ember-decorators/component";-import HCaptcha from "../../components/h-captcha";--@tagName("")-export default class HcaptchaFieldsConnector extends Component {- <template>- <div- class="create-account-after-user-fields-outlet hcaptcha-fields-connector"- ...attributes- >- <div class="input-group">- <HCaptcha @siteKey={{this.siteSettings.hcaptcha_site_key}} />- </div>- </div>- </template>-}diff --git a/plugins/discourse-hcaptcha/assets/javascripts/discourse/services/h-captcha-service.js b/plugins/discourse-hcaptcha/assets/javascripts/discourse/services/captcha-service.jssimilarity index 74%rename from plugins/discourse-hcaptcha/assets/javascripts/discourse/services/h-captcha-service.jsrename to plugins/discourse-hcaptcha/assets/javascripts/discourse/services/captcha-service.jsindex f1ba9302231..d28c01f0335 100644--- a/plugins/discourse-hcaptcha/assets/javascripts/discourse/services/h-captcha-service.js+++ b/plugins/discourse-hcaptcha/assets/javascripts/discourse/services/captcha-service.js@@ -5,12 +5,12 @@ import { disableImplicitInjections } from "discourse/lib/implicit-injections";import { i18n } from "discourse-i18n";@disableImplicitInjections-export default class hCaptchaService extends Service {+export default class CaptchaService extends Service {@tracked invalid = true;@tracked submitted = false;@tracked token = null;widgetId = null;- hCaptcha = null;+ captcha = null;get submitFailed() {return this.submitted && this.invalid;@@ -19,12 +19,12 @@ export default class hCaptchaService extends Service {get inputValidation() {return EmberObject.create({failed: this.invalid,- reason: i18n("discourse_hCaptcha.missing_token"),+ reason: i18n("discourse_captcha.missing_token"),});}- registerWidget(hCaptcha, id) {- this.hCaptcha = hCaptcha;+ registerWidget(captcha, id) {+ this.captcha = captcha;this.widgetId = id;}@@ -32,6 +32,6 @@ export default class hCaptchaService extends Service {this.invalid = true;this.submitted = false;this.token = null;- this.hCaptcha.reset(this.widgetId);+ this.captcha.reset(this.widgetId);}}diff --git a/plugins/discourse-hcaptcha/assets/javascripts/pre-initializers/h-captcha.js b/plugins/discourse-hcaptcha/assets/javascripts/pre-initializers/h-captcha.jsindex 04c59b1bcf7..314afd0d88d 100644--- a/plugins/discourse-hcaptcha/assets/javascripts/pre-initializers/h-captcha.js+++ b/plugins/discourse-hcaptcha/assets/javascripts/pre-initializers/h-captcha.js@@ -1,50 +1,56 @@-import { Promise } from "rsvp";import { ajax } from "discourse/lib/ajax";-import { getOwnerWithFallback } from "discourse/lib/get-owner";import { withPluginApi } from "discourse/lib/plugin-api";+import { i18n } from "discourse-i18n";-const PLUGIN_ID = "discourse-hCaptcha";+function captchaSelector(siteSettings) {+ if (siteSettings.discourse_captcha_provider !== "none") {+ return siteSettings.discourse_captcha_provider;+ } else {+ return false;+ }+}function initializeHCaptcha(api, container) {const siteSettings = container.lookup("service:site-settings");- if (!siteSettings.discourse_hcaptcha_enabled) {+ if (+ !siteSettings.discourse_captcha_enabled ||+ !captchaSelector(siteSettings)+ ) {return;}- api.modifyClassStatic("model:user", {- pluginId: PLUGIN_ID,+ api.registerBehaviorTransformer("create-account", async ({ next }) => {+ const captchaService = container.lookup("service:captcha-service");+ captchaService.submitted = true;- createAccount() {- const hCaptchaService = getOwnerWithFallback(this).lookup(- "service:h-captcha-service"- );- hCaptchaService.submitted = true;+ if (captchaService.invalid) {+ return {+ success: false,+ message: i18n("discourse_captcha.missing_token"),+ };+ }- if (hCaptchaService.invalid) {- return Promise.reject();- }+ const captchaRoute = captchaSelector(siteSettings);- const data = {- token: hCaptchaService.token,+ try {+ await ajax(`/captcha/${captchaRoute}/create.json`, {+ data: { token: captchaService.token },+ type: "POST",+ });+ } catch {+ captchaService.reset();+ return {+ success: false,+ message: i18n("discourse_captcha.verification_failed"),};+ }- const originalAccountCreation = this._super;- return ajax("/hcaptcha/create.json", {- data,- type: "POST",- })- .then(() => {- return originalAccountCreation(...arguments);- })- .catch(() => {- hCaptchaService.failed = true;- return Promise.reject();- })- .finally(() => {- hCaptchaService.reset();- });- },+ try {+ return await next();+ } finally {+ captchaService.reset();+ }});}diff --git a/plugins/discourse-hcaptcha/config/locales/client.en.yml b/plugins/discourse-hcaptcha/config/locales/client.en.ymlindex b4546855382..856cba13552 100644--- a/plugins/discourse-hcaptcha/config/locales/client.en.yml+++ b/plugins/discourse-hcaptcha/config/locales/client.en.yml@@ -1,12 +1,13 @@en:js:- discourse_hCaptcha:- missing_token: "Please complete the hCaptcha challenge."+ discourse_captcha:+ missing_token: "Please complete the captcha challenge."+ verification_failed: "Captcha verification failed. Please try again."placeholder: placeholder- contact_system_administrator: "There has been a problem with hCaptcha, if this problem persists please contact a system administrator"+ contact_system_administrator: "There has been a problem with your captcha provider, if this problem persists please contact a system administrator"admin_js:admin:site_settings:categories:- discourse_hcaptcha: "Discourse hCaptcha"\ No newline at end of file+ discourse_hcaptcha: "Discourse hCaptcha"diff --git a/plugins/discourse-hcaptcha/config/locales/server.en.yml b/plugins/discourse-hcaptcha/config/locales/server.en.ymlindex 5ae8c96eb16..253fcb4eccd 100644--- a/plugins/discourse-hcaptcha/config/locales/server.en.yml+++ b/plugins/discourse-hcaptcha/config/locales/server.en.yml@@ -2,15 +2,20 @@ en:dashboard: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"- admin:+ admin:site_settings:categories:discourse_hcaptcha: "hCaptcha Plugin"-+site_settings:- discourse_hcaptcha_enabled: "Enable the hCaptcha Plugin. Requires <a target='blank' href='https://hcaptcha.com'>hcaptcha.com</a> account."+ discourse_captcha_enabled: "Enable captcha verification for new user registrations. Requires configuring either hCaptcha or reCaptcha below."+ 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"- h_captcha_verification_failed: "hCaptcha verification failed"+ 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-hcaptcha/config/routes.rb b/plugins/discourse-hcaptcha/config/routes.rbindex 47fe13566e2..0f28e58d241 100644--- a/plugins/discourse-hcaptcha/config/routes.rb+++ b/plugins/discourse-hcaptcha/config/routes.rb@@ -1,5 +1,8 @@# frozen_string_literal: true-Discourse::Application.routes.draw { mount DiscourseHcaptcha::Engine, at: "hcaptcha" }+Discourse::Application.routes.draw { mount DiscourseHcaptcha::Engine, at: "captcha" }-DiscourseHcaptcha::Engine.routes.draw { post "/create" => "hcaptcha#create" }+DiscourseHcaptcha::Engine.routes.draw do+ post "/hcaptcha/create" => "hcaptcha#create"+ post "/recaptcha/create" => "recaptcha#create"+enddiff --git a/plugins/discourse-hcaptcha/config/settings.yml b/plugins/discourse-hcaptcha/config/settings.ymlindex 1d76ccd98b2..e5f1b1c4481 100644--- a/plugins/discourse-hcaptcha/config/settings.yml+++ b/plugins/discourse-hcaptcha/config/settings.yml@@ -1,7 +1,15 @@discourse_hcaptcha:- discourse_hcaptcha_enabled:+ discourse_captcha_enabled:default: falseclient: true+ discourse_captcha_provider:+ default: "none"+ client: true+ type: enum+ choices:+ - hcaptcha+ - recaptcha+ - nonehcaptcha_site_key:default: ''client: true@@ -9,3 +17,10 @@ discourse_hcaptcha:default: ''client: falsesecret: true+ recaptcha_site_key:+ default: ''+ client: true+ recaptcha_secret_key:+ default: ''+ client: false+ secret: truediff --git a/plugins/discourse-hcaptcha/db/migrate/20260422000000_migrate_hcaptcha_enabled_to_captcha_settings.rb b/plugins/discourse-hcaptcha/db/migrate/20260422000000_migrate_hcaptcha_enabled_to_captcha_settings.rbnew file mode 100644index 00000000000..774f1bc7ccb--- /dev/null+++ b/plugins/discourse-hcaptcha/db/migrate/20260422000000_migrate_hcaptcha_enabled_to_captcha_settings.rb@@ -0,0 +1,30 @@+# frozen_string_literal: true++class MigrateHcaptchaEnabledToCaptchaSettings < ActiveRecord::Migration[7.2]+ def up+ hcaptcha_was_enabled =+ DB.query_single(+ "SELECT value FROM site_settings WHERE name = 'discourse_hcaptcha_enabled'",+ ).first++ return if hcaptcha_was_enabled != "t"++ execute <<~SQL+ INSERT INTO site_settings (name, data_type, value, created_at, updated_at)+ VALUES ('discourse_captcha_enabled', 5, 't', NOW(), NOW())+ ON CONFLICT (name) DO UPDATE SET value = 't', updated_at = NOW()+ SQL++ execute <<~SQL+ INSERT INTO site_settings (name, data_type, value, created_at, updated_at)+ VALUES ('discourse_captcha_provider', 7, 'hcaptcha', NOW(), NOW())+ ON CONFLICT (name) DO UPDATE SET value = 'hcaptcha', updated_at = NOW()+ SQL++ execute "DELETE FROM site_settings WHERE name = 'discourse_hcaptcha_enabled'"+ end++ def down+ raise ActiveRecord::IrreversibleMigration+ end+enddiff --git a/plugins/discourse-hcaptcha/lib/discourse_hcaptcha/captcha_provider.rb b/plugins/discourse-hcaptcha/lib/discourse_hcaptcha/captcha_provider.rbnew file mode 100644index 00000000000..1621558810e--- /dev/null+++ b/plugins/discourse-hcaptcha/lib/discourse_hcaptcha/captcha_provider.rb@@ -0,0 +1,35 @@+# frozen_string_literal: true++module DiscourseHcaptcha+ class CaptchaProvider+ HCAPTCHA = "hcaptcha"+ RECAPTCHA = "recaptcha"+ NONE = "none"++ def fetch_captcha_token(server_session)+ raise NotImplementedError+ end++ def captcha_verification_url+ raise NotImplementedError+ end++ def send_captcha_verification(captcha_token)+ raise NotImplementedError+ end++ protected++ def send_verification(captcha_token, captcha_verification_url, secret_key)+ uri = URI.parse(captcha_verification_url)++ http = FinalDestination::HTTP.new(uri.host, uri.port)+ http.use_ssl = true++ request = FinalDestination::HTTP::Post.new(uri.request_uri)+ request.set_form_data({ "secret" => secret_key, "response" => captcha_token })++ http.request(request)+ end+ end+enddiff --git a/plugins/discourse-hcaptcha/lib/discourse_hcaptcha/create_users_controller_patch.rb b/plugins/discourse-hcaptcha/lib/discourse_hcaptcha/create_users_controller_patch.rbindex e3fc89ae62c..189831d9fae 100644--- a/plugins/discourse-hcaptcha/lib/discourse_hcaptcha/create_users_controller_patch.rb+++ b/plugins/discourse-hcaptcha/lib/discourse_hcaptcha/create_users_controller_patch.rb@@ -2,56 +2,46 @@module DiscourseHcaptchamodule CreateUsersControllerPatch- H_CAPTCHA_VERIFICATION_URL = "https://hcaptcha.com/siteverify"-extend ActiveSupport::Concern- included { before_action :check_h_captcha, only: [:create] }-- def check_h_captcha- return unless SiteSetting.discourse_hcaptcha_enabled-- h_captcha_token = fetch_h_captcha_token- raise Discourse::InvalidAccess.new if h_captcha_token.blank?-- response = send_h_captcha_verification(h_captcha_token)-- validate_h_captcha_response(response)- rescue => e- Rails.logger.warn("Error parsing hCaptcha response: #{e}")- fail_with("h_captcha_verification_failed")- end+ included { before_action :check_captcha, only: [:create] }- private+ def check_captcha+ return unless SiteSetting.discourse_captcha_enabled+ return if SiteSetting.discourse_captcha_provider == CaptchaProvider::NONE- def send_h_captcha_verification(h_captcha_token)- uri = URI.parse(H_CAPTCHA_VERIFICATION_URL)+ captcha_provider = captcha_provider_selector+ return fail_with("captcha_not_configured") if captcha_provider.nil?- http = FinalDestination::HTTP.new(uri.host, uri.port)- http.use_ssl = true+ captcha_token = captcha_provider.fetch_captcha_token(server_session)+ raise Discourse::InvalidAccess.new if captcha_token.blank?- request = FinalDestination::HTTP::Post.new(uri.request_uri)- request.set_form_data(- { "secret" => SiteSetting.hcaptcha_secret_key, "response" => h_captcha_token },- )+ response = captcha_provider.send_captcha_verification(captcha_token)- http.request(request)+ validate_captcha_response(response)+ rescue Discourse::InvalidAccess+ fail_with("captcha_verification_failed")+ rescue StandardError => e+ Rails.logger.warn("Captcha verification error: #{e.class} - #{e.message}")+ fail_with("captcha_verification_failed")end- def fetch_h_captcha_token- temp_id = cookies.encrypted[:h_captcha_temp_id]- h_captcha_token = Discourse.redis.get("hCaptchaToken_#{temp_id}")+ private- if temp_id.present?- Discourse.redis.del("hCaptchaToken_#{temp_id}")- cookies.delete(:h_captcha_temp_id)+ def captcha_provider_selector+ case SiteSetting.discourse_captcha_provider+ when CaptchaProvider::HCAPTCHA+ if SiteSetting.hcaptcha_site_key.present? && SiteSetting.hcaptcha_secret_key.present?+ DiscourseHcaptcha::HcaptchaProvider.new+ end+ when CaptchaProvider::RECAPTCHA+ if SiteSetting.recaptcha_site_key.present? && SiteSetting.recaptcha_secret_key.present?+ DiscourseHcaptcha::RecaptchaProvider.new+ endend-- h_captcha_tokenend- def validate_h_captcha_response(response)+ def validate_captcha_response(response)raise Discourse::InvalidAccess.new if response.code.to_i >= 500-response_json = JSON.parse(response.body)if response_json["success"].nil? || response_json["success"] == falseraise Discourse::InvalidAccess.newdiff --git a/plugins/discourse-hcaptcha/lib/discourse_hcaptcha/hcaptcha_provider.rb b/plugins/discourse-hcaptcha/lib/discourse_hcaptcha/hcaptcha_provider.rbnew file mode 100644index 00000000000..4f0f30d3afd--- /dev/null+++ b/plugins/discourse-hcaptcha/lib/discourse_hcaptcha/hcaptcha_provider.rb@@ -0,0 +1,21 @@+# frozen_string_literal: true++module DiscourseHcaptcha+ class HcaptchaProvider < CaptchaProvider+ CAPTCHA_VERIFICATION_URL = "https://hcaptcha.com/siteverify"++ def fetch_captcha_token(server_session)+ token = server_session["hcaptcha_token"]+ server_session.delete("hcaptcha_token")+ token+ end++ def captcha_verification_url+ CAPTCHA_VERIFICATION_URL+ end++ def send_captcha_verification(captcha_token)+ send_verification(captcha_token, CAPTCHA_VERIFICATION_URL, SiteSetting.hcaptcha_secret_key)+ end+ end+enddiff --git a/plugins/discourse-hcaptcha/lib/discourse_hcaptcha/recaptcha_provider.rb b/plugins/discourse-hcaptcha/lib/discourse_hcaptcha/recaptcha_provider.rbnew file mode 100644index 00000000000..23decbfa535--- /dev/null+++ b/plugins/discourse-hcaptcha/lib/discourse_hcaptcha/recaptcha_provider.rb@@ -0,0 +1,21 @@+# frozen_string_literal: true++module DiscourseHcaptcha+ class RecaptchaProvider < CaptchaProvider+ CAPTCHA_VERIFICATION_URL = "https://www.google.com/recaptcha/api/siteverify"++ def fetch_captcha_token(server_session)+ token = server_session["recaptcha_token"]+ server_session.delete("recaptcha_token")+ token+ end++ def captcha_verification_url+ CAPTCHA_VERIFICATION_URL+ end++ def send_captcha_verification(captcha_token)+ send_verification(captcha_token, CAPTCHA_VERIFICATION_URL, SiteSetting.recaptcha_secret_key)+ end+ end+enddiff --git a/plugins/discourse-hcaptcha/plugin.rb b/plugins/discourse-hcaptcha/plugin.rbindex 51043b5ea81..33116b42af1 100644--- a/plugins/discourse-hcaptcha/plugin.rb+++ b/plugins/discourse-hcaptcha/plugin.rb@@ -9,21 +9,22 @@# required_version: 2.7.0# meta_topic_id: 291383-enabled_site_setting :discourse_hcaptcha_enabled+enabled_site_setting :discourse_captcha_enabledregister_svg_icon "hand"-extend_content_security_policy(script_src: %w[https://hcaptcha.com])-module ::DiscourseHcaptchaPLUGIN_NAME = "discourse-hcaptcha"endrequire_relative "lib/discourse_hcaptcha/engine"+require_relative "lib/discourse_hcaptcha/captcha_provider"after_initialize doreloadable_patch { UsersController.include(DiscourseHcaptcha::CreateUsersControllerPatch) }require_relative "app/services/problem_check/hcaptcha_configuration"+ require_relative "app/services/problem_check/recaptcha_configuration"register_problem_check ProblemCheck::HcaptchaConfiguration+ register_problem_check ProblemCheck::RecaptchaConfigurationenddiff --git a/plugins/discourse-hcaptcha/spec/lib/discourse_h_captcha/create_users_controller_patch_spec.rb b/plugins/discourse-hcaptcha/spec/lib/discourse_h_captcha/create_users_controller_patch_spec.rbindex e211494d73d..b5edb5dd9d8 100644--- a/plugins/discourse-hcaptcha/spec/lib/discourse_h_captcha/create_users_controller_patch_spec.rb+++ b/plugins/discourse-hcaptcha/spec/lib/discourse_h_captcha/create_users_controller_patch_spec.rb@@ -5,8 +5,7 @@ RSpec.describe "Users", type: :request dolet(:user_params) dohoneypot_magic({- name: "unicorn",- email: "[email protected]",+ email: "[email protected]",username: "awesomeunicorn",password: "P4ssw0rd$$",},@@ -14,11 +13,19 @@ RSpec.describe "Users", type: :request doendbefore do- SiteSetting.discourse_hcaptcha_enabled = true+ SiteSetting.enable_local_logins = true+ SiteSetting.discourse_captcha_enabled = true+ SiteSetting.discourse_captcha_provider = DiscourseHcaptcha::CaptchaProvider::NONE+SiteSetting.same_site_cookies = "Lax"++ SiteSetting.hcaptcha_site_key = "site-key"SiteSetting.hcaptcha_secret_key = "secret-key"- stub_request(:post, "https://hcaptcha.com/siteverify").with(+ SiteSetting.recaptcha_site_key = "site-key"+ SiteSetting.recaptcha_secret_key = "secret-key"++ stub_request(:post, DiscourseHcaptcha::HcaptchaProvider::CAPTCHA_VERIFICATION_URL).with(body: {secret: SiteSetting.hcaptcha_secret_key,response: "token-from-hCaptcha",@@ -26,50 +33,127 @@ RSpec.describe "Users", type: :request do).to_return(status: 200, body: '{"success":true}', headers: {})end- context "when h_captcha verification fails" do- before do- stub_request(:post, "https://hcaptcha.com/siteverify").with(- body: {- secret: SiteSetting.hcaptcha_secret_key,- response: "token-from-hCaptcha",- },- ).to_return(status: 200, body: '{"success":false}', headers: {})+ context "when captcha verification fails" do+ context "when using hCaptcha" do+ before do+ SiteSetting.discourse_captcha_provider = DiscourseHcaptcha::CaptchaProvider::HCAPTCHA+ stub_request(:post, DiscourseHcaptcha::HcaptchaProvider::CAPTCHA_VERIFICATION_URL).with(+ body: {+ secret: SiteSetting.hcaptcha_secret_key,+ response: "token-from-hCaptcha",+ },+ ).to_return(status: 200, body: '{"success":false}', headers: {})+ end++ it "fails registration" do+ post "/captcha/hcaptcha/create.json", params: { token: "token-from-hCaptcha" }+ post "/u.json", params: user_params+ expect(JSON.parse(response.body)["success"]).to be(false)+ endend- it "fails registration" do- post "/hcaptcha/create.json", params: { token: "token-from-hCaptcha" }- post "/u.json", params: user_params- expect(JSON.parse(response.body)["success"]).to be(false)+ context "when using reCaptcha" do+ before do+ SiteSetting.discourse_captcha_provider = DiscourseHcaptcha::CaptchaProvider::RECAPTCHA++ stub_request(:post, DiscourseHcaptcha::RecaptchaProvider::CAPTCHA_VERIFICATION_URL).with(+ body: {+ secret: SiteSetting.recaptcha_secret_key,+ response: "token-from-reCaptcha",+ },+ ).to_return(status: 200, body: '{"success":false}', headers: {})+ end++ it "fails registration" do+ post "/captcha/recaptcha/create.json", params: { token: "token-from-reCaptcha" }+ post "/u.json", params: user_params+ expect(JSON.parse(response.body)["success"]).to be(false)+ endendend- context "when h_captcha token is missing" do- it "fails registration" do- post "/u.json", params: user_params- expect(JSON.parse(response.body)["success"]).to be(false)+ context "when captcha token is missing" do+ context "when using hCaptcha" do+ before do+ SiteSetting.discourse_captcha_provider = DiscourseHcaptcha::CaptchaProvider::HCAPTCHA+ 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" do+ before do+ SiteSetting.discourse_captcha_provider = DiscourseHcaptcha::CaptchaProvider::RECAPTCHA+ end++ it "fails registration" do+ post "/u.json", params: user_params+ expect(JSON.parse(response.body)["success"]).to be(false)+ endendend- context "when h_captcha verification is successful" do- it "succeeds in registration" do- post "/hcaptcha/create.json", params: { token: "token-from-hCaptcha" }- post "/u.json", params: user_params- expect(JSON.parse(response.body)["success"]).to be(true)+ context "when captcha verification is successful" do+ context "when using hCaptcha" do+ before do+ SiteSetting.discourse_captcha_provider = DiscourseHcaptcha::CaptchaProvider::HCAPTCHA++ stub_request(:post, DiscourseHcaptcha::HcaptchaProvider::CAPTCHA_VERIFICATION_URL).with(+ body: {+ "response" => "token-from-hCaptcha",+ "secret" => SiteSetting.hcaptcha_secret_key,+ },+ ).to_return(status: 200, body: '{"success":true}', headers: {})+ end++ it "succeeds in registration" do+ post "/captcha/hcaptcha/create.json", params: { token: "token-from-hCaptcha" }+ post "/u.json", params: user_params++ expect(JSON.parse(response.body)["success"]).to be(true)+ end+ end++ context "when using reCaptcha" do+ before do+ SiteSetting.discourse_captcha_provider = DiscourseHcaptcha::CaptchaProvider::RECAPTCHA++ stub_request(:post, DiscourseHcaptcha::RecaptchaProvider::CAPTCHA_VERIFICATION_URL).with(+ body: {+ "response" => "token-from-reCaptcha",+ "secret" => SiteSetting.recaptcha_secret_key,+ },+ ).to_return(status: 200, body: '{"success":true}', headers: {})+ end++ it "succeeds in registration" do+ post "/captcha/recaptcha/create.json", params: { token: "token-from-reCaptcha" }+ post "/u.json", params: user_params++ expect(JSON.parse(response.body)["success"]).to be(true)+ endendcontext "when site is login-required" do- before { SiteSetting.login_required = true }+ before do+ SiteSetting.login_required = true+ SiteSetting.discourse_captcha_provider = DiscourseHcaptcha::CaptchaProvider::HCAPTCHA+ endit "succeeds in registration" do- post "/hcaptcha/create.json", params: { token: "token-from-hCaptcha" }+ post "/captcha/hcaptcha/create.json", params: { token: "token-from-hCaptcha" }post "/u.json", params: user_params+expect(JSON.parse(response.body)["success"]).to be(true)endendend- context "when h_captcha is disabled" do- before { SiteSetting.discourse_hcaptcha_enabled = false }+ context "when captcha is disabled" do+ before { SiteSetting.discourse_captcha_enabled = false }it "succeeds in registration" dopost "/u.json", params: user_params@@ -77,6 +161,144 @@ RSpec.describe "Users", type: :request doendend+ context "when captcha provider is set to none" do+ before { SiteSetting.discourse_captcha_provider = DiscourseHcaptcha::CaptchaProvider::NONE }++ it "succeeds in registration without captcha" do+ post "/u.json", params: user_params+ expect(JSON.parse(response.body)["success"]).to be(true)+ end+ end++ context "when captcha is misconfigured" do+ context "when hCaptcha is selected but keys are missing" do+ before do+ SiteSetting.discourse_captcha_provider = DiscourseHcaptcha::CaptchaProvider::HCAPTCHA+ SiteSetting.hcaptcha_site_key = ""+ SiteSetting.hcaptcha_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 is selected but keys are missing" do+ before do+ SiteSetting.discourse_captcha_provider = DiscourseHcaptcha::CaptchaProvider::RECAPTCHA+ SiteSetting.recaptcha_site_key = ""+ SiteSetting.recaptcha_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+ end++ context "when captcha provider returns server error" do+ context "when using hCaptcha" do+ before do+ SiteSetting.discourse_captcha_provider = DiscourseHcaptcha::CaptchaProvider::HCAPTCHA++ stub_request(:post, DiscourseHcaptcha::HcaptchaProvider::CAPTCHA_VERIFICATION_URL).with(+ body: {+ secret: SiteSetting.hcaptcha_secret_key,+ response: "token-from-hCaptcha",+ },+ ).to_return(status: 500, body: "Internal Server Error")+ end++ it "fails registration" do+ post "/captcha/hcaptcha/create.json", params: { token: "token-from-hCaptcha" }+ post "/u.json", params: user_params+ expect(JSON.parse(response.body)["success"]).to be(false)+ end+ end++ context "when using reCaptcha" do+ before do+ SiteSetting.discourse_captcha_provider = DiscourseHcaptcha::CaptchaProvider::RECAPTCHA++ stub_request(:post, DiscourseHcaptcha::RecaptchaProvider::CAPTCHA_VERIFICATION_URL).with(+ body: {+ secret: SiteSetting.recaptcha_secret_key,+ response: "token-from-reCaptcha",+ },+ ).to_return(status: 503, body: "Service Unavailable")+ end++ it "fails registration" do+ post "/captcha/recaptcha/create.json", params: { token: "token-from-reCaptcha" }+ post "/u.json", params: user_params+ expect(JSON.parse(response.body)["success"]).to be(false)+ end+ end+ end++ context "when captcha provider returns malformed response" do+ context "when using hCaptcha" do+ before do+ SiteSetting.discourse_captcha_provider = DiscourseHcaptcha::CaptchaProvider::HCAPTCHA++ stub_request(:post, DiscourseHcaptcha::HcaptchaProvider::CAPTCHA_VERIFICATION_URL).with(+ body: {+ secret: SiteSetting.hcaptcha_secret_key,+ response: "token-from-hCaptcha",+ },+ ).to_return(status: 200, body: "not valid json")+ end++ it "fails registration" do+ post "/captcha/hcaptcha/create.json", params: { token: "token-from-hCaptcha" }+ post "/u.json", params: user_params+ expect(JSON.parse(response.body)["success"]).to be(false)+ end+ end++ context "when using reCaptcha" do+ before do+ SiteSetting.discourse_captcha_provider = DiscourseHcaptcha::CaptchaProvider::RECAPTCHA++ stub_request(:post, DiscourseHcaptcha::RecaptchaProvider::CAPTCHA_VERIFICATION_URL).with(+ body: {+ secret: SiteSetting.recaptcha_secret_key,+ response: "token-from-reCaptcha",+ },+ ).to_return(status: 200, body: "not valid json")+ end++ it "fails registration" do+ post "/captcha/recaptcha/create.json", params: { token: "token-from-reCaptcha" }+ post "/u.json", params: user_params+ expect(JSON.parse(response.body)["success"]).to be(false)+ end+ end+ end++ context "when captcha response has success field as nil" do+ before do+ SiteSetting.discourse_captcha_provider = DiscourseHcaptcha::CaptchaProvider::HCAPTCHA++ stub_request(:post, DiscourseHcaptcha::HcaptchaProvider::CAPTCHA_VERIFICATION_URL).with(+ body: {+ secret: SiteSetting.hcaptcha_secret_key,+ response: "token-from-hCaptcha",+ },+ ).to_return(status: 200, body: '{"error-codes":["missing-input-secret"]}')+ end++ it "fails registration" do+ post "/captcha/hcaptcha/create.json", params: { token: "token-from-hCaptcha" }+ post "/u.json", params: user_params+ expect(JSON.parse(response.body)["success"]).to be(false)+ end+ end+privatedef honeypot_magic(params)diff --git a/plugins/discourse-hcaptcha/spec/lib/discourse_h_captcha/hcaptcha_provider_spec.rb b/plugins/discourse-hcaptcha/spec/lib/discourse_h_captcha/hcaptcha_provider_spec.rbnew file mode 100644index 00000000000..54d31c54d00--- /dev/null+++ b/plugins/discourse-hcaptcha/spec/lib/discourse_h_captcha/hcaptcha_provider_spec.rb@@ -0,0 +1,58 @@+# frozen_string_literal: true++RSpec.describe DiscourseHcaptcha::HcaptchaProvider do+ subject(:provider) { described_class.new }++ describe "#captcha_verification_url" do+ it "returns the hCaptcha verification URL" do+ expect(provider.captcha_verification_url).to eq("https://hcaptcha.com/siteverify")+ end+ end++ describe "#fetch_captcha_token" do+ let(:token) { "test-hcaptcha-token" }+ let(:server_session) { ServerSession.new(SecureRandom.hex) }++ before { server_session["hcaptcha_token"] = token }++ it "retrieves token from server session" do+ result = provider.fetch_captcha_token(server_session)+ expect(result).to eq(token)+ end++ it "deletes the token from server session after fetching" do+ provider.fetch_captcha_token(server_session)+ expect(server_session["hcaptcha_token"]).to be_nil+ end++ context "when no token is present" do+ let(:empty_session) { ServerSession.new(SecureRandom.hex) }++ it "returns nil" do+ result = provider.fetch_captcha_token(empty_session)+ expect(result).to be_nil+ end+ end+ end++ describe "#send_captcha_verification" do+ let(:token) { "test-hcaptcha-token" }++ before { SiteSetting.hcaptcha_secret_key = "test-secret-key" }++ it "returns the response from hCaptcha" do+ stub =+ stub_request(:post, "https://hcaptcha.com/siteverify").to_return(+ status: 200,+ body: '{"success":true}',+ )++ 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+enddiff --git a/plugins/discourse-hcaptcha/spec/lib/discourse_h_captcha/recaptcha_provider_spec.rb b/plugins/discourse-hcaptcha/spec/lib/discourse_h_captcha/recaptcha_provider_spec.rbnew file mode 100644index 00000000000..1a374f865b6--- /dev/null+++ b/plugins/discourse-hcaptcha/spec/lib/discourse_h_captcha/recaptcha_provider_spec.rb@@ -0,0 +1,70 @@+# frozen_string_literal: true++RSpec.describe DiscourseHcaptcha::RecaptchaProvider do+ subject(:provider) { described_class.new }++ 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-token" }+ let(:server_session) { ServerSession.new(SecureRandom.hex) }++ before { server_session["recaptcha_token"] = token }++ it "retrieves token from server session" do+ result = provider.fetch_captcha_token(server_session)+ expect(result).to eq(token)+ end++ it "deletes the token from server session after fetching" do+ provider.fetch_captcha_token(server_session)+ expect(server_session["recaptcha_token"]).to be_nil+ end++ context "when no token is present" do+ let(:empty_session) { ServerSession.new(SecureRandom.hex) }++ it "returns nil" do+ result = provider.fetch_captcha_token(empty_session)+ expect(result).to be_nil+ end+ end+ end++ describe "#send_captcha_verification" do+ let(:token) { "test-recaptcha-token" }++ before do+ SiteSetting.enable_local_logins = true+ SiteSetting.discourse_captcha_enabled = true+ SiteSetting.discourse_captcha_provider = DiscourseHcaptcha::CaptchaProvider::RECAPTCHA++ SiteSetting.recaptcha_site_key = "site-key"+ SiteSetting.recaptcha_secret_key = "secret-key"+ end++ it "returns the response from reCAPTCHA" do+ stub =+ stub_request(+ :post,+ DiscourseHcaptcha::RecaptchaProvider::CAPTCHA_VERIFICATION_URL,+ ).to_return(+ status: 200,+ body: '{"success":true,"challenge_ts":"2024-01-01T00:00:00Z","hostname":"example.com"}',+ )++ 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+enddiff --git a/plugins/discourse-hcaptcha/spec/requests/discourse_hcaptcha/hcaptcha_controller_spec.rb b/plugins/discourse-hcaptcha/spec/requests/discourse_hcaptcha/hcaptcha_controller_spec.rbnew file mode 100644index 00000000000..51f82d5797a--- /dev/null+++ b/plugins/discourse-hcaptcha/spec/requests/discourse_hcaptcha/hcaptcha_controller_spec.rb@@ -0,0 +1,61 @@+# frozen_string_literal: true++RSpec.describe DiscourseHcaptcha::HcaptchaController do+ describe "POST /captcha/hcaptcha/create" do+ before do+ SiteSetting.discourse_captcha_enabled = true+ SiteSetting.discourse_captcha_provider = DiscourseHcaptcha::CaptchaProvider::HCAPTCHA+ SiteSetting.hcaptcha_site_key = "test-site-key"+ SiteSetting.hcaptcha_secret_key = "test-secret-key"+ end++ context "when hCaptcha is enabled and configured" do+ it "stores token in server session with 2 minute TTL" do+ post "/captcha/hcaptcha/create.json", params: { token: "test-token" }++ expect(response.status).to eq(200)+ expect(response.parsed_body["success"]).to eq("OK")+ expect(server_session["hcaptcha_token"]).to eq("test-token")+ expect(server_session.ttl("hcaptcha_token")).to be_between(1, 120)+ end+ end++ context "when token is missing" do+ it "returns 400 error" do+ post "/captcha/hcaptcha/create.json", params: {}++ expect(response.status).to eq(400)+ end++ it "returns 400 error when token is blank" do+ post "/captcha/hcaptcha/create.json", params: { token: "" }++ expect(response.status).to eq(400)+ end+ end++ context "when hCaptcha is not the selected provider" do+ before do+ SiteSetting.discourse_captcha_provider = DiscourseHcaptcha::CaptchaProvider::RECAPTCHA+ SiteSetting.recaptcha_site_key = "test-site-key"+ SiteSetting.recaptcha_secret_key = "test-secret-key"+ end++ it "returns 404 error" do+ post "/captcha/hcaptcha/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 = DiscourseHcaptcha::CaptchaProvider::NONE }++ it "returns 404 error" do+ post "/captcha/hcaptcha/create.json", params: { token: "test-token" }++ expect(response.status).to eq(404)+ end+ end+ end+enddiff --git a/plugins/discourse-hcaptcha/spec/requests/discourse_hcaptcha/recaptcha_controller_spec.rb b/plugins/discourse-hcaptcha/spec/requests/discourse_hcaptcha/recaptcha_controller_spec.rbnew file mode 100644index 00000000000..9f6abe4514f--- /dev/null+++ b/plugins/discourse-hcaptcha/spec/requests/discourse_hcaptcha/recaptcha_controller_spec.rb@@ -0,0 +1,61 @@+# frozen_string_literal: true++RSpec.describe DiscourseHcaptcha::RecaptchaController do+ describe "POST /captcha/recaptcha/create" do+ before do+ SiteSetting.discourse_captcha_enabled = true+ SiteSetting.discourse_captcha_provider = DiscourseHcaptcha::CaptchaProvider::RECAPTCHA+ SiteSetting.recaptcha_site_key = "test-site-key"+ SiteSetting.recaptcha_secret_key = "test-secret-key"+ end++ context "when reCaptcha is enabled and configured" do+ it "stores token in server session with 2 minute TTL" do+ post "/captcha/recaptcha/create.json", params: { token: "test-token" }++ expect(response.status).to eq(200)+ expect(response.parsed_body["success"]).to eq("OK")+ expect(server_session["recaptcha_token"]).to eq("test-token")+ expect(server_session.ttl("recaptcha_token")).to be_between(1, 120)+ end+ end++ context "when token is missing" do+ it "returns 400 error" do+ post "/captcha/recaptcha/create.json", params: {}++ expect(response.status).to eq(400)+ end++ it "returns 400 error when token is blank" do+ post "/captcha/recaptcha/create.json", params: { token: "" }++ expect(response.status).to eq(400)+ end+ end++ context "when reCaptcha is not the selected provider" do+ before do+ SiteSetting.discourse_captcha_provider = DiscourseHcaptcha::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/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 = DiscourseHcaptcha::CaptchaProvider::NONE }++ it "returns 404 error" do+ post "/captcha/recaptcha/create.json", params: { token: "test-token" }++ expect(response.status).to eq(404)+ end+ end+ end+enddiff --git a/plugins/discourse-hcaptcha/spec/services/problem_check/hcaptcha_configuration_spec.rb b/plugins/discourse-hcaptcha/spec/services/problem_check/hcaptcha_configuration_spec.rbindex 119720c913f..0fd7d7c8f6d 100644--- a/plugins/discourse-hcaptcha/spec/services/problem_check/hcaptcha_configuration_spec.rb+++ b/plugins/discourse-hcaptcha/spec/services/problem_check/hcaptcha_configuration_spec.rb@@ -15,8 +15,11 @@ RSpec.describe ProblemCheck::HcaptchaConfiguration doit { expect(check).to be_chill_about_it }end- context "when discourse_hcaptcha_enabled siteSetting is true" do- before { SiteSetting.discourse_hcaptcha_enabled = true }+ context "when discourse_captcha_provider siteSetting is HCaptcha" do+ before do+ SiteSetting.discourse_captcha_enabled = true+ SiteSetting.discourse_captcha_provider = DiscourseHcaptcha::CaptchaProvider::HCAPTCHA+ enddescribe "`hcaptcha_site_key` is not set" dobefore { SiteSetting.hcaptcha_secret_key = "just a string" }@@ -43,8 +46,8 @@ RSpec.describe ProblemCheck::HcaptchaConfiguration doendend- context "when discourse_hcaptcha_enabled siteSetting is false" do- before { SiteSetting.discourse_hcaptcha_enabled = false }+ context "when discourse_captcha_provider siteSetting is HCaptcha" do+ before { SiteSetting.discourse_captcha_provider = DiscourseHcaptcha::CaptchaProvider::HCAPTCHA }describe "`hcaptcha_site_key` is not set" dobefore { SiteSetting.hcaptcha_secret_key = "just a string" }diff --git a/plugins/discourse-hcaptcha/spec/services/problem_check/recaptcha_configuration_spec.rb b/plugins/discourse-hcaptcha/spec/services/problem_check/recaptcha_configuration_spec.rbnew file mode 100644index 00000000000..753bb2f43ee--- /dev/null+++ b/plugins/discourse-hcaptcha/spec/services/problem_check/recaptcha_configuration_spec.rb@@ -0,0 +1,76 @@+# frozen_string_literal: true++RSpec.describe ProblemCheck::RecaptchaConfiguration 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 `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" do+ before do+ SiteSetting.discourse_captcha_enabled = true+ SiteSetting.discourse_captcha_provider = DiscourseHcaptcha::CaptchaProvider::RECAPTCHA+ end++ describe "`recaptcha_site_key` is not set" do+ before { SiteSetting.recaptcha_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" }++ include_examples "fails_problem_check"+ end++ describe "`recaptcha_secret_key` and `recaptcha_site_key` are not set" do+ include_examples "fails_problem_check"+ end++ describe "`recaptcha_secret_key` and `recaptcha_site_key` are set" do+ before do+ SiteSetting.recaptcha_secret_key = "just a string"+ SiteSetting.recaptcha_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 = DiscourseHcaptcha::CaptchaProvider::NONE }++ describe "`recaptcha_site_key` is not set" do+ before { SiteSetting.recaptcha_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" }++ include_examples "passes_problem_check"+ end++ describe "`recaptcha_secret_key` and `recaptcha_site_key` are not set" do+ include_examples "passes_problem_check"+ end++ describe "`recaptcha_secret_key` and `recaptcha_site_key` are set" do+ before do+ SiteSetting.recaptcha_secret_key = "just a string"+ SiteSetting.recaptcha_site_key = "just a string"+ end+ include_examples "passes_problem_check"+ end+ end+enddiff --git a/plugins/discourse-hcaptcha/spec/system/page_objects/components/captcha.rb b/plugins/discourse-hcaptcha/spec/system/page_objects/components/captcha.rbnew file mode 100644index 00000000000..176c872589e--- /dev/null+++ b/plugins/discourse-hcaptcha/spec/system/page_objects/components/captcha.rb@@ -0,0 +1,40 @@+# frozen_string_literal: true++module PageObjects+ module Components+ class Captcha < PageObjects::Components::Base+ def has_hcaptcha_container?+ page.has_css?("#h-captcha-field")+ end++ def has_no_hcaptcha_container?+ page.has_no_css?("#h-captcha-field")+ end++ def has_recaptcha_container?+ page.has_css?("#g-recaptcha")+ end++ def has_no_recaptcha_container?+ page.has_no_css?("#g-recaptcha")+ end++ def has_captcha_error?+ page.has_css?(".captcha-container + .alert-error") ||+ page.has_css?(".captcha-service-tip .bad")+ end++ def has_captcha_widget?+ has_hcaptcha_widget? || has_recaptcha_widget?+ end++ def has_hcaptcha_widget?+ page.has_css?("#h-captcha-field iframe")+ end++ def has_recaptcha_widget?+ page.has_css?("#g-recaptcha iframe")+ end+ end+ end+enddiff --git a/plugins/discourse-hcaptcha/spec/system/signup_with_captcha_spec.rb b/plugins/discourse-hcaptcha/spec/system/signup_with_captcha_spec.rbnew file mode 100644index 00000000000..cd7868506e0--- /dev/null+++ b/plugins/discourse-hcaptcha/spec/system/signup_with_captcha_spec.rb@@ -0,0 +1,101 @@+# frozen_string_literal: true++RSpec.describe "Signup with captcha" do+ let(:signup_page) { PageObjects::Pages::Signup.new }+ let(:captcha) { PageObjects::Components::Captcha.new }++ before do+ SiteSetting.enable_local_logins = true+ SiteSetting.discourse_captcha_enabled = true+ end++ context "with hCaptcha" do+ before do+ SiteSetting.discourse_captcha_provider = DiscourseHcaptcha::CaptchaProvider::HCAPTCHA+ SiteSetting.hcaptcha_site_key = "10000000-ffff-ffff-ffff-000000000001"+ SiteSetting.hcaptcha_secret_key = "0x0000000000000000000000000000000000000000"+ end++ it "displays the hCaptcha widget on signup page" do+ signup_page.open+ expect(captcha).to have_hcaptcha_container+ end++ it "loads the hCaptcha iframe" do+ signup_page.open+ expect(captcha).to have_hcaptcha_widget+ end++ it "does not display reCaptcha container" do+ signup_page.open+ expect(captcha).to have_no_recaptcha_container+ end++ context "when site requires login" do+ before { SiteSetting.login_required = true }++ it "displays the captcha widget on signup page" do+ signup_page.open+ expect(captcha).to have_hcaptcha_container+ end+ end++ context "when submitting signup without completing captcha" do+ it "shows error message when captcha is not completed" 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("js.discourse_captcha.missing_token"))+ end+ end++ context "when captcha is disabled" do+ before { SiteSetting.discourse_captcha_enabled = false }++ it "does not display any captcha widget" do+ signup_page.open+ expect(captcha).to have_no_hcaptcha_container+ expect(captcha).to have_no_recaptcha_container+ end+ end+ end++ context "with reCaptcha" do+ before do+ SiteSetting.discourse_captcha_provider = DiscourseHcaptcha::CaptchaProvider::RECAPTCHA+ SiteSetting.recaptcha_site_key = "6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI"+ SiteSetting.recaptcha_secret_key = "6LeIxAcTAAAAAGG-vFI1TnRWxMZNFuojJ4WifJWe"+ end++ it "displays the reCaptcha widget on signup page" do+ signup_page.open+ expect(captcha).to have_recaptcha_container+ end++ it "loads the reCaptcha iframe" do+ signup_page.open+ expect(captcha).to have_recaptcha_widget+ end++ it "does not display hCaptcha container" do+ signup_page.open+ expect(captcha).to have_no_hcaptcha_container+ end+ end++ context "when captcha provider is none" do+ before { SiteSetting.discourse_captcha_provider = DiscourseHcaptcha::CaptchaProvider::NONE }++ it "does not display any captcha widget" do+ signup_page.open+ expect(captcha).to have_no_hcaptcha_container+ expect(captcha).to have_no_recaptcha_container+ end+ end+enddiff --git a/spec/system/page_objects/pages/signup.rb b/spec/system/page_objects/pages/signup.rbindex c5b266d79f8..dbf3dcf6d90 100644--- a/spec/system/page_objects/pages/signup.rb+++ b/spec/system/page_objects/pages/signup.rb@@ -133,6 +133,10 @@ module PageObjectsdef click_social_button(provider)click(".btn-social.#{provider}")end++ def has_flash_message?(text)+ has_css?(".alert", text: text)+ endendendend