standard_id 0.60.0 → 0.62.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.
Files changed (51) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +110 -0
  3. data/README.md +205 -24
  4. data/app/channels/concerns/standard_id/cable_authentication.rb +1 -0
  5. data/app/controllers/concerns/standard_id/api_authentication.rb +30 -0
  6. data/app/controllers/concerns/standard_id/social_authentication.rb +5 -4
  7. data/app/controllers/concerns/standard_id/web_authentication.rb +29 -7
  8. data/app/controllers/standard_id/api/step_up_controller.rb +92 -0
  9. data/app/controllers/standard_id/web/step_up_controller.rb +83 -0
  10. data/app/forms/standard_id/web/reset_password_confirm_form.rb +1 -1
  11. data/app/models/standard_id/client_application.rb +30 -1
  12. data/app/models/standard_id/password_credential.rb +77 -9
  13. data/app/models/standard_id/session.rb +45 -1
  14. data/app/views/standard_id/web/step_up/show.html.erb +65 -0
  15. data/config/brakeman.ignore +4 -0
  16. data/config/routes/api.rb +7 -0
  17. data/config/routes/web.rb +6 -0
  18. data/db/migrate/20261123000000_add_authenticated_at_to_standard_id_sessions.rb +15 -0
  19. data/lib/generators/standard_id/install/templates/standard_id_reference.rb +50 -5
  20. data/lib/standard_id/api/token_manager.rb +3 -0
  21. data/lib/standard_id/auth_lineage.rb +39 -8
  22. data/lib/standard_id/config/callable_validator.rb +26 -3
  23. data/lib/standard_id/config/schema.rb +105 -5
  24. data/lib/standard_id/email_password/authentication.rb +1 -1
  25. data/lib/standard_id/email_password/password_reset.rb +1 -1
  26. data/lib/standard_id/email_password.rb +4 -5
  27. data/lib/standard_id/error_reporting.rb +38 -0
  28. data/lib/standard_id/errors.rb +16 -0
  29. data/lib/standard_id/events/definitions.rb +14 -3
  30. data/lib/standard_id/events/subscribers/passwordless_delivery_subscriber.rb +3 -1
  31. data/lib/standard_id/events.rb +47 -0
  32. data/lib/standard_id/health_contributions.rb +27 -0
  33. data/lib/standard_id/http_client.rb +39 -6
  34. data/lib/standard_id/jwt_service.rb +31 -2
  35. data/lib/standard_id/keyed_digest.rb +43 -5
  36. data/lib/standard_id/oauth/direct_mint_flow.rb +9 -3
  37. data/lib/standard_id/oauth/oauth_session_persistence.rb +24 -9
  38. data/lib/standard_id/oauth/password_flow.rb +4 -10
  39. data/lib/standard_id/oauth/token_grant_flow.rb +28 -3
  40. data/lib/standard_id/password_pepper.rb +88 -0
  41. data/lib/standard_id/passwordless/base_strategy.rb +5 -1
  42. data/lib/standard_id/passwordless/code_handoff.rb +72 -0
  43. data/lib/standard_id/passwordless.rb +25 -0
  44. data/lib/standard_id/step_up.rb +236 -0
  45. data/lib/standard_id/testing/otp_helpers.rb +5 -5
  46. data/lib/standard_id/testing/request_helpers.rb +8 -3
  47. data/lib/standard_id/token_minter.rb +6 -2
  48. data/lib/standard_id/version.rb +1 -1
  49. data/lib/standard_id/web/session_manager.rb +9 -2
  50. data/lib/standard_id.rb +4 -0
  51. metadata +10 -1
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 6b16c75edf932c75abfde26acde06652cea845e13d60b5ec943894355eb89327
4
- data.tar.gz: 5ccd8c3889f612353415998ba063d2e10a2a0450ba099f28e7f863040ccf57e8
3
+ metadata.gz: 2362d21d45d2771288474468d9f32f18fd4be058329aafeae789e05a4ad6339f
4
+ data.tar.gz: 9b3780603bc7a3a76d936a2d780bc95522bd55034960098c1bef9c476b154211
5
5
  SHA512:
6
- metadata.gz: f2a159cbe0415275e12c90ca0b43d241f7010d4ee3c7bb0d5ad817b9668a6104f5d829fc41db76fb07deadb4164a9d3dc726957305d28053b848fa26c9198bb2
7
- data.tar.gz: 1f35e1824c63d566905576992b00cba1f62377874d069286a4353bb4f8513416809662d68e0cbcf5cc41ef61e06b5744c6680827cd6132a9f4d406a3a053c4a2
6
+ metadata.gz: f0eaa52443d01056cc784627aceed9bef678249069ab66150091871b4aa985f70ebae651e6271219623a5045a0da0b6c61342e996e7660d946c8e9af3842314b
7
+ data.tar.gz: 67737af10630f42f4625d309dbf872e9a97c6d0fc1d25165000af58e5a34cecb95e87996e2b874d579c750add493d74f9fd3bb712e9c7c9b2db56e751344067a
data/CHANGELOG.md CHANGED
@@ -7,6 +7,116 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [0.62.0] - 2026-11-23
11
+
12
+ ### Added
13
+
14
+ - **Step-up authentication (opt-in).** `require_recent_authentication!(within:)` in
15
+ `WebAuthentication` and `ApiAuthentication` lets an action run only when the session (or the
16
+ bearer token's new OIDC `auth_time` claim) proved the account's identity recently. Otherwise
17
+ the web guard redirects to `/step_up`, and the API guard answers RFC 9470's
18
+ `insufficient_user_authentication` 401 with `max_age`. The step-up re-proves identity with a
19
+ fresh `StandardId::Otp` code in its own realm (`c.step_up.realm`, default `"step_up"`), sent to
20
+ the account's verified e-mail or phone, plus the password where the account has one. It stamps
21
+ the session, or (API, `POST /step_up` then `/step_up/verify`) returns a fresh access token.
22
+ Publishes `authentication.step_up.started`, `.succeeded` and `.failed`. Sign-ins stamp the new
23
+ `Session#authenticated_at`, never remember-me. `auth_time` is carried through `/authorize`, the
24
+ authorization-code grant and every refresh (`RefreshToken#authenticated_at`).
25
+ `TokenMinter.mint(authenticated_at:)` sets it for a direct mint; while step-up is on, no custom
26
+ claim can. `c.step_up.token_profile_resolver` names the profile the API step-up re-mints for when
27
+ an account may hold several of the audience's bound type. Needs migration
28
+ `20261123000000_add_authenticated_at_to_standard_id_sessions` and `c.step_up.enabled = true`;
29
+ until then no routes are drawn, no claim is minted, and the guard raises a
30
+ `ConfigurationError`. See README, "Step-up authentication".
31
+ - **Password pepper (opt-in).** `c.password.pepper` hashes new passwords as
32
+ bcrypt(HMAC-SHA256(pepper, password)), so the digests cannot be cracked from
33
+ a database dump alone. Verification tries the current pepper, then
34
+ `c.password.previous_peppers`, then no pepper (`c.password.accept_unpeppered_passwords`,
35
+ default `true`), so turning it on or rotating it locks nobody out. A login
36
+ that matched anything but the current pepper re-hashes through
37
+ `PasswordCredential#rehash_password`: it publishes `credential.password.rehashed`
38
+ (new payload key `pepper_changed`), not `credential.password.changed`, and
39
+ voids that user's remember-me cookies and reset links, as a cost change does.
40
+ Logins for unknown addresses pay one dummy bcrypt comparison per candidate
41
+ pepper, matching a wrong password. With no pepper set (the default) nothing
42
+ changes. **Losing the pepper forces every password hashed under it to be
43
+ reset.** See README, "Password pepper".
44
+ - **`StandardId::Passwordless.issued_code(event)`** hands a `PASSWORDLESS_CODE_GENERATED`
45
+ subscriber the raw one-time code without putting it in the event payload, so delivery works
46
+ with `c.events.publish_records = false`. It returns the published record's code when there is
47
+ one; otherwise the code of the challenge being published right now, only for that event and a
48
+ matching `code_challenge_id`, and only while the publish runs (thread- or fiber-local through
49
+ `ActiveSupport::IsolatedExecutionState`). It returns `nil` after the publish, in another
50
+ thread, or in a job that received the payload, so a subscriber that defers delivery must read
51
+ the code first and pass the string on. The payload still never holds the code, so audit,
52
+ logging and breadcrumb subscribers cannot serialise it. `event[:code_challenge].code` keeps
53
+ working while records are published (the default). See `docs/MIGRATION_GUIDE.md`.
54
+
55
+ ### Changed
56
+
57
+ - **HMAC-signed JWTs verify under `config.previous_secret_key_bases`.** For HS256/384/512,
58
+ `JwtService.decode` tries the current `secret_key_base`, then each previous secret in order,
59
+ and moves on only when the signature doesn't match: an expired token, or one with the wrong
60
+ issuer or audience, is refused at once, as before. New tokens are still signed under the current
61
+ secret only, so refreshing an old-secret refresh token returns tokens under the new one. New
62
+ public `JwtService.symmetric_verification_keys` (current secret first, then previous ones; `[]`
63
+ for an asymmetric algorithm) lets a `JwtService.verify` caller pass
64
+ `key: JwtService.symmetric_verification_keys` for the same window. RS*/ES* keys keep rotating
65
+ through `oauth.previous_signing_keys`, and HS tokens are still refused when the configured
66
+ algorithm is asymmetric. Nothing changes unless previous secrets are listed.
67
+ - **Session tokens and RFC 7592 registration access tokens used under a previous
68
+ `secret_key_base` are re-keyed to the current one.** After a successful
69
+ `Session.authenticate_by_token`, web session-cookie load or Action Cable authentication, a
70
+ session whose `lookup_hash` (or HMAC `token_digest`) is still under a previous secret is
71
+ rewritten in one conditional `UPDATE` (new `StandardId::KeyedDigest.rekey`), so the old secret
72
+ stays needed only for credentials not used since the rotation, rather than for the longest
73
+ session lifetime (or forever, for registration access tokens). The `UPDATE` only applies while
74
+ the row still holds the values just read, skips callbacks, `updated_at` and events, runs in a
75
+ savepoint inside an open transaction, and never fails authentication: an error is logged (model,
76
+ id and error class only) and the token still authenticates. With no previous secrets listed,
77
+ nothing is hashed or written. One-time codes, authorization codes and JWTs are not re-keyed.
78
+
79
+ ### Fixed
80
+
81
+ - **The built-in passwordless mailer delivers with `c.events.publish_records = false`.** With
82
+ records off it found no code, sent nothing and reported `"failed"`; it now reads the code
83
+ through `issued_code` and reports `"sent"`. `StandardId::Testing::OtpHelpers`
84
+ (`capture_otp_code`, `capture_otp_codes`) also work with records off.
85
+
86
+ ## [0.61.0] - 2026-11-23
87
+
88
+ ### Added
89
+
90
+ - **standard_health contributions.** StandardId registers an `ActiveSupport.on_load(:standard_health)`
91
+ hook that offers `StandardId::Checks::Migrations` as the non-critical `standard_id_migrations`
92
+ default check and declares two env vars under `standard_id`: `APP_ENVIRONMENT` (recommended;
93
+ it decides StandardId's production-only guards) and `STANDARD_ID_BYPASS_CODE` (forbidden in
94
+ production). There is no dependency on standard_health: without a standard_health that runs the
95
+ hook, nothing happens. Apps that already `register_check :standard_id_migrations` by hand are
96
+ unaffected (`register_default_checks` skips a registered name); opt out with
97
+ `c.register_default_checks standard_id_migrations: false`.
98
+ - **`config.network_wrapper`**, a callable `->(provider:, &block)` that wraps every outbound
99
+ connection `StandardId::HttpClient` makes (social token, userinfo and JWKS calls), e.g. in a
100
+ circuit breaker: `->(provider:, &b) { StandardCircuit.run(:"oauth_#{provider}", &b) }`. `nil`
101
+ (default) runs the request directly. `HttpClient.post_form`, `.get_with_bearer` and the private
102
+ `start_connection` that plugins call for a JWKS take an optional `provider:` keyword (default
103
+ `:standard_id`), so existing callers keep working, including those that pass
104
+ `post_form`'s form as bare keywords (`post_form(url, id_token: token)`). The boot-time callable check rejects a
105
+ wrapper with an unknown keyword, a positional argument, or (for a lambda) no `&block`.
106
+ - **`StandardId::Events.auditable`**, the frozen list of event patterns worth an audit row, for
107
+ `StandardId::Events.auditable.each { |pattern| config.subscribe_to(pattern) }` in standard_audit
108
+ (one pattern per call, which every standard_audit version accepts). It keeps what the apps
109
+ subscribe to today (authentication, account, social and passwordless events; session created,
110
+ revoked and expired) and adds the password and client-secret lifecycle, refresh-token reuse,
111
+ token revocation, audience mismatches and OAuth client registration changes.
112
+ - **`config.error_reporter`**, an optional callable `(error, context)` for the errors StandardId
113
+ handles and carries on from (an event subscriber that raised after its change committed).
114
+ `context` carries `source: "standard_id"`, `handled: true` and what failed (`event:` or
115
+ `action:`). `nil` (default) keeps `Rails.error.report(error, handled: true, source:
116
+ "standard_id")`. All four report sites go through the new `StandardId::ErrorReporting.report`.
117
+ A reporter that raises is logged and the error falls back to that default report, so the flow
118
+ it was reporting from still carries on.
119
+
10
120
  ## [0.60.0] - 2026-11-22
11
121
 
12
122
  ### Security
data/README.md CHANGED
@@ -177,6 +177,106 @@ Password digests are made by `has_secure_password` at `BCrypt::Engine.cost` (bcr
177
177
 
178
178
  The digest is also the fingerprint of the remember-me cookie and the password-reset link, so the first login after a cost change signs that user out of remember-me on their other browsers and voids any reset link they have not used yet. The login itself, and a remember-me cookie it sets, are unaffected. The rewrite happens one user at a time as each signs in, never on deploy. Turn it off with `config.password.rehash_on_login = false`.
179
179
 
180
+ ### Password pepper
181
+
182
+ Off by default. A pepper is a secret mixed into every password before bcrypt, so a dump of `standard_id_password_credentials` alone is not enough to crack the digests: the attacker also needs the pepper, which lives in your credentials, not your database.
183
+
184
+ ```ruby
185
+ StandardId.configure do |c|
186
+ c.password.pepper = Rails.application.credentials.password_pepper # SecureRandom.hex(32)
187
+ end
188
+ ```
189
+
190
+ > [!WARNING]
191
+ > **If you lose the pepper, every password hashed under it is gone.** There is no way to verify those digests without it, so each of those users has to reset their password. Store it with `secret_key_base`, back it up the same way, and never commit it. Once it is set, removing it or changing it without the steps below locks those users out.
192
+
193
+ How it works:
194
+
195
+ - New digests are `bcrypt(HMAC-SHA256(pepper, password))`, hex-encoded. The pepper is never appended to the password: bcrypt reads only the first 72 bytes, so an appended pepper would be cut off long passwords.
196
+ - Verification tries the current pepper, then each of `c.password.previous_peppers`, then no pepper at all. So **turning the pepper on locks nobody out**: existing digests still verify.
197
+ - A successful password login (web, OAuth password grant, email + password API) that matched anything but the current pepper re-hashes the password under it, through the same path as a bcrypt cost change ([above](#raising-the-bcrypt-cost)): one conditional `UPDATE`, `credential.password.rehashed` with `pepper_changed: true`, and no `credential.password.changed` event or e-mail, because the password itself did not change. Like a cost change, **the re-hash voids that user's outstanding remember-me cookies and password-reset links**, one user at a time as each signs in. It needs `c.password.rehash_on_login` (on by default); with it off, digests stay where they are and keep verifying.
198
+ - A login for an address with no account pays for the same number of bcrypt comparisons as a wrong password (one per candidate pepper), so timing does not reveal which addresses exist. Each extra candidate costs one more bcrypt comparison per wrong password.
199
+
200
+ **Rotating the pepper.** Move the current pepper into `previous_peppers` and set the new one:
201
+
202
+ ```ruby
203
+ c.password.pepper = Rails.application.credentials.password_pepper_2026
204
+ c.password.previous_peppers = [Rails.application.credentials.password_pepper_2025]
205
+ ```
206
+
207
+ Users move to the new pepper as they sign in. Keep the old pepper listed for as long as anyone who has not signed in since might come back. Dropping it sooner forces those users to reset their password. There is no per-row record of which pepper a digest used, so the safe way to retire an old pepper is to wait out your inactivity window, then force a reset for the accounts that have not signed in since the rotation.
208
+
209
+ **Retiring unpeppered digests.** `c.password.accept_unpeppered_passwords` (default `true`) keeps digests made before the pepper was turned on verifiable. Set it to `false` only once none can be left, on the same terms as dropping an old pepper. It is ignored while no pepper is set.
210
+
211
+ **Turning the pepper off.** Set `pepper = nil` and list the old value in `previous_peppers`. Users move back to bare digests as they sign in.
212
+
213
+ `has_secure_password`'s own `password_challenge` attribute compares the bare password and does not know about the pepper. To check a user's current password, call `password_credential.authenticate(password)`.
214
+
215
+ ### Step-up authentication
216
+
217
+ Off by default. Before a sensitive action (changing an e-mail address, deleting an account, viewing recovery codes), ask a signed-in user to prove it is them again, unless they did so a moment ago. Nothing changes for a host that never calls the guard.
218
+
219
+ **1. Run the migration and turn it on.**
220
+
221
+ ```bash
222
+ bin/rails standard_id:install:migrations
223
+ bin/rails db:migrate # 20261123000000_add_authenticated_at_to_standard_id_sessions
224
+ ```
225
+
226
+ ```ruby
227
+ StandardId.configure do |c|
228
+ c.step_up.enabled = true
229
+ # c.step_up.max_age = 300 # default `within:`, in seconds
230
+ # c.step_up.require_password = true # also ask for the password when the account has one
231
+ # c.step_up.delivery = :built_in # or :custom: your PASSWORDLESS_CODE_GENERATED subscriber, realm "step_up"
232
+ # c.step_up.url = "/step_up" # where the web guard redirects
233
+ end
234
+ ```
235
+
236
+ **2. Guard the action.**
237
+
238
+ ```ruby
239
+ class AccountSettingsController < ApplicationController
240
+ include StandardId::WebAuthentication
241
+ before_action :authenticate_account!
242
+ before_action -> { require_recent_authentication!(within: 5.minutes) }, only: %i[edit update]
243
+ end
244
+
245
+ class Api::RecoveryCodesController < ActionController::API
246
+ include StandardId::ApiAuthentication
247
+ before_action -> { require_recent_authentication!(within: 5.minutes) }
248
+ end
249
+ ```
250
+
251
+ The guard raises `StandardId::ConfigurationError` while `c.step_up.enabled` is off or the migration has not run. It never passes or refuses silently.
252
+
253
+ **What counts as recent.** Each session row records `authenticated_at`, the last time it proved the account's identity. Every interactive sign-in sets it (password, passwordless, social, sign-up), and so does a step-up. Remember-me does not: a cookie is not a fresh proof, so a remembered visitor steps up before a guarded action. Sessions created before the migration have no time and step up once. Bearer tokens carry the OIDC `auth_time` claim, minted only while `c.step_up.enabled` is on:
254
+
255
+ | Token | `auth_time` |
256
+ | --- | --- |
257
+ | password, passwordless OTP, social, email + password grants | the grant itself |
258
+ | `authorization_code` | the browser session's `authenticated_at` at `/authorize` |
259
+ | `refresh_token` | the original grant's, carried on each refresh token (never refreshed into a newer time) |
260
+ | `TokenMinter.mint` | `authenticated_at:` when you pass it, else none |
261
+ | `client_credentials`, implicit | none |
262
+
263
+ A token with no `auth_time` is never recent. While step-up is on, only the recorded authentication sets it: an `auth_time` from `oauth.custom_claims` or `TokenMinter` `claims:` is dropped, recorded time or not.
264
+
265
+ **Web flow.** A stale session is redirected to `/step_up`, and a GET's URL is remembered. The page sends a one-time code to the account's verified e-mail address, or its verified phone number if it has no e-mail. The user enters the code and, when the account has a password, the password. On success the session's `authenticated_at` is set to now and the user returns to the guarded page. Inertia apps render `<namespace>/step_up/show` with `channel`, `target`, `code_sent`, `password_required`, `step_up_path` and `flash`. Signed-out visitors go to login, as before.
266
+
267
+ **API flow.** A stale or `auth_time`-less token gets RFC 9470's challenge:
268
+
269
+ ```http
270
+ HTTP/1.1 401 Unauthorized
271
+ WWW-Authenticate: Bearer realm="StandardId", error="insufficient_user_authentication", error_description="A more recent authentication is required", max_age=300
272
+
273
+ {"error":"insufficient_user_authentication","error_description":"A more recent authentication is required","max_age":300}
274
+ ```
275
+
276
+ The client steps up with its current token. `POST /step_up` sends the code and answers `202 {"channel":"email","password_required":true}`. `POST /step_up/verify` with `{"code":"123456","password":"…"}` answers with a new access token whose `auth_time` is now. That token keeps the old one's `client_id`, `scope` and `aud`, under `grant_type: "step_up"` (lifetime `oauth.token_lifetimes[:step_up]`, else the default). The client then retries with it. No refresh token is issued, so tokens refreshed later carry the original sign-in time. When the audience is bound to a profile type and an account may hold several such profiles, set `c.step_up.token_profile_resolver = ->(account:, claims:) { … }` to name the profile the token is for (from your own claim, e.g. `gid`); otherwise the strict lookup refuses an ambiguous account. Override `render_step_up_required(error)` to answer differently.
277
+
278
+ **The code.** It is a `StandardId::Otp` code in its own realm (`c.step_up.realm`, default `"step_up"`), so a sign-in code cannot stand in for it, and it is bound to the account it was issued to. It is checked before the password, so each code buys at most one password guess, and a wrong password spends it. Issuing is limited by `passwordless.retry_delay` and the `rate_limits.otp_start_*` limits; verifying by `rate_limits.otp_verify_per_ip`. Events: `authentication.step_up.started`, `.succeeded` and `.failed` (see the event table).
279
+
180
280
  ### OAuth Hardening Options
181
281
 
182
282
  Two spec-conformance settings default to the historical (looser) behaviour so
@@ -627,6 +727,23 @@ gets `provider_tokens:` in the `social.before_account` / `before_mint` hooks.
627
727
  Setting `config.events.publish_provider_tokens = true` restores `event[:tokens]`;
628
728
  the subscriber that reads it then has to keep them out of audit rows and logs.
629
729
 
730
+ **Wrapping provider calls.** Every outbound request StandardId makes for a
731
+ provider (token exchange, userinfo, JWKS) goes through `StandardId::HttpClient`,
732
+ and `config.network_wrapper` wraps each one, given the provider's name. Use it
733
+ for a circuit breaker, so a provider outage fails fast instead of holding
734
+ request threads for the full timeout, or for a tracing span:
735
+
736
+ ```ruby
737
+ c.network_wrapper = ->(provider:, &b) { StandardCircuit.run(:"oauth_#{provider}", &b) }
738
+ ```
739
+
740
+ It must call the block and return its result. A timeout or refused connection
741
+ raises inside the wrapper, and whatever the wrapper raises (an open circuit,
742
+ say) reaches the provider's caller as is. `provider` is the plugin's name
743
+ (`:google`, `:apple`, ...), or `:standard_id` for a plugin release that does not
744
+ pass one yet. A lambda must take the block as `&block`; the boot check rejects
745
+ one that doesn't, since it would silently skip the request.
746
+
630
747
  ### Inertia.js Integration
631
748
 
632
749
  StandardId supports [Inertia.js](https://inertiajs.com/) for modern React, Vue, or Svelte frontends. When enabled, web controllers render Inertia components instead of ERB views.
@@ -810,15 +927,23 @@ Subscribe to the `PASSWORDLESS_CODE_GENERATED` event to deliver OTP codes:
810
927
  # config/initializers/standard_id_events.rb
811
928
  StandardId::Events.subscribe(StandardId::Events::PASSWORDLESS_CODE_GENERATED) do |event|
812
929
  next if event[:skip_sender] # Otp.issue(delivery: :manual) — the caller delivers
930
+ code = StandardId::Passwordless.issued_code(event)
813
931
  case event[:channel]
814
932
  when "email"
815
- UserMailer.send_code(event[:identifier], event[:code_challenge].code).deliver_now
933
+ UserMailer.send_code(event[:identifier], code).deliver_now
816
934
  when "sms"
817
- SmsService.send_code(event[:identifier], event[:code_challenge].code)
935
+ SmsService.send_code(event[:identifier], code)
818
936
  end
819
937
  end
820
938
  ```
821
939
 
940
+ `StandardId::Passwordless.issued_code(event)` returns the raw code while the event is being
941
+ published, and `nil` afterwards or on another thread, so read it in the subscriber and pass the
942
+ string on. The code is never part of the payload: audit and event-logging subscribers serialise
943
+ payloads, and the code would end up in their rows. It works with `c.events.publish_records = false`,
944
+ where the payload carries `code_challenge_id` instead of the record. `event[:code_challenge].code`
945
+ still works while records are published.
946
+
822
947
  Set `c.passwordless.delivery = :custom` (the default) so the engine's built-in
823
948
  `PasswordlessMailer` stays out of the way; with `:built_in` the engine emails
824
949
  the code itself — `otp_email` ("Your sign-in code") for the `"authentication"`
@@ -842,10 +967,12 @@ parent's `default from:` does not apply to them.
842
967
  Event payload includes:
843
968
  - `channel` - `"email"` or `"sms"`
844
969
  - `identifier` - The email address or phone number
845
- - `code_challenge` - The code challenge object with `.code` method. The raw code exists only on
846
- this in-memory record: the database stores an HMAC of it (`code_digest`), so read `.code` in the
847
- subscriber and pass the string on; a challenge reloaded later (e.g. in a job that received the
848
- record) returns `nil`
970
+ - `code_challenge` - The code challenge record (left out under `c.events.publish_records = false`).
971
+ The raw code exists only on this in-memory record: the database stores an HMAC of it
972
+ (`code_digest`), and the record does not serialise it. Read the code with
973
+ `StandardId::Passwordless.issued_code(event)` (or `.code` on the record) in the subscriber and
974
+ pass the string on; a challenge reloaded later (e.g. in a job that received the record) returns
975
+ `nil`
849
976
  - `expires_at` - When the code expires
850
977
  - `realm` - The OTP realm (`"authentication"` for sign-in)
851
978
  - `skip_sender` - `true` for `Otp.issue(delivery: :manual)`; don't deliver
@@ -993,6 +1120,9 @@ Every StandardId event automatically carries tracing metadata (`event_id`, `time
993
1120
  | | `authentication.password.failed` | `account_lookup`, `error_code`, `error_message` | After password verification fails |
994
1121
  | | `authentication.otp.failed` | `identifier`, `channel`, `error_code`, `error_message` | After OTP verification fails |
995
1122
  | | `authentication.method.denied` | `account`, `auth_method`, `provider`, `flow`, `error_message` | `config.login_method_policy` refused the method, after the credential was proven and before any session or token was created (0.45+) |
1123
+ | | `authentication.step_up.started` | `account`, `channel` | A step-up code was issued to a signed-in account (`c.step_up`) |
1124
+ | | `authentication.step_up.succeeded` | `account`, `channel`, `methods` | The account re-proved its identity (`methods`: `["otp"]` or `["otp", "password"]`) |
1125
+ | | `authentication.step_up.failed` | `account`, `stage`, `channel`, `error_code` | A step-up could not start (`stage: :start`, e.g. `no_verified_identifier`) or was refused (`stage: :verify`: `invalid_code`, `invalid_password`, `max_attempts`, …) |
996
1126
  | Session | `session.creating` | `account`, `session_type`, `ip_address`, `user_agent` | Before a session record is created |
997
1127
  | | `session.created` | `session`, `account`, `session_type`, `token_issued`, `ip_address`, `user_agent` | After session persistence completes |
998
1128
  | | `session.validating` | `session` | Before validating an existing session |
@@ -1038,7 +1168,7 @@ Every StandardId event automatically carries tracing metadata (`event_id`, `time
1038
1168
  | | `credential.password.reset_initiated` | `credential`, `account`, `reset_token_expires_at` | After a password reset is initiated |
1039
1169
  | | `credential.password.reset_completed` | `credential`, `account` | After a password reset is confirmed |
1040
1170
  | | `credential.password.changed` | `credential`, `credential_id` (sent even with `events.publish_records = false`), `account`, `reason` (`:password_reset` / `:changed`) | After a new password is committed: by a reset, or by host code assigning `password` (never for a re-hash of the same password). Drives `password.changed_notice_delivery` |
1041
- | | `credential.password.rehashed` | `credential`, `account`, `previous_cost`, `cost` | After a login re-hashed the password at the current bcrypt cost (`password.rehash_on_login`); the password is unchanged |
1171
+ | | `credential.password.rehashed` | `credential`, `account`, `previous_cost`, `cost`, `pepper_changed` | After a login re-hashed the password at the current bcrypt cost or under the current `password.pepper` (`password.rehash_on_login`); the password is unchanged |
1042
1172
  | | `credential.client_secret.created` | `credential`, `client_id` | After a client secret is created |
1043
1173
  | | `credential.client_secret.rotated` | `credential`, `client_id`, `old_secret_revoked_at` | After a client secret rotation |
1044
1174
 
@@ -1072,6 +1202,21 @@ StandardId::Events.subscribe(/social/) do |event|
1072
1202
  end
1073
1203
  ```
1074
1204
 
1205
+ #### When a subscriber raises after the change has committed
1206
+
1207
+ A subscriber to an event that reports something already written (a completed
1208
+ password reset, a password rehash, a social link) cannot undo it, so StandardId
1209
+ logs its error and reports it instead of failing the request. Reports go to
1210
+ `Rails.error.report(error, handled: true, source: "standard_id")` unless you set
1211
+ `config.error_reporter`, a callable taking `(error, context)`; `context` carries
1212
+ `source:` and `handled:` plus what failed (`event:` or `action:`). If your
1213
+ reporter raises, StandardId logs that and falls back to the `Rails.error.report`
1214
+ call above, so the request still completes:
1215
+
1216
+ ```ruby
1217
+ c.error_reporter = ->(error, context) { Sentry.capture_exception(error, extra: context) }
1218
+ ```
1219
+
1075
1220
  ### Audit Logging
1076
1221
 
1077
1222
  For production audit trails, use the [standard_audit](https://github.com/rarebit-one/standard_audit) gem. StandardId and StandardAudit have zero direct references to each other — the host application wires them together.
@@ -1094,12 +1239,12 @@ rails db:migrate
1094
1239
 
1095
1240
  #### Wiring StandardId events to StandardAudit
1096
1241
 
1097
- Configure StandardAudit to subscribe to StandardId's event namespace and map its payload conventions:
1242
+ Configure StandardAudit to subscribe to the events StandardId marks as worth auditing, and map its payload conventions:
1098
1243
 
1099
1244
  ```ruby
1100
1245
  # config/initializers/standard_audit.rb
1101
1246
  StandardAudit.configure do |config|
1102
- config.subscribe_to /\Astandard_id\./
1247
+ StandardId::Events.auditable.each { |pattern| config.subscribe_to(pattern) }
1103
1248
 
1104
1249
  # StandardId uses :account and :current_account rather than :actor/:target.
1105
1250
  # Map them so StandardAudit extracts the right records.
@@ -1118,7 +1263,9 @@ StandardAudit.configure do |config|
1118
1263
  end
1119
1264
  ```
1120
1265
 
1121
- That's it. Every StandardId authentication event will now be persisted as an audit log entry. No changes are needed inside StandardId itself.
1266
+ That's it. Every security-relevant StandardId event will now be persisted as an audit log entry. No changes are needed inside StandardId itself.
1267
+
1268
+ `StandardId::Events.auditable` is a frozen list of Regexps and full event names: authentication, account, social and passwordless events; session created, revoked and expired; password and client-secret lifecycle; refresh-token reuse, token revocation, audience mismatches and OAuth client registration changes. It leaves out per-request noise (`session.validating`/`validated`) and high-volume token minting (`oauth.token.issued`/`refreshed`). New releases may add to it, so an app that iterates it picks those up. To audit everything instead, subscribe to `/\Astandard_id\./`.
1122
1269
 
1123
1270
  #### Querying audit logs
1124
1271
 
@@ -1998,7 +2145,7 @@ module StandardId
1998
2145
  rescue_to_oauth_error do
1999
2146
  raise StandardId::InvalidRequestError, "Missing authorization code" if code.blank?
2000
2147
 
2001
- response = HttpClient.post_form(TOKEN_ENDPOINT, { code:, redirect_uri:, ... })
2148
+ response = HttpClient.post_form(TOKEN_ENDPOINT, { code:, redirect_uri:, ... }, provider: :github)
2002
2149
  parsed = JSON.parse(response.body)
2003
2150
  build_response(fetch_profile(parsed["access_token"]), tokens: extract_tokens(parsed))
2004
2151
  end
@@ -2009,6 +2156,8 @@ module StandardId
2009
2156
  end
2010
2157
  ```
2011
2158
 
2159
+ Pass `provider:` to every `HttpClient` call so the host's `config.network_wrapper` can tell providers apart (see [Social Login Setup](#social-login-setup)). The keyword is new in 0.61.0; a plugin that supports older standard_id releases should check for it, e.g. `HttpClient.method(:post_form).parameters.include?([:key, :provider])`, and leave it out when absent.
2160
+
2012
2161
  **Required interface:** `provider_name`, `authorization_url`, `get_user_info`.
2013
2162
 
2014
2163
  **Optional hooks** (all class methods, with safe defaults):
@@ -2186,8 +2335,9 @@ patch "/login_verify", params: { code: code }
2186
2335
  codes = capture_otp_codes { ... } # every code issued in the block: identifier, channel, realm, code
2187
2336
  ```
2188
2337
 
2189
- They read `PASSWORDLESS_CODE_GENERATED`, as a delivery subscriber does, so they see nothing when
2190
- `c.events.publish_records = false`. A challenge you create yourself
2338
+ They read `PASSWORDLESS_CODE_GENERATED` with `StandardId::Passwordless.issued_code`, as a delivery
2339
+ subscriber does, so they work whether or not `c.events.publish_records` is on. A challenge you
2340
+ create yourself
2191
2341
  (`CodeChallenge.create!(code: "123456", ...)` or the `:standard_id_code_challenge` factory) still
2192
2342
  verifies with the code you gave it.
2193
2343
 
@@ -2223,8 +2373,10 @@ bundle exec rspec spec/controllers/
2223
2373
  ### Rotating `secret_key_base`
2224
2374
 
2225
2375
  Session tokens, passwordless codes, authorization codes and RFC 7592 registration access tokens are
2226
- stored as digests keyed on `secret_key_base`, so changing it invalidates all of them: everyone is
2227
- signed out. To rotate without that, list the old secret, newest first:
2376
+ stored as digests keyed on `secret_key_base`, and JWTs signed with HS256/384/512 (the default
2377
+ `oauth.signing_algorithm` is `:hs256`) are signed with it, so changing it invalidates all of them:
2378
+ everyone is signed out and every access and refresh token fails. To rotate without that, list the
2379
+ old secret, newest first:
2228
2380
 
2229
2381
  ```ruby
2230
2382
  StandardId.configure do |c|
@@ -2234,11 +2386,41 @@ end
2234
2386
 
2235
2387
  Digests are then still looked up and verified under the old secret (one indexed query covers every
2236
2388
  candidate session lookup hash), while everything new is written under the current one
2237
- (`StandardId::KeyedDigest`). Nothing is re-written in place, so keep the entry until the longest
2238
- session lifetime you issue (`session.*_lifetime`, and the lifetime of any long-lived
2239
- `ServiceSession`) has passed, then remove it.
2240
-
2241
- This covers StandardId's own digests only. The rest of the app needs Rails' rotations too:
2389
+ (`StandardId::KeyedDigest`). HMAC-signed JWTs work the same way: `JwtService.decode` verifies a
2390
+ token under the current secret and then under each previous one, while `encode` always signs with
2391
+ the current secret, so access and refresh tokens issued before the rotation keep working until they
2392
+ expire and every refreshed token is signed under the new secret. Code that calls the config-free
2393
+ `JwtService.verify` itself can pass `key: StandardId::JwtService.symmetric_verification_keys` for the
2394
+ same window. Asymmetric signing keys (RS*/ES*) are unaffected: rotate those with
2395
+ `oauth.previous_signing_keys`.
2396
+
2397
+ **Credentials move to the new secret when they are used.**
2398
+ - A session token, or an RFC 7592 registration access token, that authenticates under a previous
2399
+ secret is re-keyed on the spot. Its `lookup_hash`/`token_digest`, or its digest, is rewritten
2400
+ under the current secret in a single conditional UPDATE.
2401
+ - This happens on the authenticating paths: `Session.authenticate_by_token`, the web session
2402
+ cookie, Action Cable, and the RFC 7592 endpoints.
2403
+ - A credential that already matches under the current secret causes no write. A write that fails
2404
+ (a read-only replica, a lock timeout) is logged and the request still succeeds; that credential
2405
+ is simply tried again next time.
2406
+ - A refresh grant always returns tokens signed under the current secret.
2407
+
2408
+ **How long to keep the old secret.** Only credentials that have not been used since the rotation
2409
+ still depend on it. Keep the entry for as long as you are willing to wait for idle users to come
2410
+ back: once you remove it, anything untouched since the rotation stops working. Those users sign in
2411
+ again, and a client re-registers. The longest lifetime you issue is the point after which nothing
2412
+ can depend on the old secret any more:
2413
+ - `session.*_lifetime`
2414
+ - long-lived `ServiceSession`s
2415
+ - `oauth.refresh_token_lifetime`
2416
+ - registration access tokens, which last as long as their client
2417
+
2418
+ One-time codes and authorization codes are single-use and short-lived, so they are not rewritten.
2419
+ They need the entry only for `passwordless.code_ttl` (10 minutes by default) and the authorization
2420
+ code TTL (10 minutes).
2421
+
2422
+ This covers StandardId's own digests and HMAC-signed JWTs only. The rest of the app needs Rails'
2423
+ rotations too:
2242
2424
 
2243
2425
  - **Cookies**, including the encrypted `session_token` cookie and the Rails session that carry the
2244
2426
  web session: `config.action_dispatch.cookies_rotations` (see the Rails security guide,
@@ -2246,9 +2428,6 @@ This covers StandardId's own digests only. The rest of the app needs Rails' rota
2246
2428
  - **Message verifiers** (`generates_token_for`, so remember-me and password-reset tokens, and the
2247
2429
  signed passwordless OTP payload): `Rails.application.message_verifiers.rotate(secret_key_base:
2248
2430
  old)` in a `before_initialize` block.
2249
- - **JWTs signed with HS256** (the default `oauth.signing_algorithm`) use `secret_key_base` directly
2250
- and are not covered: access tokens fail until re-issued and HS256 refresh tokens stop refreshing.
2251
- Use an asymmetric `oauth.signing_key` if you need to rotate without that.
2252
2431
 
2253
2432
  ## OTP Start Limits
2254
2433
 
@@ -2283,12 +2462,14 @@ address with a PostgreSQL advisory lock, so two concurrent starts cannot both is
2283
2462
 
2284
2463
  - **At boot** (file-system only, no database): `config.missing_migrations` — `:warn` (default in development/test: logs and prints to stderr), `:raise` (fails boot with `StandardId::ConfigurationError`), or `:ignore` (default in every other environment — it never raises in production unless you opt in).
2285
2464
  - **`StandardId::MigrationCheck.pending(check_database: true)`** returns every gem migration that is `:not_installed` or installed but `:not_run` (one `schema_migrations` read).
2286
- - **Health check** — `StandardId::Checks::Migrations` is [standard_health](https://github.com/rarebit-one/standard_health)-compatible (duck-typed, no dependency). Register it non-critical so a missing migration degrades `/health/ready` without failing it:
2465
+ - **Health check** — `StandardId::Checks::Migrations` is [standard_health](https://github.com/rarebit-one/standard_health)-compatible (duck-typed, no dependency). With a standard_health that supports contributions, StandardId offers it through standard_health's load hook, so `c.register_default_checks` registers it, non-critical: a missing migration degrades `/health/ready` without failing it. Opt out with `c.register_default_checks standard_id_migrations: false`. With an older standard_health, register it yourself:
2287
2466
 
2288
2467
  ```ruby
2289
2468
  c.register_check :standard_id_migrations, StandardId::Checks::Migrations, critical: false
2290
2469
  ```
2291
2470
 
2471
+ The same hook declares the env vars StandardId cares about for `/diagnostics/env`: `APP_ENVIRONMENT` (recommended; it decides StandardId's production-only guards) and `STANDARD_ID_BYPASS_CODE` (forbidden in production). An entry your app declares in its own `env_spec` wins. StandardId does not depend on standard_health; without it the hook never runs.
2472
+
2292
2473
  Two cases are built in and documented in `StandardId::MigrationCheck`:
2293
2474
 
2294
2475
  - **Superseded** (`SUPERSEDED_BY`): `20260414200000_add_target_created_at_index_to_code_challenges` counts as satisfied when `20260416180511` (whose partial, concurrently built index replaces it) is installed.
@@ -27,6 +27,7 @@ module StandardId
27
27
  browser_session = StandardId::BrowserSession.eager_load(:account).by_token(session_token).first
28
28
  return nil unless browser_session&.active?
29
29
 
30
+ browser_session.rekey_token(session_token)
30
31
  browser_session.account
31
32
  end
32
33
  end
@@ -6,6 +6,10 @@ module StandardId
6
6
  if StandardId.config.alias_current_user
7
7
  define_method(:current_user) { current_account }
8
8
  end
9
+
10
+ # Only require_recent_authentication! raises it, so a controller that
11
+ # never calls the guard never reaches this.
12
+ rescue_from StandardId::StepUpRequiredError, with: :render_step_up_required
9
13
  end
10
14
 
11
15
  delegate :current_session, :current_account, :revoke_current_session!, to: :session_manager
@@ -24,6 +28,32 @@ module StandardId
24
28
  authentication_guard.require_scopes!(session_manager, *required_scopes)
25
29
  end
26
30
 
31
+ # Step-up guard for a sensitive action (opt-in, see StandardId::StepUp):
32
+ # verifies the access token, then requires its `auth_time` claim to be
33
+ # within +within+ (default c.step_up.max_age). A stale or missing
34
+ # `auth_time` raises StandardId::StepUpRequiredError, rendered as RFC 9470's
35
+ # challenge (#render_step_up_required); the client steps up through
36
+ # POST /step_up and /step_up/verify and retries with the token that returns.
37
+ # Needs c.step_up.enabled; raises StandardId::ConfigurationError otherwise.
38
+ def require_recent_authentication!(within: StandardId::StepUp.max_age)
39
+ StandardId::StepUp.ensure_usable!
40
+ api_session = verify_access_token!
41
+ return api_session if StandardId::StepUp.recent?(api_session, within: within)
42
+
43
+ raise StandardId::StepUpRequiredError.new(max_age: within)
44
+ end
45
+
46
+ # RFC 9470 §3: 401 with `error="insufficient_user_authentication"` and the
47
+ # `max_age` the authentication may have. Override to answer differently.
48
+ def render_step_up_required(error)
49
+ description = error.message
50
+ challenge = %(Bearer realm="StandardId", error="insufficient_user_authentication", error_description="#{description}")
51
+ challenge += %(, max_age=#{error.max_age}) if error.max_age
52
+ response.set_header("WWW-Authenticate", challenge)
53
+ render json: { error: "insufficient_user_authentication", error_description: description, max_age: error.max_age }.compact,
54
+ status: :unauthorized
55
+ end
56
+
27
57
  def session_manager
28
58
  @session_manager ||= StandardId::Api::SessionManager.new(token_manager, request:)
29
59
  end
@@ -376,14 +376,15 @@ module StandardId
376
376
 
377
377
  # SOCIAL_ACCOUNT_LINKED reports a link that has already committed, so it
378
378
  # cannot refuse the login: a subscriber that raises here would fail the
379
- # callback while the link stays. Its error is logged and reported to
380
- # Rails.error instead of propagating. (Guards belong on the events that
381
- # run before anything is written.)
379
+ # callback while the link stays. Its error is logged and reported
380
+ # (StandardId::ErrorReporting; Rails.error by default) instead of
381
+ # propagating. (Guards belong on the events that run before anything is
382
+ # written.)
382
383
  def emit_committed_social_link(identifier, provider)
383
384
  emit_social_account_linked(identifier.account, provider, identifier)
384
385
  rescue StandardError => e
385
386
  Rails.logger&.error("[StandardId] SOCIAL_ACCOUNT_LINKED subscriber raised after the link committed: #{e.class}: #{e.message}")
386
- Rails.error.report(e, handled: true, source: "standard_id")
387
+ StandardId::ErrorReporting.report(e, event: StandardId::Events.namespaced_event_name(StandardId::Events::SOCIAL_ACCOUNT_LINKED))
387
388
  end
388
389
 
389
390
  # A social login that recorded a link (and maybe created an account) and
@@ -23,6 +23,12 @@ module StandardId
23
23
  # session creation (for lifecycle hooks). Returns the PasswordCredential on
24
24
  # success, nil on failure.
25
25
  #
26
+ # - `require_recent_authentication!(within:)` -- Step-up guard (opt-in, see
27
+ # StandardId::StepUp): lets the action run only when the current session
28
+ # proved the account's identity within `within` (default
29
+ # c.step_up.max_age), else redirects to the step-up page and returns here
30
+ # after it.
31
+ #
26
32
  # - `session_manager` -- Returns the StandardId::Web::SessionManager instance
27
33
  # for the current request. Useful for direct session operations like
28
34
  # `session_manager.sign_in_account(account)` in passwordless flows.
@@ -79,6 +85,26 @@ module StandardId
79
85
  redirect_to_login
80
86
  end
81
87
 
88
+ # Step-up guard for a sensitive action, as a before_action:
89
+ #
90
+ # before_action -> { require_recent_authentication!(within: 5.minutes) }, only: %i[edit update]
91
+ #
92
+ # Signed out: the same redirect to login as authenticate_account!. Signed
93
+ # in, but the session last proved the account's identity longer ago than
94
+ # +within+ (or never, as for a remember-me session): redirects to
95
+ # c.step_up.url (default "/step_up"), remembering a GET's URL so the
96
+ # step-up comes back to it. Needs c.step_up.enabled; raises
97
+ # StandardId::ConfigurationError otherwise rather than silently passing or
98
+ # refusing.
99
+ def require_recent_authentication!(within: StandardId::StepUp.max_age)
100
+ StandardId::StepUp.ensure_usable!
101
+ return authenticate_account! unless authenticated?
102
+ return if StandardId::StepUp.recent?(current_session, within: within)
103
+
104
+ session[:return_to_after_step_up] = request.url if request.get?
105
+ redirect_with_inertia(StandardId.config.step_up.url.presence || "/step_up")
106
+ end
107
+
82
108
  # Store the current URL to redirect back after authentication
83
109
  def store_location_for_redirect
84
110
  session[:return_to_after_authenticating] = request.url if request.get?
@@ -129,9 +155,9 @@ module StandardId
129
155
  StandardId::PasswordCredential.find_by(login:).tap do |password_credential|
130
156
  authenticated = password_credential&.authenticate(password)
131
157
 
132
- # Perform a dummy bcrypt comparison when the credential doesn't exist
133
- # to prevent user enumeration via response timing differences.
134
- BCrypt::Password.new(dummy_password_digest).is_password?(password) unless password_credential
158
+ # Perform the dummy bcrypt comparisons when the credential doesn't
159
+ # exist to prevent user enumeration via response timing differences.
160
+ StandardId::PasswordPepper.dummy_authenticate(password) unless password_credential
135
161
 
136
162
  unless authenticated
137
163
  StandardId::Events.publish(
@@ -193,10 +219,6 @@ module StandardId
193
219
  @token_manager ||= StandardId::Web::TokenManager.new(request)
194
220
  end
195
221
 
196
- def dummy_password_digest
197
- @dummy_password_digest ||= BCrypt::Password.create("").freeze
198
- end
199
-
200
222
  def authentication_guard
201
223
  @authentication_guard ||= StandardId::Web::AuthenticationGuard.new
202
224
  end