pax_global_header 0000666 0000000 0000000 00000000064 14575636613 0014532 g ustar 00root root 0000000 0000000 52 comment=b0093de90621f8362223f28ce51fe57e9f067d7d
markets-invisible_captcha-b759a52/ 0000775 0000000 0000000 00000000000 14575636613 0017205 5 ustar 00root root 0000000 0000000 markets-invisible_captcha-b759a52/.github/ 0000775 0000000 0000000 00000000000 14575636613 0020545 5 ustar 00root root 0000000 0000000 markets-invisible_captcha-b759a52/.github/workflows/ 0000775 0000000 0000000 00000000000 14575636613 0022602 5 ustar 00root root 0000000 0000000 markets-invisible_captcha-b759a52/.github/workflows/ci.yml 0000664 0000000 0000000 00000001656 14575636613 0023730 0 ustar 00root root 0000000 0000000 name: CI
on: [push, pull_request]
jobs:
test:
name: CI
runs-on: ubuntu-latest
env:
BUNDLE_GEMFILE: ${{ github.workspace }}/gemfiles/${{ matrix.gemfile }}.gemfile
strategy:
fail-fast: false
matrix:
ruby: ["2.7", "3.0", "3.1", "3.2"]
gemfile: [rails_6.0, rails_6.1, rails_7.0, rails_7.1]
exclude:
- ruby: "3.1"
gemfile: rails_6.0
- ruby: "3.2"
gemfile: rails_6.0
include:
- ruby: "2.7"
gemfile: rails_5.2
- ruby: head
gemfile: rails_7.0
steps:
- uses: actions/checkout@v3
- uses: ruby/setup-ruby@v1
with:
ruby-version: ${{ matrix.ruby }}
bundler-cache: true
- run: bundle exec rspec
continue-on-error: ${{ endsWith(matrix.ruby, 'head') }}
- name: Upload coverage reports to Codecov
uses: codecov/codecov-action@v3
markets-invisible_captcha-b759a52/.gitignore 0000664 0000000 0000000 00000000211 14575636613 0021167 0 ustar 00root root 0000000 0000000 .bundle
pkg
.rvmrc
.ruby-version
.ruby-gemset
Gemfile.lock
*.gemfile.lock
spec/dummy/log/*.log
spec/dummy/tmp/
.byebug_history
.DS_Store
markets-invisible_captcha-b759a52/.rspec 0000664 0000000 0000000 00000000065 14575636613 0020323 0 ustar 00root root 0000000 0000000 --format documentation
--color
--require spec_helper
markets-invisible_captcha-b759a52/Appraisals 0000664 0000000 0000000 00000000204 14575636613 0021223 0 ustar 00root root 0000000 0000000 %w(
7.1
7.0
6.1
6.0
5.2
).each do |version|
appraise "rails-#{version}" do
gem "rails", "~> #{version}.0"
end
end
markets-invisible_captcha-b759a52/CHANGELOG.md 0000664 0000000 0000000 00000012044 14575636613 0021017 0 ustar 00root root 0000000 0000000 # Changelog
All notable changes to this project will be documented in this file.
## [2.3.0]
- Run honeypot + spinner checks and their callback also if timestamp triggers but passes through (#132)
- Mark as spam requests with no spinner value (#134)
## [2.2.0]
- Official support for Rails 7.1
- Fix flash message for `on_timestamp_spam` callback (#125)
- Fix potential error when lookup the honeypot parameter using (#128)
## [2.1.0]
- Drop official support for EOL Rubies: 2.5 and 2.6
- Allow random honeypots to be scoped (#117)
## [2.0.0]
- New spinner, IP based, validation check (#89)
- Drop official support for unmaintained Rails versions: 5.1, 5.0 and 4.2 (#86)
- Drop official support for EOL Rubies: 2.4 and 2.3 (#86)
## [1.1.0]
- New option `prepend: true` for the controller macro (#77)
## [1.0.1]
- Fix naming issue with Ruby 2.7 (#65)
## [1.0.0]
- Remove Ruby 2.2 and Rails 3.2 support
- Add Instrumentation event (#62)
## [0.13.0]
- Add support for the Content Security Policy nonce (#61)
- Freeze all strings (#60)
## [0.12.2]
- Allow new timestamp to be set during `on_timestamp_spam` callback (#53)
## [0.12.1]
- Clear timestamp stored in `session[:invisible_captcha_timestamp]` (#50)
- Rails 6 support
## [0.12.0]
- Honeypot input with autocomplete="off" by default (#42)
## [0.11.0]
- Improve logging (#40, #41)
- Official Rails 5.2 support
- Drop Ruby 2.1 from CI
## [0.10.0]
- New timestamp on each request to avoid stale timestamps (#24)
- Allow to inject styles manually anywhere in the layout (#27)
- Allow to change threshold per action
- Dynamic css strategy to hide the honeypot
- Remove Ruby 1.9 support
- Random default honeypots on each restart
- Allow to pass html_options to honeypot input (#28)
- Improvements on demo application and tests
- Better strong parameters interaction (#30, #33)
## [0.9.3]
- Rails 5.1 support (#29)
- Modernize CI Rubies
## [0.9.2]
- Rails 5.0 official support (#23)
- Travis CI matrix improvements
## [0.9.1]
- Add option (`timestamp_enabled`) to disable timestamp check (#22)
## [0.9.0]
- Remove model style validations (#14)
- Consider as spam if timestamp not in session (#11)
- Allow to define a different threshold per action (#8)
- Appraisals integration (#8)
- CI improvements: use new Travis infrastructure (#8)
## [0.8.2]
- Default timestamp action redirects to back (#19)
- Stores timestamps as string in session (#17)
## [0.8.1]
- Time-sensitive form submissions (#7)
- I18n integration (#13)
## [0.8.0]
- Better Rails integration with `ActiveSupport.on_load` callbacks (#5)
- Allow to override settings via the view helper (#5)
## [0.7.0]
- Revamped code base to allow more customizations (#2)
- Added basic specs (#2)
- Travis integration (#2)
- Demo app (#2)
## [0.6.5]
- Stop using Jeweler
## [0.6.4]
- Docs! (#1)
## [0.6.3]
- Internal re-naming
## [0.6.2]
- Fix gem initialization
## [0.6.0]
- Allow to configure via `InvisibleCaptcha.setup` block
## [0.5.0]
- First version of controller filters
[2.3.0]: https://github.com/markets/invisible_captcha/compare/v2.2.0...v2.3.0
[2.2.0]: https://github.com/markets/invisible_captcha/compare/v2.1.0...v2.2.0
[2.1.0]: https://github.com/markets/invisible_captcha/compare/v2.0.0...v2.1.0
[2.0.0]: https://github.com/markets/invisible_captcha/compare/v1.1.0...v2.0.0
[1.1.0]: https://github.com/markets/invisible_captcha/compare/v1.0.1...v1.1.0
[1.0.1]: https://github.com/markets/invisible_captcha/compare/v1.0.0...v1.0.1
[1.0.0]: https://github.com/markets/invisible_captcha/compare/v0.13.0...v1.0.0
[0.13.0]: https://github.com/markets/invisible_captcha/compare/v0.12.2...v0.13.0
[0.12.2]: https://github.com/markets/invisible_captcha/compare/v0.12.1...v0.12.2
[0.12.1]: https://github.com/markets/invisible_captcha/compare/v0.12.0...v0.12.1
[0.12.0]: https://github.com/markets/invisible_captcha/compare/v0.11.0...v0.12.0
[0.11.0]: https://github.com/markets/invisible_captcha/compare/v0.10.0...v0.11.0
[0.10.0]: https://github.com/markets/invisible_captcha/compare/v0.9.3...v0.10.0
[0.9.3]: https://github.com/markets/invisible_captcha/compare/v0.9.2...v0.9.3
[0.9.2]: https://github.com/markets/invisible_captcha/compare/v0.9.1...v0.9.2
[0.9.1]: https://github.com/markets/invisible_captcha/compare/v0.9.0...v0.9.1
[0.9.0]: https://github.com/markets/invisible_captcha/compare/v0.8.2...v0.9.0
[0.8.2]: https://github.com/markets/invisible_captcha/compare/v0.8.1...v0.8.2
[0.8.1]: https://github.com/markets/invisible_captcha/compare/v0.8.0...v0.8.1
[0.8.0]: https://github.com/markets/invisible_captcha/compare/v0.7.0...v0.8.0
[0.7.0]: https://github.com/markets/invisible_captcha/compare/v0.6.5...v0.7.0
[0.6.5]: https://github.com/markets/invisible_captcha/compare/v0.6.4...v0.6.5
[0.6.4]: https://github.com/markets/invisible_captcha/compare/v0.6.3...v0.6.4
[0.6.3]: https://github.com/markets/invisible_captcha/compare/v0.6.2...v0.6.3
[0.6.2]: https://github.com/markets/invisible_captcha/compare/v0.6.0...v0.6.2
[0.6.0]: https://github.com/markets/invisible_captcha/compare/v0.5.0...v0.6.0
[0.5.0]: https://github.com/markets/invisible_captcha/compare/v0.4.1...v0.5.0
markets-invisible_captcha-b759a52/Gemfile 0000664 0000000 0000000 00000000106 14575636613 0020475 0 ustar 00root root 0000000 0000000 # frozen_string_literal: true
source 'https://rubygems.org'
gemspec
markets-invisible_captcha-b759a52/LICENSE 0000664 0000000 0000000 00000002046 14575636613 0020214 0 ustar 00root root 0000000 0000000 Copyright 2012-2024 Marc Anguera Insa
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
markets-invisible_captcha-b759a52/README.md 0000664 0000000 0000000 00000034001 14575636613 0020462 0 ustar 00root root 0000000 0000000 # Invisible Captcha
[](https://rubygems.org/gems/invisible_captcha)
[](https://github.com/markets/invisible_captcha/actions)
[](https://codecov.io/gh/markets/invisible_captcha)
> Complete and flexible spam protection solution for Rails applications.
Invisible Captcha provides different techniques to protect your application against spambots.
The main protection is a solution based on the `honeypot` principle, which provides a better user experience since there are no extra steps for real users, only for the bots.
Essentially, the strategy consists on adding an input field :honey_pot: into the form that:
- shouldn't be visible by the real users
- should be left empty by the real users
- will most likely be filled by spam bots
It also comes with:
- a time-sensitive :hourglass: form submission
- an IP based :mag: spinner validation
## Installation
Invisible Captcha is tested against Rails `>= 5.2` and Ruby `>= 2.7`.
Add this line to your Gemfile and then execute `bundle install`:
```ruby
gem 'invisible_captcha'
```
## Usage
View code:
```erb
<%= form_for(@topic) do |f| %>
<%= f.invisible_captcha :subtitle %>
<%= invisible_captcha :subtitle, :topic %>
<% end %>
```
Controller code:
```ruby
class TopicsController < ApplicationController
invisible_captcha only: [:create, :update], honeypot: :subtitle
end
```
This method will act as a `before_action` that triggers when spam is detected (honeypot field has some value). By default, it responds with no content (only headers: `head(200)`). This is a good default, since the bot will surely read the response code and will think that it has achieved to submit the form properly. But, anyway, you can define your own callback by passing a method to the `on_spam` option:
```ruby
class TopicsController < ApplicationController
invisible_captcha only: [:create, :update], on_spam: :your_spam_callback_method
private
def your_spam_callback_method
redirect_to root_path
end
end
```
You should _not_ name your method `on_spam`, as this will collide with an internal method of the same name.
Note that it is not mandatory to specify a `honeypot` attribute (neither in the view nor in the controller). In this case, the engine will take a random field from `InvisibleCaptcha.honeypots`. So, if you're integrating it following this path, in your form:
```erb
<%= form_tag(new_contact_path) do |f| %>
<%= invisible_captcha %>
<% end %>
```
In your controller:
```
invisible_captcha only: [:new_contact]
```
`invisible_captcha` sends all messages to `flash[:error]`. For messages to appear on your pages, add `<%= flash[:error] %>` to `app/views/layouts/application.html.erb` (somewhere near the top of your `
` element):
```erb
Yet another Rails app
<%= stylesheet_link_tag "application", media: "all" %>
<%= javascript_include_tag "application" %>
<%= csrf_meta_tags %>
<%= flash[:error] %>
<%= yield %>
```
You can place `<%= flash[:error] %>` next to `:alert` and `:notice` message types, if you have them in your `app/views/layouts/application.html.erb`.
**NOTE:** This gem relies on data set by the backend, so in order to properly work, your forms should be rendered by Rails. Forms generated via JavaScript are not going to work well.
## Options and customization
This section contains a description of all plugin options and customizations.
### Plugin options:
You can customize:
- `sentence_for_humans`: text for real users if input field was visible. By default, it uses I18n (see below).
- `honeypots`: collection of default honeypots. Used by the view helper, called with no args, to generate a random honeypot field name. By default, a random collection is already generated. As the random collection is stored in memory, it will not work if you are running multiple Rails instances behind a load balancer (see [Multiple Rails instances](#multiple-rails-instances)). Beware that Chrome may ignore `autocomplete="off"`. Thus, consider not to use field names, which would be autocompleted, like for example `name`, `country`.
- `visual_honeypots`: make honeypots visible, also useful to test/debug your implementation.
- `timestamp_threshold`: fastest time (in seconds) to expect a human to submit the form (see [original article by Yoav Aner](https://blog.gingerlime.com/2012/simple-detection-of-comment-spam-in-rails/) outlining the idea). By default, 4 seconds. **NOTE:** It's recommended to deactivate the autocomplete feature to avoid false positives (`autocomplete="off"`).
- `timestamp_enabled`: option to disable the time threshold check at application level. Could be useful, for example, on some testing scenarios. By default, true.
- `timestamp_error_message`: flash error message thrown when form submitted quicker than the `timestamp_threshold` value. It uses I18n by default.
- `injectable_styles`: if enabled, you should call anywhere in your layout the following helper `<%= invisible_captcha_styles %>`. This allows you to inject styles, for example, in ``. False by default, styles are injected inline with the honeypot.
- `spinner_enabled`: option to disable the IP spinner validation. By default, true.
- `secret`: customize the secret key to encode some internal values. By default, it reads the environment variable `ENV['INVISIBLE_CAPTCHA_SECRET']` and fallbacks to random value. Be careful, if you are running multiple Rails instances behind a load balancer, use always the same value via the environment variable.
To change these defaults, add the following to an initializer (recommended `config/initializers/invisible_captcha.rb`):
```ruby
InvisibleCaptcha.setup do |config|
# config.honeypots << ['more', 'fake', 'attribute', 'names']
# config.visual_honeypots = false
# config.timestamp_threshold = 2
# config.timestamp_enabled = true
# config.injectable_styles = false
# config.spinner_enabled = true
# Leave these unset if you want to use I18n (see below)
# config.sentence_for_humans = 'If you are a human, ignore this field'
# config.timestamp_error_message = 'Sorry, that was too quick! Please resubmit.'
end
```
#### Multiple Rails instances
If you have multiple Rails instances running behind a load balancer, you have to share the same honeypots collection between the instances.
Either use a fixed collection or share them between the instances using `Rails.cache`:
```ruby
InvisibleCaptcha.setup do |config|
config.honeypots = Rails.cache.fetch('invisible_captcha_honeypots') do
(1..20).map { InvisibleCaptcha.generate_random_honeypot }
end
end
```
Be careful also with the `secret` setting. Since it will be stored in-memory, if you are running this setup, the best idea is to provide the environment variable (`ENV['INVISIBLE_CAPTCHA_SECRET']`) from your infrastructure.
### Controller method options:
The `invisible_captcha` method accepts some options:
- `only`: apply to given controller actions.
- `except`: exclude to given controller actions.
- `honeypot`: name of custom honeypot.
- `scope`: name of scope, ie: 'topic[subtitle]' -> 'topic' is the scope. By default, it's inferred from the `controller_name`.
- `on_spam`: custom callback to be called on spam detection.
- `timestamp_enabled`: enable/disable this technique at action level.
- `on_timestamp_spam`: custom callback to be called when form submitted too quickly. The default action redirects to `:back` printing a warning in `flash[:error]`.
- `timestamp_threshold`: custom threshold per controller/action. Overrides the global value for `InvisibleCaptcha.timestamp_threshold`.
- `prepend`: the spam detection will run in a `prepend_before_action` if `prepend: true`, otherwise will run in a `before_action`.
### View helpers options:
Using the view/form helper you can override some defaults for the given instance. Actually, it allows to change:
- `sentence_for_humans`
```erb
<%= form_for(@topic) do |f| %>
<%= f.invisible_captcha :subtitle, sentence_for_humans: "hey! leave this input empty!" %>
<% end %>
```
- `visual_honeypots`
```erb
<%= form_for(@topic) do |f| %>
<%= f.invisible_captcha :subtitle, visual_honeypots: true %>
<% end %>
```
You can also pass html options to the input:
```erb
<%= invisible_captcha :subtitle, :topic, id: "your_id", class: "your_class" %>
```
### Spam detection notifications
In addition to the `on_spam` controller callback, you can use the [Active Support Instrumentation API](https://guides.rubyonrails.org/active_support_instrumentation.html) to set up a global event handler that fires whenever spam is detected. This is useful for advanced logging, background processing, etc.
To set up a global event handler, [subscribe](https://guides.rubyonrails.org/active_support_instrumentation.html#subscribing-to-an-event) to the `invisible_captcha.spam_detected` event in an initializer:
```ruby
# config/initializers/invisible_captcha.rb
ActiveSupport::Notifications.subscribe('invisible_captcha.spam_detected') do |*args, data|
AwesomeLogger.warn(data[:message], data) # Log to an external logging service.
SpamRequest.create(data) # Record the blocked request in your database.
end
```
The `data` passed to the subscriber is hash containing information about the request that was detected as spam. For example:
```ruby
{
message: "Honeypot param 'subtitle' was present.",
remote_ip: '127.0.0.1',
user_agent: 'Chrome 77',
controller: 'users',
action: 'create',
url: 'http://example.com/users',
params: {
topic: { subtitle: 'foo' },
controller: 'users',
action: 'create'
}
}
```
**NOTE:** `params` will be filtered according to your `Rails.application.config.filter_parameters` configuration, making them (probably) safe for logging. But always double-check that you're not inadvertently logging sensitive form data, like passwords and credit cards.
### Content Security Policy
If you're using a Content Security Policy (CSP) in your Rails app, you will need to generate a nonce on the server, and pass `nonce: true` attribute to the view helper. Uncomment the following lines in your `config/initializers/content_security_policy.rb` file:
```ruby
# Be sure to restart your server when you modify this file.
# If you are using UJS then enable automatic nonce generation
Rails.application.config.content_security_policy_nonce_generator = -> request { SecureRandom.base64(16) }
# Set the nonce only to specific directives
Rails.application.config.content_security_policy_nonce_directives = %w(style-src)
```
Note that if you are already generating nonce for scripts, you'd have to include `script-src` to `content_security_policy_nonce_directives` as well:
```ruby
Rails.application.config.content_security_policy_nonce_directives = %w(script-src style-src)
```
And in your view helper, you need to pass `nonce: true` to the `invisible_captcha` helper:
```erb
<%= invisible_captcha nonce: true %>
```
**NOTE:** Content Security Policy can break your site! If you already run a website with third-party scripts, styles, images, and fonts, it is highly recommended to enable CSP in report-only mode and observe warnings as they appear. Learn more at MDN:
* https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP
* https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy
### I18n
`invisible_captcha` tries to use I18n when it's available by default. The keys it looks for are the following:
```yaml
en:
invisible_captcha:
sentence_for_humans: "If you are human, ignore this field"
timestamp_error_message: "Sorry, that was too quick! Please resubmit."
```
You can override the English ones in your i18n config files as well as add new ones for other locales.
If you intend to use I18n with `invisible_captcha`, you _must not_ set `sentence_for_humans` or `timestamp_error_message` to strings in the setup phase.
## Testing your controllers
If you're encountering unexpected behaviour while testing controllers that use the `invisible_captcha` action filter, you may want to disable timestamp check for the test environment. Add the following snippet to the `config/initializers/invisible_captcha.rb` file:
```ruby
# Be sure to restart your server when you modify this file.
InvisibleCaptcha.setup do |config|
config.timestamp_enabled = !Rails.env.test?
end
```
Another option is to wait for the timestamp check to be valid:
```ruby
# Maybe inside a before block
InvisibleCaptcha.init!
InvisibleCaptcha.timestamp_threshold = 1
# Before testing your controller action
sleep InvisibleCaptcha.timestamp_threshold
```
If you're using the "random honeypot" approach, you may want to set a known honeypot:
```ruby
config.honeypots = ['my_honeypot_field'] if Rails.env.test?
```
And for the "spinner validation" check, you may want to disable it:
```ruby
config.spinner_enabled = !Rails.env.test?
```
Or alternativelly, you should send a valid spinner value along your requests:
```ruby
# RSpec example
session[:invisible_captcha_spinner] = '32ab649161f9f6faeeb323746de1a25d'
post :create, params: { topic: { title: 'foo' }, spinner: '32ab649161f9f6faeeb323746de1a25d' }
```
## Contribute
Any kind of idea, feedback or bug report are welcome! Open an [issue](https://github.com/markets/invisible_captcha/issues) or send a [pull request](https://github.com/markets/invisible_captcha/pulls).
## Development
Clone/fork this repository, start to hack on it and send a pull request.
Run the test suite:
```
$ bundle exec rspec
```
Run the test suite against all supported versions:
```
$ bundle exec appraisal install
$ bundle exec appraisal rspec
```
Run specs against specific version:
```
$ bundle exec appraisal rails-6.0 rspec
```
### Demo
Start a sample Rails app ([source code](spec/dummy)) with `InvisibleCaptcha` integrated:
```
$ bundle exec rake web # PORT=4000 (default: 3000)
```
## License
Copyright (c) Marc Anguera. Invisible Captcha is released under the [MIT](LICENSE) License.
markets-invisible_captcha-b759a52/Rakefile 0000664 0000000 0000000 00000000441 14575636613 0020651 0 ustar 00root root 0000000 0000000 # frozen_string_literal: true
require "bundler/gem_tasks"
desc 'Start development Rails app'
task :web do
app_path = 'spec/dummy'
port = ENV['PORT'] || 3000
puts "Starting application in http://localhost:#{port} ... \n"
Dir.chdir(app_path)
exec("rails s -p #{port}")
end
markets-invisible_captcha-b759a52/gemfiles/ 0000775 0000000 0000000 00000000000 14575636613 0021000 5 ustar 00root root 0000000 0000000 markets-invisible_captcha-b759a52/gemfiles/rails_5.2.gemfile 0000664 0000000 0000000 00000000164 14575636613 0024031 0 ustar 00root root 0000000 0000000 # This file was generated by Appraisal
source "https://rubygems.org"
gem "rails", "~> 5.2.0"
gemspec path: "../"
markets-invisible_captcha-b759a52/gemfiles/rails_6.0.gemfile 0000664 0000000 0000000 00000000164 14575636613 0024030 0 ustar 00root root 0000000 0000000 # This file was generated by Appraisal
source "https://rubygems.org"
gem "rails", "~> 6.0.0"
gemspec path: "../"
markets-invisible_captcha-b759a52/gemfiles/rails_6.1.gemfile 0000664 0000000 0000000 00000000164 14575636613 0024031 0 ustar 00root root 0000000 0000000 # This file was generated by Appraisal
source "https://rubygems.org"
gem "rails", "~> 6.1.0"
gemspec path: "../"
markets-invisible_captcha-b759a52/gemfiles/rails_7.0.gemfile 0000664 0000000 0000000 00000000164 14575636613 0024031 0 ustar 00root root 0000000 0000000 # This file was generated by Appraisal
source "https://rubygems.org"
gem "rails", "~> 7.0.0"
gemspec path: "../"
markets-invisible_captcha-b759a52/gemfiles/rails_7.1.gemfile 0000664 0000000 0000000 00000000164 14575636613 0024032 0 ustar 00root root 0000000 0000000 # This file was generated by Appraisal
source "https://rubygems.org"
gem "rails", "~> 7.1.0"
gemspec path: "../"
markets-invisible_captcha-b759a52/invisible_captcha.gemspec 0000664 0000000 0000000 00000002066 14575636613 0024225 0 ustar 00root root 0000000 0000000 require './lib/invisible_captcha/version'
Gem::Specification.new do |spec|
spec.name = "invisible_captcha"
spec.version = InvisibleCaptcha::VERSION
spec.authors = ["Marc Anguera Insa"]
spec.email = ["srmarc.ai@gmail.com"]
spec.description = "Unobtrusive, flexible and complete spam protection for Rails applications using honeypot strategy for better user experience."
spec.summary = "Honeypot spam protection for Rails"
spec.homepage = "https://github.com/markets/invisible_captcha"
spec.license = "MIT"
spec.files = `git ls-files`.split($/)
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
spec.require_paths = ["lib"]
spec.add_dependency 'rails', '>= 5.2'
spec.add_development_dependency 'rspec-rails'
spec.add_development_dependency 'appraisal'
spec.add_development_dependency 'webrick'
spec.add_development_dependency 'simplecov'
spec.add_development_dependency 'simplecov-cobertura'
end
markets-invisible_captcha-b759a52/lib/ 0000775 0000000 0000000 00000000000 14575636613 0017753 5 ustar 00root root 0000000 0000000 markets-invisible_captcha-b759a52/lib/invisible_captcha.rb 0000664 0000000 0000000 00000005112 14575636613 0023746 0 ustar 00root root 0000000 0000000 # frozen_string_literal: true
require 'invisible_captcha/version'
require 'invisible_captcha/controller_ext'
require 'invisible_captcha/view_helpers'
require 'invisible_captcha/form_helpers'
require 'invisible_captcha/railtie'
module InvisibleCaptcha
class << self
attr_writer :sentence_for_humans,
:timestamp_error_message
attr_accessor :honeypots,
:timestamp_threshold,
:timestamp_enabled,
:visual_honeypots,
:injectable_styles,
:spinner_enabled,
:secret
def init!
# Default sentence for real users if text field was visible
self.sentence_for_humans = -> { I18n.t('invisible_captcha.sentence_for_humans', default: 'If you are a human, ignore this field') }
# Timestamp check enabled by default
self.timestamp_enabled = true
# Fastest time (in seconds) to expect a human to submit the form
self.timestamp_threshold = 4
# Default error message for validator when form submitted too quickly
self.timestamp_error_message = -> { I18n.t('invisible_captcha.timestamp_error_message', default: 'Sorry, that was too quick! Please resubmit.') }
# Make honeypots visibles
self.visual_honeypots = false
# If enabled, you should call anywhere in your layout the following helper, to inject the honeypot styles:
# <%= invisible_captcha_styles %>
self.injectable_styles = false
# Spinner check enabled by default
self.spinner_enabled = true
# A secret key to encode some internal values
self.secret = ENV['INVISIBLE_CAPTCHA_SECRET'] || SecureRandom.hex(64)
end
def sentence_for_humans
call_lambda_or_return(@sentence_for_humans)
end
def timestamp_error_message
call_lambda_or_return(@timestamp_error_message)
end
def setup
yield(self) if block_given?
end
def honeypots
@honeypots ||= (1..5).map { generate_random_honeypot }
end
def generate_random_honeypot
"abcdefghijkl-mnopqrstuvwxyz".chars.sample(rand(10..20)).join
end
def get_honeypot
honeypots.sample
end
def css_strategy
[
"display:none;",
"position:absolute!important;top:-9999px;left:-9999px;",
"position:absolute!important;height:1px;width:1px;overflow:hidden;"
].sample
end
def encode(value)
Digest::MD5.hexdigest("#{self.secret}-#{value}")
end
private
def call_lambda_or_return(obj)
obj.respond_to?(:call) ? obj.call : obj
end
end
end
InvisibleCaptcha.init!
markets-invisible_captcha-b759a52/lib/invisible_captcha/ 0000775 0000000 0000000 00000000000 14575636613 0023422 5 ustar 00root root 0000000 0000000 markets-invisible_captcha-b759a52/lib/invisible_captcha/controller_ext.rb 0000664 0000000 0000000 00000007337 14575636613 0027024 0 ustar 00root root 0000000 0000000 # frozen_string_literal: true
module InvisibleCaptcha
module ControllerExt
module ClassMethods
def invisible_captcha(options = {})
if options.key?(:prepend)
prepend_before_action(options) do
detect_spam(options)
end
else
before_action(options) do
detect_spam(options)
end
end
end
end
private
def detect_spam(options = {})
if timestamp_spam?(options)
on_timestamp_spam(options)
return if performed?
end
if honeypot_spam?(options) || spinner_spam?
on_spam(options)
end
end
def on_timestamp_spam(options = {})
if action = options[:on_timestamp_spam]
send(action)
else
flash[:error] = InvisibleCaptcha.timestamp_error_message
redirect_back(fallback_location: root_path)
end
end
def on_spam(options = {})
if action = options[:on_spam]
send(action)
else
head(200)
end
end
def timestamp_spam?(options = {})
enabled = if options.key?(:timestamp_enabled)
options[:timestamp_enabled]
else
InvisibleCaptcha.timestamp_enabled
end
return false unless enabled
timestamp = session.delete(:invisible_captcha_timestamp)
# Consider as spam if timestamp not in session, cause that means the form was not fetched at all
unless timestamp
warn_spam("Timestamp not found in session.")
return true
end
time_to_submit = Time.zone.now - DateTime.iso8601(timestamp)
threshold = options[:timestamp_threshold] || InvisibleCaptcha.timestamp_threshold
# Consider as spam if form submitted too quickly
if time_to_submit < threshold
warn_spam("Timestamp threshold not reached (took #{time_to_submit.to_i}s).")
return true
end
false
end
def spinner_spam?
if InvisibleCaptcha.spinner_enabled && (params[:spinner].blank? || params[:spinner] != session[:invisible_captcha_spinner])
warn_spam("Spinner value mismatch")
return true
end
false
end
def honeypot_spam?(options = {})
honeypot = options[:honeypot]
scope = options[:scope] || controller_name.singularize
if honeypot
# If honeypot is defined for this controller-action, search for:
# - honeypot: params[:subtitle]
# - honeypot with scope: params[:topic][:subtitle]
if params[honeypot].present? || (params[scope] && params[scope][honeypot].present?)
warn_spam("Honeypot param '#{honeypot}' was present.")
return true
else
# No honeypot spam detected, remove honeypot from params to avoid UnpermittedParameters exceptions
params.delete(honeypot) if params.key?(honeypot)
params[scope].try(:delete, honeypot) if params.key?(scope)
end
else
InvisibleCaptcha.honeypots.each do |default_honeypot|
if params[default_honeypot].present? || (params[scope] && params[scope][default_honeypot].present?)
warn_spam("Honeypot param '#{scope}.#{default_honeypot}' was present.")
return true
end
end
end
false
end
def warn_spam(message)
message = "[Invisible Captcha] Potential spam detected for IP #{request.remote_ip}. #{message}"
logger.warn(message)
ActiveSupport::Notifications.instrument(
'invisible_captcha.spam_detected',
message: message,
remote_ip: request.remote_ip,
user_agent: request.user_agent,
controller: params[:controller],
action: params[:action],
url: request.url,
params: request.filtered_parameters
)
end
end
end
markets-invisible_captcha-b759a52/lib/invisible_captcha/form_helpers.rb 0000664 0000000 0000000 00000000335 14575636613 0026435 0 ustar 00root root 0000000 0000000 # frozen_string_literal: true
module InvisibleCaptcha
module FormHelpers
def invisible_captcha(honeypot = nil, options = {})
@template.invisible_captcha(honeypot, self.object_name, options)
end
end
end
markets-invisible_captcha-b759a52/lib/invisible_captcha/railtie.rb 0000664 0000000 0000000 00000001011 14575636613 0025371 0 ustar 00root root 0000000 0000000 # frozen_string_literal: true
module InvisibleCaptcha
class Railtie < Rails::Railtie
initializer 'invisible_captcha.rails_integration' do
ActiveSupport.on_load(:action_controller) do
include InvisibleCaptcha::ControllerExt
extend InvisibleCaptcha::ControllerExt::ClassMethods
end
ActiveSupport.on_load(:action_view) do
include InvisibleCaptcha::ViewHelpers
ActionView::Helpers::FormBuilder.send :include, InvisibleCaptcha::FormHelpers
end
end
end
end
markets-invisible_captcha-b759a52/lib/invisible_captcha/version.rb 0000664 0000000 0000000 00000000117 14575636613 0025433 0 ustar 00root root 0000000 0000000 # frozen_string_literal: true
module InvisibleCaptcha
VERSION = "2.3.0"
end
markets-invisible_captcha-b759a52/lib/invisible_captcha/view_helpers.rb 0000664 0000000 0000000 00000006016 14575636613 0026446 0 ustar 00root root 0000000 0000000 # frozen_string_literal: true
module InvisibleCaptcha
module ViewHelpers
# Builds the honeypot html
#
# @param honeypot [Symbol] name of honeypot, ie: subtitle => input name: subtitle
# @param scope [Symbol] name of honeypot scope, ie: topic => input name: topic[subtitle]
# @param options [Hash] html_options for input and invisible_captcha options
#
# @return [String] the generated html
def invisible_captcha(honeypot = nil, scope = nil, options = {})
@captcha_ocurrences = 0 unless defined?(@captcha_ocurrences)
@captcha_ocurrences += 1
if InvisibleCaptcha.timestamp_enabled || InvisibleCaptcha.spinner_enabled
session[:invisible_captcha_timestamp] = Time.zone.now.iso8601
end
if InvisibleCaptcha.spinner_enabled && @captcha_ocurrences == 1
session[:invisible_captcha_spinner] = InvisibleCaptcha.encode("#{session[:invisible_captcha_timestamp]}-#{current_request.remote_ip}")
end
build_invisible_captcha(honeypot, scope, options)
end
def invisible_captcha_styles
if content_for?(:invisible_captcha_styles)
content_for(:invisible_captcha_styles)
end
end
private
def current_request
@request ||= request
end
def build_invisible_captcha(honeypot = nil, scope = nil, options = {})
if honeypot.is_a?(Hash)
options = honeypot
honeypot = nil
end
honeypot = honeypot ? honeypot.to_s : InvisibleCaptcha.get_honeypot
label = options.delete(:sentence_for_humans) || InvisibleCaptcha.sentence_for_humans
css_class = "#{honeypot}_#{Time.zone.now.to_i}"
styles = visibility_css(css_class, options)
provide(:invisible_captcha_styles) do
styles
end if InvisibleCaptcha.injectable_styles
content_tag(:div, class: css_class) do
concat styles unless InvisibleCaptcha.injectable_styles
concat label_tag(build_label_name(honeypot, scope), label)
concat text_field_tag(build_input_name(honeypot, scope), nil, default_honeypot_options.merge(options))
if InvisibleCaptcha.spinner_enabled
concat hidden_field_tag("spinner", session[:invisible_captcha_spinner], id: nil)
end
end
end
def visibility_css(css_class, options)
visible = if options.key?(:visual_honeypots)
options.delete(:visual_honeypots)
else
InvisibleCaptcha.visual_honeypots
end
return if visible
nonce = content_security_policy_nonce if options[:nonce]
content_tag(:style, media: 'screen', nonce: nonce) do
".#{css_class} {#{InvisibleCaptcha.css_strategy}}"
end
end
def build_label_name(honeypot, scope = nil)
if scope.present?
"#{scope}_#{honeypot}"
else
honeypot
end
end
def build_input_name(honeypot, scope = nil)
if scope.present?
"#{scope}[#{honeypot}]"
else
honeypot
end
end
def default_honeypot_options
{ autocomplete: 'off', tabindex: -1 }
end
end
end
markets-invisible_captcha-b759a52/spec/ 0000775 0000000 0000000 00000000000 14575636613 0020137 5 ustar 00root root 0000000 0000000 markets-invisible_captcha-b759a52/spec/controllers_spec.rb 0000664 0000000 0000000 00000016616 14575636613 0024056 0 ustar 00root root 0000000 0000000 # frozen_string_literal: true
RSpec.describe InvisibleCaptcha::ControllerExt, type: :controller do
render_views
before(:each) do
@controller = TopicsController.new
request.env['HTTP_REFERER'] = 'http://test.host/topics'
InvisibleCaptcha.init!
InvisibleCaptcha.timestamp_threshold = 1
InvisibleCaptcha.spinner_enabled = false
end
context 'without invisible_captcha_timestamp in session' do
it 'fails like if it was submitted too fast' do
post :create, params: { topic: { title: 'foo' } }
expect(response).to redirect_to 'http://test.host/topics'
expect(flash[:error]).to eq(InvisibleCaptcha.timestamp_error_message)
end
it 'passes if disabled at action level' do
post :copy, params: { topic: { title: 'foo' } }
expect(flash[:error]).not_to be_present
expect(response.body).to be_present
end
it 'passes if disabled at app level' do
InvisibleCaptcha.timestamp_enabled = false
post :create, params: { topic: { title: 'foo' } }
expect(flash[:error]).not_to be_present
expect(response.body).to be_present
end
end
context 'submission timestamp_threshold' do
before(:each) do
session[:invisible_captcha_timestamp] = Time.zone.now.iso8601
end
it 'fails if submission before timestamp_threshold' do
post :create, params: { topic: { title: 'foo' } }
expect(response).to redirect_to 'http://test.host/topics'
expect(flash[:error]).to eq(InvisibleCaptcha.timestamp_error_message)
# Make sure session is cleared
expect(session[:invisible_captcha_timestamp]).to be_nil
end
it 'allows a custom on_timestamp_spam callback' do
put :update, params: { id: 1, topic: { title: 'bar' } }
expect(response.status).to eq(204)
end
it 'allows a new timestamp to be set in the on_timestamp_spam callback' do
@controller.singleton_class.class_eval do
def custom_timestamp_callback
session[:invisible_captcha_timestamp] = 2.seconds.from_now(Time.zone.now).iso8601
head(204)
end
end
expect { put :update, params: { id: 1, topic: { title: 'bar' } } }
.to change { session[:invisible_captcha_timestamp] }
.to be_present
end
it 'runs on_spam callback if on_timestamp_spam callback is defined but passes' do
put :test_passthrough, params: { id: 1, topic: { title: 'bar', subtitle: 'foo' } }
expect(response.status).to eq(204)
end
context 'successful submissions' do
it 'passes if submission on or after timestamp_threshold' do
sleep InvisibleCaptcha.timestamp_threshold
post :create, params: {
topic: {
title: 'foobar',
author: 'author',
body: 'body that passes validation'
}
}
expect(flash[:error]).not_to be_present
expect(response.body).to redirect_to(new_topic_path)
# Make sure session is cleared
expect(session[:invisible_captcha_timestamp]).to be_nil
end
it 'allow to set a custom timestamp_threshold per action' do
sleep 2 # custom threshold
post :publish, params: { id: 1 }
expect(flash[:error]).not_to be_present
expect(response.body).to redirect_to(new_topic_path)
end
it 'passes if on_timestamp_spam doesn\'t perform' do
put :test_passthrough, params: { id: 1, topic: { title: 'bar' } }
expect(response.body).to redirect_to(new_topic_path)
end
end
end
context 'honeypot attribute' do
before(:each) do
session[:invisible_captcha_timestamp] = Time.zone.now.iso8601
# Wait for valid submission
sleep InvisibleCaptcha.timestamp_threshold
end
it 'fails with spam' do
post :create, params: { topic: { subtitle: 'foo' } }
expect(response.body).to be_blank
end
it 'passes with no spam' do
post :create, params: { topic: { title: 'foo' } }
expect(response.body).to be_present
end
context 'with random honeypot' do
context 'auto-scoped' do
it 'passes with no spam' do
post :categorize, params: { topic: { title: 'foo' } }
expect(response.body).to redirect_to(new_topic_path)
end
it 'fails with spam' do
post :categorize, params: { topic: { "#{InvisibleCaptcha.honeypots.sample}": 'foo' } }
expect(response.body).not_to redirect_to(new_topic_path)
end
end
context 'with no scope' do
it 'passes with no spam' do
post :categorize
expect(response.body).to redirect_to(new_topic_path)
end
it 'fails with spam' do
post :categorize, params: { "#{InvisibleCaptcha.honeypots.sample}": 'foo' }
expect(response.body).not_to redirect_to(new_topic_path)
end
end
context 'with scope' do
it 'fails with spam' do
post :rename, params: { topic: { "#{InvisibleCaptcha.honeypots.sample}": 'foo' } }
expect(response.body).to be_blank
end
it 'passes with no spam' do
post :rename, params: { topic: { title: 'foo' } }
expect(response.body).to be_blank
end
end
end
it 'allow a custom on_spam callback' do
put :update, params: { id: 1, topic: { subtitle: 'foo' } }
expect(response.body).to redirect_to(new_topic_path)
end
it 'honeypot is removed from params if you use a custom honeypot' do
post :create, params: { topic: { title: 'foo', subtitle: '' } }
expect(flash[:error]).not_to be_present
expect(@controller.params[:topic].key?(:subtitle)).to eq(false)
end
describe 'ActiveSupport::Notifications' do
let(:dummy_handler) { double(handle_event: nil) }
let!(:subscriber) do
subscriber = ActiveSupport::Notifications.subscribe('invisible_captcha.spam_detected') do |*args, data|
dummy_handler.handle_event(data)
end
subscriber
end
after { ActiveSupport::Notifications.unsubscribe(subscriber) }
it 'dispatches an `invisible_captcha.spam_detected` event' do
expect(dummy_handler).to receive(:handle_event).once.with({
message: "[Invisible Captcha] Potential spam detected for IP 0.0.0.0. Honeypot param 'subtitle' was present.",
remote_ip: '0.0.0.0',
user_agent: 'Rails Testing',
controller: 'topics',
action: 'create',
url: 'http://test.host/topics',
params: {
topic: { subtitle: "foo"},
controller: 'topics',
action: 'create'
}
})
post :create, params: { topic: { subtitle: 'foo' } }
end
end
end
context 'spinner attribute' do
before(:each) do
InvisibleCaptcha.spinner_enabled = true
InvisibleCaptcha.secret = 'secret'
session[:invisible_captcha_timestamp] = Time.zone.now.iso8601
session[:invisible_captcha_spinner] = '32ab649161f9f6faeeb323746de1a25d'
# Wait for valid submission
sleep InvisibleCaptcha.timestamp_threshold
end
it 'fails with no spam, but mismatch of spinner' do
post :create, params: { topic: { title: 'foo' }, spinner: 'mismatch' }
expect(response.body).to be_blank
end
it 'passes with no spam and spinner match' do
post :create, params: { topic: { title: 'foo' }, spinner: '32ab649161f9f6faeeb323746de1a25d' }
expect(response.body).to be_present
end
end
end
markets-invisible_captcha-b759a52/spec/dummy/ 0000775 0000000 0000000 00000000000 14575636613 0021272 5 ustar 00root root 0000000 0000000 markets-invisible_captcha-b759a52/spec/dummy/README.md 0000664 0000000 0000000 00000000520 14575636613 0022546 0 ustar 00root root 0000000 0000000 # Dummy App
Dummy Rails Application to test `Invisible Captcha`.
It's also used as a demo application to show `Invisible Captcha` in action. You can run the app by using the following command, from the root of the project:
> bundle exec rake web
[« Back to Docs](https://github.com/markets/invisible_captcha#invisible-captcha)
markets-invisible_captcha-b759a52/spec/dummy/Rakefile 0000664 0000000 0000000 00000000416 14575636613 0022740 0 ustar 00root root 0000000 0000000 #!/usr/bin/env rake
# Add your own tasks in files placed in lib/tasks ending in .rake,
# for example lib/tasks/capistrano.rake, and they will automatically be available to Rake.
require File.expand_path('../config/application', __FILE__)
Dummy::Application.load_tasks
markets-invisible_captcha-b759a52/spec/dummy/app/ 0000775 0000000 0000000 00000000000 14575636613 0022052 5 ustar 00root root 0000000 0000000 markets-invisible_captcha-b759a52/spec/dummy/app/controllers/ 0000775 0000000 0000000 00000000000 14575636613 0024420 5 ustar 00root root 0000000 0000000 markets-invisible_captcha-b759a52/spec/dummy/app/controllers/application_controller.rb 0000664 0000000 0000000 00000000120 14575636613 0031504 0 ustar 00root root 0000000 0000000 class ApplicationController < ActionController::Base
protect_from_forgery
end
markets-invisible_captcha-b759a52/spec/dummy/app/controllers/topics_controller.rb 0000664 0000000 0000000 00000003242 14575636613 0030512 0 ustar 00root root 0000000 0000000 class TopicsController < ApplicationController
invisible_captcha honeypot: :subtitle, only: :create
invisible_captcha honeypot: :subtitle, only: :update,
on_spam: :custom_callback,
on_timestamp_spam: :custom_timestamp_callback
invisible_captcha honeypot: :subtitle, only: :publish, timestamp_threshold: 2
invisible_captcha honeypot: :subtitle, only: :copy, timestamp_enabled: false
invisible_captcha scope: :topic, only: :rename
invisible_captcha only: :categorize
invisible_captcha honeypot: :subtitle, only: :test_passthrough,
on_spam: :catching_on_spam_callback,
on_timestamp_spam: :on_timestamp_spam_callback_with_passthrough
def index
redirect_to new_topic_path
end
def new
@topic = Topic.new
end
def create
@topic = Topic.new(params[:topic])
if @topic.valid?
redirect_to new_topic_path(context: params[:context]), notice: 'Topic valid!'
else
render action: 'new'
end
end
def update
redirect_to new_topic_path
end
def rename
end
def categorize
redirect_to new_topic_path
end
def publish
redirect_to new_topic_path
end
def copy
@topic = Topic.new(params[:topic])
if @topic.valid?
redirect_to new_topic_path(context: params[:context]), notice: 'Success!'
else
render action: 'new'
end
end
def test_passthrough
redirect_to new_topic_path
end
private
def custom_callback
redirect_to new_topic_path
end
def custom_timestamp_callback
head(204)
end
def on_timestamp_spam_callback_with_passthrough
end
def catching_on_spam_callback
head(204)
end
end
markets-invisible_captcha-b759a52/spec/dummy/app/helpers/ 0000775 0000000 0000000 00000000000 14575636613 0023514 5 ustar 00root root 0000000 0000000 markets-invisible_captcha-b759a52/spec/dummy/app/helpers/application_helper.rb 0000664 0000000 0000000 00000000035 14575636613 0027701 0 ustar 00root root 0000000 0000000 module ApplicationHelper
end
markets-invisible_captcha-b759a52/spec/dummy/app/models/ 0000775 0000000 0000000 00000000000 14575636613 0023335 5 ustar 00root root 0000000 0000000 markets-invisible_captcha-b759a52/spec/dummy/app/models/topic.rb 0000664 0000000 0000000 00000000631 14575636613 0025000 0 ustar 00root root 0000000 0000000 class Topic
include ActiveModel::Validations
include ActiveModel::Conversion
attr_accessor :title, :author, :body, :subtitle
validates :title, length: { minimum: 5 }
validates :author, presence: true
validates :body, length: { minimum: 10 }
def initialize(attributes = {})
attributes.each do |name, value|
send("#{name}=", value)
end
end
def persisted?
false
end
end
markets-invisible_captcha-b759a52/spec/dummy/app/views/ 0000775 0000000 0000000 00000000000 14575636613 0023207 5 ustar 00root root 0000000 0000000 markets-invisible_captcha-b759a52/spec/dummy/app/views/layouts/ 0000775 0000000 0000000 00000000000 14575636613 0024707 5 ustar 00root root 0000000 0000000 markets-invisible_captcha-b759a52/spec/dummy/app/views/layouts/application.html.erb 0000664 0000000 0000000 00000001444 14575636613 0030652 0 ustar 00root root 0000000 0000000
InvisibleCaptcha Demo
<%= stylesheet_link_tag "/styles.css" %>
<%= csrf_meta_tags %>
<%= invisible_captcha_styles %>
<% end %>
markets-invisible_captcha-b759a52/spec/dummy/bin/ 0000775 0000000 0000000 00000000000 14575636613 0022042 5 ustar 00root root 0000000 0000000 markets-invisible_captcha-b759a52/spec/dummy/bin/bundle 0000775 0000000 0000000 00000000201 14575636613 0023232 0 ustar 00root root 0000000 0000000 #!/usr/bin/env ruby
ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__)
load Gem.bin_path('bundler', 'bundle')
markets-invisible_captcha-b759a52/spec/dummy/bin/rails 0000775 0000000 0000000 00000000221 14575636613 0023075 0 ustar 00root root 0000000 0000000 #!/usr/bin/env ruby
APP_PATH = File.expand_path('../../config/application', __FILE__)
require_relative '../config/boot'
require 'rails/commands'
markets-invisible_captcha-b759a52/spec/dummy/bin/rake 0000775 0000000 0000000 00000000132 14575636613 0022706 0 ustar 00root root 0000000 0000000 #!/usr/bin/env ruby
require_relative '../config/boot'
require 'rake'
Rake.application.run
markets-invisible_captcha-b759a52/spec/dummy/bin/setup 0000775 0000000 0000000 00000001445 14575636613 0023134 0 ustar 00root root 0000000 0000000 #!/usr/bin/env ruby
require 'pathname'
# path to your application root.
APP_ROOT = Pathname.new File.expand_path('../../', __FILE__)
Dir.chdir APP_ROOT do
# This script is a starting point to setup your application.
# Add necessary setup steps to this file:
puts "== Installing dependencies =="
system "gem install bundler --conservative"
system "bundle check || bundle install"
# puts "\n== Copying sample files =="
# unless File.exist?("config/database.yml")
# system "cp config/database.yml.sample config/database.yml"
# end
puts "\n== Preparing database =="
system "bin/rake db:setup"
puts "\n== Removing old logs and tempfiles =="
system "rm -f log/*"
system "rm -rf tmp/cache"
puts "\n== Restarting application server =="
system "touch tmp/restart.txt"
end
markets-invisible_captcha-b759a52/spec/dummy/config.ru 0000664 0000000 0000000 00000000233 14575636613 0023105 0 ustar 00root root 0000000 0000000 # This file is used by Rack-based servers to start the application.
require ::File.expand_path('../config/environment', __FILE__)
run Dummy::Application
markets-invisible_captcha-b759a52/spec/dummy/config/ 0000775 0000000 0000000 00000000000 14575636613 0022537 5 ustar 00root root 0000000 0000000 markets-invisible_captcha-b759a52/spec/dummy/config/application.rb 0000664 0000000 0000000 00000002304 14575636613 0025366 0 ustar 00root root 0000000 0000000 require File.expand_path('../boot', __FILE__)
require 'action_controller/railtie'
require 'action_view/railtie'
require 'active_model/railtie'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
require 'invisible_captcha'
module Dummy
class Application < Rails::Application
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
# config.time_zone = 'Central Time (US & Canada)'
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
# config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
# config.i18n.default_locale = :de
# Do not swallow errors in after_commit/after_rollback callbacks.
# config.active_record.raise_in_transactional_callbacks = true
end
end
markets-invisible_captcha-b759a52/spec/dummy/config/boot.rb 0000664 0000000 0000000 00000000200 14575636613 0024017 0 ustar 00root root 0000000 0000000 ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../Gemfile', __dir__)
require 'bundler/setup' # Set up gems listed in the Gemfile.
markets-invisible_captcha-b759a52/spec/dummy/config/environment.rb 0000664 0000000 0000000 00000000200 14575636613 0025420 0 ustar 00root root 0000000 0000000 # Load the Rails application.
require_relative 'application'
# Initialize the Rails application.
Rails.application.initialize!
markets-invisible_captcha-b759a52/spec/dummy/config/environments/ 0000775 0000000 0000000 00000000000 14575636613 0025266 5 ustar 00root root 0000000 0000000 markets-invisible_captcha-b759a52/spec/dummy/config/environments/development.rb 0000664 0000000 0000000 00000003113 14575636613 0030133 0 ustar 00root root 0000000 0000000 Dummy::Application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# In the development environment your application's code is reloaded on
# every request. This slows down response time but is perfect for development
# since you don't have to restart the web server when you make code changes.
config.cache_classes = false
# Do not eager load code on boot.
config.eager_load = false
# Show full error reports and disable caching.
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
# Don't care if the mailer can't send.
# config.action_mailer.raise_delivery_errors = false
# Print deprecation notices to the Rails logger.
config.active_support.deprecation = :log
# Raise an error on page load if there are pending migrations.
# config.active_record.migration_error = :page_load
# Debug mode disables concatenation and preprocessing of assets.
# This option may cause significant delays in view rendering with a large
# number of complex assets.
# config.assets.debug = true
# Asset digests allow you to set far-future HTTP expiration dates on all assets,
# yet still be able to expire them through the digest params.
# config.assets.digest = true
# Adds additional error checking when serving assets at runtime.
# Checks for improperly declared sprockets dependencies.
# Raises helpful error messages.
# config.assets.raise_runtime_errors = true
# Raises error for missing translations
# config.action_view.raise_on_missing_translations = true
end
markets-invisible_captcha-b759a52/spec/dummy/config/environments/test.rb 0000664 0000000 0000000 00000003140 14575636613 0026570 0 ustar 00root root 0000000 0000000 Dummy::Application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# The test environment is used exclusively to run your application's
# test suite. You never need to work with it otherwise. Remember that
# your test database is "scratch space" for the test suite and is wiped
# and recreated between test runs. Don't rely on the data there!
config.cache_classes = true
# Do not eager load code on boot. This avoids loading your whole application
# just for the purpose of running a single test. If you are using a tool that
# preloads Rails for running tests, you may have to set it to true.
config.eager_load = false
# Disable serving static files from the `/public` folder by default since
# Apache or NGINX already handles this.
config.public_file_server.enabled = true
config.public_file_server.headers = {'Cache-Control' => 'public, max-age=3600'}
# Show full error reports and disable caching.
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
# Raise exceptions instead of rendering exception templates.
config.action_dispatch.show_exceptions = false
# Disable request forgery protection in test environment.
config.action_controller.allow_forgery_protection = false
# Tell Action Mailer not to deliver emails to the real world.
# The :test delivery method accumulates sent emails in the
# ActionMailer::Base.deliveries array.
# config.action_mailer.delivery_method = :test
# Print deprecation notices to the stderr.
config.active_support.deprecation = :stderr
end
markets-invisible_captcha-b759a52/spec/dummy/config/initializers/ 0000775 0000000 0000000 00000000000 14575636613 0025245 5 ustar 00root root 0000000 0000000 markets-invisible_captcha-b759a52/spec/dummy/config/initializers/backtrace_silencers.rb 0000664 0000000 0000000 00000000624 14575636613 0031562 0 ustar 00root root 0000000 0000000 # Be sure to restart your server when you modify this file.
# You can add backtrace silencers for libraries that you're using but don't wish to see in your backtraces.
# Rails.backtrace_cleaner.add_silencer { |line| line =~ /my_noisy_library/ }
# You can also remove all the silencers if you're trying to debug a problem that might stem from framework code.
# Rails.backtrace_cleaner.remove_silencers!
markets-invisible_captcha-b759a52/spec/dummy/config/initializers/cookies_serializer.rb 0000664 0000000 0000000 00000000204 14575636613 0031453 0 ustar 00root root 0000000 0000000 # Be sure to restart your server when you modify this file.
Rails.application.config.action_dispatch.cookies_serializer = :marshal
markets-invisible_captcha-b759a52/spec/dummy/config/initializers/filter_parameter_logging.rb 0000664 0000000 0000000 00000000302 14575636613 0032620 0 ustar 00root root 0000000 0000000 # Be sure to restart your server when you modify this file.
# Configure sensitive parameters which will be filtered from the log file.
Rails.application.config.filter_parameters += [:password]
markets-invisible_captcha-b759a52/spec/dummy/config/initializers/inflections.rb 0000664 0000000 0000000 00000001207 14575636613 0030107 0 ustar 00root root 0000000 0000000 # Be sure to restart your server when you modify this file.
# Add new inflection rules using the following format. Inflections
# are locale specific, and you may define rules for as many different
# locales as you wish. All of these examples are active by default:
# ActiveSupport::Inflector.inflections(:en) do |inflect|
# inflect.plural /^(ox)$/i, '\1en'
# inflect.singular /^(ox)en/i, '\1'
# inflect.irregular 'person', 'people'
# inflect.uncountable %w( fish sheep )
# end
# These inflection rules are supported but not enabled by default:
# ActiveSupport::Inflector.inflections(:en) do |inflect|
# inflect.acronym 'RESTful'
# end
markets-invisible_captcha-b759a52/spec/dummy/config/initializers/mime_types.rb 0000664 0000000 0000000 00000000234 14575636613 0027744 0 ustar 00root root 0000000 0000000 # Be sure to restart your server when you modify this file.
# Add new mime types for use in respond_to blocks:
# Mime::Type.register "text/richtext", :rtf
markets-invisible_captcha-b759a52/spec/dummy/config/initializers/secret_token.rb 0000664 0000000 0000000 00000000760 14575636613 0030262 0 ustar 00root root 0000000 0000000 # Be sure to restart your server when you modify this file.
# Your secret key for verifying the integrity of signed cookies.
# If you change this key, all old signed cookies will become invalid!
# Make sure the secret is at least 30 characters and all random,
# no regular words or you'll be exposed to dictionary attacks.
Dummy::Application.config.secret_token = '99a354dfaace29d4d6daae4be11b63c13799e60ddff44a5880b12bf2e551de5daef2688495da1475131b5b0a85e57c4303a6b72834edc8a1b51a8c94d9949d59'
markets-invisible_captcha-b759a52/spec/dummy/config/initializers/session_store.rb 0000664 0000000 0000000 00000000211 14575636613 0030463 0 ustar 00root root 0000000 0000000 # Be sure to restart your server when you modify this file.
Rails.application.config.session_store :cookie_store, key: '_dummy_session'
markets-invisible_captcha-b759a52/spec/dummy/config/initializers/wrap_parameters.rb 0000664 0000000 0000000 00000001005 14575636613 0030762 0 ustar 00root root 0000000 0000000 # Be sure to restart your server when you modify this file.
# This file contains settings for ActionController::ParamsWrapper which
# is enabled by default.
# Enable parameter wrapping for JSON. You can disable this by setting :format to an empty array.
ActiveSupport.on_load(:action_controller) do
wrap_parameters format: [:json] if respond_to?(:wrap_parameters)
end
# To enable root element in JSON for ActiveRecord objects.
# ActiveSupport.on_load(:active_record) do
# self.include_root_in_json = true
# end
markets-invisible_captcha-b759a52/spec/dummy/config/locales/ 0000775 0000000 0000000 00000000000 14575636613 0024161 5 ustar 00root root 0000000 0000000 markets-invisible_captcha-b759a52/spec/dummy/config/locales/en.yml 0000664 0000000 0000000 00000001172 14575636613 0025307 0 ustar 00root root 0000000 0000000 # Files in the config/locales directory are used for internationalization
# and are automatically loaded by Rails. If you want to use locales other
# than English, add the necessary files in this directory.
#
# To use the locales, use `I18n.t`:
#
# I18n.t 'hello'
#
# In views, this is aliased to just `t`:
#
# <%= t('hello') %>
#
# To use a different locale, set it with `I18n.locale`:
#
# I18n.locale = :es
#
# This would use the information in config/locales/es.yml.
#
# To learn more, please read the Rails Internationalization guide
# available at http://guides.rubyonrails.org/i18n.html.
en:
hello: "Hello world"
markets-invisible_captcha-b759a52/spec/dummy/config/routes.rb 0000664 0000000 0000000 00000000416 14575636613 0024406 0 ustar 00root root 0000000 0000000 Rails.application.routes.draw do
resources :topics do
post :publish, on: :member
post :rename, on: :collection
post :categorize, on: :collection
post :copy, on: :collection
post :test_passthrough, on: :collection
end
root to: 'topics#new'
end
markets-invisible_captcha-b759a52/spec/dummy/config/secrets.yml 0000664 0000000 0000000 00000001704 14575636613 0024734 0 ustar 00root root 0000000 0000000 # Be sure to restart your server when you modify this file.
# Your secret key is used for verifying the integrity of signed cookies.
# If you change this key, all old signed cookies will become invalid!
# Make sure the secret is at least 30 characters and all random,
# no regular words or you'll be exposed to dictionary attacks.
# You can use `rake secret` to generate a secure secret key.
# Make sure the secrets in this file are kept private
# if you're sharing your code publicly.
development:
secret_key_base: d55ed9a6ec6fc0b93d2404994c8632220ab5835d77ccbd52760c6fc4b9e0c83f87d78d9c2b66d366a698933feeac81efc445b29bad22c9f267ebdadbc5aebbd4
test:
secret_key_base: 5df5772ea2c76236d1444a2e7a491c9f99f9bc96770b6b52e995555ea7a70b2bd3a3d0a45bbe7d32bf1a0eb450db7e32a838e6aa17c494b464ff381bb4bf9910
# Do not keep production secrets in the repository,
# instead read values from the environment.
production:
secret_key_base: <%= ENV["SECRET_KEY_BASE"] %>
markets-invisible_captcha-b759a52/spec/dummy/log/ 0000775 0000000 0000000 00000000000 14575636613 0022053 5 ustar 00root root 0000000 0000000 markets-invisible_captcha-b759a52/spec/dummy/log/.gitkeep 0000664 0000000 0000000 00000000000 14575636613 0023472 0 ustar 00root root 0000000 0000000 markets-invisible_captcha-b759a52/spec/dummy/public/ 0000775 0000000 0000000 00000000000 14575636613 0022550 5 ustar 00root root 0000000 0000000 markets-invisible_captcha-b759a52/spec/dummy/public/404.html 0000664 0000000 0000000 00000001330 14575636613 0023742 0 ustar 00root root 0000000 0000000
The page you were looking for doesn't exist (404)
The page you were looking for doesn't exist.
You may have mistyped the address or the page may have moved.
markets-invisible_captcha-b759a52/spec/dummy/public/422.html 0000664 0000000 0000000 00000001307 14575636613 0023746 0 ustar 00root root 0000000 0000000
The change you wanted was rejected (422)
The change you wanted was rejected.
Maybe you tried to change something you didn't have access to.
markets-invisible_captcha-b759a52/spec/dummy/public/500.html 0000664 0000000 0000000 00000001203 14575636613 0023736 0 ustar 00root root 0000000 0000000
We're sorry, but something went wrong (500)
We're sorry, but something went wrong.
markets-invisible_captcha-b759a52/spec/dummy/public/favicon.ico 0000664 0000000 0000000 00000000000 14575636613 0024657 0 ustar 00root root 0000000 0000000 markets-invisible_captcha-b759a52/spec/dummy/public/styles.css 0000664 0000000 0000000 00000001025 14575636613 0024603 0 ustar 00root root 0000000 0000000 body {
font-family: Arial, Helvetica, sans-serif;
background-color: #ccc;
margin: 2em;
}
h1 {
border-bottom: 3px solid;
}
a {
color: #000;
}
input, textarea {
border: 0;
margin-bottom: 1.5em;
}
input {
height: 2em;
}
button {
color: #fff;
background-color: #000;
border: none;
border-radius: 0.25em;
height: 3em;
width: 10em;
font-size: 1em;
}
footer {
position: fixed;
bottom: 0;
width: 100%;
padding: 1em 0;
font-size: 0.8em;
background-color: #ccc;
}
.errors {
color: darkred;
}
markets-invisible_captcha-b759a52/spec/invisible_captcha_spec.rb 0000664 0000000 0000000 00000003707 14575636613 0025154 0 ustar 00root root 0000000 0000000 # frozen_string_literal: true
RSpec.describe InvisibleCaptcha do
it 'initialize with defaults' do
InvisibleCaptcha.init!
expect(InvisibleCaptcha.sentence_for_humans).to eq('If you are a human, ignore this field')
expect(InvisibleCaptcha.timestamp_threshold).to eq(4.seconds)
expect(InvisibleCaptcha.timestamp_error_message).to eq('Sorry, that was too quick! Please resubmit.')
expect(InvisibleCaptcha.honeypots).to be_an_instance_of(Array)
expect(InvisibleCaptcha.injectable_styles).to eq(false)
end
it 'allow setup via block' do
InvisibleCaptcha.setup do |ic|
ic.sentence_for_humans = 'Another sentence'
end
expect(InvisibleCaptcha.sentence_for_humans).to eq('Another sentence')
end
it 'It uses I18n when available' do
InvisibleCaptcha.init!
I18n.available_locales = [:en, :fr]
I18n.backend.store_translations(:en,
'invisible_captcha' => {
'sentence_for_humans' => "Can't touch this",
'timestamp_error_message' => 'Fast and furious' })
I18n.backend.store_translations(:fr,
'invisible_captcha' => {
'sentence_for_humans' => 'Ne touchez pas',
'timestamp_error_message' => 'Plus doucement SVP' })
I18n.locale = :en
expect(InvisibleCaptcha.sentence_for_humans).to eq("Can't touch this")
expect(InvisibleCaptcha.timestamp_error_message).to eq('Fast and furious')
I18n.locale = :fr
expect(InvisibleCaptcha.sentence_for_humans).to eq('Ne touchez pas')
expect(InvisibleCaptcha.timestamp_error_message).to eq('Plus doucement SVP')
I18n.backend.reload!
expect(InvisibleCaptcha.sentence_for_humans).to eq('If you are a human, ignore this field')
expect(InvisibleCaptcha.timestamp_error_message).to eq('Sorry, that was too quick! Please resubmit.')
end
end
markets-invisible_captcha-b759a52/spec/spec_helper.rb 0000664 0000000 0000000 00000001142 14575636613 0022753 0 ustar 00root root 0000000 0000000 # frozen_string_literal: true
ENV['RAILS_ENV'] = 'test'
require 'simplecov'
if ENV['CI']
require 'simplecov-cobertura'
SimpleCov.formatter = SimpleCov::Formatter::CoberturaFormatter
end
SimpleCov.start
require File.expand_path("../dummy/config/environment.rb", __FILE__)
require 'rspec/rails'
require 'invisible_captcha'
RSpec.configure do |config|
config.include ActionDispatch::ContentSecurityPolicy::Request, type: :helper
config.disable_monkey_patching!
config.order = :random
config.expect_with :rspec
config.mock_with :rspec do |mocks|
mocks.verify_partial_doubles = true
end
end
markets-invisible_captcha-b759a52/spec/view_helpers_spec.rb 0000664 0000000 0000000 00000006020 14575636613 0024170 0 ustar 00root root 0000000 0000000 # frozen_string_literal: true
RSpec.describe InvisibleCaptcha::ViewHelpers, type: :helper do
before(:each) do
allow(InvisibleCaptcha).to receive(:css_strategy).and_return("display:none;")
allow_any_instance_of(ActionDispatch::ContentSecurityPolicy::Request).to receive(:content_security_policy_nonce).and_return('123')
# to test content_for and provide
@view_flow = ActionView::OutputFlow.new
InvisibleCaptcha.init!
end
it 'with no arguments' do
InvisibleCaptcha.honeypots = [:foo_id]
expect(invisible_captcha).to match(/name="foo_id"/)
end
it 'with specific honeypot' do
expect(invisible_captcha(:subtitle)).to match(/name="subtitle"/)
end
it 'with specific honeypot and scope' do
expect(invisible_captcha(:subtitle, :topic)).to match(/name="topic\[subtitle\]"/)
end
it 'with custom html options' do
expect(invisible_captcha(:subtitle, :topic, { class: 'foo_class' })).to match(/class="foo_class"/)
end
it 'with CSP nonce' do
expect(invisible_captcha(:subtitle, :topic, { nonce: true })).to match(/nonce="123"/)
end
it 'generated html + styles' do
InvisibleCaptcha.honeypots = [:foo_id]
output = invisible_captcha.gsub("\"", "'")
regexp = %r{
}
expect(output).to match(regexp)
end
context "honeypot visibilty" do
it 'visible from defaults' do
InvisibleCaptcha.visual_honeypots = true
expect(invisible_captcha).not_to match(/display:none/)
end
it 'visible from given instance (default override)' do
expect(invisible_captcha(visual_honeypots: true)).not_to match(/display:none/)
end
it 'invisible from given instance (default override)' do
InvisibleCaptcha.visual_honeypots = true
expect(invisible_captcha(visual_honeypots: false)).to match(/display:none/)
end
end
context "should have spinner field" do
it 'that exists by default, spinner_enabled is true' do
InvisibleCaptcha.spinner_enabled = true
expect(invisible_captcha).to match(/spinner/)
end
it 'that does not exist if spinner_enabled is false' do
InvisibleCaptcha.spinner_enabled = false
expect(invisible_captcha).not_to match(/spinner/)
end
end
it 'should set spam timestamp' do
invisible_captcha
expect(session[:invisible_captcha_timestamp]).to eq(Time.zone.now.iso8601)
end
context 'injectable_styles option' do
it 'by default, render styles along with the honeypot' do
expect(invisible_captcha).to match(/display:none/)
expect(@view_flow.content[:invisible_captcha_styles]).to be_blank
end
it 'if injectable_styles is set, do not append styles inline' do
InvisibleCaptcha.injectable_styles = true
expect(invisible_captcha).not_to match(/display:none;/)
expect(@view_flow.content[:invisible_captcha_styles]).to match(/display:none;/)
end
end
end