authproto 0.3.0.beta3 → 0.3.0.beta5

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 (112) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +39 -1
  3. data/README.md +474 -311
  4. data/examples/basic_webapp/Gemfile +14 -0
  5. data/examples/{confidential_client → basic_webapp}/Gemfile.lock +1 -1
  6. data/examples/basic_webapp/README.md +300 -0
  7. data/examples/basic_webapp/app.rb +351 -0
  8. data/examples/basic_webapp/config/oauth-client-metadata.localhost.json +11 -0
  9. data/examples/basic_webapp/public/styles.css +346 -0
  10. data/examples/basic_webapp/scripts/generate_keys.rb +35 -0
  11. data/examples/basic_webapp/views/authorized.erb +48 -0
  12. data/examples/basic_webapp/views/index.erb +48 -0
  13. data/examples/{confidential_client → basic_webapp}/views/layout.erb +2 -2
  14. data/examples/bookmarks/Gemfile +16 -0
  15. data/examples/bookmarks/Gemfile.lock +158 -0
  16. data/examples/bookmarks/README.md +170 -0
  17. data/examples/bookmarks/Rakefile +23 -0
  18. data/examples/bookmarks/app/account.rb +16 -0
  19. data/examples/bookmarks/app/bookmark.rb +89 -0
  20. data/examples/bookmarks/app/init.rb +26 -0
  21. data/examples/bookmarks/app/oauth.rb +43 -0
  22. data/examples/bookmarks/app/server.rb +184 -0
  23. data/examples/bookmarks/config/oauth-client-metadata.localhost.json +11 -0
  24. data/examples/bookmarks/config/oauth-client-metadata.production.json +19 -0
  25. data/examples/bookmarks/config.ru +5 -0
  26. data/examples/bookmarks/db/migrate/20261107004141_create_bookmarks.rb +27 -0
  27. data/examples/bookmarks/db/schema.rb +33 -0
  28. data/examples/bookmarks/public/styles.css +59 -0
  29. data/examples/bookmarks/scripts/generate_keys.rb +35 -0
  30. data/examples/bookmarks/views/bookmarks.erb +86 -0
  31. data/examples/bookmarks/views/index.erb +17 -0
  32. data/examples/bookmarks/views/layout.erb +20 -0
  33. data/examples/minisky_console/Gemfile.lock +2 -2
  34. data/examples/minisky_console/README.md +29 -25
  35. data/examples/minisky_console/app.rb +3 -3
  36. data/examples/minisky_console/localhost.rb +5 -7
  37. data/examples/minisky_console/production.rb +6 -8
  38. data/lib/authproto/client.rb +505 -151
  39. data/lib/authproto/configuration.rb +1 -1
  40. data/lib/authproto/dpop/client.rb +28 -25
  41. data/lib/authproto/dpop/key_set.rb +2 -0
  42. data/lib/authproto/dpop/nonce_manager.rb +24 -25
  43. data/lib/authproto/dpop/proof_generator.rb +9 -5
  44. data/lib/authproto/dpop/stored_nonce.rb +7 -5
  45. data/lib/authproto/dpop.rb +2 -0
  46. data/lib/authproto/encryption.rb +31 -12
  47. data/lib/authproto/http_client.rb +13 -12
  48. data/lib/authproto/http_helpers.rb +6 -0
  49. data/lib/authproto/metadata/authorization_server.rb +15 -3
  50. data/lib/authproto/metadata/client_metadata.rb +34 -3
  51. data/lib/authproto/metadata/resource_server.rb +7 -6
  52. data/lib/authproto/minisky.rb +120 -33
  53. data/lib/authproto/par/client.rb +4 -2
  54. data/lib/authproto/par/client_assertion.rb +4 -1
  55. data/lib/authproto/par/request.rb +2 -0
  56. data/lib/authproto/par/response.rb +2 -0
  57. data/lib/authproto/par.rb +2 -0
  58. data/lib/authproto/pkce.rb +2 -0
  59. data/lib/authproto/serialization/session.rb +4 -2
  60. data/lib/authproto/serialization/stored_nonce.rb +2 -2
  61. data/lib/authproto/serialization/token_set.rb +5 -2
  62. data/lib/authproto/state/session.rb +23 -20
  63. data/lib/authproto/state/session_info.rb +150 -0
  64. data/lib/authproto/state/session_manager.rb +46 -19
  65. data/lib/authproto/state/token_set.rb +6 -3
  66. data/lib/authproto/state.rb +4 -2
  67. data/lib/authproto/storage/interface.rb +10 -0
  68. data/lib/authproto/storage/key_builder.rb +3 -3
  69. data/lib/authproto/storage/memory.rb +24 -18
  70. data/lib/authproto/storage/sqlite.rb +14 -0
  71. data/lib/authproto/token/identity.rb +54 -0
  72. data/lib/authproto/token/refresh.rb +44 -54
  73. data/lib/authproto/token/response.rb +75 -0
  74. data/lib/authproto/token/revocation.rb +94 -0
  75. data/lib/authproto/version.rb +1 -1
  76. data/lib/authproto.rb +6 -3
  77. data/sig/authproto/client.rbs +38 -13
  78. data/sig/authproto/dpop/client.rbs +9 -3
  79. data/sig/authproto/dpop/nonce_manager.rbs +6 -6
  80. data/sig/authproto/dpop/proof_generator.rbs +4 -4
  81. data/sig/authproto/dpop/stored_nonce.rbs +2 -2
  82. data/sig/authproto/encryption.rbs +4 -2
  83. data/sig/authproto/http_client.rbs +23 -7
  84. data/sig/authproto/http_helpers.rbs +1 -0
  85. data/sig/authproto/metadata/authorization_server.rbs +3 -3
  86. data/sig/authproto/metadata/client_metadata.rbs +2 -1
  87. data/sig/authproto/metadata/resource_server.rbs +2 -2
  88. data/sig/authproto/minisky.rbs +57 -0
  89. data/sig/authproto/state/session.rbs +13 -4
  90. data/sig/authproto/state/session_info.rbs +23 -0
  91. data/sig/authproto/state/session_manager.rbs +10 -3
  92. data/sig/authproto/storage/interface.rbs +1 -0
  93. data/sig/authproto/storage/key_builder.rbs +1 -1
  94. data/sig/authproto/storage/memory.rbs +1 -1
  95. data/sig/authproto/storage/sqlite.rbs +1 -0
  96. data/sig/authproto/token/refresh.rbs +2 -1
  97. data/sig/authproto/token/response.rbs +12 -0
  98. data/sig/authproto/token/revocation.rbs +15 -0
  99. data/sig/authproto.rbs +3 -8
  100. metadata +53 -19
  101. data/examples/confidential_client/Gemfile +0 -14
  102. data/examples/confidential_client/README.md +0 -236
  103. data/examples/confidential_client/app.rb +0 -291
  104. data/examples/confidential_client/public/styles.css +0 -70
  105. data/examples/confidential_client/scripts/generate_keys.rb +0 -21
  106. data/examples/confidential_client/views/authorized.erb +0 -46
  107. data/examples/confidential_client/views/index.erb +0 -44
  108. data/sig/authproto/minisky_oauth.rbs +0 -27
  109. /data/examples/{confidential_client/config/oauth-client-metadata.example.json → basic_webapp/config/oauth-client-metadata.production.json} +0 -0
  110. /data/examples/{confidential_client → basic_webapp}/config.ru +0 -0
  111. /data/examples/{confidential_client → basic_webapp}/screenshots/screenshot-1-sign-in.png +0 -0
  112. /data/examples/{confidential_client → basic_webapp}/screenshots/screenshot-2-success.png +0 -0
@@ -2,12 +2,12 @@
2
2
 
3
3
  require 'didkit/did'
4
4
  require 'jose'
5
- require 'json'
6
5
  require 'uri'
7
6
 
8
7
  require_relative 'configuration'
9
8
  require_relative 'dpop/client'
10
9
  require_relative 'errors'
10
+ require_relative 'http_helpers'
11
11
  require_relative 'metadata/authorization_server'
12
12
  require_relative 'metadata/client_metadata'
13
13
  require_relative 'metadata/resource_server'
@@ -18,28 +18,112 @@ require_relative 'par/request'
18
18
  require_relative 'state/session_manager'
19
19
  require_relative 'state/token_set'
20
20
  require_relative 'storage/key_builder'
21
+ require_relative 'token/identity'
21
22
  require_relative 'token/refresh'
23
+ require_relative 'token/response'
24
+ require_relative 'token/revocation'
22
25
 
23
26
  module AuthProto
24
27
 
25
28
  #
26
- # Main client class for AT Protocol OAuth implementation. Handles the complete
27
- # OAuth flow including authorization, token management, and identity verification.
29
+ # The main client class of AuthProto for authorizing and managing user sessions and making required OAuth requests.
30
+ #
31
+ # This class is the main entry point to the library, and a wrapper for most of the functionality in the other
32
+ # classes. It handles or manages:
33
+ #
34
+ # - loading and validating client metadata and resource and authorization server metadata
35
+ # - initial session authorization and generating an authorization URL
36
+ # - executing PAR requests
37
+ # - completing an authorization on an OAuth callback
38
+ # - refreshing sessions
39
+ # - generating authorization headers for data requests to the resource server (PDS)
40
+ # - handling DPoP and nonces
41
+ # - generating client assertions
42
+ # - deleting and revoking sessions
43
+ #
44
+ # A {Client} is configured for a specific Client ID and a specific redirect URI as a callback, but is not bound
45
+ # to any single user session. Session IDs are passed in the arguments to specific method calls.
46
+ #
47
+ # @example
48
+ # client = AuthProto::Client.new(
49
+ # client_id: "https://site.example.com/oauth-client-metadata.json",
50
+ # redirect_uri: "https://site.example.com/callback"
51
+ # )
52
+ #
53
+ # auth = client.authorize(
54
+ # pds: 'https://pds.example.com',
55
+ # scope: 'atproto rpc:app.bsky.feed.getTimeline?aud=*'
56
+ # )
57
+ #
58
+ # p auth[:url]
59
+ #
60
+ # # ...
61
+ #
62
+ # client.handle_callback(params, expected_session_id: auth[:session_id])
63
+ #
64
+ # url = "https://pds.example.com/xrpc/app.bsky.feed.getTimeline"
65
+ #
66
+ # response = client.with_nonce_handling(auth[:session_id], url) do
67
+ # headers = client.auth_headers(session_id: auth[:session_id], method: 'GET', url: url)
68
+ # response = Net::HTTP.get_response(URI(url), headers)
69
+ #
70
+ # {
71
+ # status: response.code,
72
+ # headers: response.to_hash,
73
+ # body: response.body
74
+ # }
75
+ # end
28
76
  #
29
77
 
30
78
  class Client
79
+ include HTTPHelpers
80
+ include Token::Identity
81
+
82
+ # An error raised when initial authorization fails.
83
+ class AuthorizationError < AuthProto::Error; end
31
84
 
32
- # Error raised when authorization callback fails
33
- class CallbackError < Error; end
85
+ #
86
+ # An error raised when authorization callback validation or authorization fails.
87
+ #
88
+
89
+ class CallbackError < AuthProto::Error
90
+
91
+ # OAuth error code returned by the authorization server, if included.
92
+ # @return [String, nil]
93
+ attr_reader :error_code
94
+
95
+ # Human-readable explanation returned by the authorization server, if included.
96
+ # @return [String, nil]
97
+ attr_reader :error_description
98
+
99
+ # URL with more information about the OAuth error, if included.
100
+ # @return [String, nil]
101
+ attr_reader :error_uri
102
+
103
+ # Creates a callback error with optional OAuth error details.
104
+ #
105
+ # @param message [String] explanation of the callback failure
106
+ # @param error_code [String, nil] `error` value from the callback URL params
107
+ # @param error_description [String, nil] `error_description` value from the callback URL params
108
+ # @param error_uri [String, nil] `error_uri` value from the callback URL params
109
+ #
110
+ def initialize(message, error_code: nil, error_description: nil, error_uri: nil)
111
+ @error_code = error_code
112
+ @error_description = error_description
113
+ @error_uri = error_uri
114
+
115
+ super(message)
116
+ end
117
+ end
34
118
 
35
- # Error raised when token operations fail
36
- class TokenError < Error; end
119
+ # An error raised when token operations fail.
120
+ class TokenError < AuthProto::Error; end
37
121
 
38
122
  #
39
- # Error raised when session operations fail
123
+ # An error raised when session operations fail.
40
124
  #
41
125
 
42
- class SessionError < Error
126
+ class SessionError < AuthProto::Error
43
127
 
44
128
  # Identifier of the session associated with the failure, if known.
45
129
  # @return [String, nil]
@@ -56,45 +140,83 @@ module AuthProto
56
140
  end
57
141
  end
58
142
 
59
- # OAuth client ID URL.
143
+ # OAuth client ID URL
60
144
  # @return [String]
61
145
  attr_reader :client_id
62
146
 
63
- # Callback URI registered in the client metadata.
147
+ # The callback URL to which the user is redirected to complete authorization
64
148
  # @return [String]
65
149
  attr_reader :redirect_uri
66
150
 
67
- # Validated client metadata.
151
+ # Parsed and validated metadata about the client
68
152
  # @return [Metadata::ClientMetadata]
69
153
  attr_reader :client_metadata
70
154
 
71
- # Manager for stored OAuth sessions.
155
+ # @api private
156
+ #
157
+ # A helper object managing stored OAuth sessions
72
158
  # @return [State::SessionManager]
73
159
  attr_reader :session_manager
74
160
 
75
- # Shared DPoP proof generator and per-server nonce manager.
76
- # @return [DPoP::Client]
77
- attr_reader :dpop_client
78
161
 
79
- # Creates an OAuth client with shared DPoP helpers and a session manager.
162
+ # Checks whether a client ID uses the localhost development URL prefix.
80
163
  #
81
- # Configure {AuthProto.configure} with an HTTP transport before fetching metadata
82
- # or starting authorization. Session storage restores the DPoP key bound to each session.
164
+ # For apps with a localhost client ID, use the {Client.for_localhost} helper to create an instance of {Client}.
83
165
  #
84
166
  # @param client_id [String] OAuth client ID URL
85
- # @param redirect_uri [String] callback URI listed in `redirect_uris`
86
- # @param metadata [Hash{String => Object}, nil] preloaded metadata, or `nil` to fetch `client_id`
87
- # @param signing_key [Hash, JOSE::JWK, nil] private ES256 client-authentication key, separate from public metadata
88
- #
89
- # @raise [InvalidClientMetadata] if metadata is invalid, unavailable, has a different client ID,
90
- # or the supplied signing key is missing, unexpected or does not match inline public metadata
91
- # @raise [PAR::ClientAssertion::Error] if the private assertion key is invalid or unusable
92
- # @raise [Error] if the redirect URI is not registered
167
+ # @return [Boolean] whether the URL starts with `http://localhost`, optionally followed by `/` or `?`
168
+ #
169
+ def self.localhost_app?(client_id)
170
+ client_id.is_a?(String) && %r{\Ahttp://localhost(?:[/?]|\z)}i.match?(client_id)
171
+ end
172
+
173
+
174
+ # Creates a localhost development client with redirect URI and scope encoded in its client ID.
175
+ #
176
+ # @param redirect_uri [String, URI::Generic] loopback callback URL used to complete authorization
177
+ # @param scope [String] space-separated scopes to declare in the generated client metadata
178
+ # @return [Client] configured localhost client
179
+ # @raise [InvalidClientMetadata] if the redirect URI or scope is invalid
180
+ #
181
+ def self.for_localhost(redirect_uri:, scope: 'atproto')
182
+ query = URI.encode_www_form(redirect_uri: redirect_uri, scope: scope)
183
+
184
+ self.new(client_id: "http://localhost/?#{query}", redirect_uri: redirect_uri)
185
+ end
186
+
187
+
188
+ # Creates an OAuth client with specified configuration.
189
+ #
190
+ # The initializer validates all passed arguments, fetches and validates the remote metadata JSON if not provided
191
+ # inline, and prepares helper objects necessary later.
192
+ #
193
+ # For localhost development:
194
+ # - pass `client_id` of `http://localhost/` with `redirect_uri` and `scope` encoded as query parameters
195
+ # - pass `redirect_uri` on `127.0.0.1` or `[::1]` hostname (optionally with port)
196
+ # - do not pass `metadata` or `signing_key`
197
+ #
198
+ # @param client_id [String] the OAuth client ID URL
199
+ # @param redirect_uri [String, URI::Generic] the callback URL to which the user is redirected to complete
200
+ # authorization; must be included on the `redirect_uris` list in the metadata
201
+ # @param metadata [Hash{String => Object}, nil] optionally, the client metadata JSON located at the client ID URL;
202
+ # if not included, it will be fetched from that URL during initialization
203
+ # @param signing_key [Hash, JOSE::JWK, nil] a private ES256 key for client authentication (client assertions)
204
+ # for confidential clients
205
+ #
206
+ # @raise [InvalidClientMetadata] if the metadata or some other parameters are invalid or don't match each other
207
+ # @raise [PAR::ClientAssertion::Error] if the signing key is invalid or not usable
93
208
  # @raise [HTTPClient::HTTPError, HTTPClient::SSRFError] if fetching client metadata fails
94
209
  #
95
210
  def initialize(client_id:, redirect_uri:, metadata: nil, signing_key: nil)
96
211
  @client_id = client_id
97
- @redirect_uri = redirect_uri
212
+ @redirect_uri = redirect_uri.is_a?(URI::Generic) ? redirect_uri.to_s : redirect_uri
213
+
214
+ if metadata && self.class.localhost_app?(client_id)
215
+ raise InvalidClientMetadata.new(
216
+ "For localhost clients, do not include metadata as a hash, " +
217
+ "but configure scope and redirect_uri through the client ID query params"
218
+ )
219
+ end
98
220
 
99
221
  if metadata && metadata['client_id'] != @client_id
100
222
  raise InvalidClientMetadata, "client_id mismatch: #{metadata['client_id']} != #{@client_id}"
@@ -107,42 +229,51 @@ module AuthProto
107
229
  initialize_client_assertion(signing_key)
108
230
 
109
231
  signing_keys = @client_assertion ? { @signing_key_kid => @signing_key_thumbprint } : {}
110
- @session_manager = State::SessionManager.new(supported_signing_keys: signing_keys)
232
+ @session_manager = State::SessionManager.new(client_id: @client_id, supported_signing_keys: signing_keys)
111
233
 
112
234
  @dpop_client = DPoP::Client.new
113
235
  end
114
236
 
115
- # Starts authorization, stores a pending session, and submits a PAR request.
237
+
238
+ # Starts the authorization process, creates a pending session, and submits a PAR request, then generates an
239
+ # authorization URL that the user should log in on.
240
+ #
241
+ # Requires either a `handle` or a `pds` argument, but not both at the same time. If `handle` is passed, the user's
242
+ # PDS is looked up from the DID document and the user is directed there with a "login hint"; otherwise, the
243
+ # authorization begins on the given PDS, but without a pre-selected account.
116
244
  #
117
- # Supply exactly one of `handle` or `pds`. Open the returned `:url` in a browser
118
- # and pass the eventual callback parameters to {#handle_callback}. Retain `:session_id`
119
- # in the initiating browser session or native login context for callback verification.
245
+ # Returns a hash containing a `:url` and a `:session_id`. Direct the user to the returned authorization URL,
246
+ # and store the session ID in a local context or a browser session, since it will be needed to complete
247
+ # authorization at the callback endpoint.
120
248
  #
121
- # @param handle [String, nil] account handle (optionally prefixed with `@`) or DID
122
- # @param pds [String, nil] PDS URL when no handle is supplied
123
- # @param scope [String] space-separated scopes, which must all be declared in client metadata, including `atproto`
249
+ # @param handle [String, nil] account handle (may be prefixed with a `@`) or a DID string
250
+ # @param pds [String, URI::HTTPS, nil] full URL of the PDS to authorize the user on
251
+ # @param scope [String] space-separated list of scopes to request authorization for; the scopes must all be
252
+ # declared in the client metadata, and must include `atproto`
124
253
  #
125
- # @return [Hash{Symbol => String}] `:url` is the browser URL; `:session_id` identifies the pending session
126
- # @raise [Error] if identity arguments or scope are invalid, the handle cannot be verified, or no HTTPS PDS is found
254
+ # @return [Hash{Symbol => String}] `:url` to direct the user to, `:session_id` of the created session
255
+ #
256
+ # @raise [AuthorizationError] if identity arguments or scope are invalid or identity can't be resolved
127
257
  # @raise [DIDKit::DIDError, DIDKit::FormatError, DIDKit::APIError] if DID validation or document fetching fails
258
+ # @raise [Encryption::EncryptionError] if session serialization cannot encrypt secrets
259
+ # @raise [HTTPClient::SSRFError] if server discovery rejects a destination
128
260
  # @raise [InvalidAuthorizationServer] if server discovery or metadata validation fails
129
- # @raise [PAR::Error] if the pushed authorization request fails
130
- # @raise [PAR::ClientAssertion::Error] if confidential-client signing fails
131
261
  # @raise [DPoP::Client::Error] if generating the PAR proof fails
132
- # @raise [HTTPClient::SSRFError] if server discovery rejects a destination
133
262
  # @raise [DPoP::KeySet::KeyError] if generating the session key fails
263
+ # @raise [PAR::ClientAssertion::Error] if client assertion signing fails
264
+ # @raise [PAR::Error] if the pushed authorization request fails
134
265
  # @raise [Storage::StorageError] if session storage or locking fails
135
- # @raise [Encryption::EncryptionError] if session serialization cannot encrypt secrets
136
266
  #
137
267
  def authorize(handle: nil, pds: nil, scope: 'atproto')
138
268
  validate_auth_params(handle, pds, scope)
269
+ pds = pds.to_s if pds.is_a?(URI::HTTP)
139
270
 
140
271
  if !pds
141
272
  did = DIDKit::DID.resolve_handle(handle)
142
- raise Error, "Could not resolve or verify identity #{handle}" unless did
273
+ raise AuthorizationError, "Could not resolve or verify identity #{handle}" unless did
143
274
 
144
275
  pds = did.document.pds_endpoint
145
- raise Error, "No HTTPS PDS location found for #{did}" unless pds && URI(pds).is_a?(URI::HTTPS)
276
+ raise AuthorizationError, "No HTTPS PDS location found for #{did}" unless pds && URI(pds).is_a?(URI::HTTPS)
146
277
  end
147
278
 
148
279
  authorization_server = resolve_auth_server_info(pds)
@@ -152,6 +283,7 @@ module AuthProto
152
283
  scope: scope,
153
284
  auth_server: authorization_server,
154
285
  did: did&.to_s,
286
+ pds: pds,
155
287
  signing_key_id: @signing_key_kid
156
288
  )
157
289
 
@@ -163,38 +295,45 @@ module AuthProto
163
295
  }
164
296
  end
165
297
 
166
- # Validates a callback, exchanges its code, and stores the authenticated session.
298
+
299
+ # Validates received callback parameters, exchanges the code for access tokens, and stores the
300
+ # authenticated session.
301
+ #
302
+ # Call this method from the callback endpoint to which the user is redirected after authorizing access for your
303
+ # app on their PDS. The callback should include `:code`, `:state` and `:iss` params, which you need to pass here
304
+ # (unless the authorization was denied or otherwise failed, in which case it will include an `:error` param).
305
+ #
306
+ # Additionally, you need to provide the `session_id` of the pending session, received earlier in the response
307
+ # from the {#authorize} method. Make sure to confirm that this is the same session that has started the process
308
+ # earlier: take the session ID either from a local context for scripts, or from the initiating browser session for
309
+ # web apps, do not infer it from the received callback parameters.
167
310
  #
168
- # The result contains `:access_token` (String), `:token_type` (String, `DPoP`),
169
- # `:expires_in` (Integer seconds remaining), `:refresh_token` (String or nil),
170
- # and `:scope` (String).
171
- # It also contains `:session_id` (String) and `:did` (String).
311
+ # Returns a {State::SessionInfo} object with the session data.
172
312
  #
173
- # Supply the session ID retained when starting authorization as `expected_session_id`.
174
- # For web apps, read it from the initiating browser's session, never from callback parameters
175
- # or the state-token lookup. It is checked before exchanging the authorization code.
176
- # Remove the browser's pending-session association after this method succeeds.
313
+ # @param callback_params [Hash{String, Symbol => Object}] callback query parameters from the URL the user gets
314
+ # redirected to after authorization (should contain `code`, `state` and `iss`, or `error`)
315
+ # @param expected_session_id [String] pending session ID previously received from {#authorize}
177
316
  #
178
- # @param code [String] authorization code from the callback
179
- # @param state [String] state token from the callback
180
- # @param iss [String] issuer URL from the callback
181
- # @param expected_session_id [String] pending session ID retained by the caller when authorization started
317
+ # @return [State::SessionInfo] current tokens and session data
182
318
  #
183
- # @return [Hash{Symbol => String, Integer, nil}] tokens and authenticated session details
184
- # @raise [CallbackError] if the expected session ID is invalid, state is unknown, or session/issuer validation fails
185
- # @raise [TokenError] if token exchange or response validation fails
186
- # @raise [DPoP::Client::Error, PAR::ClientAssertion::Error] if proof/assertion generation fails
319
+ # @raise [ArgumentError] if returned token fields fail token-set validation
320
+ # @raise [CallbackError] if parameters are invalid, the server returns an OAuth error, the expected session ID
321
+ # is invalid, state is unknown, or session/issuer validation fails
322
+ # @raise [DPoP::Client::Error] if proof/assertion generation fails
323
+ # @raise [Encryption::EncryptionError] if tokens cannot be encrypted for storage
187
324
  # @raise [HTTPClient::HTTPError, HTTPClient::SSRFError] if token transport fails
325
+ # @raise [PAR::ClientAssertion::Error] if proof/assertion generation fails
188
326
  # @raise [State::SessionError] if token subject conflicts with the session DID
189
- # @raise [ArgumentError] if returned token fields fail token-set validation
190
327
  # @raise [Storage::StorageError] if session storage or locking fails
191
- # @raise [Encryption::EncryptionError] if tokens cannot be encrypted for storage
328
+ # @raise [TokenError] if token exchange or response validation fails; identity failures attempt token revocation
192
329
  #
193
- def handle_callback(code:, state:, iss:, expected_session_id:)
330
+ def handle_callback(callback_params, expected_session_id:)
194
331
  unless expected_session_id.is_a?(String) && !expected_session_id.empty?
195
332
  raise CallbackError, "Expected session ID is required"
196
333
  end
197
334
 
335
+ params = validate_callback_params(callback_params)
336
+ code, state, iss = params.values_at('code', 'state', 'iss')
198
337
  session = session_manager.get_session_by_state_token(state)
199
338
 
200
339
  raise CallbackError, "Invalid state parameter" unless session
@@ -202,16 +341,7 @@ module AuthProto
202
341
  raise CallbackError, "Issuer mismatch" unless session.auth_server && session.auth_server.issuer == iss
203
342
 
204
343
  AuthProto.storage.with_lock(Storage::KeyBuilder.lock_key("session", session.session_id), ttl: 30) do
205
- response = exchange_code(code: code, session: session)
206
-
207
- token_set = State::TokenSet.new(
208
- access_token: response['access_token'],
209
- token_type: response['token_type'],
210
- expires_in: response['expires_in'],
211
- refresh_token: response['refresh_token'],
212
- scope: response['scope'],
213
- sub: response['sub']
214
- )
344
+ token_set = exchange_code(code: code, session: session)
215
345
 
216
346
  session.tokens = token_set
217
347
  session_manager.complete_authorization(session)
@@ -220,48 +350,46 @@ module AuthProto
220
350
  end
221
351
  end
222
352
 
223
- # Reads tokens for a session with a currently valid access token.
353
+
354
+ # Looks up an existing session by ID.
224
355
  #
225
- # The result contains `:access_token` (String), `:token_type` (String, `DPoP`),
226
- # `:expires_in` (Integer seconds remaining), `:refresh_token` (String or nil),
227
- # and `:scope` (String).
228
- # It also contains `:session_id` (String) and `:did` (String).
229
- # This method does not refresh expired tokens.
356
+ # The returned session may not always be immediately usable for making authenticated requests. A matched
357
+ # session is returned if it's pending or authorized, and possibly with expired access token, but renewable.
358
+ # The method returns nil if a session is found but it's either an expired pending session that cannot
359
+ # finish authorization, or a session with expired access token but no refresh token to replace it with.
360
+ #
361
+ # Use methods on {State::SessionInfo} like {State::SessionInfo#pending?}, {State::SessionInfo#authorized?}
362
+ # or {State::SessionInfo#renewable?} to check the status of the returned session.
230
363
  #
231
364
  # @param session_id [String] session identifier
232
- # @return [Hash{Symbol => String, Integer, nil}, nil] token details, or `nil` for missing/unauthorized sessions
365
+ # @return [State::SessionInfo, nil] current session data, or `nil` if unavailable or no longer usable
233
366
  #
234
- def get_tokens(session_id)
235
- session = session_manager.get_session(session_id)
236
- return nil unless session && session.tokens_valid?
237
-
238
- session.session_data
367
+ def get_session(session_id)
368
+ session_manager.get_session(session_id)&.session_data
239
369
  end
240
370
 
241
- # Refreshes a renewable session and persists the replacement tokens.
371
+
372
+ # Looks up a session using given ID and refreshes its set of tokens.
242
373
  #
243
- # The result contains `:access_token` (String), `:token_type` (String, `DPoP`),
244
- # `:expires_in` (Integer seconds remaining), `:refresh_token` (String or nil),
245
- # and `:scope` (String).
246
- # The result also contains `:session_id` (String) and `:did` (String). An expired access token can
247
- # still be refreshed when the stored session has a refresh token.
374
+ # Returns a {State::SessionInfo} object with the session data.
248
375
  #
249
376
  # @param session_id [String] session to refresh
250
- # @return [Hash{Symbol => String, Integer, nil}] replacement tokens and session identifiers
251
- # @raise [TokenError] if the session is missing or has no refresh token
252
- # @raise [Token::RefreshError] if token refresh fails or exhausts retries
377
+ # @return [State::SessionInfo] current tokens and session data
378
+ #
253
379
  # @raise [DPoP::Client::Error] if a refresh response lacks a valid nonce
380
+ # @raise [Encryption::EncryptionError] if replacement tokens cannot be stored
254
381
  # @raise [State::SessionError] if replacement tokens have a different subject
255
382
  # @raise [Storage::StorageError] if session storage or locking fails
256
- # @raise [Encryption::EncryptionError] if replacement tokens cannot be stored
383
+ # @raise [TokenError] if the session is missing or has no refresh token
384
+ # @raise [Token::RefreshError] if the current PDS differs or token refresh fails
257
385
  #
258
386
  def refresh_token(session_id)
259
- session = session_manager.get_session(session_id)
387
+ AuthProto.storage.with_lock(Storage::KeyBuilder.lock_key('session', session_id), ttl: 30) do
388
+ session = session_manager.get_session(session_id)
260
389
 
261
- raise TokenError, "Invalid session" unless session
262
- raise TokenError, "Session not authorized" unless session.renewable?
390
+ raise TokenError, "Invalid session" unless session
391
+ raise TokenError, "Session not authorized" unless session.renewable?
263
392
 
264
- AuthProto.storage.with_lock(Storage::KeyBuilder.lock_key("session", session.session_id), ttl: 30) do
265
393
  refresher = Token::Refresh.new(
266
394
  session: session,
267
395
  dpop_client: @dpop_client,
@@ -279,27 +407,45 @@ module AuthProto
279
407
  end
280
408
  end
281
409
 
282
- # Checks if a session has valid tokens
410
+
411
+ # Returns the global HTTP client configured through `AuthProto.configuration`.
412
+ #
413
+ # @return [#get, #post, nil] configured HTTP client, or `nil` when not configured
414
+ #
415
+ def http
416
+ AuthProto.configuration.http_client
417
+ end
418
+
419
+
420
+ # Checks if a session with given ID exists and has valid and not expired tokens.
283
421
  #
284
- # @param session_id [String] ID of session to check
285
- # @return [Boolean] true if session exists and has valid tokens
422
+ # @param session_id [String] ID of a session to look up
423
+ # @return [Boolean] true if the session exists, is authenticated, and its access token is not expired
286
424
  #
287
425
  def authorized?(session_id)
288
426
  session = session_manager.get_session(session_id)
289
427
  session ? session.tokens_valid? : false
290
428
  end
291
429
 
292
- # Builds authorization headers and a fresh DPoP proof for one HTTP request.
430
+
431
+ # Generates required authorization headers for a new HTTP request to user's resource server (PDS).
432
+ #
433
+ # The {Client} does not send the request itself; the headers are returned to the caller so you can add them
434
+ # to a request made using an HTTP client library of your choice.
435
+ #
436
+ # Returns two headers:
437
+ # - `Authorization: DPoP <access_token>`
438
+ # - `DPoP: <dpop_proof>`
293
439
  #
294
- # The caller sends the request. This method does not refresh tokens, send HTTP,
295
- # or retry nonce challenges. Feed each full HTTP response to {DPoP::Client#process_response}
296
- # and call {#refresh_token} explicitly when needed. Generate new headers for each retry.
440
+ # New set of headers are needed for each new HTTP request, including repeated requests with an updated DPoP nonce
441
+ # or refreshed access token. After the request, the response should be passed to {#process_dpop} so the DPoP
442
+ # handling code can update the stored nonce.
297
443
  #
298
- # @param session_id [String] authorized session ID
444
+ # @param session_id [String] session ID of an authorized session
299
445
  # @param method [String] HTTP method for the proof
300
- # @param url [String] absolute request URL without a query string or fragment
446
+ # @param url [String, URI::HTTPS] absolute HTTPS URL of the request; the query string and fragment are ignored
301
447
  #
302
- # @return [Hash{String => String}] `Authorization: DPoP ...` and `DPoP` proof headers
448
+ # @return [Hash{String => String}] headers to attach to an outgoing request
303
449
  # @raise [TokenError] if the session is missing or its access token is expired
304
450
  # @raise [DPoP::Client::Error] if proof generation or nonce lookup fails
305
451
  #
@@ -310,7 +456,7 @@ module AuthProto
310
456
  raise TokenError, "Session not authorized" if session.pending?
311
457
  raise TokenError, "Session has expired" unless session.tokens_valid?
312
458
 
313
- dpop_proof = dpop_client.generate_proof(
459
+ dpop_proof = @dpop_client.generate_proof(
314
460
  session: session,
315
461
  method: method,
316
462
  uri: url,
@@ -323,29 +469,156 @@ module AuthProto
323
469
  }
324
470
  end
325
471
 
326
- # Removes a stored session and its state-token lookup.
472
+
473
+ # Updates the stored DPoP server nonce from the `DPoP-Nonce` header returned in the given response.
327
474
  #
328
- # @param session_id [String] session identifier
475
+ # The response is expected to be in a hash format:
476
+ #
477
+ # ```rb
478
+ # {
479
+ # status: 200,
480
+ # headers: { ... }, # string keys and values
481
+ # body: "..." # string, not parsed JSON
482
+ # }
483
+ # ```
484
+ #
485
+ # @param response [Hash{Symbol => Object}] HTTP response hash with `:status`, `:headers`, and `:body`
486
+ # @param url [String, URI::HTTPS] URL of the request that produced the response (only the origin is used)
487
+ # @param session_id [String] ID of the session that made the request
329
488
  # @return [void]
330
- # @raise [Storage::StorageError] if deletion or locking fails
489
+ # @raise [DPoP::Client::Error] if the response or nonce is invalid or storage fails
331
490
  #
332
- def delete_session(session_id)
333
- session_manager.delete_session(session_id)
491
+ def process_dpop(response, url:, session_id:)
492
+ @dpop_client.process_response(response, url: url, session_id: session_id)
334
493
  end
335
494
 
336
- # Invokes the session manager's expiry cleanup hook.
495
+
496
+ # Checks whether an HTTP response indicates that the server has rejected the request, requiring a retry
497
+ # with a new DPoP nonce.
498
+ #
499
+ # The response is expected to be in a hash format:
500
+ #
501
+ # ```rb
502
+ # {
503
+ # status: 200,
504
+ # headers: { ... }, # string keys and values
505
+ # body: "..." # string, not parsed JSON
506
+ # }
507
+ # ```
508
+ #
509
+ # @param response [Hash{Symbol => Object}] HTTP response hash with `:status`, `:headers`, and `:body`
510
+ # @return [Boolean] if the response is a `use_dpop_nonce` error
511
+ # @raise [DPoP::Client::Error] if the response hash is invalid
512
+ #
513
+ def has_nonce_error?(response)
514
+ @dpop_client.has_nonce_error?(response)
515
+ end
516
+
517
+
518
+ # A helper for making a request with a possible retry with an updated DPoP nonce.
519
+ #
520
+ # Pass a block to this method, which makes a request to the resource or authorization server and returns the
521
+ # received response in a hash format:
522
+ #
523
+ # ```rb
524
+ # {
525
+ # status: 200,
526
+ # headers: { ... }, # string keys and values
527
+ # body: "..." # string, not parsed JSON
528
+ # }
529
+ # ```
530
+ #
531
+ # The method will run that block, process the headers from the received response, store the returned DPoP nonce,
532
+ # and if the response indicates a `use_dpop_nonce` error, it will call the block again to let you repeat the
533
+ # request with a new nonce. Returns the response from the final request, including if the second attempt returns
534
+ # an error response.
337
535
  #
338
- # Currently a no-op; expiry is checked during retrieval and by storage TTLs.
536
+ # @example using with Net::HTTP
537
+ # uri = URI.join(pds_url, '/xrpc/app.bsky.feed.getTimeline')
339
538
  #
539
+ # response = client.with_nonce_handling(session_id, uri) do
540
+ # headers = client.auth_headers(session_id: session_id, method: 'GET', url: uri)
541
+ # response = Net::HTTP.get_response(uri, headers)
542
+ #
543
+ # {
544
+ # status: response.code,
545
+ # headers: response.to_hash,
546
+ # body: response.body
547
+ # }
548
+ # end
549
+ #
550
+ # @example using with AuthProto's HTTPClient
551
+ # uri = URI.join(pds_url, '/xrpc/app.bsky.feed.getTimeline')
552
+ #
553
+ # response = client.with_nonce_handling(session_id, uri) do
554
+ # headers = client.auth_headers(session_id: session_id, method: 'GET', url: uri)
555
+ #
556
+ # client.http.get(uri, headers)
557
+ # end
558
+ #
559
+ # @param session_id [String] ID of the session making the request
560
+ # @param url [String, URI::HTTPS] URL of the request (only origin is used)
561
+ # @yield a block that generates fresh authorization headers and send a request with them
562
+ # @yieldreturn [Hash{Symbol => Object}] HTTP response with `:status`, `:headers`, and `:body`
563
+ #
564
+ # @return [Hash{Symbol => Object}] the final response
565
+ # @raise [DPoP::Client::Error] if the response or nonce is invalid or storage fails
566
+ #
567
+ def with_nonce_handling(session_id, url, &block)
568
+ @dpop_client.with_nonce_handling(session_id, url, &block)
569
+ end
570
+
571
+
572
+ # Removes the session's data from the session storage. If `revoke: true` is passed, additionally attempts to
573
+ # revoke the access & refresh tokens on the authorization server first, if a revoke endpoint is available.
574
+ #
575
+ # Does nothing if the session is not found. If the server has no revoke endpoint or the session is not
576
+ # authorized yet, session is only removed from the app's storage. If token revocation is attempted but fails,
577
+ # an error is raised and the session is *not* removed locally (if refresh token is successfully revoked,
578
+ # subsequent access token revocation is allowed to fail).
579
+ #
580
+ # @param session_id [String] session identifier
581
+ # @param revoke [Boolean] revoke the refresh token (if present) and access token before local deletion
340
582
  # @return [void]
341
583
  #
342
- def cleanup_expired_sessions
343
- session_manager.cleanup_expired
584
+ # @raise [DPoP::Client::Error, HTTPClient::HTTPError] if revocation proof or transport handling fails
585
+ # @raise [Storage::StorageError] if deletion or locking fails
586
+ # @raise [Token::Revocation::Error] if a required revocation request is rejected
587
+ #
588
+ def delete_session(session_id, revoke: false)
589
+ AuthProto.storage.with_lock(Storage::KeyBuilder.lock_key('session', session_id), ttl: 30) do
590
+ session = session_manager.get_session(session_id)
591
+ return unless session
592
+
593
+ if revoke && session.tokens && session.can_be_revoked?
594
+ revocation = Token::Revocation.new(
595
+ session: session,
596
+ dpop_client: @dpop_client,
597
+ client_metadata: @client_metadata,
598
+ client_assertion: @client_assertion
599
+ )
600
+
601
+ if session.tokens.refresh_token
602
+ revocation.revoke_token(session.tokens.refresh_token, :token_type => :refresh_token)
603
+ refresh_revoked = true
604
+ end
605
+
606
+ begin
607
+ revocation.revoke_token(session.tokens.access_token, :token_type => :access_token)
608
+ rescue StandardError
609
+ raise unless refresh_revoked
610
+ end
611
+ end
612
+
613
+ session_manager.delete_session(session_id)
614
+ end
344
615
  end
345
616
 
346
617
 
347
618
  private
348
619
 
620
+ # --- used in initialize ---
621
+
349
622
  def load_client_metadata(metadata)
350
623
  if metadata
351
624
  Metadata::ClientMetadata.new(metadata)
@@ -355,9 +628,35 @@ module AuthProto
355
628
  end
356
629
 
357
630
  def validate_redirect_uri
358
- unless @client_metadata.redirect_uris.include?(@redirect_uri)
359
- raise Error, "redirect_uri not found in client metadata"
631
+ return if @client_metadata.redirect_uris.include?(@redirect_uri)
632
+
633
+ # localhost development exception
634
+ if URI(@client_id).scheme == 'http'
635
+ components = loopback_redirect_components(@redirect_uri)
636
+
637
+ if components && @client_metadata.redirect_uris.any? { |uri| loopback_redirect_components(uri) == components }
638
+ return
639
+ end
360
640
  end
641
+
642
+ raise InvalidClientMetadata, "redirect_uri not found in client metadata"
643
+ end
644
+
645
+ def loopback_redirect_components(url)
646
+ uri = URI(url)
647
+
648
+ unless uri.is_a?(URI::HTTP) && uri.scheme == 'http' && ['127.0.0.1', '[::1]'].include?(uri.host) &&
649
+ !uri.userinfo && !uri.fragment && uri.port.between?(1, 65_535)
650
+ return nil
651
+ end
652
+
653
+ # compare the localhost URLs while ignoring the port
654
+ # "redirect_uri (string, multiple query parameters allowed, optional):
655
+ # allows declaring a local redirect/callback URL, with path component matched but port numbers ignored"
656
+
657
+ URI.split(url).tap { |components| components[3] = nil }
658
+ rescue URI::InvalidURIError
659
+ nil
361
660
  end
362
661
 
363
662
  def initialize_client_assertion(key)
@@ -395,22 +694,26 @@ module AuthProto
395
694
  %w[kid kty crv x y].all? { |field| candidate[field] == public_key[field] }
396
695
  end
397
696
 
697
+
698
+ # --- used in authorize ---
699
+
398
700
  def validate_auth_params(handle, pds, scope)
399
701
  unless scope.is_a?(String) && scope.valid_encoding? && Metadata::ClientMetadata::SCOPE_PATTERN.match?(scope)
400
- raise Error, "scope must contain valid tokens separated by single spaces"
702
+ raise ArgumentError, "scope must contain valid tokens separated by single spaces"
401
703
  end
402
704
 
403
705
  requested_scopes = scope.split(' ')
404
- raise Error, "scope must include 'atproto'" unless requested_scopes.include?('atproto')
706
+ raise ArgumentError, "scope must include 'atproto'" unless requested_scopes.include?('atproto')
405
707
 
406
- undeclared_scopes = requested_scopes - @client_metadata.scope.split(' ')
708
+ undeclared = requested_scopes - @client_metadata.scope.split(' ')
407
709
 
408
- unless undeclared_scopes.empty?
409
- raise Error, "scope contains values not declared in client metadata: #{undeclared_scopes.join(' ')}"
710
+ unless undeclared.empty?
711
+ raise ArgumentError, "scope contains values not declared in client metadata: #{undeclared.join(' ')}"
410
712
  end
411
713
 
412
- raise Error, "handle or pds must be provided" if handle.nil? && pds.nil?
413
- raise Error, "cannot provide both handle and pds" if handle && pds
714
+ raise ArgumentError, "handle or pds must be provided" if handle.nil? && pds.nil?
715
+ raise ArgumentError, "cannot provide both handle and pds" if handle && pds
716
+ raise ArgumentError, "pds must be a full URL" if pds && URI(pds).class == URI::Generic
414
717
  end
415
718
 
416
719
  def resolve_auth_server_info(pds)
@@ -430,7 +733,7 @@ module AuthProto
430
733
  req.client_id = @client_id
431
734
  req.redirect_uri = @redirect_uri
432
735
  req.state = session.state_token
433
- req.scope = session.scope
736
+ req.scope = session.requested_scope
434
737
  req.login_hint = login_hint if login_hint
435
738
  req.code_challenge = session.pkce_challenge
436
739
 
@@ -447,26 +750,61 @@ module AuthProto
447
750
  )
448
751
  end
449
752
 
450
- def exchange_code(code:, session:)
451
- response = dpop_client.with_nonce_handling(session, session.auth_server.token_endpoint) do
452
- make_token_request(code, session)
753
+
754
+ # --- used in handle_callback ---
755
+
756
+ def validate_callback_params(callback_params)
757
+ raise CallbackError, "Callback parameters must be a hash" unless callback_params.is_a?(Hash)
758
+
759
+ params = callback_params.transform_keys(&:to_s)
760
+
761
+ if params.key?('error')
762
+ unless params['error'].is_a?(String) && !params['error'].empty?
763
+ raise CallbackError, "Callback error must be a nonempty string"
764
+ end
765
+
766
+ %w[error_description error_uri].each do |field|
767
+ unless params[field].nil? || params[field].is_a?(String)
768
+ raise CallbackError, "Callback #{field} must be a string"
769
+ end
770
+ end
771
+
772
+ message = [params['error'], params['error_description']].compact.join(": ")
773
+
774
+ raise CallbackError.new(
775
+ "Authorization failed: #{message}",
776
+ error_code: params['error'],
777
+ error_description: params['error_description'],
778
+ error_uri: params['error_uri']
779
+ )
780
+ end
781
+
782
+ %w[code state iss].each do |field|
783
+ unless params[field].is_a?(String) && !params[field].empty?
784
+ raise CallbackError, "Callback #{field} must be a nonempty string"
785
+ end
453
786
  end
454
787
 
455
- raise TokenError, "Token request failed: #{response[:status]}" unless response[:status] == 200
788
+ params
789
+ end
456
790
 
457
- begin
458
- data = JSON.parse(response[:body])
459
- rescue JSON::ParserError => e
460
- raise TokenError, "Invalid token response: #{e.message}"
791
+ def exchange_code(code:, session:)
792
+ response = @dpop_client.with_nonce_handling(session.session_id, session.auth_server.token_endpoint) do
793
+ make_token_request(code, session)
461
794
  end
462
795
 
463
- validate_token_response(data, session)
796
+ raise TokenError, "Token request failed: #{response[:status]}" unless response_status(response) == 200
464
797
 
465
- data
798
+ tokens = Token::Response.parse(response)
799
+ validate_token_identity(tokens, session)
800
+
801
+ tokens
802
+ rescue Token::Response::Error => e
803
+ raise TokenError, e.message
466
804
  end
467
805
 
468
806
  def make_token_request(code, session)
469
- dpop_proof = dpop_client.generate_proof(
807
+ dpop_proof = @dpop_client.generate_proof(
470
808
  session: session,
471
809
  method: 'POST',
472
810
  uri: session.auth_server.token_endpoint
@@ -487,7 +825,7 @@ module AuthProto
487
825
  )
488
826
  end
489
827
 
490
- AuthProto.configuration.http_client.post(
828
+ http.post(
491
829
  session.auth_server.token_endpoint,
492
830
  body: body,
493
831
  headers: {
@@ -497,19 +835,35 @@ module AuthProto
497
835
  )
498
836
  end
499
837
 
500
- def validate_token_response(response, session)
501
- ['access_token', 'token_type', 'expires_in', 'scope', 'sub'].each do |field|
502
- raise TokenError, "Missing #{field} in token response" unless response[field]
838
+ def validate_token_identity(tokens, session)
839
+ if session.did
840
+ raise Token::IdentityMismatchError, "Subject mismatch in token response" if session.did != tokens.sub
841
+ else
842
+ validate_subject_pds(tokens.sub, session)
503
843
  end
844
+ rescue Token::IdentityMismatchError => e
845
+ revoke_rejected_refresh_token(tokens.refresh_token, session) if tokens.refresh_token
846
+ raise TokenError, e.message
847
+ rescue Token::IdentityLookupError => e
848
+ raise TokenError, "#{e.message}; start authorization again"
849
+ rescue Token::IdentityError => e
850
+ raise TokenError, e.message
851
+ end
504
852
 
505
- unless response['token_type'].is_a?(String) && response['token_type'].casecmp?('DPoP')
506
- raise TokenError, "Invalid token_type: #{response['token_type']}"
507
- end
853
+ def revoke_rejected_refresh_token(token, session)
854
+ return unless session.can_be_revoked?
508
855
 
509
- raise TokenError, "Missing atproto scope in token response" unless response['scope'].split.include?('atproto')
856
+ revocation = Token::Revocation.new(
857
+ session: session,
858
+ dpop_client: @dpop_client,
859
+ client_metadata: @client_metadata,
860
+ client_assertion: @client_assertion
861
+ )
510
862
 
511
- # If we have a pre-resolved DID, verify that it matches
512
- raise TokenError, "Subject mismatch in token response" if session.did && session.did != response['sub']
863
+ revocation.revoke_token(token, token_type: 'refresh_token')
864
+ rescue StandardError
865
+ # Cleanup failures must not replace the original identity error.
866
+ nil
513
867
  end
514
868
  end
515
869
  end