standard_id 0.58.0 → 0.59.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 CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: d7d42a5b149e2cd0cdfd3329781a9a7cb56f0397fce40b9aad0388bc2b3c2824
4
- data.tar.gz: 2f21ad5ca597432fe8522c1b4e97f913fb2899d29323f6387be3cdd054f0f4e7
3
+ metadata.gz: 79ed9cae0d273dccba684296744618a0002f84435359d00b56e3f5684b51d44f
4
+ data.tar.gz: 2635c31d2ee0eef5a63555ced32491b884fe67b47fc9e494c6bb55b08dfd753d
5
5
  SHA512:
6
- metadata.gz: 39b4a7a01eef961b0314a06c9208efe24ed7f8de2f4616dbfb2a333f657f0e7686d09dea307e687757d1e5aa380cb277daa3bcd00849a5f05134397af9c936c4
7
- data.tar.gz: 95349f954d9c465944299871811796d02473afae6d0583513c5c18d52466fd87628a0137df2b5b8eff9caceace26d7a827f5cf1adb4d93fce168cdc8f63ab518
6
+ metadata.gz: a9b37adf87a371f1b370462e902fdbac4405195ad17b061936b02275e6419a289e38d91ce1411fe30b2004d269959d2d90da92e20349d1f2a7f0b3b2940cf784
7
+ data.tar.gz: fbf2478a0c4834ae47f877e7d1ebd3648a394c8a1739ce3917b54283a6bcab662f1cfb7c1b05652ff42f4f7bf06ba4c6b4618ef9317958309c2e5ddb67717d1c
data/CHANGELOG.md CHANGED
@@ -7,6 +7,43 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [0.59.0] - 2026-11-03
11
+
12
+ ### Added
13
+
14
+ - **E-mail addresses must end in an ICANN-registered TLD (on by default).** A sign-in code sent to
15
+ `jaryl@rarebit.ome` was accepted by the ESP and bounced hours later on the missing MX, so the user
16
+ just never got a code: every format check in use (`EmailIdentifier::EMAIL_FORMAT`, Truemail's
17
+ `:regex`, `URI::MailTo::EMAIL_REGEXP`) accepts any run of letters as a TLD. The new
18
+ `StandardId::EmailDomain.registered_tld?(email_or_domain)` checks the domain against the ICANN
19
+ section of the Public Suffix List, offline (no DNS), including punycode IDN TLDs such as
20
+ `xn--p1ai`. It is applied (a) when a passwordless code is requested on an `email` connection, web
21
+ and API, before the code is generated or any delivery event fires, and before the host's
22
+ `passwordless.username_validator` (which still runs after), failing with "rarebit.ome isn't a
23
+ valid e-mail domain. Check the address."; and (b) when a `StandardId::EmailIdentifier`'s value is
24
+ set or changed (error `:unregistered_tld`). Existing identifier rows are never re-checked. The
25
+ special-use TLDs (`test`, `example`, `invalid`, `localhost`, `local`) still pass, since
26
+ they are never delegated and apps use them on purpose for bot accounts and fixtures; change the
27
+ list with `c.email.allowed_special_use_tlds`. Turn the check off with
28
+ `c.email.require_registered_tld = false`. Host e-mail validators should call
29
+ `StandardId::EmailDomain.allowed?` (the gem's rule) so every path agrees;
30
+ `StandardId::EmailDomain.registered_tld?` is the strict ICANN-only predicate. `public_suffix`
31
+ (`>= 5.0, < 8`) is now an explicit dependency.
32
+ - **The login-verify page shows where the code went.** The built-in ERB view names the address and
33
+ links back to the login page ("Use a different e-mail"), and the Inertia props for
34
+ `login_verify/show` gain `identifier`, `channel` and `login_path` so host front ends can do the
35
+ same.
36
+
37
+ ## [0.58.1] - 2026-10-30
38
+
39
+ ### Fixed
40
+
41
+ - **Inline scripts in the engine's web views now carry the CSP nonce.** The mobile callback
42
+ bounce, the login page and the login-verify page each ran an un-nonced inline `<script>`, which a
43
+ host enforcing a nonce-based `script-src` (no `'unsafe-inline'`) blocks. On the mobile callback
44
+ that strands the user on "Returning to your app…" instead of returning them to the app. Hosts
45
+ without a nonce generator render an empty `nonce` attribute, which changes nothing.
46
+
10
47
  ## [0.58.0] - 2026-10-28
11
48
 
12
49
  ### Security
data/README.md CHANGED
@@ -776,6 +776,8 @@ Authentication pages receive the following props:
776
776
  | `enabled_social_providers` | `string[]` | Names of the enabled providers, e.g. `["google"]` — iterate this rather than hard-coding provider names |
777
777
  | `errors` | `object` | Validation errors (on form submission failures) |
778
778
 
779
+ The code-entry page (`login_verify/show`) instead receives `flash`, plus `identifier` (the address or phone number the code was sent to), `channel` (`"email"` or `"sms"`) and `login_path` (the engine's login page, mount path included). Show the address and link back to `login_path` ("Use a different e-mail"), so a user who mistyped it can see why no code arrived and start again; the built-in ERB view does this.
780
+
779
781
  #### Using Authentication in Host App Controllers
780
782
 
781
783
  You can use the `authenticate_account!` method in your own controllers to require authentication with Inertia-compatible redirects:
@@ -126,12 +126,18 @@ module StandardId
126
126
  )
127
127
  end
128
128
 
129
+ # identifier / channel / login_path let a front end show where the code
130
+ # went and offer a way back to correct it: a mistyped address otherwise
131
+ # looks exactly like a slow e-mail.
129
132
  def verify_page_props
130
133
  {
131
134
  flash: {
132
135
  notice: flash[:notice],
133
136
  alert: flash[:alert]
134
- }.compact
137
+ }.compact,
138
+ identifier: @otp_data[:username],
139
+ channel: @otp_data[:connection],
140
+ login_path: engine_path(login_path)
135
141
  }
136
142
  end
137
143
  end
@@ -24,5 +24,19 @@ module StandardId
24
24
  # actually edits the address. Without this, saving an unrelated attribute on
25
25
  # a grandfathered identifier would start raising.
26
26
  validates :value, format: { with: EMAIL_FORMAT }, if: :value_changed?
27
+
28
+ # The format above accepts any run of letters as a TLD, so "a@rarebit.ome"
29
+ # passes it. Same grandfathering: only a new or edited value is checked.
30
+ validate :value_has_registered_tld, if: :value_changed?
31
+
32
+ private
33
+
34
+ def value_has_registered_tld
35
+ return if value.blank? || errors.include?(:value)
36
+ return unless StandardId.config.email.require_registered_tld
37
+ return if StandardId::EmailDomain.allowed?(value)
38
+
39
+ errors.add(:value, :unregistered_tld, message: "has a domain that isn't a valid e-mail domain")
40
+ end
27
41
  end
28
42
  end
@@ -32,7 +32,7 @@
32
32
  color: #555;
33
33
  }
34
34
  </style>
35
- <script>
35
+ <script nonce="<%= content_security_policy_nonce %>">
36
36
  document.addEventListener("DOMContentLoaded", function () {
37
37
  <%# to_json, not j(): ERB HTML-escapes the j() output, so every "&" in the
38
38
  query became "&amp;" and each key after the first arrived as "amp;<key>".
@@ -38,7 +38,7 @@
38
38
  (non-AJAX) submit by then, so the request still goes through. Vanilla JS
39
39
  only; the gem ships no JS framework.
40
40
  %>
41
- <script>
41
+ <script nonce="<%= content_security_policy_nonce %>">
42
42
  (function () {
43
43
  var form = document.getElementById("passwordless-login-form");
44
44
  if (!form) return;
@@ -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
- <p class="mt-2 text-center text-sm text-gray-500 dark:text-gray-400">We sent you a verification code.</p>
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]">
@@ -56,7 +64,7 @@
56
64
  Client-side resend cooldown. Progressive enhancement: with JS off the button is
57
65
  always active and the server's retry_delay guard is the backstop. Vanilla JS only.
58
66
  %>
59
- <script>
67
+ <script nonce="<%= content_security_policy_nonce %>">
60
68
  (function () {
61
69
  var btn = document.getElementById("resend-otp-button");
62
70
  if (!btn) return;
@@ -258,8 +258,19 @@ StandardId.configure do |c|
258
258
  # to disable the cooldown.
259
259
  # c.passwordless.retry_delay = 30
260
260
 
261
+ # Default: true — reject an e-mail address whose domain does not end in an
262
+ # ICANN-registered TLD (a@rarebit.ome), before a passwordless code is sent
263
+ # and when an EmailIdentifier's value is set or changed. Checked offline
264
+ # against the Public Suffix List; existing identifiers are never re-checked.
265
+ # Your own validators can reuse StandardId::EmailDomain.allowed?(email).
266
+ # c.email.require_registered_tld = true
267
+ #
268
+ # Default: %w[test example invalid localhost local] — special-use TLDs that
269
+ # pass the check above anyway (never delegated; used for bots and fixtures).
270
+ # c.email.allowed_special_use_tlds = %w[test example invalid localhost local]
271
+
261
272
  # Custom username validator; return nil/false to accept, or an error message
262
- # string to reject. Useful for domain allow-lists or truemail integration.
273
+ # string to reject. Runs after the registered-TLD check above. Useful for domain allow-lists or truemail integration.
263
274
  # Default: nil
264
275
  # c.passwordless.username_validator = ->(username, connection_type) {
265
276
  # "Invalid email" unless TruemailValidator.valid?(username)
@@ -210,6 +210,24 @@ StandardId::ConfigSchema.define do
210
210
  field :publish_provider_tokens, type: :boolean, default: false
211
211
  end
212
212
 
213
+ scope :email do
214
+ # Reject an e-mail address whose domain does not end in an ICANN-registered
215
+ # TLD (StandardId::EmailDomain.allowed?), so "a@rarebit.ome" fails at once instead
216
+ # of bouncing hours later. Applied when a passwordless code is requested
217
+ # for an e-mail connection, before any code is generated or sent, and when
218
+ # a StandardId::EmailIdentifier's value is set or changed (existing rows
219
+ # are never re-checked). Turn it off only as an escape hatch, e.g. an app
220
+ # that signs in addresses on a private or not-yet-listed TLD.
221
+ field :require_registered_tld, type: :boolean, default: true
222
+ # TLDs that pass the check above although they are not in the PSL. The
223
+ # default is the special-use names of RFC 2606 / 6761 (test, example,
224
+ # invalid, localhost) and RFC 6762 (local), which are never delegated:
225
+ # nobody mistypes .com as .invalid, and apps use them on purpose for
226
+ # synthetic accounts (bots, demo data, e2e users) and test fixtures. Set
227
+ # [] to accept registered TLDs only; add e.g. "internal" for a private one.
228
+ field :allowed_special_use_tlds, type: :array, default: -> { %w[test example invalid localhost local] }
229
+ end
230
+
213
231
  scope :passwordless do
214
232
  # Removed in 0.43 (no effect since 0.8).
215
233
  removed :enabled, "it had no effect since 0.8. Use web.passwordless_login (WebEngine) instead, and delete this line."
@@ -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
@@ -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
@@ -11,6 +11,13 @@ module StandardId
11
11
  raise StandardId::InvalidRequestError, "Invalid email format" unless email.to_s.match?(/\A[^@\s]+@[^@\s]+\z/)
12
12
  end
13
13
 
14
+ # A mistyped TLD (rarebit.ome) is accepted by the ESP and bounces hours
15
+ # later, so the user just never gets a code. Refuse it before sending.
16
+ def validate_recipient!(email)
17
+ error = StandardId::EmailDomain.validation_error(email)
18
+ raise StandardId::InvalidRequestError, error if error
19
+ end
20
+
14
21
  def find_or_create_account!(email)
15
22
  Account.find_or_create_by_verified_email!(email)
16
23
  end
@@ -1,3 +1,3 @@
1
1
  module StandardId
2
- VERSION = "0.58.0"
2
+ VERSION = "0.59.0"
3
3
  end
data/lib/standard_id.rb CHANGED
@@ -67,6 +67,7 @@ require "standard_id/oauth/protected_resource_document"
67
67
  require "standard_id/routing"
68
68
  require "standard_id/oauth/consent_payload"
69
69
  require "standard_id/oauth/client_registration"
70
+ require "standard_id/email_domain"
70
71
  require "standard_id/passwordless/base_strategy"
71
72
  require "standard_id/passwordless/email_strategy"
72
73
  require "standard_id/passwordless/sms_strategy"
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: standard_id
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.58.0
4
+ version: 0.59.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Jaryl Sim
@@ -71,6 +71,26 @@ dependencies:
71
71
  - - "~>"
72
72
  - !ruby/object:Gem::Version
73
73
  version: '1.3'
74
+ - !ruby/object:Gem::Dependency
75
+ name: public_suffix
76
+ requirement: !ruby/object:Gem::Requirement
77
+ requirements:
78
+ - - ">="
79
+ - !ruby/object:Gem::Version
80
+ version: '5.0'
81
+ - - "<"
82
+ - !ruby/object:Gem::Version
83
+ version: '8'
84
+ type: :runtime
85
+ prerelease: false
86
+ version_requirements: !ruby/object:Gem::Requirement
87
+ requirements:
88
+ - - ">="
89
+ - !ruby/object:Gem::Version
90
+ version: '5.0'
91
+ - - "<"
92
+ - !ruby/object:Gem::Version
93
+ version: '8'
74
94
  - !ruby/object:Gem::Dependency
75
95
  name: factory_bot
76
96
  requirement: !ruby/object:Gem::Requirement
@@ -276,6 +296,7 @@ files:
276
296
  - lib/standard_id/config_schema.rb
277
297
  - lib/standard_id/current_attributes.rb
278
298
  - lib/standard_id/deprecator.rb
299
+ - lib/standard_id/email_domain.rb
279
300
  - lib/standard_id/email_password.rb
280
301
  - lib/standard_id/email_password/authentication.rb
281
302
  - lib/standard_id/email_password/daily_limit.rb