standard_id 0.58.1 → 0.60.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 +4 -4
- data/CHANGELOG.md +103 -0
- data/README.md +80 -3
- data/app/controllers/concerns/standard_id/web_authentication.rb +2 -0
- data/app/controllers/standard_id/web/login_verify_controller.rb +7 -1
- data/app/forms/standard_id/web/reset_password_confirm_form.rb +1 -0
- data/app/mailers/standard_id/account_notice_mailer.rb +11 -0
- data/app/models/standard_id/authorization_code.rb +6 -3
- data/app/models/standard_id/client_application.rb +7 -6
- data/app/models/standard_id/code_challenge.rb +69 -1
- data/app/models/standard_id/email_identifier.rb +14 -0
- data/app/models/standard_id/password_credential.rb +141 -0
- data/app/models/standard_id/session.rb +22 -12
- data/app/views/standard_id/account_notice_mailer/password_changed.html.erb +22 -0
- data/app/views/standard_id/account_notice_mailer/password_changed.text.erb +10 -0
- data/app/views/standard_id/web/login_verify/show.html.erb +9 -1
- data/config/locales/en.yml +7 -0
- data/db/migrate/20261122000000_add_code_digest_to_standard_id_code_challenges.rb +24 -0
- data/lib/generators/standard_id/install/templates/standard_id_reference.rb +21 -1
- data/lib/standard_id/config/schema.rb +48 -0
- data/lib/standard_id/email_domain.rb +169 -0
- data/lib/standard_id/email_password/authentication.rb +8 -2
- data/lib/standard_id/email_password/password_reset.rb +1 -0
- data/lib/standard_id/email_password/verification.rb +5 -1
- data/lib/standard_id/engine.rb +1 -0
- data/lib/standard_id/events/definitions.rb +5 -0
- data/lib/standard_id/events/subscribers/password_changed_notice_subscriber.rb +42 -0
- data/lib/standard_id/keyed_digest.rb +65 -0
- data/lib/standard_id/oauth/password_flow.rb +1 -0
- data/lib/standard_id/passwordless/base_strategy.rb +8 -0
- data/lib/standard_id/passwordless/email_strategy.rb +7 -0
- data/lib/standard_id/passwordless/verification_service.rb +9 -7
- data/lib/standard_id/testing/otp_helpers.rb +58 -0
- data/lib/standard_id/testing.rb +1 -0
- data/lib/standard_id/version.rb +1 -1
- data/lib/standard_id.rb +3 -0
- metadata +30 -3
|
@@ -17,10 +17,20 @@ module StandardId
|
|
|
17
17
|
scope :revoked, -> { where.not(revoked_at: nil) }
|
|
18
18
|
|
|
19
19
|
scope :api_compatible, -> { where(type: ["StandardId::DeviceSession", "StandardId::ServiceSession"]) }
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
}
|
|
20
|
+
# One indexed query for every lookup hash the token may be stored under:
|
|
21
|
+
# the current secret's, plus one per `config.previous_secret_key_bases`
|
|
22
|
+
# entry (see StandardId::KeyedDigest).
|
|
23
|
+
scope :by_token, ->(token) { where(lookup_hash: lookup_hashes_for(token)) }
|
|
24
|
+
|
|
25
|
+
# SHA256 of the token under `secret` — an indexable locator, never the
|
|
26
|
+
# credential (see .authenticate_by_token).
|
|
27
|
+
def self.lookup_hash_for(token, secret: StandardId::KeyedDigest.current_secret)
|
|
28
|
+
Digest::SHA256.hexdigest("#{token}:#{secret}")
|
|
29
|
+
end
|
|
30
|
+
|
|
31
|
+
def self.lookup_hashes_for(token)
|
|
32
|
+
StandardId::KeyedDigest.candidates { |secret| lookup_hash_for(token, secret:) }
|
|
33
|
+
end
|
|
24
34
|
|
|
25
35
|
# Authenticate an opaque session token.
|
|
26
36
|
#
|
|
@@ -64,10 +74,8 @@ module StandardId
|
|
|
64
74
|
# with SHA256; this brings session tokens in line with both.
|
|
65
75
|
DIGEST_PREFIX = "standard_id.session.token_digest.v1:".freeze
|
|
66
76
|
|
|
67
|
-
def self.hmac_token_digest(token)
|
|
68
|
-
|
|
69
|
-
"SHA256", Rails.configuration.secret_key_base, "#{DIGEST_PREFIX}#{token}"
|
|
70
|
-
)
|
|
77
|
+
def self.hmac_token_digest(token, secret: StandardId::KeyedDigest.current_secret)
|
|
78
|
+
StandardId::KeyedDigest.hmac_hexdigest("#{DIGEST_PREFIX}#{token}", secret:)
|
|
71
79
|
end
|
|
72
80
|
|
|
73
81
|
# Timing-safe verification of `token` against this session's stored digest.
|
|
@@ -79,7 +87,8 @@ module StandardId
|
|
|
79
87
|
# way a config change never strands existing sessions, and no rewrite of
|
|
80
88
|
# stored digests is needed. Both branches end in a constant-time compare, so
|
|
81
89
|
# the response time carries no information about how much of the digest
|
|
82
|
-
# matched.
|
|
90
|
+
# matched. An HMAC digest is accepted under the current secret or any of
|
|
91
|
+
# `config.previous_secret_key_bases`; BCrypt digests are not keyed.
|
|
83
92
|
#
|
|
84
93
|
# @return [Boolean] false for a blank or malformed digest — never raises.
|
|
85
94
|
def authenticate_token(token)
|
|
@@ -92,8 +101,9 @@ module StandardId
|
|
|
92
101
|
BCrypt::Engine.hash_secret(token, stored.salt)
|
|
93
102
|
)
|
|
94
103
|
else
|
|
95
|
-
|
|
96
|
-
token_digest,
|
|
104
|
+
StandardId::KeyedDigest.secure_match?(
|
|
105
|
+
token_digest,
|
|
106
|
+
StandardId::KeyedDigest.candidates { |secret| self.class.hmac_token_digest(token, secret:) }
|
|
97
107
|
)
|
|
98
108
|
end
|
|
99
109
|
rescue BCrypt::Errors::InvalidHash, BCrypt::Errors::InvalidSalt
|
|
@@ -265,7 +275,7 @@ module StandardId
|
|
|
265
275
|
end
|
|
266
276
|
|
|
267
277
|
def generate_lookup_hash
|
|
268
|
-
self.lookup_hash =
|
|
278
|
+
self.lookup_hash = self.class.lookup_hash_for(token)
|
|
269
279
|
end
|
|
270
280
|
|
|
271
281
|
# Revoke any still-active refresh tokens before the session row is deleted,
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
<!DOCTYPE html>
|
|
2
|
+
<html>
|
|
3
|
+
<head>
|
|
4
|
+
<meta charset="UTF-8">
|
|
5
|
+
<style>
|
|
6
|
+
body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; background-color: #f5f5f5; margin: 0; padding: 0; }
|
|
7
|
+
.container { max-width: 480px; margin: 40px auto; background-color: #ffffff; border-radius: 8px; padding: 40px; }
|
|
8
|
+
.footer { margin-top: 32px; font-size: 13px; color: #888888; text-align: center; }
|
|
9
|
+
</style>
|
|
10
|
+
</head>
|
|
11
|
+
<body>
|
|
12
|
+
<div class="container">
|
|
13
|
+
<p><%= notice_copy(:greeting) %></p>
|
|
14
|
+
<p><%= notice_copy(:intro) %></p>
|
|
15
|
+
<p><%= notice_copy(:action) %></p>
|
|
16
|
+
<p><%= notice_copy(:warning) %></p>
|
|
17
|
+
<div class="footer">
|
|
18
|
+
<p><%= notice_copy(:footer) %></p>
|
|
19
|
+
</div>
|
|
20
|
+
</div>
|
|
21
|
+
</body>
|
|
22
|
+
</html>
|
|
@@ -5,7 +5,15 @@
|
|
|
5
5
|
<div class="flex min-h-full flex-col justify-center py-12 sm:px-6 lg:px-8">
|
|
6
6
|
<div class="sm:mx-auto sm:w-full sm:max-w-md">
|
|
7
7
|
<h2 class="mt-6 text-center text-2xl/9 font-bold tracking-tight text-gray-900 dark:text-white">Enter verification code</h2>
|
|
8
|
-
|
|
8
|
+
<%# Show where the code went: a mistyped address otherwise looks exactly like a slow e-mail. %>
|
|
9
|
+
<p class="mt-2 text-center text-sm text-gray-500 dark:text-gray-400">
|
|
10
|
+
We sent a verification code to <span id="otp-identifier" class="font-semibold text-gray-900 dark:text-white"><%= @otp_data[:username] %></span>.
|
|
11
|
+
</p>
|
|
12
|
+
<p class="mt-1 text-center text-sm">
|
|
13
|
+
<%= link_to (@otp_data[:connection].to_s == "sms" ? "Use a different phone number" : "Use a different e-mail"),
|
|
14
|
+
login_path, id: "otp-change-identifier",
|
|
15
|
+
class: "font-semibold text-indigo-600 hover:text-indigo-500 dark:text-indigo-400 dark:hover:text-indigo-300" %>
|
|
16
|
+
</p>
|
|
9
17
|
</div>
|
|
10
18
|
|
|
11
19
|
<div class="mt-10 sm:mx-auto sm:w-full sm:max-w-[480px]">
|
data/config/locales/en.yml
CHANGED
|
@@ -28,3 +28,10 @@ en:
|
|
|
28
28
|
action: "If that was you, sign in the way you did before, or reset your password if you have forgotten it."
|
|
29
29
|
ignore: "If it wasn't you, you can safely ignore this email. Your account has not changed."
|
|
30
30
|
footer: "This is an automated message. Please do not reply."
|
|
31
|
+
password_changed:
|
|
32
|
+
subject: "Your password was changed"
|
|
33
|
+
greeting: "Hi,"
|
|
34
|
+
intro: "The password for your account was just changed."
|
|
35
|
+
action: "If you made this change, you don't need to do anything."
|
|
36
|
+
warning: "If you didn't, reset your password straight away and check your account for anything you don't recognise."
|
|
37
|
+
footer: "This is an automated message. Please do not reply."
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
# Passwordless / OTP codes were stored in plaintext in `code`, so anyone who
|
|
2
|
+
# could read the table could sign in with any active code. From this migration
|
|
3
|
+
# on, StandardId stores only `code_digest`, an HMAC-SHA256 of the code keyed on
|
|
4
|
+
# secret_key_base (StandardId::CodeChallenge.digest_code), and leaves `code`
|
|
5
|
+
# NULL on new rows.
|
|
6
|
+
#
|
|
7
|
+
# Both steps are metadata-only on PostgreSQL: a nullable string column with no
|
|
8
|
+
# default and no index (a challenge is found by realm/channel/target, then its
|
|
9
|
+
# digest is compared in constant time), and dropping a NOT NULL constraint.
|
|
10
|
+
#
|
|
11
|
+
# `code` is kept, nullable, for one transition: challenges issued before the
|
|
12
|
+
# deploy still carry a plaintext code and are verified against it until they
|
|
13
|
+
# expire (code_ttl, 10 minutes by default) and CleanupExpiredCodeChallengesJob
|
|
14
|
+
# deletes them. A later release drops the column; see docs/MIGRATION_GUIDE.md.
|
|
15
|
+
# Until this has run, the gem keeps writing the plaintext column as before.
|
|
16
|
+
#
|
|
17
|
+
# Rolling back restores NOT NULL on `code`, which fails while any digest-only
|
|
18
|
+
# row exists: delete those first (they are at most code_ttl old).
|
|
19
|
+
class AddCodeDigestToStandardIdCodeChallenges < ActiveRecord::Migration[8.0]
|
|
20
|
+
def change
|
|
21
|
+
add_column :standard_id_code_challenges, :code_digest, :string
|
|
22
|
+
change_column_null :standard_id_code_challenges, :code, true
|
|
23
|
+
end
|
|
24
|
+
end
|
|
@@ -104,6 +104,15 @@ StandardId.configure do |c|
|
|
|
104
104
|
# Default: Rails.logger
|
|
105
105
|
# c.logger = Rails.logger
|
|
106
106
|
|
|
107
|
+
# Old secret_key_base values (newest first) still accepted for StandardId's
|
|
108
|
+
# keyed digests — session tokens, OTP codes, authorization codes, registration
|
|
109
|
+
# access tokens — so rotating the secret does not sign everyone out. New
|
|
110
|
+
# digests always use the current secret. Keep an entry for the longest
|
|
111
|
+
# session lifetime, and rotate Rails' cookies and message verifiers too
|
|
112
|
+
# (README "Rotating secret_key_base").
|
|
113
|
+
# Default: []
|
|
114
|
+
# c.previous_secret_key_bases = [Rails.application.credentials.old_secret_key_base]
|
|
115
|
+
|
|
107
116
|
# Layout used by built-in ERB web views. Ignored when use_inertia is true.
|
|
108
117
|
# Default: nil (StandardId's packaged layout)
|
|
109
118
|
# c.web_layout = "application"
|
|
@@ -258,8 +267,19 @@ StandardId.configure do |c|
|
|
|
258
267
|
# to disable the cooldown.
|
|
259
268
|
# c.passwordless.retry_delay = 30
|
|
260
269
|
|
|
270
|
+
# Default: true — reject an e-mail address whose domain does not end in an
|
|
271
|
+
# ICANN-registered TLD (a@rarebit.ome), before a passwordless code is sent
|
|
272
|
+
# and when an EmailIdentifier's value is set or changed. Checked offline
|
|
273
|
+
# against the Public Suffix List; existing identifiers are never re-checked.
|
|
274
|
+
# Your own validators can reuse StandardId::EmailDomain.allowed?(email).
|
|
275
|
+
# c.email.require_registered_tld = true
|
|
276
|
+
#
|
|
277
|
+
# Default: %w[test example invalid localhost local] — special-use TLDs that
|
|
278
|
+
# pass the check above anyway (never delegated; used for bots and fixtures).
|
|
279
|
+
# c.email.allowed_special_use_tlds = %w[test example invalid localhost local]
|
|
280
|
+
|
|
261
281
|
# Custom username validator; return nil/false to accept, or an error message
|
|
262
|
-
# string to reject. Useful for domain allow-lists or truemail integration.
|
|
282
|
+
# string to reject. Runs after the registered-TLD check above. Useful for domain allow-lists or truemail integration.
|
|
263
283
|
# Default: nil
|
|
264
284
|
# c.passwordless.username_validator = ->(username, connection_type) {
|
|
265
285
|
# "Invalid email" unless TruemailValidator.valid?(username)
|
|
@@ -86,6 +86,20 @@ StandardId::ConfigSchema.define do
|
|
|
86
86
|
# deliberately superseded or deferred.
|
|
87
87
|
field :ignored_migrations, type: :array, default: -> { [] }
|
|
88
88
|
|
|
89
|
+
# Previous `secret_key_base` values, newest first, still ACCEPTED when
|
|
90
|
+
# looking up and verifying the engine's keyed digests: session tokens
|
|
91
|
+
# (lookup_hash and the HMAC token_digest), passwordless code digests,
|
|
92
|
+
# authorization codes and RFC 7592 registration access tokens. New digests
|
|
93
|
+
# are always written under the current secret. See StandardId::KeyedDigest.
|
|
94
|
+
#
|
|
95
|
+
# Empty (default) means rotating `secret_key_base` invalidates all of them
|
|
96
|
+
# at once, which is what it always did. To rotate without signing everyone
|
|
97
|
+
# out, list the old secret here for at least the longest session lifetime,
|
|
98
|
+
# alongside Rails' own rotations for its cookies and message verifiers
|
|
99
|
+
# (README "Rotating secret_key_base"). Each extra entry costs one more
|
|
100
|
+
# candidate per lookup and one more HMAC per verification.
|
|
101
|
+
field :previous_secret_key_bases, type: :array, default: -> { [] }
|
|
102
|
+
|
|
89
103
|
# Scope-aware authentication: maps scope names to profile-based access config.
|
|
90
104
|
# Each scope is a hash with keys: :profile_types (Array<String>), :after_sign_in_path,
|
|
91
105
|
# :no_profile_message, :label, :allow_registration, :authorizer.
|
|
@@ -210,6 +224,24 @@ StandardId::ConfigSchema.define do
|
|
|
210
224
|
field :publish_provider_tokens, type: :boolean, default: false
|
|
211
225
|
end
|
|
212
226
|
|
|
227
|
+
scope :email do
|
|
228
|
+
# Reject an e-mail address whose domain does not end in an ICANN-registered
|
|
229
|
+
# TLD (StandardId::EmailDomain.allowed?), so "a@rarebit.ome" fails at once instead
|
|
230
|
+
# of bouncing hours later. Applied when a passwordless code is requested
|
|
231
|
+
# for an e-mail connection, before any code is generated or sent, and when
|
|
232
|
+
# a StandardId::EmailIdentifier's value is set or changed (existing rows
|
|
233
|
+
# are never re-checked). Turn it off only as an escape hatch, e.g. an app
|
|
234
|
+
# that signs in addresses on a private or not-yet-listed TLD.
|
|
235
|
+
field :require_registered_tld, type: :boolean, default: true
|
|
236
|
+
# TLDs that pass the check above although they are not in the PSL. The
|
|
237
|
+
# default is the special-use names of RFC 2606 / 6761 (test, example,
|
|
238
|
+
# invalid, localhost) and RFC 6762 (local), which are never delegated:
|
|
239
|
+
# nobody mistypes .com as .invalid, and apps use them on purpose for
|
|
240
|
+
# synthetic accounts (bots, demo data, e2e users) and test fixtures. Set
|
|
241
|
+
# [] to accept registered TLDs only; add e.g. "internal" for a private one.
|
|
242
|
+
field :allowed_special_use_tlds, type: :array, default: -> { %w[test example invalid localhost local] }
|
|
243
|
+
end
|
|
244
|
+
|
|
213
245
|
scope :passwordless do
|
|
214
246
|
# Removed in 0.43 (no effect since 0.8).
|
|
215
247
|
removed :enabled, "it had no effect since 0.8. Use web.passwordless_login (WebEngine) instead, and delete this line."
|
|
@@ -288,6 +320,22 @@ StandardId::ConfigSchema.define do
|
|
|
288
320
|
field :require_special_chars, type: :boolean, default: true
|
|
289
321
|
field :require_uppercase, type: :boolean, default: true
|
|
290
322
|
field :require_numbers, type: :boolean, default: true
|
|
323
|
+
# Re-hash a password on a successful login when its stored digest was
|
|
324
|
+
# made at a bcrypt cost other than the one has_secure_password uses now
|
|
325
|
+
# (BCrypt::Engine.cost), so raising the cost reaches existing passwords.
|
|
326
|
+
# A no-op until the cost changes. A rehash replaces the digest, which
|
|
327
|
+
# signs that user out of remember-me cookies and voids their reset links.
|
|
328
|
+
# See StandardId::PasswordCredential#rehash_password.
|
|
329
|
+
field :rehash_on_login, type: :boolean, default: true
|
|
330
|
+
# Who tells the owner, by email, that their password was changed or reset
|
|
331
|
+
# (CREDENTIAL_PASSWORD_CHANGED):
|
|
332
|
+
# :custom — (default) the engine sends nothing; subscribe to the event
|
|
333
|
+
# to send your own
|
|
334
|
+
# :built_in — the engine sends AccountNoticeMailer#password_changed to
|
|
335
|
+
# the credential's e-mail identifier
|
|
336
|
+
# Off by default so an upgrade does not start sending mail, nor a second
|
|
337
|
+
# notice next to one a host already sends on reset_completed.
|
|
338
|
+
field :changed_notice_delivery, type: :symbol, default: :custom
|
|
291
339
|
end
|
|
292
340
|
|
|
293
341
|
scope :reset_password do
|
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
require "public_suffix"
|
|
2
|
+
|
|
3
|
+
module StandardId
|
|
4
|
+
# Whether an e-mail address's domain ends in a TLD that is actually
|
|
5
|
+
# delegated, judged against the ICANN section of the Public Suffix List.
|
|
6
|
+
#
|
|
7
|
+
# A format check cannot tell `rarebit.one` from `rarebit.ome`: both are a
|
|
8
|
+
# well-formed domain, and every pattern in common use (Truemail's :regex,
|
|
9
|
+
# `URI::MailTo::EMAIL_REGEXP`, EmailIdentifier::EMAIL_FORMAT) accepts any
|
|
10
|
+
# run of letters as a TLD. On a sign-in code flow that typo fails silently:
|
|
11
|
+
# the ESP accepts the message, bounces it hours later on the missing MX, and
|
|
12
|
+
# the user is left waiting for a code that never comes. This catches the
|
|
13
|
+
# whole class of mistyped TLDs (.ome, .con, .cmo) offline, before anything
|
|
14
|
+
# is sent. It says nothing about whether the domain itself exists; that
|
|
15
|
+
# needs DNS (Truemail's :mx), which this deliberately does not do.
|
|
16
|
+
#
|
|
17
|
+
# The gem's own rule is .allowed?: a registered TLD, or one of the
|
|
18
|
+
# special-use TLDs in email.allowed_special_use_tlds (test, example, invalid,
|
|
19
|
+
# localhost, local by default). Those can never be delegated, so accepting them
|
|
20
|
+
# cannot hide a typo of a real TLD, and apps use them on purpose for
|
|
21
|
+
# synthetic accounts and fixtures (agent+1@agents.example.invalid). Host
|
|
22
|
+
# apps' own e-mail validators should call .allowed? too, so one address is
|
|
23
|
+
# judged the same way on every path:
|
|
24
|
+
#
|
|
25
|
+
# StandardId::EmailDomain.allowed?("jaryl@rarebit.ome") # => false
|
|
26
|
+
# StandardId::EmailDomain.allowed?("bot@agents.app.invalid") # => true
|
|
27
|
+
# StandardId::EmailDomain.registered_tld?("bot@agents.app.invalid") # => false
|
|
28
|
+
module EmailDomain
|
|
29
|
+
# DNS limits (RFC 1035): a name of at most 253 octets, labels of at most 63.
|
|
30
|
+
MAX_DOMAIN_LENGTH = 253
|
|
31
|
+
MAX_LABEL_LENGTH = 63
|
|
32
|
+
|
|
33
|
+
module_function
|
|
34
|
+
|
|
35
|
+
# @param email_or_domain [String] an address ("a@b.com") or a bare domain ("b.com")
|
|
36
|
+
# @return [Boolean] whether the domain ends in a registered TLD or an allowed special-use one
|
|
37
|
+
def allowed?(email_or_domain)
|
|
38
|
+
registered_tld?(email_or_domain) || special_use_tld?(email_or_domain)
|
|
39
|
+
end
|
|
40
|
+
|
|
41
|
+
# @param email_or_domain [String] an address ("a@b.com") or a bare domain ("b.com")
|
|
42
|
+
# @return [Boolean]
|
|
43
|
+
def registered_tld?(email_or_domain)
|
|
44
|
+
domain = domain_of(email_or_domain)
|
|
45
|
+
return false if domain.blank? || domain.length > MAX_DOMAIN_LENGTH
|
|
46
|
+
|
|
47
|
+
labels = domain.split(".")
|
|
48
|
+
# Checked before decoding: the punycode loop runs once per digit on
|
|
49
|
+
# arbitrary-precision integers, so an unbounded label from a public
|
|
50
|
+
# sign-in form is a cheap way to burn CPU.
|
|
51
|
+
return false if labels.any? { |label| label.length > MAX_LABEL_LENGTH }
|
|
52
|
+
|
|
53
|
+
unicode = labels.map { |label| to_unicode(label) }.join(".")
|
|
54
|
+
# default_rule: nil — without it the PSL's implicit "*" rule matches any
|
|
55
|
+
# unknown TLD, which is exactly what this exists to reject.
|
|
56
|
+
# ignore_private: true — only ICANN suffixes count; a private entry such
|
|
57
|
+
# as blogspot.com still resolves through its ICANN parent.
|
|
58
|
+
PublicSuffix.valid?(unicode, default_rule: nil, ignore_private: true)
|
|
59
|
+
rescue ArgumentError, RangeError
|
|
60
|
+
# A malformed punycode label.
|
|
61
|
+
false
|
|
62
|
+
end
|
|
63
|
+
|
|
64
|
+
# Whether the domain's last label is in email.allowed_special_use_tlds.
|
|
65
|
+
def special_use_tld?(email_or_domain)
|
|
66
|
+
tld = domain_of(email_or_domain)&.split(".")&.last
|
|
67
|
+
return false if tld.blank?
|
|
68
|
+
|
|
69
|
+
Array(StandardId.config.email.allowed_special_use_tlds).any? { |allowed| allowed.to_s.downcase.delete_prefix(".") == tld }
|
|
70
|
+
end
|
|
71
|
+
|
|
72
|
+
# The domain part of an address (or the input itself when it has no "@"),
|
|
73
|
+
# stripped, downcased and without a trailing root dot. Nil when blank.
|
|
74
|
+
def domain_of(email_or_domain)
|
|
75
|
+
domain = email_or_domain.to_s.strip.split("@").last.to_s.downcase.delete_suffix(".")
|
|
76
|
+
domain.presence
|
|
77
|
+
end
|
|
78
|
+
|
|
79
|
+
# The error shown when an address fails the check, or nil when it passes or
|
|
80
|
+
# the check is turned off (email.require_registered_tld = false).
|
|
81
|
+
def validation_error(email)
|
|
82
|
+
return unless StandardId.config.email.require_registered_tld
|
|
83
|
+
return if allowed?(email)
|
|
84
|
+
|
|
85
|
+
"#{domain_of(email)} isn't a valid e-mail domain. Check the address."
|
|
86
|
+
end
|
|
87
|
+
|
|
88
|
+
# The PSL lists internationalised suffixes in Unicode (рф), but addresses
|
|
89
|
+
# usually carry them as ASCII punycode (xn--p1ai), which PublicSuffix does
|
|
90
|
+
# not convert. Ruby's standard library has no IDNA, so decode the A-label
|
|
91
|
+
# here (RFC 3492) rather than take a dependency for one function.
|
|
92
|
+
def to_unicode(label)
|
|
93
|
+
return label unless label.start_with?("xn--")
|
|
94
|
+
|
|
95
|
+
Punycode.decode(label.delete_prefix("xn--"))
|
|
96
|
+
end
|
|
97
|
+
|
|
98
|
+
# RFC 3492 decoding, section 6.2. Raises ArgumentError on malformed input.
|
|
99
|
+
module Punycode
|
|
100
|
+
BASE = 36
|
|
101
|
+
TMIN = 1
|
|
102
|
+
TMAX = 26
|
|
103
|
+
SKEW = 38
|
|
104
|
+
DAMP = 700
|
|
105
|
+
INITIAL_BIAS = 72
|
|
106
|
+
INITIAL_N = 128
|
|
107
|
+
|
|
108
|
+
module_function
|
|
109
|
+
|
|
110
|
+
def decode(input)
|
|
111
|
+
raise ArgumentError, "punycode label too long" if input.length > MAX_LABEL_LENGTH
|
|
112
|
+
|
|
113
|
+
delimiter = input.rindex("-")
|
|
114
|
+
output = delimiter ? input[0...delimiter].chars : []
|
|
115
|
+
raise ArgumentError, "non-basic code point" unless output.all?(&:ascii_only?)
|
|
116
|
+
|
|
117
|
+
pos = delimiter ? delimiter + 1 : 0
|
|
118
|
+
n = INITIAL_N
|
|
119
|
+
bias = INITIAL_BIAS
|
|
120
|
+
i = 0
|
|
121
|
+
|
|
122
|
+
while pos < input.length
|
|
123
|
+
old_i = i
|
|
124
|
+
w = 1
|
|
125
|
+
k = BASE
|
|
126
|
+
loop do
|
|
127
|
+
raise ArgumentError, "truncated punycode" if pos >= input.length
|
|
128
|
+
|
|
129
|
+
digit = decode_digit(input[pos])
|
|
130
|
+
pos += 1
|
|
131
|
+
i += digit * w
|
|
132
|
+
t = (k - bias).clamp(TMIN, TMAX)
|
|
133
|
+
break if digit < t
|
|
134
|
+
|
|
135
|
+
w *= BASE - t
|
|
136
|
+
k += BASE
|
|
137
|
+
end
|
|
138
|
+
bias = adapt(i - old_i, output.length + 1, old_i.zero?)
|
|
139
|
+
n += i / (output.length + 1)
|
|
140
|
+
i %= output.length + 1
|
|
141
|
+
output.insert(i, n.chr(Encoding::UTF_8))
|
|
142
|
+
i += 1
|
|
143
|
+
end
|
|
144
|
+
|
|
145
|
+
output.join
|
|
146
|
+
end
|
|
147
|
+
|
|
148
|
+
def decode_digit(char)
|
|
149
|
+
case char
|
|
150
|
+
when "0".."9" then char.ord - 22
|
|
151
|
+
when "a".."z" then char.ord - 97
|
|
152
|
+
when "A".."Z" then char.ord - 65
|
|
153
|
+
else raise ArgumentError, "invalid punycode digit"
|
|
154
|
+
end
|
|
155
|
+
end
|
|
156
|
+
|
|
157
|
+
def adapt(delta, num_points, first_time)
|
|
158
|
+
delta = first_time ? delta / DAMP : delta / 2
|
|
159
|
+
delta += delta / num_points
|
|
160
|
+
k = 0
|
|
161
|
+
while delta > ((BASE - TMIN) * TMAX) / 2
|
|
162
|
+
delta /= BASE - TMIN
|
|
163
|
+
k += BASE
|
|
164
|
+
end
|
|
165
|
+
k + (((BASE - TMIN + 1) * delta) / (delta + SKEW))
|
|
166
|
+
end
|
|
167
|
+
end
|
|
168
|
+
end
|
|
169
|
+
end
|
|
@@ -12,7 +12,9 @@ module StandardId
|
|
|
12
12
|
# locked, after re-checking that the password has not changed since it was
|
|
13
13
|
# verified. Mint tokens inside it: PasswordReset.complete! takes the same
|
|
14
14
|
# lock to change the password and revoke access, so a login racing a reset
|
|
15
|
-
# either finishes first (and its tokens are revoked) or fails.
|
|
15
|
+
# either finishes first (and its tokens are revoked) or fails. The password
|
|
16
|
+
# is rehashed (PasswordCredential#rehash_password) only after that
|
|
17
|
+
# re-check passes, so the re-check never sees its own rehash.
|
|
16
18
|
module Authentication
|
|
17
19
|
class << self
|
|
18
20
|
# @return [Account]
|
|
@@ -45,10 +47,14 @@ module StandardId
|
|
|
45
47
|
)
|
|
46
48
|
|
|
47
49
|
raise StandardId::EmailPasswordError.new(:unverified) unless identifier.verified?
|
|
48
|
-
|
|
50
|
+
unless block_given?
|
|
51
|
+
password_credential.rehash_password(password, verified_digest)
|
|
52
|
+
return account
|
|
53
|
+
end
|
|
49
54
|
|
|
50
55
|
password_credential.with_lock do
|
|
51
56
|
failed!(email) unless password_credential.password_digest == verified_digest
|
|
57
|
+
password_credential.rehash_password(password, verified_digest)
|
|
52
58
|
yield account
|
|
53
59
|
end
|
|
54
60
|
end
|
|
@@ -76,6 +76,7 @@ module StandardId
|
|
|
76
76
|
raise TokenAlreadyUsed
|
|
77
77
|
end
|
|
78
78
|
|
|
79
|
+
password_credential.password_change_reason = :password_reset
|
|
79
80
|
password_credential.update!(password: password)
|
|
80
81
|
api_signup = !identifier.verified? && EmailPassword.api_signup?(identifier)
|
|
81
82
|
EmailPassword.complete_verification!(
|
|
@@ -69,10 +69,14 @@ module StandardId
|
|
|
69
69
|
)
|
|
70
70
|
identifier.account
|
|
71
71
|
end
|
|
72
|
-
|
|
72
|
+
unless block_given?
|
|
73
|
+
password_credential.rehash_password(password, verified_digest)
|
|
74
|
+
return account
|
|
75
|
+
end
|
|
73
76
|
|
|
74
77
|
password_credential.with_lock do
|
|
75
78
|
password_unchanged!(password_credential, verified_digest)
|
|
79
|
+
password_credential.rehash_password(password, verified_digest)
|
|
76
80
|
yield account
|
|
77
81
|
end
|
|
78
82
|
end
|
data/lib/standard_id/engine.rb
CHANGED
|
@@ -80,6 +80,7 @@ module StandardId
|
|
|
80
80
|
StandardId::Events::Subscribers::AccountLockingSubscriber.attach
|
|
81
81
|
StandardId::Events::Subscribers::PasswordlessDeliverySubscriber.attach
|
|
82
82
|
StandardId::Events::Subscribers::PasswordResetDeliverySubscriber.attach
|
|
83
|
+
StandardId::Events::Subscribers::PasswordChangedNoticeSubscriber.attach
|
|
83
84
|
|
|
84
85
|
StandardId::Engine.warn_about_issuer_config!
|
|
85
86
|
|
|
@@ -70,6 +70,9 @@ module StandardId
|
|
|
70
70
|
CREDENTIAL_PASSWORD_RESET_INITIATED = "credential.password.reset_initiated"
|
|
71
71
|
CREDENTIAL_PASSWORD_RESET_COMPLETED = "credential.password.reset_completed"
|
|
72
72
|
CREDENTIAL_PASSWORD_CHANGED = "credential.password.changed"
|
|
73
|
+
# A login re-hashed the password at the current bcrypt cost
|
|
74
|
+
# (PasswordCredential#rehash_password). The password itself is unchanged.
|
|
75
|
+
CREDENTIAL_PASSWORD_REHASHED = "credential.password.rehashed"
|
|
73
76
|
CREDENTIAL_CLIENT_SECRET_CREATED = "credential.client_secret.created"
|
|
74
77
|
CREDENTIAL_CLIENT_SECRET_ROTATED = "credential.client_secret.rotated"
|
|
75
78
|
CREDENTIAL_CLIENT_SECRET_REVOKED = "credential.client_secret.revoked"
|
|
@@ -156,6 +159,7 @@ module StandardId
|
|
|
156
159
|
CREDENTIAL_PASSWORD_RESET_INITIATED,
|
|
157
160
|
CREDENTIAL_PASSWORD_RESET_COMPLETED,
|
|
158
161
|
CREDENTIAL_PASSWORD_CHANGED,
|
|
162
|
+
CREDENTIAL_PASSWORD_REHASHED,
|
|
159
163
|
CREDENTIAL_CLIENT_SECRET_CREATED,
|
|
160
164
|
CREDENTIAL_CLIENT_SECRET_ROTATED,
|
|
161
165
|
CREDENTIAL_CLIENT_SECRET_REVOKED
|
|
@@ -201,6 +205,7 @@ module StandardId
|
|
|
201
205
|
CREDENTIAL_PASSWORD_RESET_INITIATED,
|
|
202
206
|
CREDENTIAL_PASSWORD_RESET_COMPLETED,
|
|
203
207
|
CREDENTIAL_PASSWORD_CHANGED,
|
|
208
|
+
CREDENTIAL_PASSWORD_REHASHED,
|
|
204
209
|
CREDENTIAL_CLIENT_SECRET_CREATED,
|
|
205
210
|
CREDENTIAL_CLIENT_SECRET_ROTATED,
|
|
206
211
|
CREDENTIAL_CLIENT_SECRET_REVOKED,
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
module StandardId
|
|
2
|
+
module Events
|
|
3
|
+
module Subscribers
|
|
4
|
+
# Emails the owner when their password is changed or reset, while
|
|
5
|
+
# c.password.changed_notice_delivery is :built_in. Sent to the
|
|
6
|
+
# credential's e-mail identifier; a credential behind a username or phone
|
|
7
|
+
# identifier gets nothing. Under events.publish_records = false the
|
|
8
|
+
# payload carries no records, so the credential is loaded from
|
|
9
|
+
# +credential_id+.
|
|
10
|
+
class PasswordChangedNoticeSubscriber < Base
|
|
11
|
+
subscribe_to StandardId::Events::CREDENTIAL_PASSWORD_CHANGED
|
|
12
|
+
|
|
13
|
+
def call(event)
|
|
14
|
+
return unless built_in_delivery?
|
|
15
|
+
|
|
16
|
+
identifier = password_credential(event)&.credential&.identifier
|
|
17
|
+
return unless identifier.is_a?(StandardId::EmailIdentifier) && identifier.value.present?
|
|
18
|
+
|
|
19
|
+
StandardId::AccountNoticeMailer.with(email: identifier.value).password_changed.deliver_later
|
|
20
|
+
end
|
|
21
|
+
|
|
22
|
+
def handle_error(error, event)
|
|
23
|
+
StandardId.logger.error(
|
|
24
|
+
"[StandardId::PasswordChangedNotice] Failed to deliver password changed notice " \
|
|
25
|
+
"for password credential #{event[:credential_id]}: #{error.message}"
|
|
26
|
+
)
|
|
27
|
+
end
|
|
28
|
+
|
|
29
|
+
private
|
|
30
|
+
|
|
31
|
+
def password_credential(event)
|
|
32
|
+
event[:credential] ||
|
|
33
|
+
(event[:credential_id] && StandardId::PasswordCredential.includes(credential: :identifier).find_by(id: event[:credential_id]))
|
|
34
|
+
end
|
|
35
|
+
|
|
36
|
+
def built_in_delivery?
|
|
37
|
+
StandardId.config.password.changed_notice_delivery == :built_in
|
|
38
|
+
end
|
|
39
|
+
end
|
|
40
|
+
end
|
|
41
|
+
end
|
|
42
|
+
end
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
require "openssl"
|
|
2
|
+
|
|
3
|
+
module StandardId
|
|
4
|
+
# The secrets StandardId keys its stored token digests on, and the
|
|
5
|
+
# comparisons that accept any of them.
|
|
6
|
+
#
|
|
7
|
+
# Every keyed digest the engine stores (Session#lookup_hash and
|
|
8
|
+
# #token_digest, CodeChallenge#code_digest, AuthorizationCode#code_hash,
|
|
9
|
+
# ClientApplication#registration_access_token_digest) is derived from
|
|
10
|
+
# `secret_key_base`, so rotating that secret used to strand every one of
|
|
11
|
+
# them: all users signed out, every in-flight code and registration access
|
|
12
|
+
# token dead.
|
|
13
|
+
#
|
|
14
|
+
# `config.previous_secret_key_bases` is the opt-in that prevents it.
|
|
15
|
+
# Digests are always WRITTEN under the current secret; they are READ (looked
|
|
16
|
+
# up and verified) under the current secret and then each previous one, in
|
|
17
|
+
# order. Rails offers the same idea for its own derived secrets
|
|
18
|
+
# (`Rails.application.message_verifiers.rotate(secret_key_base: old)`,
|
|
19
|
+
# `config.action_dispatch.cookies_rotations`), but keeps no list of previous
|
|
20
|
+
# `secret_key_base` values a gem could read, hence the setting. The shape
|
|
21
|
+
# mirrors Rodauth's `hmac_old_secret`.
|
|
22
|
+
module KeyedDigest
|
|
23
|
+
module_function
|
|
24
|
+
|
|
25
|
+
# The secret new digests are written under. Read through
|
|
26
|
+
# Rails.configuration, as the stored digests always have been, so the
|
|
27
|
+
# values for the current secret are unchanged by this module.
|
|
28
|
+
def current_secret
|
|
29
|
+
Rails.configuration.secret_key_base
|
|
30
|
+
end
|
|
31
|
+
|
|
32
|
+
# Current secret first, then `config.previous_secret_key_bases` (blank
|
|
33
|
+
# entries and duplicates of an earlier secret dropped). With no previous
|
|
34
|
+
# secrets configured this is one element and every caller does exactly the
|
|
35
|
+
# work it did before.
|
|
36
|
+
def secrets
|
|
37
|
+
previous = Array(StandardId.config.previous_secret_key_bases).map(&:to_s).reject(&:blank?)
|
|
38
|
+
[current_secret, *previous].uniq
|
|
39
|
+
end
|
|
40
|
+
|
|
41
|
+
# HMAC-SHA256 of +data+ under +secret+, hex-encoded. Callers domain-separate
|
|
42
|
+
# by prefixing +data+ with a versioned label of their own.
|
|
43
|
+
def hmac_hexdigest(data, secret: current_secret)
|
|
44
|
+
OpenSSL::HMAC.hexdigest("SHA256", secret, data)
|
|
45
|
+
end
|
|
46
|
+
|
|
47
|
+
# The value a digest may be stored as, once per accepted secret: yields
|
|
48
|
+
# each secret (current first) and collects the block's results. Use it to
|
|
49
|
+
# query an indexed digest column for every candidate at once.
|
|
50
|
+
def candidates
|
|
51
|
+
secrets.map { |secret| yield secret }
|
|
52
|
+
end
|
|
53
|
+
|
|
54
|
+
# Constant-time check of +stored+ against every candidate. Compares against
|
|
55
|
+
# all of them rather than stopping at the first match, so the response time
|
|
56
|
+
# does not say which secret a digest was written under.
|
|
57
|
+
#
|
|
58
|
+
# @return [Boolean] false for a blank +stored+ value
|
|
59
|
+
def secure_match?(stored, candidates)
|
|
60
|
+
return false if stored.blank?
|
|
61
|
+
|
|
62
|
+
candidates.map { |candidate| ActiveSupport::SecurityUtils.secure_compare(stored.to_s, candidate.to_s) }.any?
|
|
63
|
+
end
|
|
64
|
+
end
|
|
65
|
+
end
|
|
@@ -31,6 +31,7 @@ module StandardId
|
|
|
31
31
|
delivery = attrs[:delivery]&.to_sym
|
|
32
32
|
|
|
33
33
|
validate_username!(username)
|
|
34
|
+
validate_recipient!(username)
|
|
34
35
|
run_username_validator!(username)
|
|
35
36
|
enforce_start_rate_limits!(username)
|
|
36
37
|
# Cooldown check and challenge creation in ONE transaction, serialised
|
|
@@ -175,6 +176,13 @@ module StandardId
|
|
|
175
176
|
raise NotImplementedError
|
|
176
177
|
end
|
|
177
178
|
|
|
179
|
+
# Checks that only make sense before a code is SENT (e.g. that an e-mail
|
|
180
|
+
# domain can receive mail), run after validate_username! and before the
|
|
181
|
+
# host's username_validator. Unlike validate_username! it is not applied
|
|
182
|
+
# when verifying or looking up an account, so tightening it never locks
|
|
183
|
+
# out a code already in flight. No-op by default.
|
|
184
|
+
def validate_recipient!(_username); end
|
|
185
|
+
|
|
178
186
|
def find_or_create_account!(_username)
|
|
179
187
|
raise NotImplementedError
|
|
180
188
|
end
|