Insufficient Default OTP Shared Secret Length
Description
Under the default configuration, Devise-Two-Factor versions >= 2.2.0 & < 6.0.0 generate TOTP shared secrets that are 120 bits instead of the 128-bit minimum defined by RFC 4226. Using a shared secret shorter than the minimum to generate a multi-factor authentication code could make it easier for an attacker to guess the shared secret and generate valid TOTP codes.
AI Insight
LLM-synthesized narrative grounded in this CVE's description and references.
Devise-Two-Factor versions 2.2.0 to <6.0.0 generate TOTP secrets of 120 bits, below the RFC 4226 minimum, weakening MFA security.
Vulnerability
Details
Devise-Two-Factor versions 2.2.0 through 5.x (before 6.0.0) generate TOTP shared secrets that are only 120 bits long under default configuration, falling short of the 128-bit minimum required by RFC 4226 [2][4]. This occurs because the underlying ROTP library changed the interpretation of its random_base32 function argument between versions, causing the same input value to produce a shorter key [4]. The default otp_secret_length parameter in Devise-Two-Factor was not updated to compensate, resulting in insufficient entropy for the generated secrets.
Exploitation
An attacker who gains access to the stored shared secret—for example, through a database breach or SQL injection—can exploit the reduced entropy to brute-force the secret more easily than if it were 128 bits [2][4]. With a valid shared secret, the attacker can generate correct TOTP codes and bypass two-factor authentication for the targeted user account. No additional authentication is required once the secret is obtained.
Impact
Successful exploitation allows an attacker to defeat multi-factor authentication protections, potentially gaining unauthorized access to user accounts protected by Devise-Two-Factor [4]. This undermines the security benefit of MFA and could lead to account takeover, data exposure, or further lateral movement within the application.
Mitigation
The vulnerability is fixed in Devise-Two-Factor version 6.0.0, which increases the default secret length to 160 bits [3][4]. Users unable to upgrade can override the otp_secret_length attribute in their model to at least 26, ensuring newly generated secrets meet the 128-bit minimum [4]. After upgrading, applications may wish to prompt existing users to re-enroll in OTP to benefit from the stronger secrets [4].
AI Insight generated on May 20, 2026. Synthesized from this CVE's description and the cited reference URLs; citations are validated against the source bundle.
Affected packages
Versions sourced from the GitHub Security Advisory.
| Package | Affected versions | Patched versions |
|---|---|---|
devise-two-factorRubyGems | >= 4.0.0, < 6.0.0 | 6.0.0 |
Affected products
30- osv-coords29 versionspkg:apk/chainguard/gitlab-rails-ce-assets-18.1pkg:apk/chainguard/gitlab-rails-ce-assets-18.2pkg:apk/chainguard/gitlab-rails-ce-assets-18.3pkg:apk/chainguard/gitlab-rails-ce-assets-18.4pkg:apk/chainguard/gitlab-rails-ce-assets-18.5pkg:apk/chainguard/gitlab-rails-ce-assets-18.6pkg:apk/chainguard/gitlab-rails-ce-assets-18.7pkg:apk/chainguard/gitlab-rails-ce-assets-fips-18.1pkg:apk/chainguard/gitlab-rails-ce-assets-fips-18.2pkg:apk/chainguard/gitlab-rails-ce-assets-fips-18.3pkg:apk/chainguard/gitlab-rails-ce-assets-fips-18.4pkg:apk/chainguard/gitlab-rails-ce-assets-fips-18.5pkg:apk/chainguard/gitlab-rails-ce-assets-fips-18.6pkg:apk/chainguard/gitlab-rails-ce-assets-fips-18.7pkg:apk/chainguard/gitlab-rails-ce-doc-18.1pkg:apk/chainguard/gitlab-rails-ce-doc-18.2pkg:apk/chainguard/gitlab-rails-ce-doc-18.3pkg:apk/chainguard/gitlab-rails-ce-doc-18.4pkg:apk/chainguard/gitlab-rails-ce-doc-18.5pkg:apk/chainguard/gitlab-rails-ce-doc-18.6pkg:apk/chainguard/gitlab-rails-ce-doc-18.7pkg:apk/chainguard/gitlab-rails-ce-doc-fips-18.1pkg:apk/chainguard/gitlab-rails-ce-doc-fips-18.2pkg:apk/chainguard/gitlab-rails-ce-doc-fips-18.3pkg:apk/chainguard/gitlab-rails-ce-doc-fips-18.4pkg:apk/chainguard/gitlab-rails-ce-doc-fips-18.5pkg:apk/chainguard/gitlab-rails-ce-doc-fips-18.6pkg:apk/chainguard/gitlab-rails-ce-doc-fips-18.7pkg:gem/devise-two-factor
< 18.1.6-r1+ 28 more
- (no CPE)range: < 18.1.6-r1
- (no CPE)range: < 18.2.8-r1
- (no CPE)range: < 18.3.5-r0
- (no CPE)range: < 18.4.3-r0
- (no CPE)range: < 18.5.1-r0
- (no CPE)range: < 18.6.1-r1
- (no CPE)range: < 18.7.0-r0
- (no CPE)range: < 18.1.6-r2
- (no CPE)range: < 18.2.8-r2
- (no CPE)range: < 18.3.5-r2
- (no CPE)range: < 18.4.3-r3
- (no CPE)range: < 18.5.1-r2
- (no CPE)range: < 18.6.1-r2
- (no CPE)range: < 18.7.0-r0
- (no CPE)range: < 18.1.6-r1
- (no CPE)range: < 18.2.8-r1
- (no CPE)range: < 18.3.5-r0
- (no CPE)range: < 18.4.3-r0
- (no CPE)range: < 18.5.1-r0
- (no CPE)range: < 18.6.2-r0
- (no CPE)range: < 18.7.0-r0
- (no CPE)range: < 18.1.6-r2
- (no CPE)range: < 18.2.8-r2
- (no CPE)range: < 18.3.5-r2
- (no CPE)range: < 18.4.3-r3
- (no CPE)range: < 18.5.1-r2
- (no CPE)range: < 18.6.1-r2
- (no CPE)range: < 18.7.0-r0
- (no CPE)range: >= 4.0.0, < 6.0.0
- devise-two-factor/devise-two-factorv5Range: 4.0.0
Patches
1cc6f34423d9cMerge commit from fork
94 files changed · +61 −1141
demo/app/assets/images/.keep+0 −0 removeddemo/app/assets/javascripts/application.js+0 −16 removed@@ -1,16 +0,0 @@ -// This is a manifest file that'll be compiled into application.js, which will include all the files -// listed below. -// -// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, -// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path. -// -// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the -// compiled file. -// -// Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details -// about supported directives. -// -//= require jquery -//= require jquery_ujs -//= require turbolinks -//= require_tree .
demo/app/assets/javascripts/home.js.coffee+0 −3 removed@@ -1,3 +0,0 @@ -# Place all the behaviors and hooks related to the matching controller here. -# All this logic will automatically be available in application.js. -# You can use CoffeeScript in this file: http://coffeescript.org/
demo/app/assets/stylesheets/application.css+0 −15 removed@@ -1,15 +0,0 @@ -/* - * This is a manifest file that'll be compiled into application.css, which will include all the files - * listed below. - * - * Any CSS and SCSS file within this directory, lib/assets/stylesheets, vendor/assets/stylesheets, - * or vendor/assets/stylesheets of plugins, if any, can be referenced here using a relative path. - * - * You're free to add application-wide styles to this file and they'll appear at the bottom of the - * compiled file so the styles you add here take precedence over styles defined in any styles - * defined in the other CSS/SCSS files in this directory. It is generally better to create a new - * file per style scope. - * - *= require_tree . - *= require_self - */
demo/app/assets/stylesheets/home.css.scss+0 −3 removed@@ -1,3 +0,0 @@ -// Place all the styles related to the home controller here. -// They will automatically be included in application.css. -// You can use Sass (SCSS) here: http://sass-lang.com/
demo/app/controllers/application_controller.rb+0 −13 removed@@ -1,13 +0,0 @@ -class ApplicationController < ActionController::Base - # Prevent CSRF attacks by raising an exception. - # For APIs, you may want to use :null_session instead. - protect_from_forgery with: :exception - - before_action :configure_permitted_parameters, if: :devise_controller? - - protected - - def configure_permitted_parameters - devise_parameter_sanitizer.permit(:sign_in, keys: [:otp_attempt]) - end -end
demo/app/controllers/concerns/.keep+0 −0 removeddemo/app/controllers/home_controller.rb+0 −4 removed@@ -1,4 +0,0 @@ -class HomeController < ApplicationController - def index - end -end
demo/app/controllers/users_controller.rb+0 −14 removed@@ -1,14 +0,0 @@ -class UsersController < ApplicationController - def disable_otp - current_user.otp_required_for_login = false - current_user.save! - redirect_to home_index_path - end - - def enable_otp - current_user.otp_secret = User.generate_otp_secret - current_user.otp_required_for_login = true - current_user.save! - redirect_to home_index_path - end -end
demo/app/helpers/application_helper.rb+0 −2 removed@@ -1,2 +0,0 @@ -module ApplicationHelper -end
demo/app/helpers/home_helper.rb+0 −2 removed@@ -1,2 +0,0 @@ -module HomeHelper -end
demo/app/mailers/.keep+0 −0 removeddemo/app/models/concerns/.keep+0 −0 removeddemo/app/models/.keep+0 −0 removeddemo/app/models/user.rb+0 −6 removed@@ -1,6 +0,0 @@ -class User < ActiveRecord::Base - devise :two_factor_authenticatable - - devise :registerable, :recoverable, :rememberable, - :trackable, :validatable -end
demo/app/views/devise/confirmations/new.html.erb+0 −12 removed@@ -1,12 +0,0 @@ -<h2>Resend confirmation instructions</h2> - -<%= form_for(resource, as: resource_name, url: confirmation_path(resource_name), html: { method: :post }) do |f| %> - <%= devise_error_messages! %> - - <div><%= f.label :email %><br /> - <%= f.email_field :email, autofocus: true %></div> - - <div><%= f.submit "Resend confirmation instructions" %></div> -<% end %> - -<%= render "devise/shared/links" %>
demo/app/views/devise/mailer/confirmation_instructions.html.erb+0 −5 removed@@ -1,5 +0,0 @@ -<p>Welcome <%= @email %>!</p> - -<p>You can confirm your account email through the link below:</p> - -<p><%= link_to 'Confirm my account', confirmation_url(@resource, confirmation_token: @token) %></p>
demo/app/views/devise/mailer/reset_password_instructions.html.erb+0 −8 removed@@ -1,8 +0,0 @@ -<p>Hello <%= @resource.email %>!</p> - -<p>Someone has requested a link to change your password. You can do this through the link below.</p> - -<p><%= link_to 'Change my password', edit_password_url(@resource, reset_password_token: @token) %></p> - -<p>If you didn't request this, please ignore this email.</p> -<p>Your password won't change until you access the link above and create a new one.</p>
demo/app/views/devise/mailer/unlock_instructions.html.erb+0 −7 removed@@ -1,7 +0,0 @@ -<p>Hello <%= @resource.email %>!</p> - -<p>Your account has been locked due to an excessive number of unsuccessful sign in attempts.</p> - -<p>Click the link below to unlock your account:</p> - -<p><%= link_to 'Unlock my account', unlock_url(@resource, unlock_token: @token) %></p>
demo/app/views/devise/passwords/edit.html.erb+0 −16 removed@@ -1,16 +0,0 @@ -<h2>Change your password</h2> - -<%= form_for(resource, as: resource_name, url: password_path(resource_name), html: { method: :put }) do |f| %> - <%= devise_error_messages! %> - <%= f.hidden_field :reset_password_token %> - - <div><%= f.label :password, "New password" %><br /> - <%= f.password_field :password, autofocus: true, autocomplete: "off" %></div> - - <div><%= f.label :password_confirmation, "Confirm new password" %><br /> - <%= f.password_field :password_confirmation, autocomplete: "off" %></div> - - <div><%= f.submit "Change my password" %></div> -<% end %> - -<%= render "devise/shared/links" %>
demo/app/views/devise/passwords/new.html.erb+0 −12 removed@@ -1,12 +0,0 @@ -<h2>Forgot your password?</h2> - -<%= form_for(resource, as: resource_name, url: password_path(resource_name), html: { method: :post }) do |f| %> - <%= devise_error_messages! %> - - <div><%= f.label :email %><br /> - <%= f.email_field :email, autofocus: true %></div> - - <div><%= f.submit "Send me reset password instructions" %></div> -<% end %> - -<%= render "devise/shared/links" %>
demo/app/views/devise/registrations/edit.html.erb+0 −29 removed@@ -1,29 +0,0 @@ -<h2>Edit <%= resource_name.to_s.humanize %></h2> - -<%= form_for(resource, as: resource_name, url: registration_path(resource_name), html: { method: :put }) do |f| %> - <%= devise_error_messages! %> - - <div><%= f.label :email %><br /> - <%= f.email_field :email, autofocus: true %></div> - - <% if devise_mapping.confirmable? && resource.pending_reconfirmation? %> - <div>Currently waiting confirmation for: <%= resource.unconfirmed_email %></div> - <% end %> - - <div><%= f.label :password %> <i>(leave blank if you don't want to change it)</i><br /> - <%= f.password_field :password, autocomplete: "off" %></div> - - <div><%= f.label :password_confirmation %><br /> - <%= f.password_field :password_confirmation, autocomplete: "off" %></div> - - <div><%= f.label :current_password %> <i>(we need your current password to confirm your changes)</i><br /> - <%= f.password_field :current_password, autocomplete: "off" %></div> - - <div><%= f.submit "Update" %></div> -<% end %> - -<h3>Cancel my account</h3> - -<p>Unhappy? <%= button_to "Cancel my account", registration_path(resource_name), data: { confirm: "Are you sure?" }, method: :delete %></p> - -<%= link_to "Back", :back %>
demo/app/views/devise/registrations/new.html.erb+0 −18 removed@@ -1,18 +0,0 @@ -<h2>Sign up</h2> - -<%= form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %> - <%= devise_error_messages! %> - - <div><%= f.label :email %><br /> - <%= f.email_field :email, autofocus: true %></div> - - <div><%= f.label :password %><br /> - <%= f.password_field :password, autocomplete: "off" %></div> - - <div><%= f.label :password_confirmation %><br /> - <%= f.password_field :password_confirmation, autocomplete: "off" %></div> - - <div><%= f.submit "Sign up" %></div> -<% end %> - -<%= render "devise/shared/links" %>
demo/app/views/devise/sessions/new.html.erb+0 −20 removed@@ -1,20 +0,0 @@ -<h2>Sign in</h2> - -<%= form_for(resource, as: resource_name, url: session_path(resource_name)) do |f| %> - <div><%= f.label :email %><br /> - <%= f.email_field :email, autofocus: true %></div> - - <div><%= f.label :password %><br /> - <%= f.password_field :password, autocomplete: "off" %></div> - - <div><%= f.label :otp_attempt %><br /> - <%= f.text_field :otp_attempt %> </div> - - <% if devise_mapping.rememberable? -%> - <div><%= f.check_box :remember_me %> <%= f.label :remember_me %></div> - <% end -%> - - <div><%= f.submit "Sign in" %></div> -<% end %> - -<%= render "devise/shared/links" %>
demo/app/views/devise/shared/_links.erb+0 −25 removed@@ -1,25 +0,0 @@ -<%- if controller_name != 'sessions' %> - <%= link_to "Sign in", new_session_path(resource_name) %><br /> -<% end -%> - -<%- if devise_mapping.registerable? && controller_name != 'registrations' %> - <%= link_to "Sign up", new_registration_path(resource_name) %><br /> -<% end -%> - -<%- if devise_mapping.recoverable? && controller_name != 'passwords' && controller_name != 'registrations' %> - <%= link_to "Forgot your password?", new_password_path(resource_name) %><br /> -<% end -%> - -<%- if devise_mapping.confirmable? && controller_name != 'confirmations' %> - <%= link_to "Didn't receive confirmation instructions?", new_confirmation_path(resource_name) %><br /> -<% end -%> - -<%- if devise_mapping.lockable? && resource_class.unlock_strategy_enabled?(:email) && controller_name != 'unlocks' %> - <%= link_to "Didn't receive unlock instructions?", new_unlock_path(resource_name) %><br /> -<% end -%> - -<%- if devise_mapping.omniauthable? %> - <%- resource_class.omniauth_providers.each do |provider| %> - <%= link_to "Sign in with #{provider.to_s.titleize}", omniauth_authorize_path(resource_name, provider) %><br /> - <% end -%> -<% end -%>
demo/app/views/devise/unlocks/new.html.erb+0 −12 removed@@ -1,12 +0,0 @@ -<h2>Resend unlock instructions</h2> - -<%= form_for(resource, as: resource_name, url: unlock_path(resource_name), html: { method: :post }) do |f| %> - <%= devise_error_messages! %> - - <div><%= f.label :email %><br /> - <%= f.email_field :email, autofocus: true %></div> - - <div><%= f.submit "Resend unlock instructions" %></div> -<% end %> - -<%= render "devise/shared/links" %>
demo/app/views/home/index.html.erb+0 −20 removed@@ -1,20 +0,0 @@ -<% if !current_user %> - <%= link_to "Sign up", new_user_registration_path %> - <%= link_to "Login", new_user_session_path %> -<% end %> - -<% if current_user %> - <% if !current_user.otp_required_for_login %> - <%= button_to "Enable 2FA", users_enable_otp_path, :method => :post %> - <% end %> - - <% if current_user.otp_required_for_login %> - <%= button_to "Disable 2FA", users_disable_otp_path, :method => :post %> - <%= raw RQRCode::render_qrcode(current_user.otp_provisioning_uri(current_user.email, issuer: "Devise-Two-Factor-Demo"), - :svg, - :level => :l, - :unit => 2) %> - <br> - <% end %> - <%= link_to "Log out", destroy_user_session_path, :method => :delete %> -<% end %>
demo/app/views/layouts/application.html.erb+0 −17 removed@@ -1,17 +0,0 @@ -<!DOCTYPE html> -<html> -<head> - <title>DeviseTwoFactorDemo</title> - <%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track' => true %> - <%= javascript_include_tag 'application', 'data-turbolinks-track' => true %> - <%= csrf_meta_tags %> -</head> -<body> - -<%= content_tag :div, flash[:notice] if flash[:notice] %> -<%= content_tag :div, flash[:alert] if flash[:alert] %> - -<%= yield %> - -</body> -</html>
demo/bin/bundle+0 −3 removed@@ -1,3 +0,0 @@ -#!/usr/bin/env ruby -ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__) -load Gem.bin_path('bundler', 'bundle')
demo/bin/rails+0 −4 removed@@ -1,4 +0,0 @@ -#!/usr/bin/env ruby -APP_PATH = File.expand_path('../../config/application', __FILE__) -require_relative '../config/boot' -require 'rails/commands'
demo/bin/rake+0 −4 removed@@ -1,4 +0,0 @@ -#!/usr/bin/env ruby -require_relative '../config/boot' -require 'rake' -Rake.application.run
demo/config/application.rb+0 −28 removed@@ -1,28 +0,0 @@ -require File.expand_path('../boot', __FILE__) - -require 'rails/all' - -# Require the gems listed in Gemfile, including any gems -# you've limited to :test, :development, or :production. -Bundler.require(*Rails.groups) - -module DeviseTwoFactorDemo - 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. - - env_file = File.join(Rails.root, 'config', 'local_env.yml') - YAML.load(File.open(env_file)).each do |key, value| - ENV[key.to_s] = value - end if File.exists?(env_file) - - # 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 - end -end
demo/config/boot.rb+0 −4 removed@@ -1,4 +0,0 @@ -# Set up gems listed in the Gemfile. -ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__) - -require 'bundler/setup' if File.exist?(ENV['BUNDLE_GEMFILE'])
demo/config/database.yml+0 −25 removed@@ -1,25 +0,0 @@ -# SQLite version 3.x -# gem install sqlite3 -# -# Ensure the SQLite 3 gem is defined in your Gemfile -# gem 'sqlite3' -# -default: &default - adapter: sqlite3 - pool: 5 - timeout: 5000 - -development: - <<: *default - database: db/development.sqlite3 - -# Warning: The database defined as "test" will be erased and -# re-generated from your development database when you run "rake". -# Do not set this db to the same as development or production. -test: - <<: *default - database: db/test.sqlite3 - -production: - <<: *default - database: db/production.sqlite3
demo/config/environment.rb+0 −5 removed@@ -1,5 +0,0 @@ -# Load the Rails application. -require File.expand_path('../application', __FILE__) - -# Initialize the Rails application. -Rails.application.initialize!
demo/config/environments/development.rb+0 −37 removed@@ -1,37 +0,0 @@ -Rails.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 - - # 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
demo/config/environments/production.rb+0 −83 removed@@ -1,83 +0,0 @@ -Rails.application.configure do - # Settings specified here will take precedence over those in config/application.rb. - - # Code is not reloaded between requests. - config.cache_classes = true - - # Eager load code on boot. This eager loads most of Rails and - # your application in memory, allowing both threaded web servers - # and those relying on copy on write to perform better. - # Rake tasks automatically ignore this option for performance. - config.eager_load = true - - # Full error reports are disabled and caching is turned on. - config.consider_all_requests_local = false - config.action_controller.perform_caching = true - - # Enable Rack::Cache to put a simple HTTP cache in front of your application - # Add `rack-cache` to your Gemfile before enabling this. - # For large-scale production use, consider using a caching reverse proxy like nginx, varnish or squid. - # config.action_dispatch.rack_cache = true - - # Disable Rails's static asset server (Apache or nginx will already do this). - config.serve_static_assets = false - - # Compress JavaScripts and CSS. - config.assets.js_compressor = :uglifier - # config.assets.css_compressor = :sass - - # Do not fallback to assets pipeline if a precompiled asset is missed. - config.assets.compile = false - - # Generate digests for assets URLs. - config.assets.digest = true - - # Version of your assets, change this if you want to expire all your assets. - config.assets.version = '1.0' - - # Specifies the header that your server uses for sending files. - # config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache - # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx - - # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. - # config.force_ssl = true - - # Set to :debug to see everything in the log. - config.log_level = :info - - # Prepend all log lines with the following tags. - # config.log_tags = [ :subdomain, :uuid ] - - # Use a different logger for distributed setups. - # config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new) - - # Use a different cache store in production. - # config.cache_store = :mem_cache_store - - # Enable serving of images, stylesheets, and JavaScripts from an asset server. - # config.action_controller.asset_host = "http://assets.example.com" - - # Precompile additional assets. - # application.js, application.css, and all non-JS/CSS in app/assets folder are already added. - # config.assets.precompile += %w( search.js ) - - # Ignore bad email addresses and do not raise email delivery errors. - # Set this to true and configure the email server for immediate delivery to raise delivery errors. - # config.action_mailer.raise_delivery_errors = false - - # Enable locale fallbacks for I18n (makes lookups for any locale fall back to - # the I18n.default_locale when a translation cannot be found). - config.i18n.fallbacks = true - - # Send deprecation notices to registered listeners. - config.active_support.deprecation = :notify - - # Disable automatic flushing of the log to improve performance. - # config.autoflush_log = false - - # Use default logging formatter so that PID and timestamp are not suppressed. - config.log_formatter = ::Logger::Formatter.new - - # Do not dump schema after migrations. - config.active_record.dump_schema_after_migration = false -end
demo/config/environments/test.rb+0 −39 removed@@ -1,39 +0,0 @@ -Rails.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 - - # Configure static asset server for tests with Cache-Control for performance. - config.serve_static_assets = true - config.static_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 - - # Raises error for missing translations - # config.action_view.raise_on_missing_translations = true -end
demo/config/initializers/backtrace_silencers.rb+0 −7 removed@@ -1,7 +0,0 @@ -# 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!
demo/config/initializers/cookies_serializer.rb+0 −3 removed@@ -1,3 +0,0 @@ -# Be sure to restart your server when you modify this file. - -Rails.application.config.action_dispatch.cookies_serializer = :json \ No newline at end of file
demo/config/initializers/devise.rb+0 −18 removed@@ -1,18 +0,0 @@ -Devise.setup do |config| - config.warden do |manager| - manager.default_strategies(:scope => :user).unshift :two_factor_authenticatable - end - - config.mailer_sender = 'please-change-me-at-config-initializers-devise@example.com' - - require 'devise/orm/active_record' - - config.case_insensitive_keys = [ :email ] - config.strip_whitespace_keys = [ :email ] - config.skip_session_storage = [:http_auth] - config.stretches = Rails.env.test? ? 1 : 10 - config.reconfirmable = true - config.password_length = 8..128 - config.reset_password_within = 6.hours - config.sign_out_via = :delete -end
demo/config/initializers/filter_parameter_logging.rb+0 −4 removed@@ -1,4 +0,0 @@ -# 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]
demo/config/initializers/inflections.rb+0 −16 removed@@ -1,16 +0,0 @@ -# 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
demo/config/initializers/mime_types.rb+0 −4 removed@@ -1,4 +0,0 @@ -# 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
demo/config/initializers/session_store.rb+0 −3 removed@@ -1,3 +0,0 @@ -# Be sure to restart your server when you modify this file. - -Rails.application.config.session_store :cookie_store, key: '_DeviseTwoFactorDemo_session'
demo/config/initializers/wrap_parameters.rb+0 −14 removed@@ -1,14 +0,0 @@ -# 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
demo/config/locales/devise.en.yml+0 −59 removed@@ -1,59 +0,0 @@ -# Additional translations at https://github.com/plataformatec/devise/wiki/I18n - -en: - devise: - confirmations: - confirmed: "Your account was successfully confirmed." - send_instructions: "You will receive an email with instructions about how to confirm your account in a few minutes." - send_paranoid_instructions: "If your email address exists in our database, you will receive an email with instructions about how to confirm your account in a few minutes." - failure: - already_authenticated: "You are already signed in." - inactive: "Your account is not activated yet." - invalid: "Invalid email or password." - locked: "Your account is locked." - last_attempt: "You have one more attempt before your account will be locked." - not_found_in_database: "Invalid email or password." - timeout: "Your session expired. Please sign in again to continue." - unauthenticated: "You need to sign in or sign up before continuing." - unconfirmed: "You have to confirm your account before continuing." - mailer: - confirmation_instructions: - subject: "Confirmation instructions" - reset_password_instructions: - subject: "Reset password instructions" - unlock_instructions: - subject: "Unlock Instructions" - omniauth_callbacks: - failure: "Could not authenticate you from %{kind} because \"%{reason}\"." - success: "Successfully authenticated from %{kind} account." - passwords: - no_token: "You can't access this page without coming from a password reset email. If you do come from a password reset email, please make sure you used the full URL provided." - send_instructions: "You will receive an email with instructions on how to reset your password in a few minutes." - send_paranoid_instructions: "If your email address exists in our database, you will receive a password recovery link at your email address in a few minutes." - updated: "Your password was changed successfully. You are now signed in." - updated_not_active: "Your password was changed successfully." - registrations: - destroyed: "Bye! Your account was successfully cancelled. We hope to see you again soon." - signed_up: "Welcome! You have signed up successfully." - signed_up_but_inactive: "You have signed up successfully. However, we could not sign you in because your account is not yet activated." - signed_up_but_locked: "You have signed up successfully. However, we could not sign you in because your account is locked." - signed_up_but_unconfirmed: "A message with a confirmation link has been sent to your email address. Please open the link to activate your account." - update_needs_confirmation: "You updated your account successfully, but we need to verify your new email address. Please check your email and click on the confirm link to finalize confirming your new email address." - updated: "You updated your account successfully." - sessions: - signed_in: "Signed in successfully." - signed_out: "Signed out successfully." - unlocks: - send_instructions: "You will receive an email with instructions about how to unlock your account in a few minutes." - send_paranoid_instructions: "If your account exists, you will receive an email with instructions about how to unlock it in a few minutes." - unlocked: "Your account has been unlocked successfully. Please sign in to continue." - errors: - messages: - already_confirmed: "was already confirmed, please try signing in" - confirmation_period_expired: "needs to be confirmed within %{period}, please request a new one" - expired: "has expired, please request a new one" - not_found: "not found" - not_locked: "was not locked" - not_saved: - one: "1 error prohibited this %{resource} from being saved:" - other: "%{count} errors prohibited this %{resource} from being saved:"
demo/config/locales/en.yml+0 −23 removed@@ -1,23 +0,0 @@ -# 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"
demo/config/routes.rb+0 −9 removed@@ -1,9 +0,0 @@ -Rails.application.routes.draw do - get 'home/index' - post 'users/enable_otp' - post 'users/disable_otp' - - devise_for :users - - root to: "home#index", via: [:get, :post] -end
demo/config.ru+0 −4 removed@@ -1,4 +0,0 @@ -# This file is used by Rack-based servers to start the application. - -require ::File.expand_path('../config/environment', __FILE__) -run Rails.application
demo/config/secrets.yml+0 −22 removed@@ -1,22 +0,0 @@ -# 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: c8c845b85a69d2b67ec99c1912ddcde63f0fcd05a74052f396daf68a2688d576c203bdc239c9423a0cf88218e201d30616959d5eeceea00eedf915677ecd373b - -test: - secret_key_base: df468dd66c4b0f143354d216d96cdb8542ffe215afd78ebf977f7a8bfdb93010db134320cb738d27385bd7884cd73f3f22f90b147d4d176c3c8d0d63d5427fa9 - -# Do not keep production secrets in the repository, -# instead read values from the environment. -production: - secret_key_base: <%= ENV["SECRET_KEY_BASE"] %>
demo/db/migrate/20140515190128_devise_create_users.rb+0 −42 removed@@ -1,42 +0,0 @@ -class DeviseCreateUsers < ActiveRecord::Migration - def change - create_table(:users) do |t| - ## Database authenticatable - t.string :email, null: false, default: "" - t.string :encrypted_password, null: false, default: "" - - ## Recoverable - t.string :reset_password_token - t.datetime :reset_password_sent_at - - ## Rememberable - t.datetime :remember_created_at - - ## Trackable - t.integer :sign_in_count, default: 0, null: false - t.datetime :current_sign_in_at - t.datetime :last_sign_in_at - t.string :current_sign_in_ip - t.string :last_sign_in_ip - - ## Confirmable - # t.string :confirmation_token - # t.datetime :confirmed_at - # t.datetime :confirmation_sent_at - # t.string :unconfirmed_email # Only if using reconfirmable - - ## Lockable - # t.integer :failed_attempts, default: 0, null: false # Only if lock strategy is :failed_attempts - # t.string :unlock_token # Only if unlock strategy is :email or :both - # t.datetime :locked_at - - - t.timestamps - end - - add_index :users, :email, unique: true - add_index :users, :reset_password_token, unique: true - # add_index :users, :confirmation_token, unique: true - # add_index :users, :unlock_token, unique: true - end -end
demo/db/migrate/20140516191259_add_devise_two_factor_to_users.rb+0 −9 removed@@ -1,9 +0,0 @@ -class AddDeviseTwoFactorToUsers < ActiveRecord::Migration - def change - add_column :users, :encrypted_otp_secret, :string - add_column :users, :encrypted_otp_secret_iv, :string - add_column :users, :encrypted_otp_secret_salt, :string - add_column :users, :consumed_timestep, :integer - add_column :users, :otp_required_for_login, :boolean - end -end
demo/db/schema.rb+0 −39 removed@@ -1,39 +0,0 @@ -# encoding: UTF-8 -# This file is auto-generated from the current state of the database. Instead -# of editing this file, please use the migrations feature of Active Record to -# incrementally modify your database, and then regenerate this schema definition. -# -# Note that this schema.rb definition is the authoritative source for your -# database schema. If you need to create the application database on another -# system, you should be using db:schema:load, not running all the migrations -# from scratch. The latter is a flawed and unsustainable approach (the more migrations -# you'll amass, the slower it'll run and the greater likelihood for issues). -# -# It's strongly recommended that you check this file into your version control system. - -ActiveRecord::Schema.define(version: 20140516191259) do - - create_table "users", force: :cascade do |t| - t.string "email", default: "", null: false - t.string "encrypted_password", default: "", null: false - t.string "reset_password_token" - t.datetime "reset_password_sent_at" - t.datetime "remember_created_at" - t.integer "sign_in_count", default: 0, null: false - t.datetime "current_sign_in_at" - t.datetime "last_sign_in_at" - t.string "current_sign_in_ip" - t.string "last_sign_in_ip" - t.datetime "created_at" - t.datetime "updated_at" - t.string "encrypted_otp_secret" - t.string "encrypted_otp_secret_iv" - t.string "encrypted_otp_secret_salt" - t.integer "consumed_timestep" - t.boolean "otp_required_for_login" - end - - add_index "users", ["email"], name: "index_users_on_email", unique: true - add_index "users", ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true - -end
demo/db/seeds.rb+0 −7 removed@@ -1,7 +0,0 @@ -# This file should contain all the record creation needed to seed the database with its default values. -# The data can then be loaded with the rake db:seed (or created alongside the db with db:setup). -# -# Examples: -# -# cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }]) -# Mayor.create(name: 'Emanuel', city: cities.first)
demo/Gemfile+0 −16 removed@@ -1,16 +0,0 @@ -source 'https://rubygems.org' - -gem 'rails', '4.2.7.1' -gem 'sqlite3' -gem 'sass-rails', '~> 4.0.3' -gem 'uglifier', '>= 1.3.0' -gem 'coffee-rails', '~> 4.0.0' -# See https://github.com/sstephenson/execjs#readme for more supported runtimes -# gem 'therubyracer', platforms: :ruby - -gem 'jquery-rails' -gem 'turbolinks' - -gem 'devise' -gem 'devise-two-factor', path: '../' -gem 'rqrcode-rails3'
demo/.gitignore+0 −16 removed@@ -1,16 +0,0 @@ -# See https://help.github.com/articles/ignoring-files for more about ignoring files. -# -# If you find yourself ignoring temporary files generated by your text editor -# or operating system, you probably want to add a global ignore instead: -# git config --global core.excludesfile '~/.gitignore_global' - -# Ignore bundler config. -/.bundle - -# Ignore the default SQLite database. -/db/*.sqlite3 -/db/*.sqlite3-journal - -# Ignore all logfiles and tempfiles. -/log/*.log -/tmp
demo/lib/assets/.keep+0 −0 removeddemo/lib/tasks/.keep+0 −0 removeddemo/log/.keep+0 −0 removeddemo/public/404.html+0 −67 removed@@ -1,67 +0,0 @@ -<!DOCTYPE html> -<html> -<head> - <title>The page you were looking for doesn't exist (404)</title> - <meta name="viewport" content="width=device-width,initial-scale=1"> - <style> - body { - background-color: #EFEFEF; - color: #2E2F30; - text-align: center; - font-family: arial, sans-serif; - margin: 0; - } - - div.dialog { - width: 95%; - max-width: 33em; - margin: 4em auto 0; - } - - div.dialog > div { - border: 1px solid #CCC; - border-right-color: #999; - border-left-color: #999; - border-bottom-color: #BBB; - border-top: #B00100 solid 4px; - border-top-left-radius: 9px; - border-top-right-radius: 9px; - background-color: white; - padding: 7px 12% 0; - box-shadow: 0 3px 8px rgba(50, 50, 50, 0.17); - } - - h1 { - font-size: 100%; - color: #730E15; - line-height: 1.5em; - } - - div.dialog > p { - margin: 0 0 1em; - padding: 1em; - background-color: #F7F7F7; - border: 1px solid #CCC; - border-right-color: #999; - border-left-color: #999; - border-bottom-color: #999; - border-bottom-left-radius: 4px; - border-bottom-right-radius: 4px; - border-top-color: #DADADA; - color: #666; - box-shadow: 0 3px 8px rgba(50, 50, 50, 0.17); - } - </style> -</head> - -<body> - <!-- This file lives in public/404.html --> - <div class="dialog"> - <div> - <h1>The page you were looking for doesn't exist.</h1> - <p>You may have mistyped the address or the page may have moved.</p> - </div> - <p>If you are the application owner check the logs for more information.</p> - </div> -</body> -</html>
demo/public/422.html+0 −67 removed@@ -1,67 +0,0 @@ -<!DOCTYPE html> -<html> -<head> - <title>The change you wanted was rejected (422)</title> - <meta name="viewport" content="width=device-width,initial-scale=1"> - <style> - body { - background-color: #EFEFEF; - color: #2E2F30; - text-align: center; - font-family: arial, sans-serif; - margin: 0; - } - - div.dialog { - width: 95%; - max-width: 33em; - margin: 4em auto 0; - } - - div.dialog > div { - border: 1px solid #CCC; - border-right-color: #999; - border-left-color: #999; - border-bottom-color: #BBB; - border-top: #B00100 solid 4px; - border-top-left-radius: 9px; - border-top-right-radius: 9px; - background-color: white; - padding: 7px 12% 0; - box-shadow: 0 3px 8px rgba(50, 50, 50, 0.17); - } - - h1 { - font-size: 100%; - color: #730E15; - line-height: 1.5em; - } - - div.dialog > p { - margin: 0 0 1em; - padding: 1em; - background-color: #F7F7F7; - border: 1px solid #CCC; - border-right-color: #999; - border-left-color: #999; - border-bottom-color: #999; - border-bottom-left-radius: 4px; - border-bottom-right-radius: 4px; - border-top-color: #DADADA; - color: #666; - box-shadow: 0 3px 8px rgba(50, 50, 50, 0.17); - } - </style> -</head> - -<body> - <!-- This file lives in public/422.html --> - <div class="dialog"> - <div> - <h1>The change you wanted was rejected.</h1> - <p>Maybe you tried to change something you didn't have access to.</p> - </div> - <p>If you are the application owner check the logs for more information.</p> - </div> -</body> -</html>
demo/public/500.html+0 −66 removed@@ -1,66 +0,0 @@ -<!DOCTYPE html> -<html> -<head> - <title>We're sorry, but something went wrong (500)</title> - <meta name="viewport" content="width=device-width,initial-scale=1"> - <style> - body { - background-color: #EFEFEF; - color: #2E2F30; - text-align: center; - font-family: arial, sans-serif; - margin: 0; - } - - div.dialog { - width: 95%; - max-width: 33em; - margin: 4em auto 0; - } - - div.dialog > div { - border: 1px solid #CCC; - border-right-color: #999; - border-left-color: #999; - border-bottom-color: #BBB; - border-top: #B00100 solid 4px; - border-top-left-radius: 9px; - border-top-right-radius: 9px; - background-color: white; - padding: 7px 12% 0; - box-shadow: 0 3px 8px rgba(50, 50, 50, 0.17); - } - - h1 { - font-size: 100%; - color: #730E15; - line-height: 1.5em; - } - - div.dialog > p { - margin: 0 0 1em; - padding: 1em; - background-color: #F7F7F7; - border: 1px solid #CCC; - border-right-color: #999; - border-left-color: #999; - border-bottom-color: #999; - border-bottom-left-radius: 4px; - border-bottom-right-radius: 4px; - border-top-color: #DADADA; - color: #666; - box-shadow: 0 3px 8px rgba(50, 50, 50, 0.17); - } - </style> -</head> - -<body> - <!-- This file lives in public/500.html --> - <div class="dialog"> - <div> - <h1>We're sorry, but something went wrong.</h1> - </div> - <p>If you are the application owner check the logs for more information.</p> - </div> -</body> -</html>
demo/public/favicon.ico+0 −0 removeddemo/public/robots.txt+0 −5 removed@@ -1,5 +0,0 @@ -# See http://www.robotstxt.org/robotstxt.html for documentation on how to use the robots.txt file -# -# To ban all spiders from the entire site uncomment the next two lines: -# User-agent: * -# Disallow: /
demo/Rakefile+0 −6 removed@@ -1,6 +0,0 @@ -# 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__) - -Rails.application.load_tasks
demo/README.md+5 −0 added@@ -0,0 +1,5 @@ +# Demo + +Examples have been moved to their own repositories! + +* [Rails 7.1](https://github.com/devise-two-factor/example-rails_7_1)
demo/README.rdoc+0 −28 removed@@ -1,28 +0,0 @@ -== README - -This README would normally document whatever steps are necessary to get the -application up and running. - -Things you may want to cover: - -* Ruby version - -* System dependencies - -* Configuration - -* Database creation - -* Database initialization - -* How to run the test suite - -* Services (job queues, cache servers, search engines, etc.) - -* Deployment instructions - -* ... - - -Please feel free to use a different markup language if you do not plan to run -<tt>rake doc:app</tt>.
demo/test/controllers/home_controller_test.rb+0 −9 removed@@ -1,9 +0,0 @@ -require 'test_helper' - -class HomeControllerTest < ActionController::TestCase - test "should get index" do - get :index - assert_response :success - end - -end
demo/test/controllers/.keep+0 −0 removeddemo/test/fixtures/.keep+0 −0 removeddemo/test/fixtures/users.yml+0 −11 removed@@ -1,11 +0,0 @@ -# Read about fixtures at http://api.rubyonrails.org/classes/ActiveRecord/FixtureSet.html - -# This model initially had no columns defined. If you add columns to the -# model remove the '{}' from the fixture names and add the columns immediately -# below each fixture, per the syntax in the comments below -# -one: {} -# column: value -# -two: {} -# column: value
demo/test/helpers/home_helper_test.rb+0 −4 removed@@ -1,4 +0,0 @@ -require 'test_helper' - -class HomeHelperTest < ActionView::TestCase -end
demo/test/helpers/.keep+0 −0 removeddemo/test/integration/.keep+0 −0 removeddemo/test/mailers/.keep+0 −0 removeddemo/test/models/.keep+0 −0 removeddemo/test/models/user_test.rb+0 −7 removed@@ -1,7 +0,0 @@ -require 'test_helper' - -class UserTest < ActiveSupport::TestCase - # test "the truth" do - # assert true - # end -end
demo/test/test_helper.rb+0 −13 removed@@ -1,13 +0,0 @@ -ENV['RAILS_ENV'] ||= 'test' -require File.expand_path('../../config/environment', __FILE__) -require 'rails/test_help' - -class ActiveSupport::TestCase - # Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order. - # - # Note: You'll currently still have to declare fixtures explicitly in integration tests - # -- they do not yet inherit this setting - fixtures :all - - # Add more helper methods to be used by all tests here... -end
demo/vendor/assets/javascripts/.keep+0 −0 removeddemo/vendor/assets/stylesheets/.keep+0 −0 removedlib/devise_two_factor/models/two_factor_authenticatable.rb+4 −2 modified@@ -81,7 +81,8 @@ def clean_up_passwords def consume_otp! if self.consumed_timestep != current_otp_timestep self.consumed_timestep = current_otp_timestep - return save(validate: false) + save!(validate: false) + return true end false @@ -93,8 +94,9 @@ module ClassMethods :otp_encrypted_attribute_options, :otp_secret_encryption_key) + # Geneartes an OTP secret of the specified length, returning it after Base32 encoding. def generate_otp_secret(otp_secret_length = self.otp_secret_length) - ROTP::Base32.random_base32(otp_secret_length) + ROTP::Base32.random(otp_secret_length) end # Return value will be splatted with ** so return a version of the
lib/devise_two_factor/models/two_factor_backupable.rb+2 −1 modified@@ -20,7 +20,7 @@ def generate_otp_backup_codes! code_length = self.class.otp_backup_code_length number_of_codes.times do - codes << SecureRandom.hex(code_length / 2) # Hexstring has length 2*n + codes << SecureRandom.hex(code_length) end hashed_codes = codes.map { |code| Devise::Encryptor.digest(self.class, code) } @@ -39,6 +39,7 @@ def invalidate_otp_backup_code!(code) codes.delete(backup_code) self.otp_backup_codes = codes + save!(validate: false) return true end
lib/devise-two-factor.rb+5 −3 modified@@ -3,9 +3,10 @@ require 'devise_two_factor/strategies' module Devise - # The length of generated OTP secrets + # The length of randomly generated OTP shared secret (in bytes). + # The secrets will be base32-encoded and have a length 1.6 times the configured value. mattr_accessor :otp_secret_length - @@otp_secret_length = 24 + @@otp_secret_length = 20 # The number of seconds before and after the current # time for which codes will be accepted @@ -20,7 +21,8 @@ module Devise mattr_accessor :otp_encrypted_attribute_options @@otp_encrypted_attribute_options = {} - # The length of all generated OTP backup codes + # The length of randomly generated OTP backup codes (in bytes). + # The codes will be hex-encoded and have a length twice the configured value. mattr_accessor :otp_backup_code_length @@otp_backup_code_length = 16
lib/devise_two_factor/spec_helpers/two_factor_authenticatable_shared_examples.rb+4 −4 modified@@ -13,8 +13,8 @@ end describe '#otp_secret' do - it 'should be of the configured length' do - expect(subject.otp_secret.length).to eq(subject.class.otp_secret_length) + it 'should be of the expected length' do + expect(subject.otp_secret.length).to eq(subject.class.otp_secret_length*8/5) end end @@ -129,11 +129,11 @@ let(:issuer) { 'Tinfoil' } it 'should return uri with specified account' do - expect(subject.otp_provisioning_uri(account)).to match(%r{otpauth://totp/#{CGI.escape(account)}\?secret=\w{#{otp_secret_length}}}) + expect(subject.otp_provisioning_uri(account)).to match(%r{otpauth://totp/#{CGI.escape(account)}\?secret=\w{#{otp_secret_length*8/5}}}) end it 'should return uri with issuer option' do - expect(subject.otp_provisioning_uri(account, issuer: issuer)).to match(%r{otpauth://totp/#{issuer}:#{CGI.escape(account)}\?.*secret=\w{#{otp_secret_length}}(&|$)}) + expect(subject.otp_provisioning_uri(account, issuer: issuer)).to match(%r{otpauth://totp/#{issuer}:#{CGI.escape(account)}\?.*secret=\w{#{otp_secret_length*8/5}}(&|$)}) expect(subject.otp_provisioning_uri(account, issuer: issuer)).to match(%r{otpauth://totp/#{issuer}:#{CGI.escape(account)}\?.*issuer=#{issuer}(&|$)}) end end
lib/devise_two_factor/spec_helpers/two_factor_backupable_shared_examples.rb+1 −1 modified@@ -17,7 +17,7 @@ it 'generates recovery codes of the correct length' do @plaintext_codes.each do |code| - expect(code.length).to eq(subject.class.otp_backup_code_length) + expect(code.length).to eq(subject.class.otp_backup_code_length*2) end end
lib/devise_two_factor/strategies/two_factor_backupable.rb+0 −3 modified@@ -6,9 +6,6 @@ def authenticate! resource = mapping.to.find_for_database_authentication(authentication_hash) if validate(resource) { resource.invalidate_otp_backup_code!(params[scope]['otp_attempt']) } - # Devise fails to authenticate invalidated resources, but if we've - # gotten here, the object changed (Since we deleted a recovery code) - resource.save! super end
lib/devise_two_factor/version.rb+1 −1 modified@@ -1,3 +1,3 @@ module DeviseTwoFactor - VERSION = '5.1.0'.freeze + VERSION = '6.0.0'.freeze end
.markdownlint.json+6 −0 added@@ -0,0 +1,6 @@ +{ + "MD026": false, + "MD029": false, + "MD031": false, + "MD034": false +}
README.md+1 −3 modified@@ -15,9 +15,7 @@ We welcome pull requests, bug reports, and other contributions. We're especially ## Example App -An example Rails 4 application is provided in the `demo` directory. It showcases a minimal example of Devise-Two-Factor in action, and can act as a reference for integrating the gem into your own application. - -For the demo app to work, create an encryption key and store it as an environment variable. One way to do this is to create a file named `local_env.yml` in the application root. Set the value of `ENCRYPTION_KEY` in the YML file. That value will be loaded into the application environment by `application.rb`. +See [examples](demo/README.md). ## Getting Started
SECURITY.md+1 −1 modified@@ -2,4 +2,4 @@ ## Reporting a Vulnerability -Please report any vulnerabilities to the [Synopsys PSIRT](https://www.synopsys.com/company/legal/vulnerability-disclosure-policy.html). +Please report any vulnerabilities to the [Black Duck PSIRT](psirt@blackduck.com).
spec/devise/models/two_factor_authenticatable_spec.rb+1 −1 modified@@ -18,7 +18,7 @@ def self.encrypts(*attrs) attr_accessor :consumed_timestep - def save(validate) + def save!(_) # noop for testing true end
spec/devise/models/two_factor_backupable_spec.rb+4 −0 modified@@ -17,6 +17,10 @@ def self.encrypts(*attrs) devise :two_factor_authenticatable, :two_factor_backupable attr_accessor :otp_backup_codes + + def save!(_) + true + end end describe ::Devise::Models::TwoFactorBackupable do
UPGRADING.md+26 −12 modified@@ -1,8 +1,25 @@ -# Upgrading from 4.x to 5.x +# Upgrading -## Background +## Upgrading from 5.x to 6.x -### Database columns in version 4.x and older +### save! + +`consume_otp!` and `invalidate_otp_backup_code!` now call `save!` instead of `save` (or nothing at all in the case of `invalide_otp_backup_code!`). If you manually called `save`/`save!` after calling `invalidate_otp_backup_code` you may be able to remove it. + +### Secret Lengths + +The `otp_secret_length` and `otp_backup_code_length` options have changed to be the number of random bytes that are generated. +If you had configured these values you may want to change them if you wish to keep the same output length. + +`otp_secret_length` now has a default value of 20, generating a 160 bit secret key with an output length length of 32 bytes. + +`otp_backup_code_length` now has a default value of 16, generating a 32 byte backup code. + +## Upgrading from 4.x to 5.x + +### Background + +#### Database columns in version 4.x and older Versions 4.x and older stored the OTP secret in an attribute called `encrypted_otp_secret` using the [attr_encrypted](https://github.com/attr-encrypted/attr_encrypted) gem. This gem is currently unmaintained which is part of the motivation for moving to Rails encrypted attributes. This attribute was backed by three database columns: @@ -21,7 +38,7 @@ otp_required_for_login A fresh install of 4.x would create all five of the database columns above. -### Database columns in version 5.x and later +#### Database columns in version 5.x and later Versions 5+ of this gem uses a single [Rails 7+ encrypted attribute](https://edgeguides.rubyonrails.org/active_record_encryption.html) named `otp_secret`to store the OTP secret in the database table (usually `users` but will be whatever model you picked). @@ -33,18 +50,15 @@ consumed_timestep otp_required_for_login ``` -### Upgrading from 4.x to 5.x - - We have attempted to make the upgrade as painless as possible but unfortunately because of the secret storage change, it cannot be as simple as `bundle update devise-two-factor` :heart: -#### Assumptions +### Assumptions This guide assumes you are upgrading an existing Rails 6 app (with `devise` and `devise-two-factor`) to Rails 7. This gem must be upgraded **as part of a Rails 7 upgrade**. See [the official Rails upgrading guide](https://guides.rubyonrails.org/upgrading_ruby_on_rails.html) for an overview of upgrading Rails. -#### Phase 1: Upgrading devise-two-factor as part of Rails 7 upgrade +### Phase 1: Upgrading devise-two-factor as part of Rails 7 upgrade 1. Update the version constraint for Rails in your `Gemfile` to your desired version e.g. `gem "rails", "~> 7.0.3"` 1. Run `bundle install` and resolve any issues with dependencies. @@ -149,7 +163,7 @@ You can now deploy your upgraded application and devise-two-factor should work a This gem will fall back to **reading** the OTP secret from the legacy columns if it cannot find one in the new `otp_secret` column. When you **write** a new OTP secret it will always be written to the new `otp_secret` column. -#### Phase 2: Clean up +### Phase 2: Clean up This "clean up" phase can happen at the same time as your initial deployment but teams managing existing apps will likely want to do clean-up as separate, later deployments. @@ -200,7 +214,7 @@ This "clean up" phase can happen at the same time as your initial deployment but devise :two_factor_authenticatable ``` -# Guide to upgrading from 2.x to 3.x +## Upgrading from 2.x to 3.x Pull request #76 allows for compatibility with `attr_encrypted` 3.0, which should be used due to a security vulnerability discovered in 2.0. @@ -220,7 +234,7 @@ class User < ActiveRecord::Base :otp_secret_encryption_key => ENV['DEVISE_TWO_FACTOR_ENCRYPTION_KEY'] ``` -# Guide to upgrading from 1.x to 2.x +## Upgrading from 1.x to 2.x Pull request #43 added a new field to protect against "shoulder-surfing" attacks. If upgrading, you'll need to add the `:consumed_timestep` column to your `Users` model.
Vulnerability mechanics
Generated on May 9, 2026. Inputs: CWE entries + fix-commit diffs from this CVE's patches. Citations validated against bundle.
References
4- github.com/advisories/GHSA-qjxf-mc72-wjr2ghsaADVISORY
- github.com/devise-two-factor/devise-two-factor/security/advisories/GHSA-qjxf-mc72-wjr2ghsavendor-advisoryWEB
- nvd.nist.gov/vuln/detail/CVE-2024-8796ghsaADVISORY
- github.com/devise-two-factor/devise-two-factor/commit/cc6f34423d9c6af9f3e02be478c3c40dc7462e19ghsaWEB
News mentions
0No linked articles in our index yet.