]> cat aescling's git repositories - mastodon.git/commitdiff
Add optional hCaptcha support
authorClaire <claire.github-309c@sitedethib.com>
Mon, 24 Jan 2022 18:06:19 +0000 (19:06 +0100)
committerClaire <claire.github-309c@sitedethib.com>
Mon, 24 Jan 2022 20:22:13 +0000 (21:22 +0100)
Fixes #1649

This requires setting `HCAPTCHA_SECRET_KEY` and `HCAPTCHA_SITE_KEY`, then
enabling the admin setting at
`/admin/settings/edit#form_admin_settings_captcha_enabled`

Subsequently, a hCaptcha widget will be displayed on `/about` and
`/auth/sign_up` unless:
- the user is already signed-up already
- the user has used an invite link
- the user has already solved the captcha (and registration failed for another
  reason)

The Content-Security-Policy headers are altered automatically to allow the
third-party hCaptcha scripts on `/about` and `/auth/sign_up` following the same
rules as above.

15 files changed:
.env.production.sample
Gemfile
Gemfile.lock
app/controllers/about_controller.rb
app/controllers/api/v1/accounts_controller.rb
app/controllers/auth/registrations_controller.rb
app/controllers/concerns/captcha_concern.rb [new file with mode: 0644]
app/helpers/admin/settings_helper.rb
app/javascript/flavours/glitch/styles/forms.scss
app/models/form/admin_settings.rb
app/views/about/_registration.html.haml
app/views/admin/settings/edit.html.haml
app/views/auth/registrations/new.html.haml
config/locales-glitch/en.yml
config/settings.yml

index 13e89b40d27eb0845e6c57db6a7eb57773886421..7de5e00f40e006aaf392c954b8e4e777395bc907 100644 (file)
@@ -285,3 +285,7 @@ MAX_POLL_OPTION_CHARS=100
 # Units are in bytes
 MAX_EMOJI_SIZE=51200
 MAX_REMOTE_EMOJI_SIZE=204800
+
+# Optional hCaptcha support
+# HCAPTCHA_SECRET_KEY=
+# HCAPTCHA_SITE_KEY=
diff --git a/Gemfile b/Gemfile
index eae5f11b7cfc07b7261a2800c25a8438d97d0993..282ab65e404899a127ce184c33df03c9d04b6b54 100644 (file)
--- a/Gemfile
+++ b/Gemfile
@@ -156,3 +156,5 @@ gem 'concurrent-ruby', require: false
 gem 'connection_pool', require: false
 
 gem 'xorcist', '~> 1.1'
+
+gem "hcaptcha", "~> 7.1"
index 8d72732ebb35245db67854455eb7fae88118a363..cc9a53e41073ad7dbfb2709a7fa4c0e6440aad3f 100644 (file)
@@ -271,6 +271,8 @@ GEM
       railties (>= 4.0.1)
     hashdiff (1.0.1)
     hashie (4.1.0)
+    hcaptcha (7.1.0)
+      json
     highline (2.0.3)
     hiredis (0.6.3)
     hkdf (0.3.0)
@@ -719,6 +721,7 @@ DEPENDENCIES
   fog-openstack (~> 0.3)
   fuubar (~> 2.5)
   hamlit-rails (~> 0.2)
+  hcaptcha (~> 7.1)
   hiredis (~> 0.6)
   htmlentities (~> 4.3)
   http (~> 5.0)
index 620c0ff78fe060d31cc659363c32b69b005036e3..5a35dbbcb62af618459cd2d7e538cce335295cd0 100644 (file)
@@ -2,6 +2,7 @@
 
 class AboutController < ApplicationController
   include RegistrationSpamConcern
+  include CaptchaConcern
 
   before_action :set_pack
 
@@ -12,6 +13,7 @@ class AboutController < ApplicationController
   before_action :set_instance_presenter
   before_action :set_expires_in, only: [:more, :terms]
   before_action :set_registration_form_time, only: :show
+  before_action :extend_csp_for_captcha!, only: :show
 
   skip_before_action :require_functional!, only: [:more, :terms]
 
index 5c47158e02c64d00dbf3b0b813680022c705f4b6..8916c3f96ec2154dc630340de1e59a83e16973c6 100644 (file)
@@ -1,6 +1,8 @@
 # frozen_string_literal: true
 
 class Api::V1::AccountsController < Api::BaseController
+  include CaptchaConcern
+
   before_action -> { authorize_if_got_token! :read, :'read:accounts' }, except: [:create, :follow, :unfollow, :remove_from_followers, :block, :unblock, :mute, :unmute]
   before_action -> { doorkeeper_authorize! :follow, :'write:follows' }, only: [:follow, :unfollow, :remove_from_followers]
   before_action -> { doorkeeper_authorize! :follow, :'write:mutes' }, only: [:mute, :unmute]
@@ -83,7 +85,7 @@ class Api::V1::AccountsController < Api::BaseController
   end
 
   def check_enabled_registrations
-    forbidden if single_user_mode? || omniauth_only? || !allowed_registrations?
+    forbidden if single_user_mode? || omniauth_only? || !allowed_registrations? || captcha_enabled?
   end
 
   def allowed_registrations?
index 6b1f3fa822a975b42a1f031d72ab4008e640d950..3c9b38a4bf4757a86dec9362bbd2fb5c727970cd 100644 (file)
@@ -2,6 +2,7 @@
 
 class Auth::RegistrationsController < Devise::RegistrationsController
   include RegistrationSpamConcern
+  include CaptchaConcern
 
   layout :determine_layout
 
@@ -15,6 +16,8 @@ class Auth::RegistrationsController < Devise::RegistrationsController
   before_action :require_not_suspended!, only: [:update]
   before_action :set_cache_headers, only: [:edit, :update]
   before_action :set_registration_form_time, only: :new
+  before_action :extend_csp_for_captcha!, only: [:new, :create]
+  before_action :check_captcha!, only: :create
 
   skip_before_action :require_functional!, only: [:edit, :update]
 
@@ -135,4 +138,18 @@ class Auth::RegistrationsController < Devise::RegistrationsController
   def set_cache_headers
     response.headers['Cache-Control'] = 'no-cache, no-store, max-age=0, must-revalidate'
   end
+
+  def sign_up(resource_name, resource)
+    clear_captcha!
+    super
+  end
+
+  def check_captcha!
+    super do |error|
+      build_resource(sign_up_params)
+      resource.validate
+      resource.errors.add(:base, error)
+      respond_with resource
+    end
+  end
 end
diff --git a/app/controllers/concerns/captcha_concern.rb b/app/controllers/concerns/captcha_concern.rb
new file mode 100644 (file)
index 0000000..5a23e59
--- /dev/null
@@ -0,0 +1,66 @@
+# frozen_string_literal: true
+
+module CaptchaConcern
+  extend ActiveSupport::Concern
+  include Hcaptcha::Adapters::ViewMethods
+
+  CAPTCHA_TIMEOUT = 2.hours.freeze
+
+  included do
+    helper_method :render_captcha_if_needed
+  end
+
+  def captcha_available?
+    ENV['HCAPTCHA_SECRET_KEY'].present? && ENV['HCAPTCHA_SITE_KEY'].present?
+  end
+
+  def captcha_enabled?
+    captcha_available? && Setting.captcha_enabled
+  end
+
+  def captcha_recently_passed?
+    session[:captcha_passed_at].present? && session[:captcha_passed_at] >= CAPTCHA_TIMEOUT.ago
+  end
+
+  def captcha_required?
+    captcha_enabled? && !current_user && !(@invite.present? && @invite.valid_for_use? && !@invite.max_uses.nil?) && !captcha_recently_passed?
+  end
+
+  def clear_captcha!
+    session.delete(:captcha_passed_at)
+  end
+
+  def check_captcha!
+    return true unless captcha_required?
+
+    if verify_hcaptcha
+      session[:captcha_passed_at] = Time.now.utc
+      return true
+    else
+      if block_given?
+        message = flash[:hcaptcha_error]
+        flash.delete(:hcaptcha_error)
+        yield message
+      end
+      return false
+    end
+  end
+
+  def extend_csp_for_captcha!
+    policy = request.content_security_policy
+    return unless captcha_required? && policy.present?
+
+    %w(script_src frame_src style_src connect_src).each do |directive|
+      values = policy.send(directive)
+      values << 'https://hcaptcha.com' unless values.include?('https://hcaptcha.com') || values.include?('https:')
+      values << 'https://*.hcaptcha.com' unless values.include?('https://*.hcaptcha.com') || values.include?('https:')
+      policy.send(directive, *values)
+    end
+  end
+
+  def render_captcha_if_needed
+    return unless captcha_required?
+
+    hcaptcha_tags
+  end
+end
index baf14ab2574e3fd8bf0733df92bd5597ce2d6398..f99a2b8c8ac3b6746f622b428dc259b44261e7d1 100644 (file)
@@ -8,4 +8,8 @@ module Admin::SettingsHelper
     link = link_to t('admin.site_uploads.delete'), admin_site_upload_path(upload), data: { method: :delete }
     safe_join([hint, link], '<br/>'.html_safe)
   end
+
+  def captcha_available?
+    ENV['HCAPTCHA_SECRET_KEY'].present? && ENV['HCAPTCHA_SITE_KEY'].present?
+  end
 end
index 3433abcddb30e702ad0bef38b224e6526e5c4059..64d441fb25d827f9834bf9f79d834c38c1f048a4 100644 (file)
@@ -1058,3 +1058,7 @@ code {
     display: none;
   }
 }
+
+.simple_form .h-captcha {
+  text-align: center;
+}
index 3202d1fc246908055e1e4b8d0b443e38d9b8894f..34f14e3124c44b8e2fc113e0a18c208aca3b3b42 100644 (file)
@@ -40,6 +40,7 @@ class Form::AdminSettings
     noindex
     outgoing_spoilers
     require_invite_text
+    captcha_enabled
   ).freeze
 
   BOOLEAN_KEYS = %i(
@@ -58,6 +59,7 @@ class Form::AdminSettings
     trendable_by_default
     noindex
     require_invite_text
+    captcha_enabled
   ).freeze
 
   UPLOAD_KEYS = %i(
index e4d614d71e7a7c17770d3b559c41cdff27bd8227..5bb5d08a2abf8eafca16953a45639c88549aa1ad 100644 (file)
@@ -21,6 +21,9 @@
     .fields-group
       = f.input :agreement, as: :boolean, wrapper: :with_label, label: t('auth.checkbox_agreement_html', rules_path: about_more_path, terms_path: terms_path), required: true, disabled: closed_registrations?
 
+    .fields-group
+      = render_captcha_if_needed
+
     .actions
       = f.button :button, sign_up_message, type: :submit, class: 'button button-primary', disabled: closed_registrations?
 
index b9daae8f05b7660636f551f3acb809609b57ca12..49b03a9e3582c2357629ae457356eb9eb79a0c79 100644 (file)
 
   .fields-group
     = f.input :require_invite_text, as: :boolean, wrapper: :with_label, label: t('admin.settings.registrations.require_invite_text.title'), hint: t('admin.settings.registrations.require_invite_text.desc_html'), disabled: !approved_registrations?
-  .fields-group
+
+  - if captcha_available?
+    .fields-group
+      = f.input :captcha_enabled, as: :boolean, wrapper: :with_label, label: t('admin.settings.captcha_enabled.title'), hint: t('admin.settings.captcha_enabled.desc_html')
 
   %hr.spacer/
 
index 6981195ed90f212e29e54efb411f4632197abcbb..5cb558297a576d5f27c953d3d7b2f397f8b3fe32 100644 (file)
@@ -38,6 +38,9 @@
   .fields-group
     = f.input :agreement, as: :boolean, wrapper: :with_label, label: whitelist_mode? ? t('auth.checkbox_agreement_without_rules_html', terms_path: terms_path) : t('auth.checkbox_agreement_html', rules_path: about_more_path, terms_path: terms_path), required: true
 
+  .field-group
+    = render_captcha_if_needed
+
   .actions
     = f.button :button, @invite.present? ? t('auth.register') : sign_up_message, type: :submit
 
index 5cc2625fc669685d320940a9ea1b10772c326157..c96f21c92debbcd467b76ebf1bbcc47937f07d11 100644 (file)
@@ -2,6 +2,9 @@
 en:
   admin:
     settings:
+      captcha_enabled:
+        desc_html: Enable hCaptcha integration, requiring new users to solve a challenge when signing up. Note that this disables app-based registration, and requires third-party scripts from hCaptcha to be embedded in the registration pages. This may have security and privacy concerns.
+        title: Require new users to go through a CAPTCHA to sign up
       enable_keybase:
         desc_html: Allow your users to prove their identity via keybase
         title: Enable keybase integration
index 0942098226c179e5e78dc5dac99e384826f18de1..7d192f3691c0a64056d56ce6759ecb675c3b7140 100644 (file)
@@ -77,6 +77,7 @@ defaults: &defaults
   show_domain_blocks_rationale: 'disabled'
   outgoing_spoilers: ''
   require_invite_text: false
+  captcha_enabled: false
 
 development:
   <<: *defaults