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
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 77c4682515836e03bc41e1d03724f5ca2a85e65a11655b2af8a8ba09049a73fc
4
- data.tar.gz: 0ba9433f0ee89b8617354d1e0245644f421fc1e7264597391b2efa5ebc015f79
3
+ metadata.gz: 61754b5e7342299c331cabc76c9585ef1f7b1398d0eae4eed252f5d9a2a019bd
4
+ data.tar.gz: 5879610764cb56945d3fc260ed0538f5cdaaabfaec4982af38408290a34a547f
5
5
  SHA512:
6
- metadata.gz: ebbd4f4c9df22f002bbe9be7c02b502bf4fcf5c056d4d0e9290a2c91dde8f03b4756e3b3db9f306cc1b9d5be6be183b88ace24ddb195733c37e92823ec0d5d78
7
- data.tar.gz: 3b96e49a8ea9bbb555dab5996c0e6a53f0894616928c4416199f00561f2d9603cf327d0c868cf66501fd7b5982a8ec985d9e27e5032de274ef8daaccad58dbb4
6
+ metadata.gz: fe5452fe5a70e70bb3c100b30656eb63fcca61dec4617ccec1413eff03e952156523f39f479096dc2fa23467ad7fa792639571ce5d46a9985049bbb7c0806e82
7
+ data.tar.gz: 2c6fb2275d03bf3b812a731841fe2b7364d41b8799f5e937a4c4191d7da0b843d68bd5d67a941dea4f6d4b0590320cd757041f518a3c1416000888ca165583d5
data/CHANGELOG.md CHANGED
@@ -1,34 +1,94 @@
1
- ## [0.2.5] - 2024-12-13
1
+ ## [0.3.0.beta3] - 2026-11-02
2
+
3
+ - session's state token is deleted on successfully completed authentication (i.e. `handle_callback`)
4
+ - pending sessions (that haven't completed authentication) are stored with a TTL of 15 minutes by default, and expire after that; this can be changed through `pending_session_ttl` in the global configuration
5
+ - completed but non-renewable session (without a refresh token) are set with a TTL such that they expire when their access token expires
6
+ - fixed deleting a session's state token in `Client#delete_session`
7
+ - DPoP keys are now connected to a specific session and saved & restored with it; multiple sessions used from the same `AuthProto::Client` will have proofs signed with different DPoP keys, and the keys are automatically restored and don't need to be passed in the argument to `Client` or `Minisky::OAuthClient`
8
+ - DPoP nonces are now stored separately per session and per service, not just one per service
9
+ - the `minisky_console` example now supports restoring previous sessions using session ID
10
+ - for security, `Client#handle_callback` and `Minisky::OAuthClient#handle_callback` now require an `expected_session_id:` argument, where you need to pass a session ID previously saved from the output of `authorize` in browser storage or a local variable; token callback is rejected if the passed saved session ID doesn't match the ID of the session looked up using the state token from the callback
11
+ - added `Session#pending?` and `Session#tokens_valid?`
12
+ - removed unused `default_token_lifetime` and `encryption` configuration settings
13
+ - added `client_assertion_lifetime` configuration setting
14
+ - nonce manager now uses the global `dpop_nonce_lifetime` ttl setting by default
15
+ - simplified the DPoP public key JWT included in headers
16
+ - improved validation of nonce-related headers & responses, client metadata, refresh errors, and assertion signing keys
17
+ - sessions store the client assertion signing key's ID in the metadata and check it when deserialized
18
+ - various refactors and reorganizations
19
+
20
+ ## [0.3.0.beta2] – 2026-10-31 👻
21
+
22
+ - private keys for signing are now passed separately as `signing_key:` instead of being taken from the same `jwks` in the metadata that holds public keys
23
+ - generate localhost metadata from `client_id` params
24
+ - `confidential_client`: validate `SESSION_SECRET` before start and throw an error early
25
+ - additional validations for URLs, resource server and authorization server metadata, and PAR request and response
26
+ - set `code_challenge_method` in the PAR request automatically to `S256`
27
+ - various renames, refactors, cleanups
28
+ - encode '*' in the authorization URL – unencoded asterisk might break click-to-open-URL in some terminals
29
+ - strip query part from URLs in `htu` in the DPoP proof generator
30
+ - keep existing query part in the PAR authorization endpoint when adding params to it
31
+ - verify that all scopes passed during authorization are declared in client metadata
32
+ - don't reuse client assertion JWT on retried requests
33
+ - POST redirects are not allowed, GET redirects are disabled by default
34
+
35
+ ## [0.3.0.beta1], as AuthProto – 2026-10-28
36
+
37
+ - modernized code
38
+ - various renames, refactors, cleanups
39
+ - removed some unused code
40
+ - removed strict dependency on the Redis gem
41
+ - added alternative SQLite storage
42
+ - added HTTP client version that allows `http://` connections
43
+ - added experimental Minisky adapter and `minisky_console` example
44
+ - added temporary in-process `localhost` HTTP server for receiving callbacks inside `irb`
45
+ - additional validations for request IPs and URLs, responses, and client metadata
46
+ - fixed `confidential_example` running on localhost
47
+ - updated `confidential_example` with a UI for making a test post to Bluesky
48
+ - updated examples to use `oauth-client-metadata.json` instead of `client-metadata.json`
49
+ - converted test suite to RSpec
50
+ - replaced `Identity` module with DIDKit
51
+ - fixed randomly generated encryption key not being shared between different parts of the app
52
+ - fixed some token refresh code failing due to wrong exception names
53
+ - don't try to add client assertions for public clients
54
+ - switched to JWT gem version 3.x
55
+
56
+
57
+ ---
58
+
59
+ # Earlier releases as `atproto_auth`:
60
+
61
+ ## [0.2.5] – 2024-12-13
2
62
 
3
63
  Fixed:
4
64
 
5
65
  - Additional token refresh edge case handling
6
66
 
7
- ## [0.2.4] - 2024-12-13
67
+ ## [0.2.4] – 2024-12-13
8
68
 
9
69
  Fixed:
10
70
 
11
71
  - Token refresh now correctly handles expired tokens
12
72
 
13
- ## [0.2.2] - 2024-12-12
73
+ ## [0.2.2] – 2024-12-12
14
74
 
15
75
  Added:
16
76
 
17
77
  - Added support for did:web users
18
78
 
19
- ## [0.2.1] - 2024-12-11
79
+ ## [0.2.1] – 2024-12-11
20
80
 
21
81
  Fixed:
22
82
 
23
83
  - Fixed a bug with access token hash generation
24
84
 
25
- ## [0.2.0] - 2024-12-10
85
+ ## [0.2.0] – 2024-12-10
26
86
 
27
87
  Added:
28
88
 
29
89
  - Client#handle_callback now returns session did as part of the response
30
90
 
31
- ## [0.1.0] - 2024-12-07
91
+ ## [0.1.0] – 2024-12-07
32
92
 
33
93
  Added:
34
94
 
@@ -47,6 +107,6 @@ Changed:
47
107
  - Session and token management now use configured storage backend
48
108
  - Improved thread safety for all storage operations
49
109
 
50
- ## [0.0.1] - 2024-12-05
110
+ ## [0.0.1] – 2024-12-05
51
111
 
52
112
  - Initial release
data/README.md CHANGED
@@ -62,10 +62,12 @@ AuthProto.configure do |config|
62
62
  verify_ssl: true
63
63
  )
64
64
 
65
- # Set token lifetimes
66
- config.default_token_lifetime = 300 # 5 minutes
65
+ # Set the default nonce cache lifetime (seconds), used by newly created clients.
67
66
  config.dpop_nonce_lifetime = 300 # 5 minutes
68
67
 
68
+ # Set client assertion validity (seconds), used for each newly generated JWT.
69
+ config.client_assertion_lifetime = 300 # 5 minutes
70
+
69
71
  # Configure storage backend (default is in-memory)
70
72
  config.storage = AuthProto::Storage::Memory.new
71
73
  end
@@ -75,6 +77,16 @@ gem 'sqlite3', '~> 2.9'
75
77
  gem 'redis', '~> 5.4'
76
78
  ```
77
79
 
80
+ Set `dpop_nonce_lifetime` to a positive integer before creating clients or nonce
81
+ managers. Its default is 300 seconds. An explicit `NonceManager.new(ttl: ...)` or
82
+ `DPoP::Client.new(nonce_ttl: ...)` overrides it. Existing managers retain the
83
+ lifetime chosen at initialization.
84
+
85
+ `client_assertion_lifetime` must also be a positive integer and defaults to 300
86
+ seconds. It is read for each assertion, including by existing clients and signers.
87
+ An explicit `ClientAssertion#generate_jwt(lifetime: ...)` overrides the configured
88
+ default. This controls assertion validity, not access-token or session lifetime.
89
+
78
90
  ### Local HTTP debugging
79
91
 
80
92
  For debugging a flow that needs both local HTTP and remote HTTPS (handle/PLC
@@ -103,10 +115,30 @@ Client metadata must explicitly set `token_endpoint_auth_method` to `none` for
103
115
  public clients or `private_key_jwt` for confidential clients. Omitting it defaults
104
116
  to `client_secret_basic` in OAuth metadata, which this library does not support.
105
117
 
118
+ For localhost development, `Metadata::ClientMetadata.from_url` generates virtual metadata
119
+ without making an HTTP request. It defaults to native public authentication,
120
+ the `atproto` scope, and redirects `http://127.0.0.1/` and `http://[::1]/`.
121
+ The client ID query can specify one `scope` parameter and multiple `redirect_uri`
122
+ parameters, encoded using `URI.encode_www_form`. These values are decoded and
123
+ validated; the original client ID is preserved exactly.
124
+
106
125
  ### Storage Backends
107
126
 
108
127
  The library supports multiple storage backends for managing OAuth state:
109
128
 
129
+ Pending authorization sessions and their state-token lookups expire after 15 minutes by default.
130
+ Configure the lifetime in seconds with a positive integer:
131
+
132
+ ```ruby
133
+ AuthProto.configure do |config|
134
+ config.pending_session_ttl = 900
135
+ end
136
+ ```
137
+
138
+ Updating a pending session preserves its original deadline. Successful authorization removes
139
+ the pending deadline and state-token lookup. Authenticated sessions without refresh tokens
140
+ expire with their access token; sessions with refresh tokens have no automatic storage expiry.
141
+
110
142
  #### In-Memory Storage (Default)
111
143
 
112
144
  ```ruby
@@ -186,15 +218,80 @@ class CustomStorage < AuthProto::Storage::Interface
186
218
  end
187
219
  ```
188
220
 
221
+ ### DPoP Session Keys
222
+
223
+ Each new OAuth session generates its own DPoP key before PAR. The session serializer
224
+ stores its private JWK with the session and encrypts the private `d` component.
225
+ Restoring the session restores that same key for code exchange, refresh and API
226
+ requests. Configure persistent storage and a stable `ATPROTO_MASTER_KEY` to retain
227
+ sessions across application restarts.
228
+
229
+ `Client` and the Minisky integration no longer accept `dpop_key:`. Restore sessions
230
+ by their session ID; no separate key export or constructor argument is needed.
231
+ `Client#dpop_client` remains shared and accepts `session:` when generating proofs.
232
+ Its `ProofGenerator` accepts `key_set:` per call. Nonces are stored separately with
233
+ TTLs, indexed by session ID and server origin. URLs on the same origin share a
234
+ nonce within that session; other sessions and origins have independent nonces.
235
+ `DPoP::Client#with_nonce_handling(session, url) { ... }` runs a request block,
236
+ processes its response, and runs it once more if the server sends a nonce challenge.
237
+ The block must generate a fresh proof and send the request on each invocation.
238
+ The helper returns the final response; other errors and exceptions are left to
239
+ its caller. PAR, code exchange, and refresh use this helper.
240
+
241
+ `DPoP::Client#process_response` accepts the whole HTTP response hash and requires
242
+ `server_url:` and `session_id:` to update the requesting
243
+ session's nonce. When sending requests without `with_nonce_handling`, call it
244
+ for every DPoP response, including successes, failures, and retry responses; missing or empty `DPoP-Nonce` headers raise an error. Nonces must use RFC 9449's
245
+ `NQCHAR` syntax; malformed values and duplicate nonce headers are rejected.
246
+ `has_nonce_error?` recognizes HTTP 400 JSON nonce errors and HTTP 401 DPoP
247
+ authentication challenges. It does not update the nonce or send a retry.
248
+ Direct nonce manager calls to `get`, `update`, and `clear` also
249
+ require `server_url:` and `session_id:` keywords. Old per-server cache entries are
250
+ ignored and expire normally; a missing nonce can be obtained through a server challenge.
251
+
252
+ Serialized sessions from older versions that lack a private DPoP key cannot be
253
+ restored: start authorization again. Loading never generates a replacement key for
254
+ an existing session. Client-authentication signing keys remain separate from these
255
+ per-session DPoP keys.
256
+
189
257
  ### Confidential Client Example
190
258
 
191
259
  Here's a basic example of using the library in a confidential client application:
192
260
 
261
+ Supply the private EC P-256 client-authentication JWK through `signing_key:`,
262
+ separately from metadata. It must have a nonempty `kid` and permit ES256 signing.
263
+ Metadata's `jwks` contains only public keys; the client checks that the matching
264
+ public key and `kid` are advertised and active. A public key may declare
265
+ `use: "sig"` or `key_ops: ["verify"]`.
266
+ Each key in an inline `jwks` must have a distinct, case-sensitive `kid`.
267
+ Other advertised public keys may serve other purposes, such as encryption;
268
+ the matching authentication key must permit signature verification.
269
+
270
+ With `jwks_uri`, the client still uses your separate private signing key. It does
271
+ not fetch that URL or check the advertised key locally; the authorization server
272
+ fetches it to verify assertions.
273
+
274
+ New confidential-client sessions record the signing key's `kid` as `signing_key_id`
275
+ and its RFC 7638 SHA-256 thumbprint as `signing_key_thumbprint` before PAR. Both
276
+ values persist through callbacks and refreshes without including the private
277
+ client-authentication key. The session manager returns `nil` if the key ID is
278
+ unsupported or its thumbprint no longer matches, leaving stored data intact.
279
+ `Client` supplies a key-ID-to-thumbprint mapping derived from its configured
280
+ private signing key, rather than the public keys advertised in metadata.
281
+ Sessions with a recorded key ID but no thumbprint must authorize again.
282
+ Clients still accept one `signing_key:`; automatic key selection and rotation
283
+ are not implemented.
284
+
285
+ Public-client sessions have no signing key ID. Older serialized sessions without
286
+ this field remain readable and use the configured signing key without an ID check;
287
+ their original key ID cannot be inferred from the stored session.
288
+
193
289
  ```ruby
194
290
  # Initialize client with metadata
195
291
  client = AuthProto::Client.new(
196
292
  client_id: "https://app.example.com/oauth-client-metadata.json",
197
293
  redirect_uri: "https://app.example.com/callback",
294
+ signing_key: JSON.parse(File.read("config/keys.json")).fetch("keys").first,
198
295
  metadata: {
199
296
  # Your client metadata...
200
297
  }
@@ -206,14 +303,17 @@ auth = client.authorize(
206
303
  scope: "atproto"
207
304
  )
208
305
 
209
- # Use auth[:url] to redirect user
306
+ # Retain the expected ID in this browser's session before redirecting to auth[:url].
307
+ session[:pending_oauth_session_id] = auth.fetch(:session_id)
210
308
 
211
309
  # Handle callback
212
310
  tokens = client.handle_callback(
213
311
  code: params[:code],
214
312
  state: params[:state],
215
- iss: params[:iss]
313
+ iss: params[:iss],
314
+ expected_session_id: session[:pending_oauth_session_id]
216
315
  )
316
+ session.delete(:pending_oauth_session_id)
217
317
 
218
318
  # Make authenticated requests
219
319
  headers = client.auth_headers(
@@ -247,14 +347,37 @@ auth = client.authorize(
247
347
  scope: "atproto"
248
348
  )
249
349
 
350
+ # Retain this in the initiating browser session, or locally for a native app.
351
+ session[:pending_oauth_session_id] = auth.fetch(:session_id)
352
+
250
353
  # After callback, exchange code for tokens
251
354
  tokens = client.handle_callback(
252
355
  code: params[:code],
253
356
  state: params[:state],
254
- iss: params[:iss]
357
+ iss: params[:iss],
358
+ expected_session_id: session[:pending_oauth_session_id]
255
359
  )
360
+ session.delete(:pending_oauth_session_id)
256
361
  ```
257
362
 
363
+ ### Binding Callbacks to the Initiating Login
364
+
365
+ `handle_callback` requires `expected_session_id:` for both `AuthProto::Client` and
366
+ `Minisky::OAuthClient`. Retain the `:session_id` returned by `authorize` in the
367
+ initiating browser's session, then supply that retained ID on callback. Missing,
368
+ `nil`, empty, or mismatched IDs are rejected before any token exchange.
369
+
370
+ Never take the expected ID from callback parameters or derive it from the returned
371
+ `state`: that would not establish which browser started the login. A shared web
372
+ client's `session_id` is not a substitute for per-browser session storage. Remove
373
+ the pending association after successful completion. For concurrent login attempts,
374
+ retain each expected ID separately and verify membership in that browser's pending attempts.
375
+
376
+ Native and console apps can retain the ID in the local context for that login
377
+ attempt, as the localhost example does. The console example's manual callback helper
378
+ uses the ID remembered by its local Minisky client. When upgrading existing callers,
379
+ add this required keyword using the retained authorization result.
380
+
258
381
  ## Features In Detail
259
382
 
260
383
  ### Identity Resolution
@@ -1,16 +1,20 @@
1
1
  PATH
2
2
  remote: ../..
3
3
  specs:
4
- authproto (0.2.5)
4
+ authproto (0.3.0.beta1)
5
+ didkit (~> 0.5.0)
5
6
  jose (~> 1.2)
6
7
  jwt (~> 3.3)
7
8
 
8
9
  GEM
9
10
  remote: https://rubygems.org/
10
11
  specs:
12
+ base58 (0.2.3)
11
13
  base64 (0.3.0)
12
14
  concurrent-ruby (1.3.8)
13
15
  connection_pool (3.0.2)
16
+ didkit (0.5.0)
17
+ base58 (~> 0.2)
14
18
  dotenv (3.2.0)
15
19
  faraday (2.14.3)
16
20
  faraday-net_http (>= 2.0, < 3.5)
@@ -43,7 +43,7 @@ bundle install
43
43
  3. Generate EC keys for client authentication:
44
44
 
45
45
  ```bash
46
- bundle exec ruby scripts/generate_keys.rb > config/keys.json
46
+ bundle exec ruby scripts/generate_keys.rb
47
47
  ```
48
48
 
49
49
  4. Generate session & encryption keys:
@@ -64,7 +64,7 @@ SESSION_SECRET=<hex value from second command>
64
64
  ```
65
65
  - Set the correct `client_id` URL where your metadata will be hosted
66
66
  - Configure valid `redirect_uris` for your application
67
- - Add your generated keys from step 3 to the `jwks` field
67
+ - Copy the public JWKS from `config/public-keys.json` (not `config/keys.json`, which is the private keys) into the `jwks` field in oauth-client-metadata.json.
68
68
  - For localhost testing, set `client_id` to `http://localhost/` and `redirect_uris` to `["http://127.0.0.1:9292/callback"]`
69
69
 
70
70
  6. Set up environment variables:
@@ -168,6 +168,16 @@ export SESSION_SECRET=your-secure-random-string
168
168
 
169
169
  If not set, a random secret will be generated on startup (not recommended for production).
170
170
 
171
+ The app stores the ID returned by `authorize` as `session[:pending_oauth_session_id]`
172
+ before redirecting. On callback, it passes that browser-session value as the required
173
+ `expected_session_id:` argument to `handle_callback`. The library rejects a missing
174
+ or mismatched ID before exchanging the code. After success, the app removes the
175
+ pending association and remembers the authenticated session separately.
176
+
177
+ The expected ID must come from the initiating browser session, never from the
178
+ callback URL or by looking up the returned `state`. This example supports one pending
179
+ login per browser; starting another replaces the previous pending association.
180
+
171
181
  ## Running the Application
172
182
 
173
183
  ### Development
@@ -12,6 +12,9 @@ require 'faraday'
12
12
  require 'sinatra/base'
13
13
  require 'sinatra/reloader'
14
14
 
15
+ session_secret = ENV.fetch("SESSION_SECRET") { SecureRandom.hex(32) }
16
+ raise "SESSION_SECRET must be at least 64 characters long (got: #{session_secret})" unless session_secret.length >= 64
17
+
15
18
  # Main app entry point
16
19
  class ExampleApp < Sinatra::Base
17
20
  def check_stored_session(session_id)
@@ -31,7 +34,6 @@ class ExampleApp < Sinatra::Base
31
34
  # Configure AuthProto settings
32
35
  AuthProto.configure do |config|
33
36
  config.http_client = AuthProto::HTTPClient.new(timeout: 10, verify_ssl: true)
34
- config.default_token_lifetime = 300
35
37
  config.dpop_nonce_lifetime = 300
36
38
 
37
39
  case ENV.fetch("STORAGE_BACKEND", "memory")
@@ -54,20 +56,23 @@ class ExampleApp < Sinatra::Base
54
56
  metadata_path = File.join(__dir__, "config", "oauth-client-metadata.json")
55
57
  metadata = JSON.parse(File.read(metadata_path))
56
58
 
57
- client_id = metadata["client_id"]
59
+ client_id = metadata['client_id']
58
60
 
59
61
  if client_id.chomp("/") == "http://localhost"
60
- scope = CGI.escape(metadata["scope"])
61
- redirect_uri = CGI.escape(metadata["redirect_uris"][0])
62
+ scope = CGI.escape(metadata['scope'])
63
+ redirect_uri = CGI.escape(metadata['redirect_uris'][0])
62
64
  client_id += "?scope=#{scope}&redirect_uri=#{redirect_uri}"
63
65
  end
64
66
 
67
+ # Private client-authentication keys are kept outside public metadata.
68
+ signing_key = JSON.parse(File.read(File.join(__dir__, "config", "keys.json")))["keys"].first
69
+
65
70
  # Create OAuth client
66
71
  set :oauth_client, AuthProto::Client.new(
67
72
  client_id: client_id,
68
- redirect_uri: metadata["redirect_uris"][0],
73
+ redirect_uri: metadata['redirect_uris'][0],
69
74
  metadata: metadata,
70
- dpop_key: metadata["jwks"]["keys"][0]
75
+ signing_key: signing_key
71
76
  )
72
77
  end
73
78
 
@@ -78,7 +83,7 @@ class ExampleApp < Sinatra::Base
78
83
  use Rack::Session::Cookie,
79
84
  key: "atproto.session",
80
85
  expire_after: 86_400, # 1 day in seconds
81
- secret: ENV.fetch("SESSION_SECRET") { SecureRandom.hex(32) },
86
+ secret: session_secret,
82
87
  secure: ENV.fetch("RACK_ENV", "development") == "production", # Only send over HTTPS
83
88
  httponly: true, # Not accessible via JavaScript
84
89
  same_site: :lax # CSRF protection
@@ -115,14 +120,7 @@ class ExampleApp < Sinatra::Base
115
120
  metadata_path = File.join(__dir__, "config", "oauth-client-metadata.json")
116
121
  metadata = JSON.parse(File.read(metadata_path))
117
122
 
118
- # Strip private key 'd' component from each key in the JWKS
119
- if metadata["jwks"] && metadata["jwks"]["keys"]
120
- metadata["jwks"]["keys"] = metadata["jwks"]["keys"].map do |key|
121
- key.except("d")
122
- end
123
- end
124
-
125
- # Return sanitized metadata
123
+ # This file contains only the public counterparts of config/keys.json.
126
124
  JSON.generate(metadata)
127
125
  end
128
126
 
@@ -137,8 +135,8 @@ class ExampleApp < Sinatra::Base
137
135
  scope: "atproto repo:app.bsky.feed.post"
138
136
  )
139
137
 
140
- # Store session ID in user's browser session
141
- session[:oauth_session_id] = auth[:session_id]
138
+ # Bind the pending authorization attempt to this browser, separately from any active login.
139
+ session[:pending_oauth_session_id] = auth[:session_id]
142
140
 
143
141
  # Redirect to authorization URL
144
142
  redirect auth[:url]
@@ -154,10 +152,13 @@ class ExampleApp < Sinatra::Base
154
152
  result = settings.oauth_client.handle_callback(
155
153
  code: params[:code],
156
154
  state: params[:state],
157
- iss: params[:iss]
155
+ iss: params[:iss],
156
+ expected_session_id: session[:pending_oauth_session_id]
158
157
  )
159
158
 
160
- # Store tokens
159
+ session.delete(:pending_oauth_session_id)
160
+
161
+ # Remember the authenticated session ID.
161
162
  session[:oauth_session_id] = result[:session_id]
162
163
 
163
164
  redirect "/authorized"
@@ -190,7 +191,7 @@ class ExampleApp < Sinatra::Base
190
191
  # Get auth headers for request
191
192
  headers = settings.oauth_client.auth_headers(
192
193
  session_id: session_id,
193
- method: "GET",
194
+ method: 'GET',
194
195
  url: "https://api.bsky.app/xrpc/com.atproto.identity.resolveHandle"
195
196
  )
196
197
 
@@ -236,7 +237,7 @@ class ExampleApp < Sinatra::Base
236
237
 
237
238
  headers = settings.oauth_client.auth_headers(
238
239
  session_id: session_id,
239
- method: "POST",
240
+ method: 'POST',
240
241
  url: endpoint
241
242
  )
242
243
 
@@ -273,7 +274,7 @@ class ExampleApp < Sinatra::Base
273
274
  get "/signout" do
274
275
  if session[:oauth_session_id]
275
276
  # Clean up stored session
276
- settings.oauth_client.remove_session(session[:oauth_session_id])
277
+ settings.oauth_client.delete_session(session[:oauth_session_id])
277
278
  end
278
279
 
279
280
  session.clear
@@ -16,7 +16,6 @@
16
16
  "kid": "key-1",
17
17
  "x": "...",
18
18
  "crv": "P-256",
19
- "d": "...",
20
19
  "kty": "EC",
21
20
  "y": "..."
22
21
  }
@@ -1,15 +1,21 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require 'jose'
4
+ require 'json'
4
5
 
5
- # Generate a new EC key using P-256 curve
6
- keypair = JOSE::JWK.generate_key([:ec, "P-256"])
6
+ key = JOSE::JWK.generate_key([:ec, "P-256"])
7
7
 
8
- # Get the key as a hash (need to convert from JOSE::Map)
9
- jwk = keypair.to_map.to_h
8
+ private_jwk = key.to_map.to_h.merge("kid" => "key-1", "use" => "sig")
9
+ public_jwk = key.to_public_map.to_h.merge("kid" => "key-1", "use" => "sig")
10
10
 
11
- # Pretty print the JWK to stdout
12
- require 'json'
13
- puts JSON.pretty_generate({
14
- keys: [jwk]
15
- })
11
+ config_dir = File.expand_path('../config', __dir__)
12
+ private_path = File.join(config_dir, 'keys.json')
13
+
14
+ File.open(private_path, File::WRONLY | File::CREAT | File::TRUNC, 0o600) do |file|
15
+ file.chmod(0o600)
16
+ file.write(JSON.pretty_generate('keys' => [private_jwk]) + "\n")
17
+ end
18
+
19
+ File.write(File.join(config_dir, 'public-keys.json'), JSON.pretty_generate('keys' => [public_jwk]) + "\n")
20
+
21
+ puts "Private keys saved to config/keys.json; publish only config/public-keys.json in metadata."
@@ -1,7 +1,7 @@
1
1
  PATH
2
2
  remote: ../..
3
3
  specs:
4
- authproto (0.2.5)
4
+ authproto (0.3.0.beta2)
5
5
  didkit (~> 0.5.0)
6
6
  jose (~> 1.2)
7
7
  jwt (~> 3.3)
@@ -91,7 +91,7 @@ DEPENDENCIES
91
91
  sqlite3
92
92
 
93
93
  CHECKSUMS
94
- authproto (0.2.5)
94
+ authproto (0.3.0.beta2)
95
95
  base58 (0.2.3) sha256=fda5c5d3bda8b429ad0d1a5309c2d1e488ba46f0a2ab99a639890f26c61bf3be
96
96
  base64 (0.3.0) sha256=27337aeabad6ffae05c265c450490628ef3ebd4b67be58257393227588f5a97b
97
97
  bundler (4.0.23) sha256=407ba8a1d928f412847f819aa5f8b6aef7c59fb51feb517112af8a165487287b
@@ -62,12 +62,19 @@ Once the browser redirects to the callback URL after your approval, the console
62
62
 
63
63
  ```
64
64
  Authentication complete ✓
65
+ Your session id: ......
65
66
  ```
66
67
 
68
+ The callback block supplies `expected_session_id:` from the authorization result
69
+ retained locally before opening the browser. The library checks it before exchanging the code.
70
+
67
71
  Then, you can run `client.get_request(...)` and `client.post_request(...)` to perform authorized actions on the given account. By default, the example asks for permissions `repo:app.bsky.feed.post` and `rpc:app.bsky.feed.getTimeline?aud=*`, which allow calling `getTimeline` and creating/modifying posts.
68
72
 
69
- (Note, the session is currently lost when you close the console.)
73
+ To restore a session after closing and reopening the console, write down the sesion ID printed after successful authentication, and then pass it back to the `OAuthClient` constructor:
70
74
 
75
+ ```rb
76
+ client = create_client('your.pds.hostname.here', session_id: '123456-789-abc-...')
77
+ ```
71
78
 
72
79
  ## Production use
73
80
 
@@ -103,10 +110,22 @@ Copy the printed command back to the console:
103
110
  handle_callback(client, { ... })
104
111
  ```
105
112
 
113
+ Use the same local `client` that started this authorization attempt. The helper
114
+ passes its remembered session ID as `expected_session_id:` and forwards only the
115
+ `code`, `state`, and `iss` callback parameters. The expected ID is not supplied by
116
+ the callback page. Each console client supports one current login attempt.
117
+
106
118
  This will print:
107
119
 
108
120
  ```
109
121
  Authentication complete ✓
122
+ Your session id: ......
110
123
  ```
111
124
 
112
125
  Then, you can run `client.get_request(...)` and `client.post_request(...)` to perform authorized actions on the given account.
126
+
127
+ Again, to restore a session after closing and reopening the console, write down the sesion ID printed after successful authentication, and then pass it back to the `OAuthClient` constructor:
128
+
129
+ ```rb
130
+ client = create_client('your.server.hostname', 'your.pds.hostname', session_id: '123456-789-abc-...')
131
+ ```
@@ -1,3 +1,7 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'authproto/insecure_http_client'
4
+ require 'authproto/localhost_server'
1
5
  require 'authproto/minisky'
2
6
  require 'dotenv/load'
3
7
  require 'uri'
@@ -10,42 +14,23 @@ AuthProto.configure do |config|
10
14
  )
11
15
  end
12
16
 
13
- $metadata = {
14
- 'application_type' => 'native',
15
- 'client_id' => 'http://localhost/',
16
- 'client_name' => 'AT Protocol OAuth Ruby Example',
17
- 'redirect_uris' => ['http://127.0.0.1:9292/callback'],
18
- 'grant_types' => ['authorization_code', 'refresh_token'],
19
- 'response_types' => ['code'],
20
- 'scope' => 'atproto repo:app.bsky.feed.post rpc:app.bsky.feed.getTimeline?aud=*',
21
- 'token_endpoint_auth_method' => 'none',
22
- 'dpop_bound_access_tokens' => true,
23
- }
24
-
25
- $client_id = $metadata['client_id'] + '?' + URI.encode_www_form({
26
- redirect_uri: $metadata['redirect_uris'][0],
27
- scope: $metadata['scope']
28
- })
29
-
30
- $metadata['client_id'] = $client_id
31
-
32
- def create_client(pds)
33
- Minisky::OAuthClient.new(pds,
34
- client_id: $client_id,
35
- redirect_uri: $metadata['redirect_uris'][0],
36
- metadata: $metadata
37
- )
17
+ REDIRECT_URI = 'http://127.0.0.1:9292/callback'
18
+ SCOPE = 'atproto repo:app.bsky.feed.post rpc:app.bsky.feed.getTimeline?aud=*'
19
+ CLIENT_ID = 'http://localhost/?' + URI.encode_www_form({ redirect_uri: REDIRECT_URI, scope: SCOPE })
20
+
21
+ def create_client(pds, session_id: nil)
22
+ Minisky::OAuthClient.new(pds, client_id: CLIENT_ID, redirect_uri: REDIRECT_URI, session_id: session_id)
38
23
  end
39
24
 
40
25
  def authorize(client)
41
- auth = client.authorize(pds_url: "https://#{client.host}", scope: $metadata['scope'])
26
+ auth = client.authorize(pds: "https://#{client.host}", scope: SCOPE)
42
27
 
43
28
  puts "Open this URL in the browser and complete authorization:"
44
29
  puts auth[:url]
45
30
  puts
46
31
 
47
- AuthProto::LocalhostServer.start($metadata) do |json|
48
- client.handle_callback(**json)
32
+ AuthProto::LocalhostServer.start(client.oauth_client.client_metadata) do |json|
33
+ client.handle_callback(**json, expected_session_id: auth.fetch(:session_id))
49
34
  end
50
35
 
51
36
  puts "Authentication complete ✓"