authproto 0.3.0.beta4 → 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 (106) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +21 -0
  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 +413 -126
  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 +23 -20
  43. data/lib/authproto/dpop/proof_generator.rb +6 -3
  44. data/lib/authproto/dpop/stored_nonce.rb +7 -5
  45. data/lib/authproto/dpop.rb +2 -0
  46. data/lib/authproto/encryption.rb +2 -0
  47. data/lib/authproto/http_client.rb +5 -5
  48. data/lib/authproto/http_helpers.rb +6 -0
  49. data/lib/authproto/metadata/authorization_server.rb +4 -3
  50. data/lib/authproto/metadata/client_metadata.rb +6 -2
  51. data/lib/authproto/metadata/resource_server.rb +4 -3
  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 +2 -2
  60. data/lib/authproto/serialization/stored_nonce.rb +2 -2
  61. data/lib/authproto/state/session.rb +8 -41
  62. data/lib/authproto/state/session_info.rb +150 -0
  63. data/lib/authproto/state/session_manager.rb +18 -15
  64. data/lib/authproto/state.rb +3 -1
  65. data/lib/authproto/storage/interface.rb +10 -0
  66. data/lib/authproto/storage/key_builder.rb +3 -3
  67. data/lib/authproto/storage/memory.rb +24 -18
  68. data/lib/authproto/storage/sqlite.rb +14 -0
  69. data/lib/authproto/token/refresh.rb +2 -2
  70. data/lib/authproto/token/response.rb +2 -0
  71. data/lib/authproto/token/revocation.rb +4 -2
  72. data/lib/authproto/version.rb +1 -1
  73. data/lib/authproto.rb +6 -3
  74. data/sig/authproto/client.rbs +33 -10
  75. data/sig/authproto/dpop/client.rbs +9 -3
  76. data/sig/authproto/dpop/nonce_manager.rbs +6 -6
  77. data/sig/authproto/dpop/proof_generator.rbs +4 -4
  78. data/sig/authproto/dpop/stored_nonce.rbs +2 -2
  79. data/sig/authproto/http_client.rbs +23 -6
  80. data/sig/authproto/http_helpers.rbs +1 -0
  81. data/sig/authproto/metadata/authorization_server.rbs +3 -3
  82. data/sig/authproto/metadata/client_metadata.rbs +1 -1
  83. data/sig/authproto/metadata/resource_server.rbs +2 -2
  84. data/sig/authproto/minisky.rbs +57 -0
  85. data/sig/authproto/state/session.rbs +12 -6
  86. data/sig/authproto/state/session_info.rbs +23 -0
  87. data/sig/authproto/state/session_manager.rbs +7 -2
  88. data/sig/authproto/storage/interface.rbs +1 -0
  89. data/sig/authproto/storage/key_builder.rbs +1 -1
  90. data/sig/authproto/storage/memory.rbs +1 -1
  91. data/sig/authproto/storage/sqlite.rbs +1 -0
  92. data/sig/authproto/token/revocation.rbs +1 -0
  93. data/sig/authproto.rbs +3 -8
  94. metadata +37 -15
  95. data/examples/confidential_client/Gemfile +0 -14
  96. data/examples/confidential_client/README.md +0 -236
  97. data/examples/confidential_client/app.rb +0 -308
  98. data/examples/confidential_client/public/styles.css +0 -70
  99. data/examples/confidential_client/scripts/generate_keys.rb +0 -21
  100. data/examples/confidential_client/views/authorized.erb +0 -46
  101. data/examples/confidential_client/views/index.erb +0 -44
  102. data/sig/authproto/minisky_oauth.rbs +0 -27
  103. /data/examples/{confidential_client/config/oauth-client-metadata.example.json → basic_webapp/config/oauth-client-metadata.production.json} +0 -0
  104. /data/examples/{confidential_client → basic_webapp}/config.ru +0 -0
  105. /data/examples/{confidential_client → basic_webapp}/screenshots/screenshot-1-sign-in.png +0 -0
  106. /data/examples/{confidential_client → basic_webapp}/screenshots/screenshot-2-success.png +0 -0
@@ -7,6 +7,7 @@ require 'uri'
7
7
  require_relative 'configuration'
8
8
  require_relative 'dpop/client'
9
9
  require_relative 'errors'
10
+ require_relative 'http_helpers'
10
11
  require_relative 'metadata/authorization_server'
11
12
  require_relative 'metadata/client_metadata'
12
13
  require_relative 'metadata/resource_server'
@@ -25,24 +26,104 @@ require_relative 'token/revocation'
25
26
  module AuthProto
26
27
 
27
28
  #
28
- # Main client class for AT Protocol OAuth implementation. Handles the complete
29
- # 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
30
76
  #
31
77
 
32
78
  class Client
79
+ include HTTPHelpers
33
80
  include Token::Identity
34
81
 
35
- # Error raised when authorization callback fails
36
- class CallbackError < Error; end
82
+ # An error raised when initial authorization fails.
83
+ class AuthorizationError < AuthProto::Error; end
84
+
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
37
94
 
38
- # Error raised when token operations fail
39
- class TokenError < Error; end
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
118
+
119
+ # An error raised when token operations fail.
120
+ class TokenError < AuthProto::Error; end
40
121
 
41
122
  #
42
- # Error raised when session operations fail
123
+ # An error raised when session operations fail.
43
124
  #
44
125
 
45
- class SessionError < Error
126
+ class SessionError < AuthProto::Error
46
127
 
47
128
  # Identifier of the session associated with the failure, if known.
48
129
  # @return [String, nil]
@@ -59,45 +140,83 @@ module AuthProto
59
140
  end
60
141
  end
61
142
 
62
- # OAuth client ID URL.
143
+ # OAuth client ID URL
63
144
  # @return [String]
64
145
  attr_reader :client_id
65
146
 
66
- # Callback URI registered in the client metadata.
147
+ # The callback URL to which the user is redirected to complete authorization
67
148
  # @return [String]
68
149
  attr_reader :redirect_uri
69
150
 
70
- # Validated client metadata.
151
+ # Parsed and validated metadata about the client
71
152
  # @return [Metadata::ClientMetadata]
72
153
  attr_reader :client_metadata
73
154
 
74
- # Manager for stored OAuth sessions.
155
+ # @api private
156
+ #
157
+ # A helper object managing stored OAuth sessions
75
158
  # @return [State::SessionManager]
76
159
  attr_reader :session_manager
77
160
 
78
- # Shared DPoP proof generator and per-server nonce manager.
79
- # @return [DPoP::Client]
80
- attr_reader :dpop_client
81
161
 
82
- # Creates an OAuth client with shared DPoP helpers and a session manager.
162
+ # Checks whether a client ID uses the localhost development URL prefix.
83
163
  #
84
- # Configure {AuthProto.configure} with an HTTP transport before fetching metadata
85
- # 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}.
86
165
  #
87
166
  # @param client_id [String] OAuth client ID URL
88
- # @param redirect_uri [String] callback URI listed in `redirect_uris`
89
- # @param metadata [Hash{String => Object}, nil] preloaded metadata, or `nil` to fetch `client_id`
90
- # @param signing_key [Hash, JOSE::JWK, nil] private ES256 client-authentication key, separate from public metadata
91
- #
92
- # @raise [InvalidClientMetadata] if metadata is invalid, unavailable, has a different client ID,
93
- # or the supplied signing key is missing, unexpected or does not match inline public metadata
94
- # @raise [PAR::ClientAssertion::Error] if the private assertion key is invalid or unusable
95
- # @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
96
208
  # @raise [HTTPClient::HTTPError, HTTPClient::SSRFError] if fetching client metadata fails
97
209
  #
98
210
  def initialize(client_id:, redirect_uri:, metadata: nil, signing_key: nil)
99
211
  @client_id = client_id
100
- @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
101
220
 
102
221
  if metadata && metadata['client_id'] != @client_id
103
222
  raise InvalidClientMetadata, "client_id mismatch: #{metadata['client_id']} != #{@client_id}"
@@ -115,37 +234,46 @@ module AuthProto
115
234
  @dpop_client = DPoP::Client.new
116
235
  end
117
236
 
118
- # 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.
119
240
  #
120
- # Supply exactly one of `handle` or `pds`. Open the returned `:url` in a browser
121
- # and pass the eventual callback parameters to {#handle_callback}. Retain `:session_id`
122
- # in the initiating browser session or native login context for callback verification.
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.
123
244
  #
124
- # @param handle [String, nil] account handle (optionally prefixed with `@`) or DID
125
- # @param pds [String, nil] PDS URL when no handle is supplied
126
- # @param scope [String] space-separated scopes, which must all be declared in client metadata, including `atproto`
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.
127
248
  #
128
- # @return [Hash{Symbol => String}] `:url` is the browser URL; `:session_id` identifies the pending session
129
- # @raise [Error] if identity arguments or scope are invalid, the handle cannot be verified, or no HTTPS PDS is found
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`
253
+ #
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
130
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
131
260
  # @raise [InvalidAuthorizationServer] if server discovery or metadata validation fails
132
- # @raise [PAR::Error] if the pushed authorization request fails
133
- # @raise [PAR::ClientAssertion::Error] if confidential-client signing fails
134
261
  # @raise [DPoP::Client::Error] if generating the PAR proof fails
135
- # @raise [HTTPClient::SSRFError] if server discovery rejects a destination
136
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
137
265
  # @raise [Storage::StorageError] if session storage or locking fails
138
- # @raise [Encryption::EncryptionError] if session serialization cannot encrypt secrets
139
266
  #
140
267
  def authorize(handle: nil, pds: nil, scope: 'atproto')
141
268
  validate_auth_params(handle, pds, scope)
269
+ pds = pds.to_s if pds.is_a?(URI::HTTP)
142
270
 
143
271
  if !pds
144
272
  did = DIDKit::DID.resolve_handle(handle)
145
- raise Error, "Could not resolve or verify identity #{handle}" unless did
273
+ raise AuthorizationError, "Could not resolve or verify identity #{handle}" unless did
146
274
 
147
275
  pds = did.document.pds_endpoint
148
- 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)
149
277
  end
150
278
 
151
279
  authorization_server = resolve_auth_server_info(pds)
@@ -167,38 +295,45 @@ module AuthProto
167
295
  }
168
296
  end
169
297
 
170
- # 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.
171
301
  #
172
- # The result contains `:access_token` (String), `:token_type` (String, `DPoP`),
173
- # `:expires_in` (Integer seconds remaining), `:refresh_token` (String or nil),
174
- # and `:scope` / `:granted_scope` (String, the granted permissions).
175
- # It also contains `:session_id` (String) and `:did` (String).
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).
176
305
  #
177
- # Supply the session ID retained when starting authorization as `expected_session_id`.
178
- # For web apps, read it from the initiating browser's session, never from callback parameters
179
- # or the state-token lookup. It is checked before exchanging the authorization code.
180
- # Remove the browser's pending-session association after this method succeeds.
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.
181
310
  #
182
- # @param code [String] authorization code from the callback
183
- # @param state [String] state token from the callback
184
- # @param iss [String] issuer URL from the callback
185
- # @param expected_session_id [String] pending session ID retained by the caller when authorization started
311
+ # Returns a {State::SessionInfo} object with the session data.
186
312
  #
187
- # @return [Hash{Symbol => String, Integer, nil}] tokens and authenticated session details
188
- # @raise [CallbackError] if the expected session ID is invalid, state is unknown, or session/issuer validation fails
189
- # @raise [TokenError] if token exchange or response validation fails; identity failures attempt token revocation
190
- # @raise [DPoP::Client::Error, PAR::ClientAssertion::Error] if proof/assertion generation fails
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}
316
+ #
317
+ # @return [State::SessionInfo] current tokens and session data
318
+ #
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
191
324
  # @raise [HTTPClient::HTTPError, HTTPClient::SSRFError] if token transport fails
325
+ # @raise [PAR::ClientAssertion::Error] if proof/assertion generation fails
192
326
  # @raise [State::SessionError] if token subject conflicts with the session DID
193
- # @raise [ArgumentError] if returned token fields fail token-set validation
194
327
  # @raise [Storage::StorageError] if session storage or locking fails
195
- # @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
196
329
  #
197
- def handle_callback(code:, state:, iss:, expected_session_id:)
330
+ def handle_callback(callback_params, expected_session_id:)
198
331
  unless expected_session_id.is_a?(String) && !expected_session_id.empty?
199
332
  raise CallbackError, "Expected session ID is required"
200
333
  end
201
334
 
335
+ params = validate_callback_params(callback_params)
336
+ code, state, iss = params.values_at('code', 'state', 'iss')
202
337
  session = session_manager.get_session_by_state_token(state)
203
338
 
204
339
  raise CallbackError, "Invalid state parameter" unless session
@@ -215,40 +350,38 @@ module AuthProto
215
350
  end
216
351
  end
217
352
 
218
- # Reads tokens for a session with a currently valid access token.
353
+
354
+ # Looks up an existing session by ID.
355
+ #
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.
219
360
  #
220
- # The result contains `:access_token` (String), `:token_type` (String, `DPoP`),
221
- # `:expires_in` (Integer seconds remaining), `:refresh_token` (String or nil),
222
- # and `:scope` / `:granted_scope` (String, the granted permissions).
223
- # It also contains `:session_id` (String) and `:did` (String).
224
- # This method does not refresh expired tokens.
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.
225
363
  #
226
364
  # @param session_id [String] session identifier
227
- # @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
228
366
  #
229
- def get_tokens(session_id)
230
- session = session_manager.get_session(session_id)
231
- return nil unless session && session.tokens_valid?
232
-
233
- session.session_data
367
+ def get_session(session_id)
368
+ session_manager.get_session(session_id)&.session_data
234
369
  end
235
370
 
236
- # Refreshes a renewable session and persists the replacement tokens.
371
+
372
+ # Looks up a session using given ID and refreshes its set of tokens.
237
373
  #
238
- # The result contains `:access_token` (String), `:token_type` (String, `DPoP`),
239
- # `:expires_in` (Integer seconds remaining), `:refresh_token` (String or nil),
240
- # and `:scope` / `:granted_scope` (String, the granted permissions).
241
- # The result also contains `:session_id` (String) and `:did` (String). An expired access token can
242
- # still be refreshed when the stored session has a refresh token.
374
+ # Returns a {State::SessionInfo} object with the session data.
243
375
  #
244
376
  # @param session_id [String] session to refresh
245
- # @return [Hash{Symbol => String, Integer, nil}] replacement tokens and session identifiers
246
- # @raise [TokenError] if the session is missing or has no refresh token
247
- # @raise [Token::RefreshError] if the current PDS differs, token refresh fails or retries are exhausted
377
+ # @return [State::SessionInfo] current tokens and session data
378
+ #
248
379
  # @raise [DPoP::Client::Error] if a refresh response lacks a valid nonce
380
+ # @raise [Encryption::EncryptionError] if replacement tokens cannot be stored
249
381
  # @raise [State::SessionError] if replacement tokens have a different subject
250
382
  # @raise [Storage::StorageError] if session storage or locking fails
251
- # @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
252
385
  #
253
386
  def refresh_token(session_id)
254
387
  AuthProto.storage.with_lock(Storage::KeyBuilder.lock_key('session', session_id), ttl: 30) do
@@ -274,27 +407,45 @@ module AuthProto
274
407
  end
275
408
  end
276
409
 
277
- # 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.
278
421
  #
279
- # @param session_id [String] ID of session to check
280
- # @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
281
424
  #
282
425
  def authorized?(session_id)
283
426
  session = session_manager.get_session(session_id)
284
427
  session ? session.tokens_valid? : false
285
428
  end
286
429
 
287
- # 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).
288
432
  #
289
- # The caller sends the request. This method does not refresh tokens, send HTTP,
290
- # or retry nonce challenges. Feed each full HTTP response to {DPoP::Client#process_response}
291
- # and call {#refresh_token} explicitly when needed. Generate new headers for each retry.
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.
292
435
  #
293
- # @param session_id [String] authorized session ID
436
+ # Returns two headers:
437
+ # - `Authorization: DPoP <access_token>`
438
+ # - `DPoP: <dpop_proof>`
439
+ #
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.
443
+ #
444
+ # @param session_id [String] session ID of an authorized session
294
445
  # @param method [String] HTTP method for the proof
295
- # @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
296
447
  #
297
- # @return [Hash{String => String}] `Authorization: DPoP ...` and `DPoP` proof headers
448
+ # @return [Hash{String => String}] headers to attach to an outgoing request
298
449
  # @raise [TokenError] if the session is missing or its access token is expired
299
450
  # @raise [DPoP::Client::Error] if proof generation or nonce lookup fails
300
451
  #
@@ -305,7 +456,7 @@ module AuthProto
305
456
  raise TokenError, "Session not authorized" if session.pending?
306
457
  raise TokenError, "Session has expired" unless session.tokens_valid?
307
458
 
308
- dpop_proof = dpop_client.generate_proof(
459
+ dpop_proof = @dpop_client.generate_proof(
309
460
  session: session,
310
461
  method: method,
311
462
  uri: url,
@@ -318,19 +469,121 @@ module AuthProto
318
469
  }
319
470
  end
320
471
 
321
- # Removes a stored session and its state-token lookup, optionally revoking its tokens first.
322
- # Refresh-token revocation must succeed when a refresh token is present; access-token revocation
323
- # is then best effort. Without a refresh token, access-token revocation must succeed.
324
- # Required revocation failures leave the local session intact so the caller can retry or delete locally.
325
- # A missing session is a no-op; pending sessions have no tokens to revoke.
326
- # Servers without a revocation endpoint are skipped and the session is deleted locally.
472
+
473
+ # Updates the stored DPoP server nonce from the `DPoP-Nonce` header returned in the given response.
474
+ #
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
488
+ # @return [void]
489
+ # @raise [DPoP::Client::Error] if the response or nonce is invalid or storage fails
490
+ #
491
+ def process_dpop(response, url:, session_id:)
492
+ @dpop_client.process_response(response, url: url, session_id: session_id)
493
+ end
494
+
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.
535
+ #
536
+ # @example using with Net::HTTP
537
+ # uri = URI.join(pds_url, '/xrpc/app.bsky.feed.getTimeline')
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).
327
579
  #
328
580
  # @param session_id [String] session identifier
329
- # @param revoke [Boolean] revoke the refresh token, if present, and access token before deletion
581
+ # @param revoke [Boolean] revoke the refresh token (if present) and access token before local deletion
330
582
  # @return [void]
331
- # @raise [Token::Revocation::Error] if a required revocation request is rejected
583
+ #
332
584
  # @raise [DPoP::Client::Error, HTTPClient::HTTPError] if revocation proof or transport handling fails
333
585
  # @raise [Storage::StorageError] if deletion or locking fails
586
+ # @raise [Token::Revocation::Error] if a required revocation request is rejected
334
587
  #
335
588
  def delete_session(session_id, revoke: false)
336
589
  AuthProto.storage.with_lock(Storage::KeyBuilder.lock_key('session', session_id), ttl: 30) do
@@ -361,19 +614,11 @@ module AuthProto
361
614
  end
362
615
  end
363
616
 
364
- # Invokes the session manager's expiry cleanup hook.
365
- #
366
- # Currently a no-op; expiry is checked during retrieval and by storage TTLs.
367
- #
368
- # @return [void]
369
- #
370
- def cleanup_expired_sessions
371
- session_manager.cleanup_expired
372
- end
373
-
374
617
 
375
618
  private
376
619
 
620
+ # --- used in initialize ---
621
+
377
622
  def load_client_metadata(metadata)
378
623
  if metadata
379
624
  Metadata::ClientMetadata.new(metadata)
@@ -394,7 +639,7 @@ module AuthProto
394
639
  end
395
640
  end
396
641
 
397
- raise Error, "redirect_uri not found in client metadata"
642
+ raise InvalidClientMetadata, "redirect_uri not found in client metadata"
398
643
  end
399
644
 
400
645
  def loopback_redirect_components(url)
@@ -449,22 +694,26 @@ module AuthProto
449
694
  %w[kid kty crv x y].all? { |field| candidate[field] == public_key[field] }
450
695
  end
451
696
 
697
+
698
+ # --- used in authorize ---
699
+
452
700
  def validate_auth_params(handle, pds, scope)
453
701
  unless scope.is_a?(String) && scope.valid_encoding? && Metadata::ClientMetadata::SCOPE_PATTERN.match?(scope)
454
- raise Error, "scope must contain valid tokens separated by single spaces"
702
+ raise ArgumentError, "scope must contain valid tokens separated by single spaces"
455
703
  end
456
704
 
457
705
  requested_scopes = scope.split(' ')
458
- raise Error, "scope must include 'atproto'" unless requested_scopes.include?('atproto')
706
+ raise ArgumentError, "scope must include 'atproto'" unless requested_scopes.include?('atproto')
459
707
 
460
- undeclared_scopes = requested_scopes - @client_metadata.scope.split(' ')
708
+ undeclared = requested_scopes - @client_metadata.scope.split(' ')
461
709
 
462
- unless undeclared_scopes.empty?
463
- 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(' ')}"
464
712
  end
465
713
 
466
- raise Error, "handle or pds must be provided" if handle.nil? && pds.nil?
467
- 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
468
717
  end
469
718
 
470
719
  def resolve_auth_server_info(pds)
@@ -484,7 +733,7 @@ module AuthProto
484
733
  req.client_id = @client_id
485
734
  req.redirect_uri = @redirect_uri
486
735
  req.state = session.state_token
487
- req.scope = session.scope
736
+ req.scope = session.requested_scope
488
737
  req.login_hint = login_hint if login_hint
489
738
  req.code_challenge = session.pkce_challenge
490
739
 
@@ -501,12 +750,50 @@ module AuthProto
501
750
  )
502
751
  end
503
752
 
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
786
+ end
787
+
788
+ params
789
+ end
790
+
504
791
  def exchange_code(code:, session:)
505
- response = dpop_client.with_nonce_handling(session, session.auth_server.token_endpoint) do
792
+ response = @dpop_client.with_nonce_handling(session.session_id, session.auth_server.token_endpoint) do
506
793
  make_token_request(code, session)
507
794
  end
508
795
 
509
- raise TokenError, "Token request failed: #{response[:status]}" unless response[:status] == 200
796
+ raise TokenError, "Token request failed: #{response[:status]}" unless response_status(response) == 200
510
797
 
511
798
  tokens = Token::Response.parse(response)
512
799
  validate_token_identity(tokens, session)
@@ -517,7 +804,7 @@ module AuthProto
517
804
  end
518
805
 
519
806
  def make_token_request(code, session)
520
- dpop_proof = dpop_client.generate_proof(
807
+ dpop_proof = @dpop_client.generate_proof(
521
808
  session: session,
522
809
  method: 'POST',
523
810
  uri: session.auth_server.token_endpoint
@@ -538,7 +825,7 @@ module AuthProto
538
825
  )
539
826
  end
540
827
 
541
- AuthProto.configuration.http_client.post(
828
+ http.post(
542
829
  session.auth_server.token_endpoint,
543
830
  body: body,
544
831
  headers: {