{"id":13423479,"url":"https://github.com/huacnlee/rucaptcha","last_synced_at":"2025-05-14T01:04:43.805Z","repository":{"id":1866888,"uuid":"44949349","full_name":"huacnlee/rucaptcha","owner":"huacnlee","description":"Captcha Gem for Rails, which generates captcha image by Rust.","archived":false,"fork":false,"pushed_at":"2025-02-12T07:47:27.000Z","size":390,"stargazers_count":693,"open_issues_count":3,"forks_count":132,"subscribers_count":17,"default_branch":"main","last_synced_at":"2025-04-03T17:25:23.496Z","etag":null,"topics":["captcha","ffi","magnus","recaptcha","rust"],"latest_commit_sha":null,"homepage":"https://huacnlee.github.io/rucaptcha","language":"Ruby","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/huacnlee.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2015-10-26T06:07:48.000Z","updated_at":"2025-02-12T07:47:30.000Z","dependencies_parsed_at":"2024-01-13T19:23:22.069Z","dependency_job_id":"d2b89340-3e2e-42a2-a8f7-b0079969dbaf","html_url":"https://github.com/huacnlee/rucaptcha","commit_stats":{"total_commits":223,"total_committers":30,"mean_commits":7.433333333333334,"dds":"0.15695067264573992","last_synced_commit":"c4ee69a712d6981124c0fe772fdf6600471ca380"},"previous_names":[],"tags_count":63,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/huacnlee%2Frucaptcha","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/huacnlee%2Frucaptcha/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/huacnlee%2Frucaptcha/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/huacnlee%2Frucaptcha/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/huacnlee","download_url":"https://codeload.github.com/huacnlee/rucaptcha/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248294134,"owners_count":21079788,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["captcha","ffi","magnus","recaptcha","rust"],"created_at":"2024-07-31T00:00:35.595Z","updated_at":"2025-04-10T20:43:51.077Z","avatar_url":"https://github.com/huacnlee.png","language":"Ruby","funding_links":[],"categories":["C","Ruby"],"sub_categories":[],"readme":"# RuCaptcha\n\n[![Gem Version](https://badge.fury.io/rb/rucaptcha.svg)](https://badge.fury.io/rb/rucaptcha)\n[![build](https://github.com/huacnlee/rucaptcha/workflows/build/badge.svg)](https://github.com/huacnlee/rucaptcha/actions?query=workflow%3Abuild)\n\nCaptcha Gem for Rails, which generates captcha image by Rust.\n\n\u003e NOTE: According to the use of Ruby China, the verification code looks like has a lower than 5% probability of being parsed by OCR and the verification code is cracked (All Image Captcha libs are has same problem). It is recommended that you use the IP rate limit to enhance the protection.\n\u003e NOTE: 以 Ruby China 的使用来看，验证码似乎有低于 5% 的概率被 OCR 读取解析 (图片验证码都有这个问题) 导致验证码被破解（我们从日志分析绝大多数是成功的，但偶尔一个成功，配合大量机器攻击，导致注册了很多的垃圾账号），建议你额外配合 IP 频率限制的功能来加强保护。\n\n\u003e 如果你需要更高强度的验证，建议选择商用服务。\n\n[中文介绍和使用说明](https://ruby-china.org/topics/27832)\n\n## Example\n\n\u003cimg src=\"https://user-images.githubusercontent.com/5518/196329734-fee49f62-050b-44c8-a5a8-7ffdd3c5a3f6.png\" height=\"50\" alt=\"0\"\u003e \u003cimg src=\"https://user-images.githubusercontent.com/5518/196329738-64b264a1-e3fb-4804-ac46-0df18fb31d1e.png\" height=\"50\" alt=\"1\"\u003e \u003cimg src=\"https://user-images.githubusercontent.com/5518/196329740-e10ded26-ba46-4e9b-93b8-ce30c198f880.png\" height=\"50\" alt=\"2\"\u003e \u003cimg src=\"https://user-images.githubusercontent.com/5518/196329743-c7b055b8-b309-4554-8c95-66c5caf4437d.png\" height=\"50\" alt=\"3\"\u003e \u003cimg src=\"https://user-images.githubusercontent.com/5518/196329745-eb68f0c3-ccac-4fa3-aa7a-cc4c2caeb41e.png\" height=\"50\" alt=\"4\"\u003e \u003cimg src=\"https://user-images.githubusercontent.com/5518/196329746-b15a9f71-262e-4699-87c7-a5561c6caf2c.png\" height=\"50\" alt=\"5\"\u003e \u003cimg src=\"https://user-images.githubusercontent.com/5518/196329747-d111a5d3-89a1-487b-989e-5be8059488c2.png\" height=\"50\" alt=\"6\"\u003e \u003cimg src=\"https://user-images.githubusercontent.com/5518/196329749-2cb44aa3-8b59-427c-91f3-59566d6de8a5.png\" height=\"50\" alt=\"7\"\u003e \u003cimg src=\"https://user-images.githubusercontent.com/5518/196329754-ae64374b-f2e5-44b8-a7f4-3aee1405c193.png\" height=\"50\" alt=\"8\"\u003e \u003cimg src=\"https://user-images.githubusercontent.com/5518/196329755-26b88705-bf34-4d32-a4dc-076530582a90.png\" height=\"50\" alt=\"9\"\u003e\n\n## Feature\n\n- Native Gem base on Rust.\n- For Rails Application;\n- Simple, Easy to use;\n- High performance.\n\n## Usage\n\nPut rucaptcha in your `Gemfile`:\n\n```\ngem 'rucaptcha'\n```\n\nCreate `config/initializers/rucaptcha.rb`\n\n```rb\nRuCaptcha.configure do\n  # Custom captcha code expire time if you need, default: 2 minutes\n  # self.expires_in = 120\n\n  # [Requirement / 重要]\n  # Store Captcha code where, this config more like Rails config.cache_store\n  # default: Read config info from `Rails.application.config.cache_store`\n  # But RuCaptcha requirements cache_store not in [:null_store, :memory_store, :file_store]\n  # 默认：会从 Rails 配置的 cache_store 里面读取相同的配置信息，并尝试用可以运行的方式，用于存储验证码字符\n  # 但如果是 [:null_store, :memory_store, :file_store] 之类的，你可以通过下面的配置项单独给 RuCaptcha 配置 cache_store\n  self.cache_store = :mem_cache_store\n\n  # If you wants disable `cache_store` check warning, you can do it, default: false\n  # 如果想要 disable cache_store 的 warning，就设置为 true，default false\n  # self.skip_cache_store_check = true\n\n  # Chars length, default: 5, allows: [3 - 7]\n  # self.length = 5\n\n  # Enable or disable Strikethrough, default: true\n  # self.line = true\n\n  # Enable or disable noise, default: false\n  # self.noise = false\n\n  # Enable or disable circle background, default: true\n  # self.circle = true\n\n  # Set the difficulty level, default: 5, allows: [1..10].\n  # Only valid when noise is enabled\n  # self.difficulty = 5\n\n  # Set the case sensitive, default: false\n  # self.case_sensitive = false\n\n  # Set the image format, default: png, allows: [jpeg, png, webp]\n  # self.format = 'png'\n\n  # Custom mount path, default: '/rucaptcha'\n  # self.mount_path = '/rucaptcha'\nend\n```\n\nRuCaptcha 没有使用 Rails Session 来存储验证码信息，因为 Rails 的默认 Session 是存储在 Cookie 里面，如果验证码存在里面会存在 [Replay attack](https://en.wikipedia.org/wiki/Replay_attack) 漏洞，导致验证码关卡被攻破。\n\n所以我在设计上要求 RuCaptcha 得配置一个可以支持分布式的后端存储方案例如：Memcached 或 Redis 以及其他可以支持分布式的 cache_store 方案。\n\n同时，为了保障易用性，默认会尝试使用 `:file_store` 的方式，将验证码存在应用程序的 `tmp/cache/rucaptcha/session` 目录（但请注意，多机器部署这样是无法正常运作的）。\n\n所以，我建议大家使用的时候，配置上 `cache_store` （详见 [Rails Guides 缓存配置部分](https://ruby-china.github.io/rails-guides/caching_with_rails.html#%E9%85%8D%E7%BD%AE)的文档）到一个 Memcached 或 Redis，这才是最佳实践。\n\n#\n\n(RuCaptha do not use Rails Session to store captcha information. As the default session is stored in Cookie in Rails, there's a [Replay attack](https://en.wikipedia.org/wiki/Replay_attack) bug which may causes capthcha being destroyed if we store captcha in Rails Session.\n\nSo in my design I require RuCaptcha to configure a distributed backend storage scheme, such as Memcached, Redis or other cache_store schemes which support distribution.\n\nMeanwhile, for the ease of use, RuCapthca would try to use `:file_store` by default and store the capthca in `tmp/cache/rucaptcha/session` directory (kindly note that it's not working if deploy on multiple machine).\n\nFor recommendation, configure the `cache_store`（more details on [Rails Guides Configuration of Cache Stores](http://guides.rubyonrails.org/caching_with_rails.html#configuration)） to Memcached or Redis, that would be the best practice.)\n\n#\n\nController `app/controller/account_controller.rb`\n\nWhen you called `verify_rucaptcha?`, it uses value from `params[:_rucaptcha]` to validate.\n\n```rb\nclass AccountController \u003c ApplicationController\n  def create\n    @user = User.new(params[:user])\n    if verify_rucaptcha?(@user) \u0026\u0026 @user.save\n      redirect_to root_path, notice: 'Sign up successed.'\n    else\n      render 'account/new'\n    end\n  end\nend\n\nclass ForgotPasswordController \u003c ApplicationController\n  def create\n    # without any args\n    if verify_rucaptcha?\n      to_send_email\n    else\n      redirect_to '/forgot-password', alert: 'Invalid captcha code.'\n    end\n  end\nend\n```\n\n\u003e TIP: Sometimes you may need to keep last verified captcha code in session on `verify_rucaptcha?` method call, you can use `keep_session: true`. For example: `verify_rucaptcha? @user, keep_session: true`.\n\nView `app/views/account/new.html.erb`\n\n```erb\n\u003cform method=\"POST\"\u003e\n  ...\n  \u003cdiv class=\"form-group\"\u003e\n    \u003c%= rucaptcha_input_tag(class: 'form-control', placeholder: 'Input Captcha') %\u003e\n    \u003c%= rucaptcha_image_tag(alt: 'Captcha') %\u003e\n  \u003c/div\u003e\n  ...\n\n  \u003cdiv class=\"form-group\"\u003e\n    \u003cbutton type=\"submit\" class=\"btn btn-primary\"\u003eSubmit\u003c/button\u003e\n  \u003c/div\u003e\n\u003c/form\u003e\n```\n\nAnd if you are using [Devise](https://github.com/plataformatec/devise), you can read this reference to add validation: [RuCaptcha with Devise](https://github.com/huacnlee/rucaptcha/wiki/Working-with-Devise).\n\n### Write your test skip captcha validation\n\nfor RSpec\n\n```rb\ndescribe 'sign up and login', type: :feature do\n  before do\n    allow_any_instance_of(ActionController::Base).to receive(:verify_rucaptcha?).and_return(true)\n  end\n\n  it { ... }\nend\n```\n\nfor MiniTest\n\n```rb\nclass ActionDispatch::IntegrationTest\n  def sign_in(user)\n    ActionController::Base.any_instance.stubs(:verify_rucaptcha?).returns(true)\n    post user_session_path \\\n         'user[email]'    =\u003e user.email,\n         'user[password]' =\u003e user.password\n  end\nend\n```\n\n### Invalid message without Devise\n\nWhen you are using this gem without Devise, you may find out that the invalid message is missing.\nFor this case, use the trick below to add your i18n invalid message manually.\n\n```rb\nif verify_rucaptcha?(@user) \u0026\u0026 @user.save\n  do_whatever_you_want\n  redirect_to someplace_you_want\nelse\n  # this is the trick\n  @user.errors.add(:base, t('rucaptcha.invalid'))\n  render :new\nend\n```\n\n## Performance\n\n\u003e Based on MacBook Pro (Apple M3)\n\n`rake benchmark` to run benchmark test.\n\n```\nWarming up --------------------------------------\n      Generate image    84.000 i/100ms\nCalculating -------------------------------------\n      Generate image    859.075 (± 1.5%) i/s    (1.16 ms/i) -      4.368k in   5.085775s\n```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fhuacnlee%2Frucaptcha","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fhuacnlee%2Frucaptcha","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fhuacnlee%2Frucaptcha/lists"}