authproto 0.3.0.beta1 → 0.3.0.beta3

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 (91) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +67 -7
  3. data/README.md +128 -5
  4. data/examples/confidential_client/Gemfile.lock +5 -1
  5. data/examples/confidential_client/README.md +12 -2
  6. data/examples/confidential_client/app.rb +23 -22
  7. data/examples/confidential_client/config/{client-metadata.example.json → oauth-client-metadata.example.json} +0 -1
  8. data/examples/confidential_client/scripts/generate_keys.rb +15 -9
  9. data/examples/minisky_console/Gemfile.lock +2 -2
  10. data/examples/minisky_console/README.md +20 -1
  11. data/examples/minisky_console/localhost.rb +13 -28
  12. data/examples/minisky_console/production.rb +10 -4
  13. data/lib/authproto/client.rb +185 -253
  14. data/lib/authproto/configuration.rb +37 -16
  15. data/lib/authproto/dpop/client.rb +96 -79
  16. data/lib/authproto/dpop/key_set.rb +157 -0
  17. data/lib/authproto/dpop/nonce_manager.rb +38 -39
  18. data/lib/authproto/dpop/proof_generator.rb +39 -50
  19. data/lib/authproto/dpop.rb +19 -0
  20. data/lib/authproto/errors.rb +1 -1
  21. data/lib/authproto/http_client.rb +17 -31
  22. data/lib/authproto/http_helpers.rb +85 -0
  23. data/lib/authproto/localhost_server.rb +15 -6
  24. data/lib/authproto/metadata/authorization_server.rb +364 -0
  25. data/lib/authproto/metadata/client_metadata.rb +587 -0
  26. data/lib/authproto/metadata/resource_server.rb +139 -0
  27. data/lib/authproto/{server_metadata.rb → metadata.rb} +7 -7
  28. data/lib/authproto/minisky.rb +41 -41
  29. data/lib/authproto/par/client.rb +60 -115
  30. data/lib/authproto/par/client_assertion.rb +95 -21
  31. data/lib/authproto/par/request.rb +60 -146
  32. data/lib/authproto/par/response.rb +9 -10
  33. data/lib/authproto/par.rb +5 -6
  34. data/lib/authproto/pkce.rb +29 -106
  35. data/lib/authproto/serialization/session.rb +36 -18
  36. data/lib/authproto/serialization/token_set.rb +6 -7
  37. data/lib/authproto/state/session.rb +93 -37
  38. data/lib/authproto/state/session_manager.rb +97 -23
  39. data/lib/authproto/state/token_set.rb +19 -19
  40. data/lib/authproto/state.rb +4 -4
  41. data/lib/authproto/storage/key_builder.rb +3 -11
  42. data/lib/authproto/storage/memory.rb +8 -2
  43. data/lib/authproto/token/refresh.rb +50 -91
  44. data/lib/authproto/validated_uri.rb +80 -0
  45. data/lib/authproto/version.rb +1 -1
  46. data/lib/authproto.rb +1 -1
  47. data/sig/authproto/client.rbs +11 -14
  48. data/sig/authproto/dependencies.rbs +2 -0
  49. data/sig/authproto/dpop/client.rbs +9 -9
  50. data/sig/authproto/dpop/{key_manager.rbs → key_set.rbs} +9 -11
  51. data/sig/authproto/dpop/nonce_manager.rbs +4 -5
  52. data/sig/authproto/dpop/proof_generator.rbs +10 -15
  53. data/sig/authproto/dpop.rbs +6 -0
  54. data/sig/authproto/http_client.rbs +2 -2
  55. data/sig/authproto/http_helpers.rbs +7 -0
  56. data/sig/authproto/localhost_server.rbs +1 -1
  57. data/sig/authproto/{server_metadata → metadata}/authorization_server.rbs +19 -12
  58. data/sig/authproto/metadata/client_metadata.rbs +119 -0
  59. data/sig/authproto/metadata/resource_server.rbs +28 -0
  60. data/sig/authproto/minisky_oauth.rbs +9 -4
  61. data/sig/authproto/par/client.rbs +8 -14
  62. data/sig/authproto/par/client_assertion.rbs +6 -1
  63. data/sig/authproto/par/request.rbs +5 -28
  64. data/sig/authproto/par/response.rbs +1 -5
  65. data/sig/authproto/pkce.rbs +6 -16
  66. data/sig/authproto/serialization/session.rbs +2 -2
  67. data/sig/authproto/state/session.rbs +13 -9
  68. data/sig/authproto/state/session_manager.rbs +9 -4
  69. data/sig/authproto/state/token_set.rbs +1 -2
  70. data/sig/authproto/storage/key_builder.rbs +1 -2
  71. data/sig/authproto/token/refresh.rbs +6 -7
  72. data/sig/authproto/validated_uri.rbs +36 -0
  73. data/sig/authproto.rbs +10 -5
  74. metadata +24 -27
  75. data/.rspec +0 -1
  76. data/.rubocop.yml +0 -31
  77. data/.tm_properties +0 -1
  78. data/.yardopts +0 -4
  79. data/Rakefile +0 -8
  80. data/examples/confidential_client/.gitignore +0 -5
  81. data/examples/minisky_console/.gitignore +0 -2
  82. data/lib/authproto/client_metadata.rb +0 -478
  83. data/lib/authproto/dpop/key_manager.rb +0 -223
  84. data/lib/authproto/serialization/dpop_key.rb +0 -38
  85. data/lib/authproto/server_metadata/authorization_server.rb +0 -267
  86. data/lib/authproto/server_metadata/origin_url.rb +0 -71
  87. data/lib/authproto/server_metadata/resource_server.rb +0 -98
  88. data/sig/authproto/client_metadata.rbs +0 -113
  89. data/sig/authproto/serialization/dpop_key.rbs +0 -14
  90. data/sig/authproto/server_metadata/origin_url.rbs +0 -21
  91. data/sig/authproto/server_metadata/resource_server.rbs +0 -27
@@ -5,17 +5,16 @@ require 'jose'
5
5
  require 'json'
6
6
  require 'uri'
7
7
 
8
- require_relative 'client_metadata'
9
8
  require_relative 'configuration'
10
9
  require_relative 'dpop/client'
11
- require_relative 'dpop/key_manager'
12
10
  require_relative 'errors'
11
+ require_relative 'metadata/authorization_server'
12
+ require_relative 'metadata/client_metadata'
13
+ require_relative 'metadata/resource_server'
13
14
  require_relative 'par'
14
15
  require_relative 'par/client'
15
16
  require_relative 'par/client_assertion'
16
17
  require_relative 'par/request'
17
- require_relative 'server_metadata/authorization_server'
18
- require_relative 'server_metadata/resource_server'
19
18
  require_relative 'state/session_manager'
20
19
  require_relative 'state/token_set'
21
20
  require_relative 'storage/key_builder'
@@ -66,52 +65,62 @@ module AuthProto
66
65
  attr_reader :redirect_uri
67
66
 
68
67
  # Validated client metadata.
69
- # @return [ClientMetadata]
68
+ # @return [Metadata::ClientMetadata]
70
69
  attr_reader :client_metadata
71
70
 
72
71
  # Manager for stored OAuth sessions.
73
72
  # @return [State::SessionManager]
74
73
  attr_reader :session_manager
75
74
 
76
- # DPoP key, proof and nonce manager.
75
+ # Shared DPoP proof generator and per-server nonce manager.
77
76
  # @return [DPoP::Client]
78
77
  attr_reader :dpop_client
79
78
 
80
- # Creates an OAuth client with its own DPoP key and session manager.
79
+ # Creates an OAuth client with shared DPoP helpers and a session manager.
81
80
  #
82
81
  # Configure {AuthProto.configure} with an HTTP transport before fetching metadata
83
- # or starting authorization. Reuse `dpop_key` when restoring tokens bound to that key.
82
+ # or starting authorization. Session storage restores the DPoP key bound to each session.
84
83
  #
85
84
  # @param client_id [String] OAuth client ID URL
86
85
  # @param redirect_uri [String] callback URI listed in `redirect_uris`
87
86
  # @param metadata [Hash{String => Object}, nil] preloaded metadata, or `nil` to fetch `client_id`
88
- # @param dpop_key [Hash{String => Object}, nil] existing private DPoP JWK, or `nil` to generate one
87
+ # @param signing_key [Hash, JOSE::JWK, nil] private ES256 client-authentication key, separate from public metadata
89
88
  #
90
- # @raise [InvalidClientMetadata] if client metadata is invalid or unavailable
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
91
92
  # @raise [Error] if the redirect URI is not registered
92
- # @raise [DPoP::KeyManager::KeyError] if the DPoP key cannot be imported or generated
93
93
  # @raise [HTTPClient::HTTPError, HTTPClient::SSRFError] if fetching client metadata fails
94
94
  #
95
- def initialize(client_id:, redirect_uri:, metadata: nil, dpop_key: nil)
95
+ def initialize(client_id:, redirect_uri:, metadata: nil, signing_key: nil)
96
96
  @client_id = client_id
97
97
  @redirect_uri = redirect_uri
98
98
 
99
- # Initialize core dependencies
99
+ if metadata && metadata['client_id'] != @client_id
100
+ raise InvalidClientMetadata, "client_id mismatch: #{metadata['client_id']} != #{@client_id}"
101
+ end
102
+
103
+ # Client metadata is fetched from the client ID URL if not provided directly
100
104
  @client_metadata = load_client_metadata(metadata)
105
+
101
106
  validate_redirect_uri
107
+ initialize_client_assertion(signing_key)
108
+
109
+ signing_keys = @client_assertion ? { @signing_key_kid => @signing_key_thumbprint } : {}
110
+ @session_manager = State::SessionManager.new(supported_signing_keys: signing_keys)
102
111
 
103
- @session_manager = State::SessionManager.new
104
- @dpop_client = initialize_dpop(dpop_key)
112
+ @dpop_client = DPoP::Client.new
105
113
  end
106
114
 
107
115
  # Starts authorization, stores a pending session, and submits a PAR request.
108
116
  #
109
- # Supply exactly one of `handle` or `pds_url`. Open the returned `:url` in a browser
110
- # and pass the eventual callback parameters to {#handle_callback}.
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.
111
120
  #
112
121
  # @param handle [String, nil] account handle (optionally prefixed with `@`) or DID
113
- # @param pds_url [String, nil] PDS URL when no handle is supplied
114
- # @param scope [String] space-separated scopes, including `atproto`
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`
115
124
  #
116
125
  # @return [Hash{Symbol => String}] `:url` is the browser URL; `:session_id` identifies the pending session
117
126
  # @raise [Error] if identity arguments or scope are invalid, the handle cannot be verified, or no HTTPS PDS is found
@@ -121,37 +130,33 @@ module AuthProto
121
130
  # @raise [PAR::ClientAssertion::Error] if confidential-client signing fails
122
131
  # @raise [DPoP::Client::Error] if generating the PAR proof fails
123
132
  # @raise [HTTPClient::SSRFError] if server discovery rejects a destination
133
+ # @raise [DPoP::KeySet::KeyError] if generating the session key fails
124
134
  # @raise [Storage::StorageError] if session storage or locking fails
125
135
  # @raise [Encryption::EncryptionError] if session serialization cannot encrypt secrets
126
136
  #
127
- def authorize(handle: nil, pds_url: nil, scope: "atproto")
128
- validate_auth_params(handle, pds_url, scope)
137
+ def authorize(handle: nil, pds: nil, scope: 'atproto')
138
+ validate_auth_params(handle, pds, scope)
129
139
 
130
- # Create new session
131
- session = session_manager.create_session(
132
- client_id: client_id,
133
- scope: scope
134
- )
140
+ if !pds
141
+ did = DIDKit::DID.resolve_handle(handle)
142
+ raise Error, "Could not resolve or verify identity #{handle}" unless did
135
143
 
136
- # Store session with storage backend
137
- session_manager.update_session(session)
138
-
139
- # Resolve identity and authorization server if handle provided
140
- if handle
141
- auth_info = resolve_from_handle(handle, session)
142
- elsif pds_url
143
- auth_info = resolve_from_pds(pds_url, session)
144
- else
145
- raise Error, "Either handle or pds_url must be provided"
144
+ pds = did.document.pds_endpoint
145
+ raise Error, "No HTTPS PDS location found for #{did}" unless pds && URI(pds).is_a?(URI::HTTPS)
146
146
  end
147
147
 
148
- # Generate authorization URL
149
- auth_url = generate_authorization_url(
150
- auth_info[:server],
151
- session,
152
- login_hint: handle
148
+ authorization_server = resolve_auth_server_info(pds)
149
+
150
+ session = session_manager.create_session(
151
+ client_id: @client_id,
152
+ scope: scope,
153
+ auth_server: authorization_server,
154
+ did: did&.to_s,
155
+ signing_key_id: @signing_key_kid
153
156
  )
154
157
 
158
+ auth_url = submit_authorization_par(authorization_server, session, login_hint: handle)
159
+
155
160
  {
156
161
  url: auth_url,
157
162
  session_id: session.session_id
@@ -165,12 +170,18 @@ module AuthProto
165
170
  # and `:scope` (String).
166
171
  # It also contains `:session_id` (String) and `:did` (String).
167
172
  #
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.
177
+ #
168
178
  # @param code [String] authorization code from the callback
169
179
  # @param state [String] state token from the callback
170
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
171
182
  #
172
183
  # @return [Hash{Symbol => String, Integer, nil}] tokens and authenticated session details
173
- # @raise [CallbackError] if state is unknown or the issuer does not match the session
184
+ # @raise [CallbackError] if the expected session ID is invalid, state is unknown, or session/issuer validation fails
174
185
  # @raise [TokenError] if token exchange or response validation fails
175
186
  # @raise [DPoP::Client::Error, PAR::ClientAssertion::Error] if proof/assertion generation fails
176
187
  # @raise [HTTPClient::HTTPError, HTTPClient::SSRFError] if token transport fails
@@ -179,47 +190,33 @@ module AuthProto
179
190
  # @raise [Storage::StorageError] if session storage or locking fails
180
191
  # @raise [Encryption::EncryptionError] if tokens cannot be encrypted for storage
181
192
  #
182
- def handle_callback(code:, state:, iss:)
183
- # Find and validate session
184
- session = session_manager.get_session_by_state(state)
185
- raise CallbackError, "Invalid state parameter" unless session
193
+ def handle_callback(code:, state:, iss:, expected_session_id:)
194
+ unless expected_session_id.is_a?(String) && !expected_session_id.empty?
195
+ raise CallbackError, "Expected session ID is required"
196
+ end
186
197
 
187
- # Verify issuer matches session
198
+ session = session_manager.get_session_by_state_token(state)
199
+
200
+ raise CallbackError, "Invalid state parameter" unless session
201
+ raise CallbackError, "Session ID mismatch" unless session.session_id == expected_session_id
188
202
  raise CallbackError, "Issuer mismatch" unless session.auth_server && session.auth_server.issuer == iss
189
203
 
190
204
  AuthProto.storage.with_lock(Storage::KeyBuilder.lock_key("session", session.session_id), ttl: 30) do
191
- # Exchange code for tokens
192
- token_response = exchange_code(
193
- code: code,
194
- session: session
195
- )
196
-
197
- # Validate token response
198
- validate_token_response(token_response, session)
205
+ response = exchange_code(code: code, session: session)
199
206
 
200
- # Create token set and store in session
201
207
  token_set = State::TokenSet.new(
202
- access_token: token_response["access_token"],
203
- token_type: token_response["token_type"],
204
- expires_in: token_response["expires_in"],
205
- refresh_token: token_response["refresh_token"],
206
- scope: token_response["scope"],
207
- sub: token_response["sub"]
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']
208
214
  )
209
- session.tokens = token_set
210
215
 
211
- # Update stored session
212
- session_manager.update_session(session)
216
+ session.tokens = token_set
217
+ session_manager.complete_authorization(session)
213
218
 
214
- {
215
- access_token: token_set.access_token,
216
- token_type: token_set.token_type,
217
- expires_in: (token_set.expires_at - Time.now).to_i,
218
- refresh_token: token_set.refresh_token,
219
- scope: token_set.scope,
220
- session_id: session.session_id,
221
- did: session.did
222
- }
219
+ session.session_data
223
220
  end
224
221
  end
225
222
 
@@ -228,6 +225,7 @@ module AuthProto
228
225
  # The result contains `:access_token` (String), `:token_type` (String, `DPoP`),
229
226
  # `:expires_in` (Integer seconds remaining), `:refresh_token` (String or nil),
230
227
  # and `:scope` (String).
228
+ # It also contains `:session_id` (String) and `:did` (String).
231
229
  # This method does not refresh expired tokens.
232
230
  #
233
231
  # @param session_id [String] session identifier
@@ -235,15 +233,9 @@ module AuthProto
235
233
  #
236
234
  def get_tokens(session_id)
237
235
  session = session_manager.get_session(session_id)
238
- return nil unless session&.authorized?
236
+ return nil unless session && session.tokens_valid?
239
237
 
240
- {
241
- access_token: session.tokens.access_token,
242
- token_type: session.tokens.token_type,
243
- expires_in: (session.tokens.expires_at - Time.now).to_i,
244
- refresh_token: session.tokens.refresh_token,
245
- scope: session.tokens.scope
246
- }
238
+ session.session_data
247
239
  end
248
240
 
249
241
  # Refreshes a renewable session and persists the replacement tokens.
@@ -251,19 +243,21 @@ module AuthProto
251
243
  # The result contains `:access_token` (String), `:token_type` (String, `DPoP`),
252
244
  # `:expires_in` (Integer seconds remaining), `:refresh_token` (String or nil),
253
245
  # and `:scope` (String).
254
- # The result also contains `:session_id` (String). An expired access token can
246
+ # The result also contains `:session_id` (String) and `:did` (String). An expired access token can
255
247
  # still be refreshed when the stored session has a refresh token.
256
248
  #
257
249
  # @param session_id [String] session to refresh
258
- # @return [Hash{Symbol => String, Integer, nil}] replacement tokens and session ID
250
+ # @return [Hash{Symbol => String, Integer, nil}] replacement tokens and session identifiers
259
251
  # @raise [TokenError] if the session is missing or has no refresh token
260
252
  # @raise [Token::RefreshError] if token refresh fails or exhausts retries
253
+ # @raise [DPoP::Client::Error] if a refresh response lacks a valid nonce
261
254
  # @raise [State::SessionError] if replacement tokens have a different subject
262
255
  # @raise [Storage::StorageError] if session storage or locking fails
263
256
  # @raise [Encryption::EncryptionError] if replacement tokens cannot be stored
264
257
  #
265
258
  def refresh_token(session_id)
266
259
  session = session_manager.get_session(session_id)
260
+
267
261
  raise TokenError, "Invalid session" unless session
268
262
  raise TokenError, "Session not authorized" unless session.renewable?
269
263
 
@@ -272,23 +266,16 @@ module AuthProto
272
266
  session: session,
273
267
  dpop_client: @dpop_client,
274
268
  auth_server: session.auth_server,
275
- client_metadata: client_metadata
269
+ client_metadata: @client_metadata,
270
+ client_assertion: @client_assertion
276
271
  )
277
272
 
278
- new_tokens = refresher.perform
279
- session.tokens = new_tokens
273
+ new_tokens = refresher.perform_refresh
280
274
 
281
- # Update stored session
275
+ session.tokens = new_tokens
282
276
  session_manager.update_session(session)
283
277
 
284
- {
285
- access_token: new_tokens.access_token,
286
- token_type: new_tokens.token_type,
287
- expires_in: (new_tokens.expires_at - Time.now).to_i,
288
- refresh_token: new_tokens.refresh_token,
289
- scope: new_tokens.scope,
290
- session_id: session.session_id
291
- }
278
+ session.session_data
292
279
  end
293
280
  end
294
281
 
@@ -299,13 +286,13 @@ module AuthProto
299
286
  #
300
287
  def authorized?(session_id)
301
288
  session = session_manager.get_session(session_id)
302
- session&.authorized? || false
289
+ session ? session.tokens_valid? : false
303
290
  end
304
291
 
305
292
  # Builds authorization headers and a fresh DPoP proof for one HTTP request.
306
293
  #
307
294
  # The caller sends the request. This method does not refresh tokens, send HTTP,
308
- # or retry nonce challenges. Feed response headers to {DPoP::Client#process_response}
295
+ # or retry nonce challenges. Feed each full HTTP response to {DPoP::Client#process_response}
309
296
  # and call {#refresh_token} explicitly when needed. Generate new headers for each retry.
310
297
  #
311
298
  # @param session_id [String] authorized session ID
@@ -318,19 +305,21 @@ module AuthProto
318
305
  #
319
306
  def auth_headers(session_id:, method:, url:)
320
307
  session = session_manager.get_session(session_id)
308
+
321
309
  raise TokenError, "Invalid session" unless session
322
- raise TokenError, "Session not authorized" unless session.authorized?
310
+ raise TokenError, "Session not authorized" if session.pending?
311
+ raise TokenError, "Session has expired" unless session.tokens_valid?
323
312
 
324
- # Generate DPoP proof
325
- proof = dpop_client.generate_proof(
326
- http_method: method,
327
- http_uri: url,
313
+ dpop_proof = dpop_client.generate_proof(
314
+ session: session,
315
+ method: method,
316
+ uri: url,
328
317
  access_token: session.tokens.access_token
329
318
  )
330
319
 
331
320
  {
332
321
  "Authorization" => "DPoP #{session.tokens.access_token}",
333
- "DPoP" => proof
322
+ "DPoP" => dpop_proof
334
323
  }
335
324
  end
336
325
 
@@ -340,10 +329,8 @@ module AuthProto
340
329
  # @return [void]
341
330
  # @raise [Storage::StorageError] if deletion or locking fails
342
331
  #
343
- def remove_session(session_id)
344
- key = Storage::KeyBuilder.session_key(session_id)
345
- AuthProto.storage.delete(key)
346
- session_manager.remove_session(session_id)
332
+ def delete_session(session_id)
333
+ session_manager.delete_session(session_id)
347
334
  end
348
335
 
349
336
  # Invokes the session manager's expiry cleanup hook.
@@ -356,173 +343,147 @@ module AuthProto
356
343
  session_manager.cleanup_expired
357
344
  end
358
345
 
346
+
359
347
  private
360
348
 
361
349
  def load_client_metadata(metadata)
362
350
  if metadata
363
- ClientMetadata.new(metadata)
351
+ Metadata::ClientMetadata.new(metadata)
364
352
  else
365
- ClientMetadata.from_url(@client_id)
353
+ Metadata::ClientMetadata.from_url(@client_id)
366
354
  end
367
355
  end
368
356
 
369
357
  def validate_redirect_uri
370
- valid = @client_metadata.redirect_uris.include?(@redirect_uri)
371
- raise Error, "redirect_uri not found in client metadata" unless valid
358
+ unless @client_metadata.redirect_uris.include?(@redirect_uri)
359
+ raise Error, "redirect_uri not found in client metadata"
360
+ end
372
361
  end
373
362
 
374
- def initialize_dpop(key)
375
- key_manager = if key
376
- DPoP::KeyManager.from_jwk(key)
377
- else
378
- DPoP::KeyManager.new
379
- end
380
-
381
- DPoP::Client.new(key_manager: key_manager)
382
- end
363
+ def initialize_client_assertion(key)
364
+ if @client_metadata.confidential?
365
+ raise InvalidClientMetadata, "Confidential clients require a signing_key" if key.nil?
366
+ else
367
+ raise InvalidClientMetadata, "Public clients must not supply a signing_key" unless key.nil?
368
+ return nil
369
+ end
383
370
 
384
- def validate_auth_params(handle, pds_url, scope)
385
- raise Error, "scope must include 'atproto'" unless scope.split.include?("atproto")
386
- raise Error, "handle or pds_url must be provided" if handle.nil? && pds_url.nil?
387
- raise Error, "cannot provide both handle and pds_url" if handle && pds_url
388
- end
371
+ assertion = PAR::ClientAssertion.new(client_id: @client_id, signing_key: key)
372
+ private_key = assertion.signing_key
389
373
 
390
- def resolve_from_handle(handle, session)
391
- did = DIDKit::DID.resolve_handle(handle)
392
- raise Error, "Could not resolve or verify identity #{handle}" unless did
374
+ if @client_metadata.jwks
375
+ public_key = private_key.to_public_map.to_h
393
376
 
394
- pds_url = did.document.pds_endpoint
395
- raise Error, "No HTTPS PDS location found for #{did}" unless pds_url && URI(pds_url).is_a?(URI::HTTPS)
377
+ key_in_jwks = @client_metadata.jwks['keys'].any? { |candidate|
378
+ metadata_key_matches_public_key?(candidate, public_key)
379
+ }
396
380
 
397
- session.did = did.to_s
381
+ raise InvalidClientMetadata, "signing_key must match an active public key advertised in jwks" if !key_in_jwks
382
+ end
398
383
 
399
- # Get authorization server from PDS
400
- server = resolve_auth_server(pds_url)
401
- session.authorization_server = server
384
+ @client_assertion = assertion
385
+ @signing_key_kid = private_key.fields.fetch('kid')
386
+ @signing_key_thumbprint = private_key.thumbprint('SHA256')
387
+ end
402
388
 
403
- # Update stored session
404
- session_manager.update_session(session)
389
+ def metadata_key_matches_public_key?(candidate, public_key)
390
+ return false if candidate['revoked']
391
+ return false if candidate.key?('alg') && candidate['alg'] != PAR::ClientAssertion::ALGORITHM
392
+ return false if candidate.key?('use') && candidate['use'] != 'sig'
393
+ return false if candidate.key?('key_ops') && !candidate['key_ops'].include?('verify')
405
394
 
406
- { server: server, pds: pds_url }
395
+ %w[kid kty crv x y].all? { |field| candidate[field] == public_key[field] }
407
396
  end
408
397
 
409
- def resolve_from_pds(pds_url, session)
410
- # Get authorization server from PDS
411
- server = resolve_auth_server(pds_url)
412
- session.authorization_server = server
398
+ def validate_auth_params(handle, pds, scope)
399
+ 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"
401
+ end
402
+
403
+ requested_scopes = scope.split(' ')
404
+ raise Error, "scope must include 'atproto'" unless requested_scopes.include?('atproto')
413
405
 
414
- # Update stored session
415
- session_manager.update_session(session)
406
+ undeclared_scopes = requested_scopes - @client_metadata.scope.split(' ')
407
+
408
+ unless undeclared_scopes.empty?
409
+ raise Error, "scope contains values not declared in client metadata: #{undeclared_scopes.join(' ')}"
410
+ end
416
411
 
417
- { server: server, pds: pds_url }
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
418
414
  end
419
415
 
420
- def resolve_auth_server(pds_url)
421
- # Get resource server metadata
422
- resource_server = ServerMetadata::ResourceServer.from_url(pds_url)
423
- auth_server_url = resource_server.authorization_servers.first
416
+ def resolve_auth_server_info(pds)
417
+ resource_server = Metadata::ResourceServer.from_url(pds)
418
+ auth_server_url = resource_server.authorization_server
424
419
 
425
- # Get and validate authorization server metadata
426
- ServerMetadata::AuthorizationServer.from_issuer(auth_server_url)
420
+ Metadata::AuthorizationServer.from_url(auth_server_url)
427
421
  end
428
422
 
429
- def generate_authorization_url(auth_server, session, login_hint: nil)
430
- # Create PAR client
423
+ def submit_authorization_par(authorization_server, session, login_hint: nil)
431
424
  par_client = PAR::Client.new(
432
- endpoint: auth_server.pushed_authorization_request_endpoint,
425
+ authorization_server: authorization_server,
433
426
  dpop_client: @dpop_client
434
427
  )
435
428
 
436
- # Build PAR request
437
- par_request = PAR::Request.build do |config|
438
- config.client_id = client_id
439
- config.redirect_uri = redirect_uri
440
- config.state = session.state_token
441
- config.scope = session.scope
442
- config.login_hint = login_hint if login_hint
443
-
444
- # Add PKCE parameters
445
- config.code_challenge = session.pkce_challenge
446
- config.code_challenge_method = "S256"
447
-
448
- # Public clients use PKCE and DPoP without client authentication.
449
- if client_metadata.confidential?
450
- signing_key = JOSE::JWK.from_map(client_metadata.jwks.fetch("keys").first)
451
- client_assertion = PAR::ClientAssertion.new(client_id: client_id, signing_key: signing_key)
452
- config.client_assertion = client_assertion.generate_jwt(audience: auth_server.issuer)
453
- config.client_assertion_type = PAR::CLIENT_ASSERTION_TYPE
454
- end
429
+ par_request = PAR::Request.build do |req|
430
+ req.client_id = @client_id
431
+ req.redirect_uri = @redirect_uri
432
+ req.state = session.state_token
433
+ req.scope = session.scope
434
+ req.login_hint = login_hint if login_hint
435
+ req.code_challenge = session.pkce_challenge
455
436
 
456
- # Add DPoP proof
457
- proof = @dpop_client.generate_proof(
458
- http_method: "POST",
459
- http_uri: auth_server.pushed_authorization_request_endpoint
460
- )
461
- config.dpop_proof = proof
437
+ if @client_metadata.confidential?
438
+ req.client_assertion = @client_assertion
439
+ end
462
440
  end
463
441
 
464
- # Submit PAR request
465
- response = par_client.submit(par_request)
442
+ par_response = par_client.submit(par_request, session: session)
466
443
 
467
- # Build final authorization URL
468
- par_client.authorization_url(
469
- authorize_endpoint: auth_server.authorization_endpoint,
470
- request_uri: response.request_uri,
471
- client_id: client_id
444
+ par_client.build_authorization_url(
445
+ request_uri: par_response.request_uri,
446
+ client_id: @client_id
472
447
  )
473
448
  end
474
449
 
475
450
  def exchange_code(code:, session:)
476
- # Initial token request without nonce
477
- response = make_token_request(code, session)
478
-
479
- # Handle DPoP nonce requirement
480
- if requires_dpop_nonce?(response)
481
- # Extract and store nonce from error response
482
- extract_dpop_nonce(response)
483
- dpop_client.process_response(response[:headers], session.auth_server.issuer)
484
-
485
- # Retry request with nonce
486
- response = make_token_request(code, session)
451
+ response = dpop_client.with_nonce_handling(session, session.auth_server.token_endpoint) do
452
+ make_token_request(code, session)
487
453
  end
488
454
 
489
455
  raise TokenError, "Token request failed: #{response[:status]}" unless response[:status] == 200
490
456
 
491
457
  begin
492
- JSON.parse(response[:body])
458
+ data = JSON.parse(response[:body])
493
459
  rescue JSON::ParserError => e
494
460
  raise TokenError, "Invalid token response: #{e.message}"
495
461
  end
462
+
463
+ validate_token_response(data, session)
464
+
465
+ data
496
466
  end
497
467
 
498
468
  def make_token_request(code, session)
499
- # Generate proof
500
- proof = dpop_client.generate_proof(
501
- http_method: "POST",
502
- http_uri: session.auth_server.token_endpoint
469
+ dpop_proof = dpop_client.generate_proof(
470
+ session: session,
471
+ method: 'POST',
472
+ uri: session.auth_server.token_endpoint
503
473
  )
504
474
 
505
475
  body = {
506
- grant_type: "authorization_code",
476
+ grant_type: 'authorization_code',
507
477
  code: code,
508
- redirect_uri: redirect_uri,
509
- client_id: client_id,
478
+ redirect_uri: @redirect_uri,
479
+ client_id: @client_id,
510
480
  code_verifier: session.pkce_verifier
511
481
  }
512
482
 
513
- # Add client authentication
514
- if client_metadata.confidential?
515
- signing_key = JOSE::JWK.from_map(client_metadata.jwks["keys"].first)
516
- client_assertion = PAR::ClientAssertion.new(
517
- client_id: client_id,
518
- signing_key: signing_key
519
- )
520
-
483
+ if @client_metadata.confidential?
521
484
  body.merge!(
522
485
  client_assertion_type: PAR::CLIENT_ASSERTION_TYPE,
523
- client_assertion: client_assertion.generate_jwt(
524
- audience: session.auth_server.issuer
525
- )
486
+ client_assertion: @client_assertion.generate_jwt(audience: session.auth_server.issuer)
526
487
  )
527
488
  end
528
489
 
@@ -531,53 +492,24 @@ module AuthProto
531
492
  body: body,
532
493
  headers: {
533
494
  "Content-Type" => "application/x-www-form-urlencoded",
534
- "DPoP" => proof
495
+ "DPoP" => dpop_proof
535
496
  }
536
497
  )
537
498
  end
538
499
 
539
- def requires_dpop_nonce?(response)
540
- return false unless response[:status] == 400
541
-
542
- error_data = JSON.parse(response[:body])
543
- error_data["error"] == "use_dpop_nonce"
544
- rescue JSON::ParserError
545
- false
546
- end
547
-
548
- def extract_dpop_nonce(response)
549
- headers = response[:headers]
550
- nonce = headers["DPoP-Nonce"] ||
551
- headers["dpop-nonce"] ||
552
- headers["Dpop-Nonce"]
553
-
554
- raise TokenError, "No DPoP nonce provided in error response" unless nonce
555
-
556
- nonce
557
- end
558
-
559
500
  def validate_token_response(response, session)
560
- # Required fields
561
- %w[access_token token_type expires_in scope sub].each do |field|
501
+ ['access_token', 'token_type', 'expires_in', 'scope', 'sub'].each do |field|
562
502
  raise TokenError, "Missing #{field} in token response" unless response[field]
563
503
  end
564
504
 
565
- # Token type must be DPoP
566
- raise TokenError, "Invalid token_type: #{response["token_type"]}" unless response["token_type"] == "DPoP"
567
-
568
- # Scope must include atproto
569
- raise TokenError, "Missing atproto scope in token response" unless response["scope"].split.include?("atproto")
570
-
571
- # If we have a pre-resolved DID, verify it matches
572
- raise TokenError, "Subject mismatch in token response" if session.did && session.did != response["sub"]
505
+ unless response['token_type'].is_a?(String) && response['token_type'].casecmp?('DPoP')
506
+ raise TokenError, "Invalid token_type: #{response['token_type']}"
507
+ end
573
508
 
574
- # Process DPoP-Nonce from response headers if present
575
- return unless response[:headers] && response[:headers]["DPoP-Nonce"]
509
+ raise TokenError, "Missing atproto scope in token response" unless response['scope'].split.include?('atproto')
576
510
 
577
- dpop_client.process_response(
578
- response[:headers],
579
- session.auth_server.issuer
580
- )
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']
581
513
  end
582
514
  end
583
515
  end