devise_login_alerts 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 206062cc8e7c409c75285eca567ff1ac7c84e45387838945f9ae55419a20e068
4
+ data.tar.gz: 542ceff9ce520a2c44783ad2ae30fd93917e60c513e5009af4279a39795e06ce
5
+ SHA512:
6
+ metadata.gz: 32caafb187157097d808e6d26560ce1428af899bbfad136f63ee78fb4030cd5ad8962285a1be21bbcd0b8246fe1bc032f44abb2a4b7b1717d76366c48cbba890
7
+ data.tar.gz: e88d95cc0ac1a091a42255bae9ae9db4bf1a76651869fd64a2234540decb9776f68b20126601a57b082b6ae88efa8ae25502ebe55c6f00884cc71134612569be
data/CHANGELOG.md ADDED
@@ -0,0 +1,12 @@
1
+ # Changelog
2
+
3
+ ## 0.1.0 (17 November 2026)
4
+
5
+ - Record successful and failed Devise sign-ins with IP, location and user agent.
6
+ - Recognise returning browsers with a hashed first-party cookie.
7
+ - Email the account owner on a sign-in from a new device, without the IP address.
8
+ - Configurable IP and location resolvers, including Cloudflare.
9
+ - Install generator and retention purge.
10
+ - `on_event` hook and ActiveSupport notifications for every sign-in and failed attempt, for metrics.
11
+ - `recent_login_attempts`, `last_successful_login_attempt` and `failed_login_attempts_since` on the model.
12
+ - Supports Ruby 3.2+, Rails 7.1 to 8.x and Devise 4.9 to 5.x.
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Jammed
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,221 @@
1
+ # devise_login_alerts
2
+
3
+ Sign-in history and "new device" alert emails for [Devise](https://github.com/heartcombo/devise).
4
+
5
+ - Records every successful and failed sign-in: IP, rough location, user agent, failure reason.
6
+ - Recognises returning browsers with a first-party cookie, and emails the account owner when a sign-in comes from a device it hasn't seen before.
7
+ - Works with any Devise model, and with two-factor gems that sign in only after the second step (such as `devise-otp`). A remember-me cookie restoring an expired session, or a sign-in that isn't kept in the session (HTTP Basic, API tokens), is not counted as a sign-in.
8
+ - The email, the IP source, the location lookup and when to alert are all configurable.
9
+
10
+ ## Requirements
11
+
12
+ - Ruby 3.2 or newer
13
+ - Rails 7.1 to 8.x
14
+ - Devise 4.9 or newer
15
+
16
+ ## Installation
17
+
18
+ ```ruby
19
+ # Gemfile
20
+ gem 'devise_login_alerts'
21
+ ```
22
+
23
+ ```bash
24
+ bin/rails generate devise_login_alerts:install
25
+ bin/rails db:migrate
26
+ ```
27
+
28
+ Add the module to your Devise model:
29
+
30
+ ```ruby
31
+ class User < ApplicationRecord
32
+ devise :database_authenticatable, :recoverable, :login_alertable
33
+ end
34
+ ```
35
+
36
+ That gives you:
37
+
38
+ ```ruby
39
+ user.login_attempts # every recorded attempt
40
+ user.login_devices # browsers this user has signed in from
41
+ user.recent_login_attempts(20) # newest first
42
+ user.last_successful_login_attempt
43
+ user.failed_login_attempts_since(1.day.ago)
44
+
45
+ attempt.successful? # and failure_reason, e.g. "invalid", "locked"
46
+ attempt.new_device?
47
+ attempt.location # "Manchester, GB", or nil
48
+ attempt.device_summary # "Firefox on Windows", or nil
49
+ attempt.created_at
50
+ ```
51
+
52
+ Both associations are deleted with the user.
53
+
54
+ ## How devices are recognised
55
+
56
+ On a successful sign-in the browser gets an `httponly`, `SameSite=Lax` cookie holding a random token. The database only stores an HMAC of that token, keyed to the user and your `secret_key_base`, so:
57
+
58
+ - a leaked database can't be turned back into working cookies;
59
+ - the same browser used by two accounts can't be linked across them.
60
+
61
+ There is no browser fingerprinting. A sign-in from a browser without a recognised cookie counts as a new device, so clearing cookies or using a private window triggers an alert. The email says so.
62
+
63
+ The first device a user ever signs in from is remembered silently, so existing users don't all get an email the day you install the gem. Set `alert_on_first_device = true` to change that.
64
+
65
+ ## Choosing when to alert
66
+
67
+ Three layers, all optional:
68
+
69
+ ```ruby
70
+ # Per model
71
+ class User < ApplicationRecord
72
+ def send_login_alert?(login_attempt)
73
+ !admin_impersonation? && super
74
+ end
75
+ end
76
+
77
+ # Globally
78
+ DeviseLoginAlerts.config.skip_alert_if = ->(user, login_attempt) { user.email.end_with?('@example.test') }
79
+
80
+ # Per sign-in, e.g. right after accepting an invite
81
+ sign_in(user, skip_login_alert: true)
82
+ ```
83
+
84
+ Skipped sign-ins are still recorded and their device is still remembered.
85
+
86
+ ## Failed sign-ins
87
+
88
+ Failures raised by Devise's strategies (wrong password, locked, inactive account) are recorded against the account the submitted email belongs to. Unknown emails are ignored. Failures your own code detects, such as a wrong two-factor code, can be recorded explicitly:
89
+
90
+ ```ruby
91
+ DeviseLoginAlerts.record_failure(user, request, reason: :invalid_otp)
92
+ ```
93
+
94
+ Failed attempts never set the device cookie.
95
+
96
+ IP and location values are validated before they are stored, whichever resolver supplied them. An unrecognised user agent is never echoed into the email, since the client controls it.
97
+
98
+ ## Configuration
99
+
100
+ ```ruby
101
+ DeviseLoginAlerts.configure do |config|
102
+ config.ip_resolver = :remote_ip # :ip, :cloudflare, 'X-Real-IP', or ->(request) { ... }
103
+ config.verify_cloudflare_peer = false # with :cloudflare, only trust the header from Cloudflare addresses
104
+ config.location_resolver = nil # :cloudflare, or ->(request, ip) { { country_code: 'GB', city: 'Leeds' } }
105
+ config.country_name = ->(code) { code } # how a stored country code is shown in the email
106
+
107
+ config.cookie_name = 'devise_login_alerts_device'
108
+ config.cookie_lifetime = 1.year
109
+ config.cookie_options = {} # e.g. { domain: :all }
110
+
111
+ config.alert_on_first_device = false
112
+ config.skip_alert_if = nil
113
+
114
+ config.mailer = 'DeviseLoginAlerts::Mailer'
115
+ config.parent_mailer = 'ActionMailer::Base'
116
+ config.mailer_sender = nil # falls back to the parent mailer's default, then Devise.mailer_sender
117
+ config.deliver_later = true
118
+ config.app_name = -> { Rails.application.class.module_parent_name }
119
+ config.security_url = nil # defaults to the Devise "forgot password" URL for the scope
120
+
121
+ config.attempt_retention = 90.days
122
+ config.device_retention = 1.year
123
+ end
124
+ ```
125
+
126
+ ### IP addresses behind a proxy or CDN
127
+
128
+ `request.remote_ip` is right for most apps once Rails' trusted proxies are configured. Behind Cloudflare use `:cloudflare`, which reads `CF-Connecting-IP`. Anyone who can reach your origin directly can send that header, so either only accept traffic from Cloudflare or turn on `verify_cloudflare_peer`, which then also guards the `:cloudflare` location headers.
129
+
130
+ ### Location
131
+
132
+ `:cloudflare` reads the `CF-IPCountry` and `CF-IPCity` headers. City needs Cloudflare's "Add visitor location headers" managed transform. Only the country code and city are stored, never coordinates. Emails show the code unless you set `country_name`, for example with the [`countries`](https://github.com/countries/countries) gem:
133
+
134
+ ```ruby
135
+ config.country_name = ->(code) { ISO3166::Country[code]&.translation(I18n.locale.to_s) || code }
136
+ ```
137
+
138
+ ## The email
139
+
140
+ The alert says when, roughly where and on what browser and system the sign-in happened. The IP address is recorded for the history but kept out of the email.
141
+
142
+ Override `app/views/devise_login_alerts/mailer/new_device_login.{html,text}.erb` and the `devise_login_alerts.mailer.new_device_login.*` translations, or point `config.mailer` at your own mailer. A custom mailer must respond to `with(login_attempt:).new_device_login`. Set `parent_mailer` to reuse your app's layout and sender.
143
+
144
+ ## Events and metrics
145
+
146
+ Every recorded attempt produces an event once its sign-in, device and any alert have been handled:
147
+
148
+ | `event.name` | When |
149
+ | --- | --- |
150
+ | `:sign_in` | a successful sign-in |
151
+ | `:failed_sign_in` | a failed attempt for a known account |
152
+
153
+ The event carries `login_attempt` and offers `successful?`, `failure_reason`, `alerted?`, `user`, and `device`, which is `:first` (the user's first device), `:new` (an unrecognised device for a user with others) or `:known`.
154
+
155
+ Point `on_event` at your metrics service:
156
+
157
+ ```ruby
158
+ config.on_event = ->(event) do
159
+ Appsignal.increment_counter('sign_ins', 1, outcome: event.name.to_s, device: event.device.to_s, alerted: event.alerted?.to_s)
160
+ end
161
+ ```
162
+
163
+ The same events are published through ActiveSupport::Notifications as `sign_in.devise_login_alerts` and `failed_sign_in.devise_login_alerts`, with `event:` and `login_attempt:` in the payload.
164
+
165
+ Errors raised by `on_event` or a subscriber are reported through `Rails.error` and never affect the sign-in. Tracking errors are reported the same way.
166
+
167
+ ## Retention and privacy
168
+
169
+ Sign-in records are personal data. Run the purge on a schedule:
170
+
171
+ ```ruby
172
+ DeviseLoginAlerts.purge!
173
+ ```
174
+
175
+ It deletes attempts older than `attempt_retention` and devices unused for `device_retention`, except each user's most recent device. Keeping that one means an account whose devices have all aged out doesn't treat its next sign-in, which may not be the owner's, as a silent first device. The device cookie is used only to secure sign-ins, which generally falls under the "strictly necessary" exemption from cookie consent (UK PECR, EU ePrivacy). Mention it in your privacy notice.
176
+
177
+ ## Contributing
178
+
179
+ Bug reports and pull requests are welcome at <https://github.com/jammed-org/devise-login-alerts>. For anything bigger than a small fix, open an issue first so we can agree on the approach.
180
+
181
+ ### Setting up
182
+
183
+ ```bash
184
+ bundle install
185
+ bundle exec rspec
186
+ bundle exec rubocop
187
+ ```
188
+
189
+ The specs run against a small Rails app in `spec/dummy`, on an in-memory SQLite database, so there is nothing else to set up.
190
+
191
+ `Gemfile.lock` is not committed. CI resolves dependencies fresh on each supported Ruby version (3.2 to 3.4), so each one gets the newest gems it can run.
192
+
193
+ ### Pull requests
194
+
195
+ - Add or update specs for any behaviour change. Request specs in `spec/requests` cover the sign-in flow end to end.
196
+ - Keep `bundle exec rspec` and `bundle exec rubocop` passing. CI runs both on every pull request.
197
+ - Don't use syntax or core classes newer than Ruby 3.2, or Rails APIs newer than 7.1.
198
+ - Add a line to the "unreleased" section of `CHANGELOG.md` describing the change for users.
199
+ - Be careful with anything that stores or shows personal data: IP addresses, locations and user agents. Validate what is stored, and keep the IP out of the email.
200
+
201
+ ### Releasing
202
+
203
+ Maintainers only. Releases are published by the `Release` GitHub Actions workflow using [RubyGems trusted publishing](https://guides.rubygems.org/trusted-publishing/), so nobody needs a RubyGems API key.
204
+
205
+ 1. Update `DeviseLoginAlerts::VERSION` in `lib/devise_login_alerts/version.rb` and date the release in `CHANGELOG.md`.
206
+ 2. Commit and push to `main`, and wait for CI to pass.
207
+ 3. Tag and push: `git tag vX.Y.Z && git push origin vX.Y.Z`.
208
+
209
+ The workflow checks the tag matches `VERSION`, runs the specs and rubocop, pushes the gem to RubyGems and creates a GitHub release.
210
+
211
+ ### Security issues
212
+
213
+ Please don't open public issues for security problems. Report them privately through GitHub's "Report a vulnerability" button on the repository's Security tab.
214
+
215
+ ### Using an AI coding agent
216
+
217
+ [AGENTS.md](AGENTS.md) has instructions for coding agents (Claude Code, Codex, Cursor and others) working in this repository.
218
+
219
+ ## License
220
+
221
+ MIT, see [LICENSE.txt](LICENSE.txt).
@@ -0,0 +1,34 @@
1
+ module DeviseLoginAlerts
2
+ class Mailer < DeviseLoginAlerts.config.parent_mailer.constantize
3
+ def new_device_login
4
+ @login_attempt = params[:login_attempt]
5
+ @user = @login_attempt.user
6
+ @app_name = DeviseLoginAlerts.config.resolved_app_name
7
+ @security_url = security_url
8
+
9
+ mail(
10
+ **sender,
11
+ to: @user.email,
12
+ subject: t('devise_login_alerts.mailer.new_device_login.subject', app_name: @app_name),
13
+ template_path: 'devise_login_alerts/mailer'
14
+ )
15
+ end
16
+
17
+ private
18
+
19
+ def sender
20
+ sender = DeviseLoginAlerts.config.mailer_sender
21
+ sender ||= Devise.mailer_sender if self.class.default[:from].blank?
22
+ sender = sender.call if sender.respond_to?(:call)
23
+ sender ? { from: sender } : {}
24
+ end
25
+
26
+ def security_url
27
+ custom = DeviseLoginAlerts.config.security_url
28
+ return custom.call(@user, @login_attempt) if custom
29
+
30
+ route = "new_#{@login_attempt.scope}_password_url"
31
+ public_send(route) if respond_to?(route)
32
+ end
33
+ end
34
+ end
@@ -0,0 +1,10 @@
1
+ module DeviseLoginAlerts
2
+ class Device < ActiveRecord::Base
3
+ belongs_to :user, polymorphic: true
4
+ has_many :login_attempts, class_name: 'DeviseLoginAlerts::LoginAttempt', dependent: :nullify
5
+
6
+ def summary
7
+ UserAgentSummary.call(user_agent)
8
+ end
9
+ end
10
+ end
@@ -0,0 +1,22 @@
1
+ module DeviseLoginAlerts
2
+ class LoginAttempt < ActiveRecord::Base
3
+ belongs_to :user, polymorphic: true
4
+ belongs_to :device, class_name: 'DeviseLoginAlerts::Device', optional: true
5
+
6
+ scope :successful, -> { where(successful: true) }
7
+ scope :failed, -> { where(successful: false) }
8
+ scope :recent, -> { order(created_at: :desc) }
9
+
10
+ def location
11
+ [city, country_name].compact_blank.join(', ').presence
12
+ end
13
+
14
+ def country_name
15
+ DeviseLoginAlerts.config.country_name.call(country_code) if country_code.present?
16
+ end
17
+
18
+ def device_summary
19
+ UserAgentSummary.call(user_agent)
20
+ end
21
+ end
22
+ end
@@ -0,0 +1,29 @@
1
+ <% signed_in_at = @login_attempt.created_at.in_time_zone %>
2
+ <p><%= @user.try(:name).present? ? t('.greeting', name: @user.name) : t('.greeting_without_name') %></p>
3
+
4
+ <p><%= t('.intro', app_name: @app_name, email: @user.email) %></p>
5
+
6
+ <table cellpadding="4" cellspacing="0" border="0">
7
+ <tr>
8
+ <td><strong><%= t('.when') %></strong></td>
9
+ <td><%= l(signed_in_at, format: :long) %> (<%= signed_in_at.zone %>)</td>
10
+ </tr>
11
+ <tr>
12
+ <td><strong><%= t('.where') %></strong></td>
13
+ <td>
14
+ <%= @login_attempt.location || t('.unknown') %>
15
+ <% if @login_attempt.location %><br><small><%= t('.where_hint') %></small><% end %>
16
+ </td>
17
+ </tr>
18
+ <tr>
19
+ <td><strong><%= t('.device') %></strong></td>
20
+ <td><%= @login_attempt.device_summary || t('.unknown') %></td>
21
+ </tr>
22
+ </table>
23
+
24
+ <p><%= t('.was_you') %></p>
25
+
26
+ <p>
27
+ <%= t('.was_not_you') %>
28
+ <% if @security_url %><br><a href="<%= @security_url %>"><%= t('.change_password') %></a><% end %>
29
+ </p>
@@ -0,0 +1,15 @@
1
+ <% signed_in_at = @login_attempt.created_at.in_time_zone -%>
2
+ <%= @user.try(:name).present? ? t('.greeting', name: @user.name) : t('.greeting_without_name') %>
3
+
4
+ <%= t('.intro', app_name: @app_name, email: @user.email) %>
5
+
6
+ <%= t('.when') %>: <%= l(signed_in_at, format: :long) %> (<%= signed_in_at.zone %>)
7
+ <%= t('.where') %>: <%= @login_attempt.location ? "#{@login_attempt.location} (#{t('.where_hint')})" : t('.unknown') %>
8
+ <%= t('.device') %>: <%= @login_attempt.device_summary || t('.unknown') %>
9
+
10
+ <%= t('.was_you') %>
11
+
12
+ <%= t('.was_not_you') %>
13
+ <% if @security_url -%>
14
+ <%= t('.change_password') %>: <%= @security_url %>
15
+ <% end -%>
@@ -0,0 +1,16 @@
1
+ en:
2
+ devise_login_alerts:
3
+ mailer:
4
+ new_device_login:
5
+ subject: "New sign-in to your %{app_name} account"
6
+ greeting: "Hi %{name},"
7
+ greeting_without_name: "Hi,"
8
+ intro: "Your %{app_name} account (%{email}) was just signed in to from a device or browser we haven't seen before."
9
+ when: "When"
10
+ where: "Where"
11
+ where_hint: "approximate, based on the connection"
12
+ device: "Device"
13
+ unknown: "Unknown"
14
+ was_you: "If this was you, you don't need to do anything. You'll also get this email after clearing your browser's cookies or signing in from a private window."
15
+ was_not_you: "If this wasn't you, change your password straight away."
16
+ change_password: "Change your password"
@@ -0,0 +1,34 @@
1
+ module DeviseLoginAlerts
2
+ class Configuration
3
+ attr_accessor :ip_resolver, :verify_cloudflare_peer, :location_resolver, :country_name,
4
+ :cookie_name, :cookie_lifetime, :cookie_options,
5
+ :alert_on_first_device, :skip_alert_if, :on_event,
6
+ :mailer, :parent_mailer, :mailer_sender, :deliver_later, :app_name, :security_url,
7
+ :attempt_retention, :device_retention
8
+
9
+ def initialize
10
+ @ip_resolver = :remote_ip
11
+ @verify_cloudflare_peer = false
12
+ @location_resolver = nil
13
+ @country_name = ->(country_code) { country_code }
14
+ @cookie_name = 'devise_login_alerts_device'
15
+ @cookie_lifetime = 1.year
16
+ @cookie_options = {}
17
+ @alert_on_first_device = false
18
+ @skip_alert_if = nil
19
+ @on_event = nil
20
+ @mailer = 'DeviseLoginAlerts::Mailer'
21
+ @parent_mailer = 'ActionMailer::Base'
22
+ @mailer_sender = nil
23
+ @deliver_later = true
24
+ @app_name = -> { Rails.application.class.module_parent_name }
25
+ @security_url = nil
26
+ @attempt_retention = 90.days
27
+ @device_retention = 1.year
28
+ end
29
+
30
+ def resolved_app_name
31
+ app_name.respond_to?(:call) ? app_name.call : app_name
32
+ end
33
+ end
34
+ end
@@ -0,0 +1,45 @@
1
+ require 'openssl'
2
+ require 'securerandom'
3
+
4
+ module DeviseLoginAlerts
5
+ class DeviceCookie
6
+ TOKEN_FORMAT = /\A[A-Za-z0-9_-]{43}\z/
7
+
8
+ def self.digest(user, token)
9
+ OpenSSL::HMAC.hexdigest('SHA256', secret, [user.class.base_class.name, user.id, token].join(':'))
10
+ end
11
+
12
+ def self.secret
13
+ Rails.application.key_generator.generate_key('devise_login_alerts/device_token', 32)
14
+ end
15
+
16
+ def initialize(request)
17
+ @request = request
18
+ end
19
+
20
+ def token
21
+ value = @request.cookie_jar[config.cookie_name]
22
+ value if value.is_a?(String) && value.match?(TOKEN_FORMAT)
23
+ end
24
+
25
+ def token!
26
+ @token ||= token || SecureRandom.urlsafe_base64(32)
27
+ end
28
+
29
+ def write!
30
+ @request.cookie_jar[config.cookie_name] = {
31
+ value: token!,
32
+ expires: config.cookie_lifetime.from_now,
33
+ httponly: true,
34
+ secure: @request.ssl?,
35
+ same_site: :lax
36
+ }.merge(config.cookie_options)
37
+ end
38
+
39
+ private
40
+
41
+ def config
42
+ DeviseLoginAlerts.config
43
+ end
44
+ end
45
+ end
@@ -0,0 +1,6 @@
1
+ require 'rails/engine'
2
+
3
+ module DeviseLoginAlerts
4
+ class Engine < ::Rails::Engine
5
+ end
6
+ end
@@ -0,0 +1,11 @@
1
+ module DeviseLoginAlerts
2
+ Event = Data.define(:name, :login_attempt, :first_device) do
3
+ delegate :user, :successful?, :failure_reason, :new_device?, :alerted?, to: :login_attempt
4
+
5
+ def device
6
+ return :known unless new_device?
7
+
8
+ first_device ? :first : :new
9
+ end
10
+ end
11
+ end
@@ -0,0 +1,62 @@
1
+ module DeviseLoginAlerts
2
+ module Hooks
3
+ IGNORED_FAILURES = %i[unauthenticated timeout].freeze
4
+
5
+ module_function
6
+
7
+ def after_set_user(user, warden, options)
8
+ return unless tracked?(user) && warden.authenticated?(options[:scope])
9
+ return if options[:store] == false
10
+ return if user.respond_to?(:active_for_authentication?) && !user.active_for_authentication?
11
+ return if remember_me_restore?(warden)
12
+
13
+ request = ActionDispatch::Request.new(warden.env)
14
+ Tracker.new(user, request, scope: options[:scope]).record_success(alert: !options[:skip_login_alert])
15
+ rescue StandardError => e
16
+ report(e)
17
+ end
18
+
19
+ def before_failure(env, options)
20
+ reason = options[:message]
21
+ mapping = Devise.mappings[options[:scope]]
22
+ return if reason.blank? || IGNORED_FAILURES.include?(reason.to_sym) || mapping.nil?
23
+
24
+ request = ActionDispatch::Request.new(env)
25
+ user = find_user(mapping, request)
26
+ Tracker.new(user, request, scope: mapping.name).record_failure(reason) if tracked?(user)
27
+ rescue StandardError => e
28
+ report(e)
29
+ end
30
+
31
+ def find_user(mapping, request)
32
+ params = request.params[mapping.name.to_s]
33
+ return unless params.is_a?(Hash)
34
+
35
+ keys = mapping.to.authentication_keys
36
+ conditions = (keys.is_a?(Hash) ? keys.keys : keys).index_with { |key| params[key.to_s] }
37
+ return if conditions.values.any? { |value| !value.is_a?(String) || value.blank? }
38
+
39
+ mapping.to.find_for_authentication(conditions)
40
+ end
41
+
42
+ def remember_me_restore?(warden)
43
+ defined?(Devise::Strategies::Rememberable) && warden.winning_strategy.is_a?(Devise::Strategies::Rememberable)
44
+ end
45
+
46
+ def tracked?(user)
47
+ user.respond_to?(:devise_modules) && user.devise_modules.include?(:login_alertable)
48
+ end
49
+
50
+ def report(error)
51
+ Rails.error.report(error, handled: true, source: 'devise_login_alerts')
52
+ end
53
+ end
54
+ end
55
+
56
+ Warden::Manager.after_set_user except: :fetch do |user, warden, options|
57
+ DeviseLoginAlerts::Hooks.after_set_user(user, warden, options)
58
+ end
59
+
60
+ Warden::Manager.before_failure do |env, options|
61
+ DeviseLoginAlerts::Hooks.before_failure(env, options)
62
+ end
@@ -0,0 +1,59 @@
1
+ require 'ipaddr'
2
+
3
+ module DeviseLoginAlerts
4
+ module IpResolver
5
+ CLOUDFLARE_HEADER = 'CF-Connecting-IP'.freeze
6
+
7
+ # https://www.cloudflare.com/ips/
8
+ CLOUDFLARE_RANGES = %w[
9
+ 173.245.48.0/20 103.21.244.0/22 103.22.200.0/22 103.31.4.0/22 141.101.64.0/18 108.162.192.0/18
10
+ 190.93.240.0/20 188.114.96.0/20 197.234.240.0/22 198.41.128.0/17 162.158.0.0/15 104.16.0.0/13
11
+ 104.24.0.0/14 172.64.0.0/13 131.0.72.0/22
12
+ 2400:cb00::/32 2606:4700::/32 2803:f800::/32 2405:b500::/32 2405:8100::/32 2a06:98c0::/29 2c0f:f248::/32
13
+ ].map { |range| IPAddr.new(range) }.freeze
14
+
15
+ module_function
16
+
17
+ def call(request)
18
+ ip = resolve(request, DeviseLoginAlerts.config.ip_resolver)
19
+ ip_address?(ip) ? ip : request.remote_ip
20
+ end
21
+
22
+ def resolve(request, resolver)
23
+ case resolver
24
+ when :remote_ip then request.remote_ip
25
+ when :ip then request.ip
26
+ when :cloudflare then cloudflare(request)
27
+ when String then header(request, resolver)
28
+ else resolver.call(request)
29
+ end
30
+ end
31
+
32
+ def cloudflare(request)
33
+ return request.remote_ip if DeviseLoginAlerts.config.verify_cloudflare_peer && !cloudflare_ip?(request.remote_ip)
34
+
35
+ header(request, CLOUDFLARE_HEADER) || request.remote_ip
36
+ end
37
+
38
+ def header(request, name)
39
+ value = request.get_header("HTTP_#{name.upcase.tr('-', '_')}")
40
+ value.to_s.split(',').first&.strip.presence
41
+ end
42
+
43
+ def ip_address?(value)
44
+ return false unless value.is_a?(String) && value.match?(/\A[0-9a-fA-F.:]{2,45}\z/)
45
+
46
+ IPAddr.new(value)
47
+ true
48
+ rescue IPAddr::Error
49
+ false
50
+ end
51
+
52
+ def cloudflare_ip?(ip)
53
+ address = IPAddr.new(ip.to_s)
54
+ CLOUDFLARE_RANGES.any? { |range| range.include?(address) }
55
+ rescue IPAddr::Error
56
+ false
57
+ end
58
+ end
59
+ end
@@ -0,0 +1,43 @@
1
+ module DeviseLoginAlerts
2
+ module LocationResolver
3
+ UNKNOWN_COUNTRY = 'XX'.freeze
4
+ COUNTRY_CODE = /\A[A-Z0-9]{2}\z/
5
+ CITY_LIMIT = 100
6
+
7
+ module_function
8
+
9
+ def call(request, ip)
10
+ resolver = DeviseLoginAlerts.config.location_resolver
11
+
12
+ location = case resolver
13
+ when nil then {}
14
+ when :cloudflare then cloudflare(request)
15
+ else resolver.call(request, ip) || {}
16
+ end
17
+ sanitize(location.to_h.symbolize_keys)
18
+ end
19
+
20
+ def sanitize(location)
21
+ country_code = location[:country_code].to_s.upcase
22
+ city = location[:city].to_s.gsub(/[[:cntrl:]]/, '').squish.truncate(CITY_LIMIT, omission: '')
23
+
24
+ { country_code: (country_code if country_code.match?(COUNTRY_CODE)), city: city.presence }.compact
25
+ end
26
+
27
+ def cloudflare(request)
28
+ return {} if DeviseLoginAlerts.config.verify_cloudflare_peer && !IpResolver.cloudflare_ip?(request.remote_ip)
29
+
30
+ country = request.get_header('HTTP_CF_IPCOUNTRY').presence
31
+ {
32
+ country_code: (country unless country == UNKNOWN_COUNTRY),
33
+ city: utf8(request.get_header('HTTP_CF_IPCITY')).presence
34
+ }
35
+ end
36
+
37
+ def utf8(value)
38
+ return if value.nil?
39
+
40
+ value.dup.force_encoding(Encoding::UTF_8).scrub('')
41
+ end
42
+ end
43
+ end
@@ -0,0 +1,30 @@
1
+ require 'devise_login_alerts/hooks'
2
+
3
+ module Devise
4
+ module Models
5
+ module LoginAlertable
6
+ extend ActiveSupport::Concern
7
+
8
+ included do
9
+ has_many :login_attempts, as: :user, class_name: 'DeviseLoginAlerts::LoginAttempt', dependent: :delete_all
10
+ has_many :login_devices, as: :user, class_name: 'DeviseLoginAlerts::Device', dependent: :delete_all
11
+ end
12
+
13
+ def send_login_alert?(_login_attempt)
14
+ true
15
+ end
16
+
17
+ def recent_login_attempts(limit = 20)
18
+ login_attempts.recent.limit(limit)
19
+ end
20
+
21
+ def last_successful_login_attempt
22
+ login_attempts.successful.recent.first
23
+ end
24
+
25
+ def failed_login_attempts_since(time)
26
+ login_attempts.failed.where(created_at: time..)
27
+ end
28
+ end
29
+ end
30
+ end
@@ -0,0 +1,87 @@
1
+ module DeviseLoginAlerts
2
+ class Tracker
3
+ USER_AGENT_LIMIT = 512
4
+
5
+ def initialize(user, request, scope:)
6
+ @user = user
7
+ @request = request
8
+ @scope = scope.to_s
9
+ end
10
+
11
+ # The cookie is written last so a failure anywhere before it leaves the browser unknown, and the next sign-in alerts.
12
+ def record_success(alert: true)
13
+ cookie = DeviceCookie.new(@request)
14
+ had_devices = @user.login_devices.exists?
15
+
16
+ attempt = LoginAttempt.transaction do
17
+ device = touch_device(cookie.token!)
18
+ create_attempt(successful: true, device: device, new_device: device.previously_new_record?)
19
+ end
20
+
21
+ deliver_alert(attempt) if attempt.new_device? && alert && alert?(attempt, had_devices)
22
+ cookie.write!
23
+ emit(:sign_in, attempt, first_device: !had_devices)
24
+ attempt
25
+ end
26
+
27
+ def record_failure(reason)
28
+ token = DeviceCookie.new(@request).token
29
+ device = token && @user.login_devices.find_by(token_digest: DeviceCookie.digest(@user, token))
30
+
31
+ attempt = create_attempt(successful: false, failure_reason: reason.to_s, device: device, new_device: device.nil?)
32
+ emit(:failed_sign_in, attempt)
33
+ attempt
34
+ end
35
+
36
+ private
37
+
38
+ def touch_device(token)
39
+ digest = DeviceCookie.digest(@user, token)
40
+ device = @user.login_devices.find_or_initialize_by(token_digest: digest)
41
+ Device.transaction(requires_new: true) { device.update!(user_agent: user_agent, last_seen_at: Time.current) }
42
+ device
43
+ rescue ActiveRecord::RecordNotUnique
44
+ @user.login_devices.find_by!(token_digest: digest)
45
+ end
46
+
47
+ def create_attempt(**attributes)
48
+ ip = IpResolver.call(@request)
49
+ @user.login_attempts.create!(
50
+ scope: @scope, ip: ip, user_agent: user_agent, **LocationResolver.call(@request, ip), **attributes
51
+ )
52
+ end
53
+
54
+ def emit(name, attempt, first_device: false)
55
+ event = Event.new(name: name, login_attempt: attempt, first_device: first_device && attempt.new_device?)
56
+ safely { ActiveSupport::Notifications.instrument("#{name}.devise_login_alerts", event: event, login_attempt: attempt) }
57
+ safely { config.on_event&.call(event) }
58
+ end
59
+
60
+ def safely
61
+ yield
62
+ rescue StandardError => e
63
+ Rails.error.report(e, handled: true, source: 'devise_login_alerts')
64
+ end
65
+
66
+ def alert?(attempt, had_devices)
67
+ return false unless had_devices || config.alert_on_first_device
68
+ return false if config.skip_alert_if&.call(@user, attempt)
69
+
70
+ @user.send_login_alert?(attempt)
71
+ end
72
+
73
+ def deliver_alert(attempt)
74
+ message = config.mailer.constantize.with(login_attempt: attempt).new_device_login
75
+ config.deliver_later ? message.deliver_later : message.deliver_now
76
+ attempt.update!(alerted: true)
77
+ end
78
+
79
+ def user_agent
80
+ @request.user_agent.to_s.truncate(USER_AGENT_LIMIT).presence
81
+ end
82
+
83
+ def config
84
+ DeviseLoginAlerts.config
85
+ end
86
+ end
87
+ end
@@ -0,0 +1,33 @@
1
+ module DeviseLoginAlerts
2
+ module UserAgentSummary
3
+ BROWSERS = [
4
+ ['Edge', %r{Edg(e|A|iOS)?/}],
5
+ ['Opera', %r{OPR/|Opera}],
6
+ ['Samsung Internet', /SamsungBrowser/],
7
+ ['Firefox', %r{Firefox/|FxiOS}],
8
+ ['Chrome', %r{Chrome/|CriOS}],
9
+ ['Safari', %r{Safari/}]
10
+ ].freeze
11
+
12
+ PLATFORMS = [
13
+ ['iOS', /iPhone|iPad|iPod/],
14
+ ['Android', /Android/],
15
+ ['ChromeOS', /CrOS/],
16
+ ['Windows', /Windows/],
17
+ ['macOS', /Macintosh|Mac OS X/],
18
+ ['Linux', /Linux/]
19
+ ].freeze
20
+
21
+ module_function
22
+
23
+ def call(user_agent)
24
+ return if user_agent.blank?
25
+
26
+ [match(BROWSERS, user_agent), match(PLATFORMS, user_agent)].compact.join(' on ').presence
27
+ end
28
+
29
+ def match(patterns, user_agent)
30
+ patterns.find { |_name, pattern| user_agent.match?(pattern) }&.first
31
+ end
32
+ end
33
+ end
@@ -0,0 +1,3 @@
1
+ module DeviseLoginAlerts
2
+ VERSION = '0.1.0'.freeze
3
+ end
@@ -0,0 +1,49 @@
1
+ require 'devise'
2
+ require 'devise_login_alerts/version'
3
+ require 'devise_login_alerts/configuration'
4
+ require 'devise_login_alerts/ip_resolver'
5
+ require 'devise_login_alerts/location_resolver'
6
+ require 'devise_login_alerts/device_cookie'
7
+ require 'devise_login_alerts/user_agent_summary'
8
+ require 'devise_login_alerts/event'
9
+ require 'devise_login_alerts/tracker'
10
+ require 'devise_login_alerts/engine'
11
+
12
+ module DeviseLoginAlerts
13
+ def self.config
14
+ @config ||= Configuration.new
15
+ end
16
+
17
+ def self.configure
18
+ yield config
19
+ end
20
+
21
+ def self.reset_config!
22
+ @config = Configuration.new
23
+ end
24
+
25
+ def self.table_name_prefix
26
+ 'devise_login_alerts_'
27
+ end
28
+
29
+ def self.record_failure(user, request, reason:, scope: Devise::Mapping.find_scope!(user))
30
+ Tracker.new(user, request, scope: scope).record_failure(reason)
31
+ end
32
+
33
+ def self.purge!(now: Time.current)
34
+ LoginAttempt.where(created_at: ...(now - config.attempt_retention)).in_batches.delete_all
35
+ stale_devices(now - config.device_retention).in_batches.delete_all
36
+ end
37
+
38
+ # Each user's newest device is kept, so an account with no devices left can't take a silent first sign-in.
39
+ def self.stale_devices(cutoff)
40
+ table = Device.quoted_table_name
41
+
42
+ Device.where(last_seen_at: ...cutoff).where(<<~SQL.squish)
43
+ EXISTS (SELECT 1 FROM #{table} newer WHERE newer.user_type = #{table}.user_type
44
+ AND newer.user_id = #{table}.user_id AND newer.last_seen_at > #{table}.last_seen_at)
45
+ SQL
46
+ end
47
+ end
48
+
49
+ Devise.add_module :login_alertable, model: 'devise_login_alerts/model'
@@ -0,0 +1,26 @@
1
+ require 'rails/generators'
2
+ require 'rails/generators/active_record'
3
+
4
+ module DeviseLoginAlerts
5
+ module Generators
6
+ class InstallGenerator < Rails::Generators::Base
7
+ include ActiveRecord::Generators::Migration
8
+
9
+ source_root File.expand_path('templates', __dir__)
10
+
11
+ def copy_initializer
12
+ template 'initializer.rb', 'config/initializers/devise_login_alerts.rb'
13
+ end
14
+
15
+ def copy_migration
16
+ migration_template 'migration.rb', 'db/migrate/create_devise_login_alerts.rb'
17
+ end
18
+
19
+ private
20
+
21
+ def migration_version
22
+ "[#{ActiveRecord::VERSION::STRING.to_f}]"
23
+ end
24
+ end
25
+ end
26
+ end
@@ -0,0 +1,36 @@
1
+ DeviseLoginAlerts.configure do |config|
2
+ # Where the client IP comes from: :remote_ip (default), :ip, :cloudflare, a header name, or ->(request) { ... }
3
+ # config.ip_resolver = :remote_ip
4
+
5
+ # With :cloudflare, only trust CF-Connecting-IP when request.remote_ip is a Cloudflare address.
6
+ # config.verify_cloudflare_peer = false
7
+
8
+ # Rough location for the alert email: nil, :cloudflare, or ->(request, ip) { { country_code:, city: } }
9
+ # config.location_resolver = nil
10
+
11
+ # How a stored country code is shown in the email, e.g. with the countries gem:
12
+ # config.country_name = ->(code) { ISO3166::Country[code]&.translation(I18n.locale.to_s) || code }
13
+
14
+ # config.cookie_name = 'devise_login_alerts_device'
15
+ # config.cookie_lifetime = 1.year
16
+ # config.cookie_options = { domain: :all }
17
+
18
+ # The first device a user signs in from is remembered without an alert.
19
+ # config.alert_on_first_device = false
20
+
21
+ # config.skip_alert_if = ->(user, login_attempt) { false }
22
+
23
+ # Called after every recorded sign-in and failed attempt, e.g. to count them in your metrics service.
24
+ # config.on_event = ->(event) { StatsD.increment("sign_ins.#{event.name}", tags: ["device:#{event.device}"]) }
25
+
26
+ # config.mailer = 'DeviseLoginAlerts::Mailer'
27
+ # config.parent_mailer = 'ActionMailer::Base'
28
+ # config.mailer_sender = 'security@example.com'
29
+ # config.deliver_later = true
30
+ # config.app_name = -> { Rails.application.class.module_parent_name }
31
+ # config.security_url = ->(user, login_attempt) { Rails.application.routes.url_helpers.edit_user_registration_url }
32
+
33
+ # Used by DeviseLoginAlerts.purge!, which you should run on a schedule.
34
+ # config.attempt_retention = 90.days
35
+ # config.device_retention = 1.year
36
+ end
@@ -0,0 +1,32 @@
1
+ class CreateDeviseLoginAlerts < ActiveRecord::Migration<%= migration_version %>
2
+ def change
3
+ create_table :devise_login_alerts_devices do |t|
4
+ t.references :user, polymorphic: true, null: false, index: false
5
+ t.string :token_digest, null: false
6
+ t.string :user_agent, limit: 512
7
+ t.datetime :last_seen_at, null: false
8
+ t.timestamps
9
+ end
10
+ add_index :devise_login_alerts_devices, %i[user_type user_id token_digest],
11
+ unique: true, name: 'index_devise_login_alerts_devices_on_user_and_token'
12
+ add_index :devise_login_alerts_devices, :last_seen_at
13
+
14
+ create_table :devise_login_alerts_login_attempts do |t|
15
+ t.references :user, polymorphic: true, null: false, index: false
16
+ t.references :device, foreign_key: { to_table: :devise_login_alerts_devices, on_delete: :nullify }
17
+ t.string :scope, null: false
18
+ t.boolean :successful, null: false
19
+ t.string :failure_reason
20
+ t.boolean :new_device, null: false, default: false
21
+ t.boolean :alerted, null: false, default: false
22
+ t.string :ip
23
+ t.string :country_code, limit: 2
24
+ t.string :city
25
+ t.string :user_agent, limit: 512
26
+ t.datetime :created_at, null: false
27
+ end
28
+ add_index :devise_login_alerts_login_attempts, %i[user_type user_id created_at],
29
+ name: 'index_devise_login_alerts_login_attempts_on_user_and_created_at'
30
+ add_index :devise_login_alerts_login_attempts, :created_at
31
+ end
32
+ end
metadata ADDED
@@ -0,0 +1,149 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: devise_login_alerts
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Jammed
8
+ bindir: bin
9
+ cert_chain: []
10
+ date: 2026-11-17 00:00:00.000000000 Z
11
+ dependencies:
12
+ - !ruby/object:Gem::Dependency
13
+ name: actionmailer
14
+ requirement: !ruby/object:Gem::Requirement
15
+ requirements:
16
+ - - ">="
17
+ - !ruby/object:Gem::Version
18
+ version: '7.1'
19
+ - - "<"
20
+ - !ruby/object:Gem::Version
21
+ version: '9'
22
+ type: :runtime
23
+ prerelease: false
24
+ version_requirements: !ruby/object:Gem::Requirement
25
+ requirements:
26
+ - - ">="
27
+ - !ruby/object:Gem::Version
28
+ version: '7.1'
29
+ - - "<"
30
+ - !ruby/object:Gem::Version
31
+ version: '9'
32
+ - !ruby/object:Gem::Dependency
33
+ name: activerecord
34
+ requirement: !ruby/object:Gem::Requirement
35
+ requirements:
36
+ - - ">="
37
+ - !ruby/object:Gem::Version
38
+ version: '7.1'
39
+ - - "<"
40
+ - !ruby/object:Gem::Version
41
+ version: '9'
42
+ type: :runtime
43
+ prerelease: false
44
+ version_requirements: !ruby/object:Gem::Requirement
45
+ requirements:
46
+ - - ">="
47
+ - !ruby/object:Gem::Version
48
+ version: '7.1'
49
+ - - "<"
50
+ - !ruby/object:Gem::Version
51
+ version: '9'
52
+ - !ruby/object:Gem::Dependency
53
+ name: devise
54
+ requirement: !ruby/object:Gem::Requirement
55
+ requirements:
56
+ - - ">="
57
+ - !ruby/object:Gem::Version
58
+ version: '4.9'
59
+ - - "<"
60
+ - !ruby/object:Gem::Version
61
+ version: '6'
62
+ type: :runtime
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - ">="
67
+ - !ruby/object:Gem::Version
68
+ version: '4.9'
69
+ - - "<"
70
+ - !ruby/object:Gem::Version
71
+ version: '6'
72
+ - !ruby/object:Gem::Dependency
73
+ name: railties
74
+ requirement: !ruby/object:Gem::Requirement
75
+ requirements:
76
+ - - ">="
77
+ - !ruby/object:Gem::Version
78
+ version: '7.1'
79
+ - - "<"
80
+ - !ruby/object:Gem::Version
81
+ version: '9'
82
+ type: :runtime
83
+ prerelease: false
84
+ version_requirements: !ruby/object:Gem::Requirement
85
+ requirements:
86
+ - - ">="
87
+ - !ruby/object:Gem::Version
88
+ version: '7.1'
89
+ - - "<"
90
+ - !ruby/object:Gem::Version
91
+ version: '9'
92
+ description: Records successful and failed Devise sign-ins, recognises returning browsers
93
+ with a first-party cookie, and emails the account owner when a sign-in comes from
94
+ a new device.
95
+ executables: []
96
+ extensions: []
97
+ extra_rdoc_files: []
98
+ files:
99
+ - CHANGELOG.md
100
+ - LICENSE.txt
101
+ - README.md
102
+ - app/mailers/devise_login_alerts/mailer.rb
103
+ - app/models/devise_login_alerts/device.rb
104
+ - app/models/devise_login_alerts/login_attempt.rb
105
+ - app/views/devise_login_alerts/mailer/new_device_login.html.erb
106
+ - app/views/devise_login_alerts/mailer/new_device_login.text.erb
107
+ - config/locales/en.yml
108
+ - lib/devise_login_alerts.rb
109
+ - lib/devise_login_alerts/configuration.rb
110
+ - lib/devise_login_alerts/device_cookie.rb
111
+ - lib/devise_login_alerts/engine.rb
112
+ - lib/devise_login_alerts/event.rb
113
+ - lib/devise_login_alerts/hooks.rb
114
+ - lib/devise_login_alerts/ip_resolver.rb
115
+ - lib/devise_login_alerts/location_resolver.rb
116
+ - lib/devise_login_alerts/model.rb
117
+ - lib/devise_login_alerts/tracker.rb
118
+ - lib/devise_login_alerts/user_agent_summary.rb
119
+ - lib/devise_login_alerts/version.rb
120
+ - lib/generators/devise_login_alerts/install_generator.rb
121
+ - lib/generators/devise_login_alerts/templates/initializer.rb.tt
122
+ - lib/generators/devise_login_alerts/templates/migration.rb.tt
123
+ homepage: https://github.com/jammed-org/devise-login-alerts
124
+ licenses:
125
+ - MIT
126
+ metadata:
127
+ source_code_uri: https://github.com/jammed-org/devise-login-alerts
128
+ changelog_uri: https://github.com/jammed-org/devise-login-alerts/blob/main/CHANGELOG.md
129
+ bug_tracker_uri: https://github.com/jammed-org/devise-login-alerts/issues
130
+ documentation_uri: https://github.com/jammed-org/devise-login-alerts#readme
131
+ rubygems_mfa_required: 'true'
132
+ rdoc_options: []
133
+ require_paths:
134
+ - lib
135
+ required_ruby_version: !ruby/object:Gem::Requirement
136
+ requirements:
137
+ - - ">="
138
+ - !ruby/object:Gem::Version
139
+ version: '3.2'
140
+ required_rubygems_version: !ruby/object:Gem::Requirement
141
+ requirements:
142
+ - - ">="
143
+ - !ruby/object:Gem::Version
144
+ version: '0'
145
+ requirements: []
146
+ rubygems_version: 3.6.2
147
+ specification_version: 4
148
+ summary: Sign-in history and new device alert emails for Devise.
149
+ test_files: []