Turnstile Ruby
A simple Ruby client for verifying Cloudflare Turnstile tokens. Turnstile is a CAPTCHA alternative from Cloudflare, similar to Google reCAPTCHA, but lightweight and privacy-friendly.
This gem makes it easy to integrate Turnstile into Ruby and Rails applications.
β¨ Features
- Verify Turnstile tokens with Cloudflareβs API
- Lightweight, no heavy dependencies
- Works with plain Ruby and Ruby on Rails
- Provides meaningful error codes and success flags
- Simple configuration via environment variables or initializer
π¦ Installation
Add this line to your Gemfile:
gem "turnstile-ruby"
And install:
bundle install
Or install directly with:
gem install turnstile-ruby
βοΈ Configuration
Set your Cloudflare Turnstile Site Key and Secret Key in environment variables:
export TURNSTILE_SITE_KEY="your_site_key"
export TURNSTILE_SECRET_KEY="your_secret_key"
For Rails, you can create an initializer (config/initializers/turnstile.rb
):
Turnstile.configure do |config|
config.site_key = ENV["TURNSTILE_SITE_KEY"]
config.secret_key = ENV["TURNSTILE_SECRET_KEY"]
config.timeout = 5 # optional, in seconds
end
π Usage
Rails Views
Embed the Turnstile widget:
<form action="/signup" method="POST">
<!-- Your form fields -->
<div class="cf-turnstile"
data-sitekey="<%= Turnstile.site_key %>">
</div>
<button type="submit">Submit</button>
</form>
<script src="https://challenges.cloudflare.com/turnstile/v0/api.js" async defer></script>
Rails Controller
Verify the token on form submission:
def create
token = params["cf-turnstile-response"]
result = Turnstile.verify(token, remote_ip: request.remote_ip)
if result.success?
# proceed with signup
else
flash[:error] = "Turnstile verification failed: #{result.error_codes.join(", ")}"
render :new
end
end
Plain Ruby Example
require "turnstile"
token = "client-submitted-token"
result = Turnstile.verify(token)
if result.success?
puts "Verification passed!"
else
puts "Verification failed: #{result.error_codes.inspect}"
end
β Response Object
Turnstile.verify
returns a Turnstile::Response
object with:
-
success?
βtrue
orfalse
-
error_codes
β array of error codes -
hostname
β hostname (if provided) -
challenge_ts
β challenge timestamp (if provided)
π Development
Clone the repo and install dependencies:
git clone https://github.com/urkkv/turnstile-ruby.git
cd turnstile-ruby
bundle install
Run tests:
bundle exec rspec
π License
This project is licensed under the MIT License.
π Contributing
Bug reports and pull requests are welcome at
https://github.com/urkkv/turnstile-ruby.