authproto 0.3.0.beta3 → 0.3.0.beta5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (112) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +39 -1
  3. data/README.md +474 -311
  4. data/examples/basic_webapp/Gemfile +14 -0
  5. data/examples/{confidential_client → basic_webapp}/Gemfile.lock +1 -1
  6. data/examples/basic_webapp/README.md +300 -0
  7. data/examples/basic_webapp/app.rb +351 -0
  8. data/examples/basic_webapp/config/oauth-client-metadata.localhost.json +11 -0
  9. data/examples/basic_webapp/public/styles.css +346 -0
  10. data/examples/basic_webapp/scripts/generate_keys.rb +35 -0
  11. data/examples/basic_webapp/views/authorized.erb +48 -0
  12. data/examples/basic_webapp/views/index.erb +48 -0
  13. data/examples/{confidential_client → basic_webapp}/views/layout.erb +2 -2
  14. data/examples/bookmarks/Gemfile +16 -0
  15. data/examples/bookmarks/Gemfile.lock +158 -0
  16. data/examples/bookmarks/README.md +170 -0
  17. data/examples/bookmarks/Rakefile +23 -0
  18. data/examples/bookmarks/app/account.rb +16 -0
  19. data/examples/bookmarks/app/bookmark.rb +89 -0
  20. data/examples/bookmarks/app/init.rb +26 -0
  21. data/examples/bookmarks/app/oauth.rb +43 -0
  22. data/examples/bookmarks/app/server.rb +184 -0
  23. data/examples/bookmarks/config/oauth-client-metadata.localhost.json +11 -0
  24. data/examples/bookmarks/config/oauth-client-metadata.production.json +19 -0
  25. data/examples/bookmarks/config.ru +5 -0
  26. data/examples/bookmarks/db/migrate/20261107004141_create_bookmarks.rb +27 -0
  27. data/examples/bookmarks/db/schema.rb +33 -0
  28. data/examples/bookmarks/public/styles.css +59 -0
  29. data/examples/bookmarks/scripts/generate_keys.rb +35 -0
  30. data/examples/bookmarks/views/bookmarks.erb +86 -0
  31. data/examples/bookmarks/views/index.erb +17 -0
  32. data/examples/bookmarks/views/layout.erb +20 -0
  33. data/examples/minisky_console/Gemfile.lock +2 -2
  34. data/examples/minisky_console/README.md +29 -25
  35. data/examples/minisky_console/app.rb +3 -3
  36. data/examples/minisky_console/localhost.rb +5 -7
  37. data/examples/minisky_console/production.rb +6 -8
  38. data/lib/authproto/client.rb +505 -151
  39. data/lib/authproto/configuration.rb +1 -1
  40. data/lib/authproto/dpop/client.rb +28 -25
  41. data/lib/authproto/dpop/key_set.rb +2 -0
  42. data/lib/authproto/dpop/nonce_manager.rb +24 -25
  43. data/lib/authproto/dpop/proof_generator.rb +9 -5
  44. data/lib/authproto/dpop/stored_nonce.rb +7 -5
  45. data/lib/authproto/dpop.rb +2 -0
  46. data/lib/authproto/encryption.rb +31 -12
  47. data/lib/authproto/http_client.rb +13 -12
  48. data/lib/authproto/http_helpers.rb +6 -0
  49. data/lib/authproto/metadata/authorization_server.rb +15 -3
  50. data/lib/authproto/metadata/client_metadata.rb +34 -3
  51. data/lib/authproto/metadata/resource_server.rb +7 -6
  52. data/lib/authproto/minisky.rb +120 -33
  53. data/lib/authproto/par/client.rb +4 -2
  54. data/lib/authproto/par/client_assertion.rb +4 -1
  55. data/lib/authproto/par/request.rb +2 -0
  56. data/lib/authproto/par/response.rb +2 -0
  57. data/lib/authproto/par.rb +2 -0
  58. data/lib/authproto/pkce.rb +2 -0
  59. data/lib/authproto/serialization/session.rb +4 -2
  60. data/lib/authproto/serialization/stored_nonce.rb +2 -2
  61. data/lib/authproto/serialization/token_set.rb +5 -2
  62. data/lib/authproto/state/session.rb +23 -20
  63. data/lib/authproto/state/session_info.rb +150 -0
  64. data/lib/authproto/state/session_manager.rb +46 -19
  65. data/lib/authproto/state/token_set.rb +6 -3
  66. data/lib/authproto/state.rb +4 -2
  67. data/lib/authproto/storage/interface.rb +10 -0
  68. data/lib/authproto/storage/key_builder.rb +3 -3
  69. data/lib/authproto/storage/memory.rb +24 -18
  70. data/lib/authproto/storage/sqlite.rb +14 -0
  71. data/lib/authproto/token/identity.rb +54 -0
  72. data/lib/authproto/token/refresh.rb +44 -54
  73. data/lib/authproto/token/response.rb +75 -0
  74. data/lib/authproto/token/revocation.rb +94 -0
  75. data/lib/authproto/version.rb +1 -1
  76. data/lib/authproto.rb +6 -3
  77. data/sig/authproto/client.rbs +38 -13
  78. data/sig/authproto/dpop/client.rbs +9 -3
  79. data/sig/authproto/dpop/nonce_manager.rbs +6 -6
  80. data/sig/authproto/dpop/proof_generator.rbs +4 -4
  81. data/sig/authproto/dpop/stored_nonce.rbs +2 -2
  82. data/sig/authproto/encryption.rbs +4 -2
  83. data/sig/authproto/http_client.rbs +23 -7
  84. data/sig/authproto/http_helpers.rbs +1 -0
  85. data/sig/authproto/metadata/authorization_server.rbs +3 -3
  86. data/sig/authproto/metadata/client_metadata.rbs +2 -1
  87. data/sig/authproto/metadata/resource_server.rbs +2 -2
  88. data/sig/authproto/minisky.rbs +57 -0
  89. data/sig/authproto/state/session.rbs +13 -4
  90. data/sig/authproto/state/session_info.rbs +23 -0
  91. data/sig/authproto/state/session_manager.rbs +10 -3
  92. data/sig/authproto/storage/interface.rbs +1 -0
  93. data/sig/authproto/storage/key_builder.rbs +1 -1
  94. data/sig/authproto/storage/memory.rbs +1 -1
  95. data/sig/authproto/storage/sqlite.rbs +1 -0
  96. data/sig/authproto/token/refresh.rbs +2 -1
  97. data/sig/authproto/token/response.rbs +12 -0
  98. data/sig/authproto/token/revocation.rbs +15 -0
  99. data/sig/authproto.rbs +3 -8
  100. metadata +53 -19
  101. data/examples/confidential_client/Gemfile +0 -14
  102. data/examples/confidential_client/README.md +0 -236
  103. data/examples/confidential_client/app.rb +0 -291
  104. data/examples/confidential_client/public/styles.css +0 -70
  105. data/examples/confidential_client/scripts/generate_keys.rb +0 -21
  106. data/examples/confidential_client/views/authorized.erb +0 -46
  107. data/examples/confidential_client/views/index.erb +0 -44
  108. data/sig/authproto/minisky_oauth.rbs +0 -27
  109. /data/examples/{confidential_client/config/oauth-client-metadata.example.json → basic_webapp/config/oauth-client-metadata.production.json} +0 -0
  110. /data/examples/{confidential_client → basic_webapp}/config.ru +0 -0
  111. /data/examples/{confidential_client → basic_webapp}/screenshots/screenshot-1-sign-in.png +0 -0
  112. /data/examples/{confidential_client → basic_webapp}/screenshots/screenshot-2-success.png +0 -0
@@ -0,0 +1,14 @@
1
+ # frozen_string_literal: true
2
+
3
+ source 'https://rubygems.org'
4
+
5
+ gem 'authproto', path: '../..'
6
+ gem 'dotenv'
7
+ gem 'faraday'
8
+ gem 'json'
9
+ gem 'puma'
10
+ gem 'rackup'
11
+ gem 'redis'
12
+ gem 'sinatra'
13
+ gem 'sinatra-contrib'
14
+ gem 'sqlite3', '~> 2.9'
@@ -1,7 +1,7 @@
1
1
  PATH
2
2
  remote: ../..
3
3
  specs:
4
- authproto (0.3.0.beta1)
4
+ authproto (0.3.0.beta5)
5
5
  didkit (~> 0.5.0)
6
6
  jose (~> 1.2)
7
7
  jwt (~> 3.3)
@@ -0,0 +1,300 @@
1
+ # Basic OAuth webapp client example
2
+
3
+ This is an example implementation of a simple webapp with an OAuth client for the AT Protocol using the AuthProto gem. It demonstrates how to implement the OAuth flow for a web application. Can be run both as a public and a confidential client.
4
+
5
+ <img src="https://github.com/mackuba/authproto/blob/main/examples/basic_webapp/screenshots/screenshot-1-sign-in.png?raw=true" alt="Sign In Form Screenshot" title="Sign In Form" width="450">
6
+ <img src="https://github.com/mackuba/authproto/blob/main/examples/basic_webapp/screenshots/screenshot-2-success.png?raw=true" alt="Sign In Success Screenshot" title="Sign In Success" width="450">
7
+
8
+ ## Overview
9
+
10
+ The example implements a simple web application using Sinatra which:
11
+
12
+ - Allows a user to log in using their AT Protocol @handle
13
+ - Implements the complete OAuth authorization flow
14
+ - Shows how to make authenticated API calls to Bluesky, displaying account info and letting the user make a test Bluesky post
15
+ - Allows you to choose a storage configuration for session management
16
+ - Supports running on localhost (as a public client) and on a live domain (as public or confidential client)
17
+
18
+ ## Requirements
19
+
20
+ - Ruby 3.3+
21
+ - a domain name and an SSL certificate for your application for live deployment
22
+
23
+ ## Setup
24
+
25
+ 1. Clone the repository and navigate to the example app directory:
26
+
27
+ ```bash
28
+ cd examples/basic_webapp
29
+ ```
30
+
31
+ 2. Install dependencies:
32
+
33
+ ```bash
34
+ bundle install
35
+ ```
36
+
37
+
38
+ ## Client metadata
39
+
40
+ An ATProto OAuth app needs to have a [Client Metadata JSON file](https://atproto.com/specs/oauth#client-id-metadata-document), which configures the app's security settings and some user-facing info. This JSON file is normally hosted at the `/oauth-client-metadata.json` path. This app includes such endpoint, and reads the contents of the JSON to serve there from a file at `config/oauth-client-metadata.json`.
41
+
42
+ The configuration differs for localhost testing and a production site:
43
+
44
+ For localhost testing:
45
+
46
+ - Create a metadata file from the included **<u>localhost</u>** example:
47
+ ```bash
48
+ cp config/oauth-client-metadata.localhost.json config/oauth-client-metadata.json
49
+ ```
50
+ Here, this file is only used by the app to read the redirect URI and scope from there – it's not accessed by the authorization server.
51
+
52
+ For a live version:
53
+
54
+ - Create a metadata file from the included **<u>production</u>** example:
55
+ ```bash
56
+ cp config/oauth-client-metadata.production.json config/oauth-client-metadata.json
57
+ ```
58
+ - Replace the `YOUR_DOMAIN_HERE` in the URLs with the hostname where your app will be hosted
59
+ - If you want to use the app as a confidential client, generate the signing keys for client authentication (client assertions):
60
+ ```bash
61
+ bundle exec ruby scripts/generate_keys.rb
62
+ ```
63
+ and copy the private and public keys to `config/keys.json` and `config/oauth-client-metadata.json` respectively.
64
+ - Otherwise, if you want to run it as a public client:
65
+ - change `token_endpoint_auth_method` in the metadata JSON to `"none"`
66
+ - remove the `token_endpoint_auth_signing_alg` line
67
+ - remove the `jwks` section
68
+
69
+ ## App configuration
70
+
71
+ Apart from the `oauth-client-metadata.json` & `keys.json` files, the app is configured through ENV variables. You can set them through `export` on the command line, but it also has [dotenv](https://github.com/bkeepers/dotenv) set up, so you can put the config vars in a file named `.env`.
72
+
73
+ You will need:
74
+
75
+ ### 1. Session & encryption keys
76
+
77
+ Generate them like this:
78
+
79
+ ```bash
80
+ openssl rand -base64 32
81
+ openssl rand -hex 32
82
+
83
+ cat > .env
84
+ ATPROTO_MASTER_KEY=<base64 value from first command>
85
+ SESSION_SECRET=<hex value from second command>
86
+ ```
87
+
88
+ `ATPROTO_MASTER_KEY` is used by AuthProto to encrypt some of the stored session/nonce data in the configured storage; `SESSION_SECRET` is used by `Rack::Session::Cookie` for the browser session.
89
+
90
+ ### 2. Storage configuration
91
+
92
+ AuthProto includes three storage backends:
93
+
94
+ * SQLite database
95
+ * Redis database
96
+ * transient in-memory storage (lost on restart)
97
+
98
+ In this example app, use these env vars to configure the storage:
99
+
100
+ # Select a storage backend: memory (default), sqlite, or redis
101
+ STORAGE_BACKEND=sqlite
102
+
103
+ # Optional SQLite path (defaults to ./db/authproto.sqlite3)
104
+ SQLITE_PATH=/var/lib/my-app/authproto.sqlite3
105
+
106
+ # Required when STORAGE_BACKEND=redis
107
+ REDIS_URL=redis://localhost:6379
108
+
109
+ ### 3. Host authorization
110
+
111
+ When running the app on a live domain, set `PERMITTED_DOMAIN` env var to that domain. This is passed to the [:host_authorization](https://sinatrarb.com/intro.html#available-settings) option in Sinatra, which uses it to configure the [Rack::Protection::HostAuthorization](https://github.com/sinatra/sinatra/blob/main/rack-protection/lib/rack/protection/host_authorization.rb) middleware.
112
+
113
+ PERMITTED_DOMAIN=your.domain.com
114
+
115
+ Remember to also set that domain in the URLs in `oauth-client-metadata.json` under `client_id` & `redirect_uris`.
116
+
117
+
118
+ ## Running the Application
119
+
120
+ ### Development
121
+
122
+ ```bash
123
+ bundle exec rackup
124
+ ```
125
+
126
+ ### Production
127
+
128
+ ```bash
129
+ RACK_ENV=production bundle exec rackup
130
+ ```
131
+
132
+ This will start the server on `http://localhost:9292`. For a live deployment, the application must be accessible from the Internet for OAuth to work – the Authorization Server (PDS or entryway) needs to be able to load your `oauth-client-metadata.json` file before you can start the OAuth flow – so you will need to configure e.g. Nginx or Caddy to route requests from a given domain to your app, or use something like Passenger inside Nginx/Apache.
133
+
134
+
135
+ ### Tailscale
136
+
137
+ Alternatively, you can use a **Tailscale Funnel** to expose your local development server to the Internet:
138
+
139
+ 1. Install Tailscale, sign in, and follow the [Funnel setup instructions](https://tailscale.com/docs/features/tailscale-funnel), including enabling MagicDNS.
140
+ 2. Start your Funnel in a separate terminal, and follow any prompts to enable Funnel and HTTPS. Tailscale automatically provisions the HTTPS certificate:
141
+ ```bash
142
+ tailscale funnel 9292
143
+ ```
144
+
145
+ 3. Keep this command running. It prints the public HTTPS URL for your machine, such as https://machinename.xyz.ts.net. ([Funnel command documentation](https://tailscale.com/docs/reference/tailscale-cli/funnel))
146
+ 4. Update your metadata to use that public URL, e.g.:
147
+ ```
148
+ "client_id": "https://machinename.xyz.ts.net/oauth-client-metadata.json",
149
+ "redirect_uris": ["https://machinename.xyz.ts.net/callback"]
150
+ ```
151
+ 5. Set `PERMITTED_DOMAIN` to that hostname in the `.env` file:
152
+ ```
153
+ PERMITTED_DOMAIN=machinename.xyz.ts.net
154
+ ```
155
+ or set it in an ENV var in the terminal where you will run the application:
156
+ ```bash
157
+ export PERMITTED_DOMAIN=machinename.xyz.ts.net
158
+ ```
159
+
160
+ 6. Run the application on port 9292 as described above.
161
+
162
+ Open the public HTTPS URL to use the application – Funnel now forwards requests to your local HTTP server.
163
+
164
+
165
+ ### Cloudflare
166
+
167
+ Another option is a **Cloudflare Quick Tunnel**:
168
+
169
+ 1. Install [cloudflared](https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/downloads/) (no Cloudflare account or domain is required).
170
+ 2. Start your tunnel in a separate terminal:
171
+ ```bash
172
+ cloudflared tunnel --url http://localhost:9292
173
+ ```
174
+ 3. Keep this command running. It prints a public HTTPS URL, such as https://random-words.trycloudflare.com; HTTPS is configured automatically.
175
+ 4. Update your metadata to use that public URL, e.g.:
176
+ ```
177
+ "client_id": "https://random-words.trycloudflare.com/oauth-client-metadata.json",
178
+ "redirect_uris": ["https://random-words.trycloudflare.com/callback"]
179
+ ```
180
+ 5. Set `PERMITTED_DOMAIN` to that hostname in the `.env` file:
181
+ ```
182
+ PERMITTED_DOMAIN=random-words.trycloudflare.com
183
+ ```
184
+ or set it in an ENV var in the terminal where you will run the application:
185
+ ```bash
186
+ export PERMITTED_DOMAIN=random-words.trycloudflare.com
187
+ ```
188
+
189
+ 6. Run the application on port 9292 as described above.
190
+
191
+ Then open the public HTTPS URL to use the application. The hostname changes each time you create a Quick Tunnel, so update the metadata and `PERMITTED_DOMAIN`, then restart the application whenever it changes. ([Cloudflare Quick Tunnel documentation](https://developers.cloudflare.com/tunnel/get-started/quick-tunnels/))
192
+
193
+
194
+ ## Troubleshooting
195
+
196
+ Some common issues you might come across:
197
+
198
+ * Invalid redirect URI
199
+ - Ensure your redirect URI matches exactly what's in your client metadata
200
+ - Check if your domain matches the `client_id` domain
201
+ * Invalid client metadata
202
+ - Verify that your client metadata is accessible at the URL specified in `client_id`
203
+ - Check if your JSON is valid and contains all required fields:
204
+ - `grant_types` must include `"authorization_code"` and should include `"refresh_token"` too
205
+ - `response_types` must include `"code"`
206
+ - `scope` must be one string with a space-separated list
207
+ - the scopes must include `atproto`
208
+ - `token_endpoint_auth_method` must be `"none"` for public and `"private_key_jwt"` for confidential clients
209
+ - `token_endpoint_auth_signing_alg` must be `"ES256"` for confidential clients and should not be set for public ones
210
+ - `dpop_bound_access_tokens` must be `true`
211
+ - `jwks` must be included for confidential clients and not included for public ones
212
+ * Authorization failed
213
+ - Verify your JWKS configuration
214
+ * Storage errors
215
+ - For SQLite storage, verify that the database path is writable
216
+ - For Redis storage, verify Redis connection settings
217
+ - Check Redis SSL configuration, if using encrypted connections
218
+ - Ensure proper Redis authentication credentials, if required
219
+ * Session state lost
220
+ - Verify if storage configuration is correct
221
+ - Check that SQLite storage is on persistent local disk
222
+ - Check Redis connection if using Redis storage
223
+ - Check if TTL configuration isn't overridden
224
+ - Check if `ATPROTO_MASTER_KEY` and `SESSION_SECRET` env vars are being set & read correctly
225
+
226
+
227
+ ## Walkthrough of the app code
228
+
229
+ The whole app is contained in the single [app.rb](https://tangled.org/mackuba.eu/authproto/blob/main/examples/basic_webapp/app.rb) file.
230
+
231
+ Here's what it does:
232
+
233
+
234
+ ### Configuration
235
+
236
+ * verifies that the `SESSION_SECRET` and `config/oauth-client-metadata.json` are provided
237
+ * calls `AuthProto.configure` to configure:
238
+ - required HTTP client
239
+ - session storage depending on `STORAGE_BACKEND`
240
+ * parses the metadata file and reads some fields like `client_id` and `redirect_uris` from it
241
+ * creates an `AuthProto::Client` in one of two ways depending on the configuration
242
+ * sets up `Rack::Protection::HostAuthorization` and `Rack::Session::Cookie`
243
+
244
+
245
+ ### Helpers
246
+
247
+ The `helpers do ... end` block defines some helper functions – these are accessible both in the endpoint action methods and in the ERB templates. `load_session` looks up a saved session using a browser session variable if set, and `html_escape` escapes some content in the template for safety.
248
+
249
+
250
+ ### GET /
251
+
252
+ This just renders a landing page template, and redirects to the authorized page if authorized.
253
+
254
+
255
+ ### GET /oauth-client-metadata.json
256
+
257
+ Serves the required metadata JSON file on the production site (this is ignored when testing on localhost).
258
+
259
+
260
+ ### POST /authenticate
261
+
262
+ This endpoint starts the authorization flow:
263
+
264
+ - calls `AuthProto::Client#authorize` to generate an authorization URL on user's PDS (behind the scenes, this actually submits all required parameters to the server first in a PAR request)
265
+ - saves the ID of the new pending session into a browser session variable
266
+ - redirects the user's browser to the authorization URL
267
+
268
+ The user then either approves or rejects the authorization prompt, which redirects them to:
269
+
270
+
271
+ ### GET /callback
272
+
273
+ This endpoint handles the callback and checks the results of the authorization:
274
+
275
+ - if an error is returned, presents it to the user
276
+ - otherwise, passes the authorization codes to `AuthProto::Client#handle_callback` and gets back access tokens
277
+ - `handle_callback` also requires us to pass the session ID read back from the browser session – we need to confirm here that this is the same browser session that started the authorization flow a moment earlier
278
+
279
+
280
+ ### GET /authorized
281
+
282
+ The home page for an authorized user:
283
+
284
+ - looks up the session to check if a user is logged in (and which user)
285
+ - refreshes the access token if it's expired or expiring soon
286
+ - makes a test authenticated call to `com.atproto.server.checkAccountStatus` and shows the returned account info; this uses:
287
+ - `#auth_headers` to generate authentication headers for a request
288
+ - `#with_nonce_handling` wrapper to handle DPoP nonces and repeat the request if necessary
289
+ - Faraday gem (as an example) to make the requests
290
+
291
+
292
+ ### POST /posts
293
+
294
+ This endpoint makes a test post on Bluesky, with a text submitted from the text area on the authorized home page. It follows similar steps as above to make an authenticated call to the PDS API.
295
+
296
+
297
+ ### GET /logout
298
+
299
+ This deletes the session data from the configured session storage, revokes the access tokens on the authentication server (PDS), and erases the session ID variable from the browser session, returning to the landing page.
300
+
@@ -0,0 +1,351 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'json'
4
+ require 'securerandom'
5
+ require 'time'
6
+ require 'uri'
7
+
8
+ require 'authproto'
9
+ require 'dotenv/load'
10
+ require 'faraday'
11
+ require 'sinatra/base'
12
+ require 'sinatra/reloader'
13
+
14
+
15
+ class ExampleApp < Sinatra::Base
16
+ configure :development do
17
+ register Sinatra::Reloader
18
+ end
19
+
20
+ configure do
21
+ # Configure AuthProto settings
22
+ AuthProto.configure do |config|
23
+ config.http_client = AuthProto::HTTPClient.new(timeout: 10)
24
+
25
+ storage = ENV.fetch("STORAGE_BACKEND", 'memory')
26
+
27
+ case storage
28
+ when 'memory'
29
+ config.storage = AuthProto::Storage::Memory.new
30
+ when 'sqlite'
31
+ config.storage = AuthProto::Storage::SQLite.new(
32
+ path: ENV.fetch("SQLITE_PATH", File.join(__dir__, 'db', 'authproto.sqlite3'))
33
+ )
34
+ when 'redis'
35
+ config.storage = AuthProto::Storage::Redis.new(
36
+ redis_client: Redis.new(url: ENV.fetch("REDIS_URL"))
37
+ )
38
+ else
39
+ raise "STORAGE_BACKEND must be memory, sqlite, or redis"
40
+ end
41
+ end
42
+
43
+ # Load client metadata
44
+ metadata_path = File.join(__dir__, 'config', 'oauth-client-metadata.json')
45
+ raise "Missing metadata JSON file at config/oauth-client-metadata.json" unless File.exist?(metadata_path)
46
+
47
+ metadata = JSON.parse(File.read(metadata_path))
48
+ client_id = metadata['client_id']
49
+ redirect_uri = metadata['redirect_uris'][0]
50
+
51
+ keys_path = File.join(__dir__, 'config', 'keys.json')
52
+
53
+ # Load private signing key for client assertions, if found
54
+ if File.exist?(keys_path)
55
+ signing_key = JSON.parse(File.read(keys_path))['keys'].first
56
+ end
57
+
58
+ if AuthProto::Client.localhost_app?(client_id)
59
+ # For localhost apps, redirect_uri & scope are appended as query params to the client_id URI
60
+ # Use this helper which does that for you:
61
+ oauth_client = AuthProto::Client.for_localhost(redirect_uri: redirect_uri, scope: metadata['scope'])
62
+
63
+ if signing_key
64
+ warn "-" * 100
65
+ warn "Running the app on localhost as a public client - confidential clients require a production server."
66
+ warn "-" * 100
67
+ end
68
+ else
69
+ oauth_client = AuthProto::Client.new(
70
+ client_id: client_id,
71
+ redirect_uri: redirect_uri,
72
+ metadata: metadata,
73
+ signing_key: signing_key
74
+ )
75
+
76
+ # Apps on a live server can be public or confidential clients
77
+ if !signing_key
78
+ warn "-" * 100
79
+ warn "Missing config/keys.json - running the app as a public client."
80
+ warn "-" * 100
81
+ end
82
+ end
83
+
84
+ # Store the OAuth client in the global settings
85
+ set :oauth_client, oauth_client
86
+ set :metadata_path, metadata_path
87
+
88
+ set :host_authorization, {
89
+ permitted_hosts: ["localhost", "127.0.0.1", ENV.fetch("PERMITTED_DOMAIN", nil)].compact
90
+ }
91
+
92
+ session_secret = ENV.fetch("SESSION_SECRET") { SecureRandom.hex(32) }
93
+ raise "SESSION_SECRET must be at least 64 characters long (got: #{session_secret})" if session_secret.length < 64
94
+
95
+ use Rack::Session::Cookie,
96
+ key: "atproto.session",
97
+ expire_after: 86_400, # 1 day in seconds
98
+ secret: session_secret,
99
+ secure: production?, # Only send over HTTPS
100
+ httponly: true, # Not accessible via JavaScript
101
+ same_site: :lax # CSRF protection
102
+ end
103
+
104
+ helpers do
105
+ def load_session
106
+ session_id = session[:oauth_session_id]
107
+ return nil unless session_id
108
+
109
+ begin
110
+ oauth_session = settings.oauth_client.get_session(session_id)
111
+ return nil if !oauth_session || oauth_session.pending?
112
+
113
+ session_id
114
+ rescue AuthProto::Client::SessionError
115
+ # Clear invalid session
116
+ session.delete(:oauth_session_id)
117
+ nil
118
+ end
119
+ end
120
+
121
+ def log_error(e)
122
+ if settings.development?
123
+ puts e
124
+ puts e.backtrace.take_while { |l| !l.include?('/lib/sinatra/base') }
125
+ end
126
+ end
127
+
128
+ def html_escape(text)
129
+ Rack::Utils.escape_html(text)
130
+ end
131
+ end
132
+
133
+ # The landing / login page
134
+ get "/" do
135
+ redirect "/authorized" if load_session
136
+
137
+ erb :index
138
+ end
139
+
140
+ # Client metadata served on a standard endpoint (only needed on the live site)
141
+ get "/oauth-client-metadata.json" do
142
+ content_type :json
143
+
144
+ File.read(settings.metadata_path)
145
+ end
146
+
147
+ # Starts the OAuth flow and redirects the user to the PDS's OAuth authorization page
148
+ post "/authenticate" do
149
+ handle = params[:handle]
150
+
151
+ begin
152
+ auth = settings.oauth_client.authorize(
153
+ handle: handle,
154
+ scope: "atproto repo:app.bsky.feed.post"
155
+ )
156
+
157
+ session_id, authorization_url = auth.values_at(:session_id, :url)
158
+
159
+ # Remember the ID of the created OAuth session in the browser session.
160
+ #
161
+ # We need to extract it later when receiving the callback completing the authorization, in order to verify
162
+ # that the authorization was started in the same browser session (and that we aren't logging in the user to
163
+ # someone else's browser session).
164
+
165
+ session[:pending_oauth_session_id] = session_id
166
+
167
+ # This is an authorization URL on the user's PDS, redirect them there:
168
+ redirect authorization_url
169
+ rescue StandardError => e
170
+ log_error(e)
171
+ session[:error] = "Authorization failed: #{e.message}"
172
+ redirect "/"
173
+ end
174
+ end
175
+
176
+ # OAuth callback handler to which the user gets redirected back, which completes the authorization flow
177
+ get "/callback" do
178
+ # Handle possible errors (e.g. user has rejected authorization)
179
+ # You can also pass it as is to `oauth_client.handle_callback` and get a `CallbackError`
180
+ if params[:error]
181
+ message = params[:error]
182
+ message += ": " + params[:error_description] if params[:error_description]
183
+ session[:error] = "Authorization failed: #{message}"
184
+ redirect "/"
185
+ end
186
+
187
+ # Extract the session ID previously stored in this browser session and pass it to oauth_client for verification.
188
+ pending_session_id = session[:pending_oauth_session_id]
189
+
190
+ result = settings.oauth_client.handle_callback(
191
+ params,
192
+ expected_session_id: pending_session_id
193
+ )
194
+
195
+ session.delete(:pending_oauth_session_id)
196
+ session[:oauth_session_id] = result.session_id
197
+
198
+ redirect "/authorized"
199
+ rescue StandardError => e
200
+ log_error(e)
201
+ session[:error] = "Authorization failed: #{e.message}"
202
+ redirect "/"
203
+ end
204
+
205
+ # Home page for a logged in user. Makes a sample request to test authorization headers API.
206
+ get "/authorized" do
207
+ session_id = load_session
208
+ redirect "/" if session_id.nil?
209
+
210
+ # Get current session info
211
+ oauth_session = settings.oauth_client.get_session(session_id)
212
+
213
+ # Check if token needs refresh
214
+ begin
215
+ if !oauth_session.tokens_valid?
216
+ oauth_session = settings.oauth_client.refresh_token(session_id)
217
+ end
218
+ rescue StandardError => e
219
+ log_error(e)
220
+ session[:error] = "Token refresh failed: #{e.message}"
221
+ halt erb(:index)
222
+ end
223
+
224
+ # Make test API call to com.atproto.server.checkAccountStatus using Faraday
225
+ begin
226
+ pds = oauth_session.pds
227
+ endpoint = "/xrpc/com.atproto.server.checkAccountStatus"
228
+ url = URI.join(pds, endpoint)
229
+
230
+ connection = Faraday.new(url: pds) do |f|
231
+ f.request :json
232
+ end
233
+
234
+ # This wrapper repeats the request if needed with updated DPoP nonce
235
+ response = settings.oauth_client.with_nonce_handling(session_id, url) do
236
+ # Create authentication headers for this request
237
+ headers = settings.oauth_client.auth_headers(
238
+ session_id: session_id,
239
+ method: 'GET',
240
+ url: url
241
+ )
242
+
243
+ # Make authenticated request
244
+ res = connection.get(endpoint) do |req|
245
+ req.headers.merge!(headers)
246
+ end
247
+
248
+ # Convert the Faraday response to expected format
249
+ { status: res.status, body: res.body, headers: res.headers }
250
+ end
251
+
252
+ if response[:status] == 200
253
+ @api_result = JSON.parse(response[:body])
254
+ @session = oauth_session
255
+ else
256
+ session[:error] = "API call failed: HTTP #{response[:status]}: #{response[:body]}"
257
+ end
258
+
259
+ erb :authorized
260
+ rescue StandardError => e
261
+ log_error(e)
262
+ session[:error] = "API call failed: #{e.message}"
263
+ erb :index
264
+ end
265
+ end
266
+
267
+ # Make a test post on Bluesky
268
+ post "/posts" do
269
+ session_id = load_session
270
+ redirect "/" if session_id.nil?
271
+
272
+ # Get current session info and refresh expired tokens before publishing
273
+ oauth_session = settings.oauth_client.get_session(session_id)
274
+
275
+ if !oauth_session.tokens_valid?
276
+ oauth_session = settings.oauth_client.refresh_token(session_id)
277
+ end
278
+
279
+ text = params[:text].to_s
280
+
281
+ if text.strip.empty?
282
+ session[:error] = "Post text cannot be empty"
283
+ redirect "/authorized"
284
+ end
285
+
286
+ if text.length > 300 || text.bytesize > 3_000
287
+ session[:error] = "Post text must be at most 300 characters and 3,000 bytes"
288
+ redirect "/authorized"
289
+ end
290
+
291
+ pds = oauth_session.pds
292
+ endpoint = "/xrpc/com.atproto.repo.createRecord"
293
+ url = URI.join(pds, endpoint)
294
+
295
+ record = {
296
+ repo: oauth_session.did,
297
+ collection: "app.bsky.feed.post",
298
+ record: {
299
+ text: text,
300
+ langs: ["en"],
301
+ createdAt: Time.now.utc.iso8601(3)
302
+ }
303
+ }
304
+
305
+ connection = Faraday.new(url: pds) do |f|
306
+ f.request :json
307
+ end
308
+
309
+ # This wrapper repeats the request if needed with updated DPoP nonce
310
+ response = settings.oauth_client.with_nonce_handling(session_id, url) do
311
+ # Create authentication headers for this request
312
+ headers = settings.oauth_client.auth_headers(
313
+ session_id: session_id,
314
+ method: 'POST',
315
+ url: url
316
+ )
317
+
318
+ # Make authenticated request
319
+ res = connection.post(endpoint) do |req|
320
+ req.headers.merge!(headers)
321
+ req.body = record
322
+ end
323
+
324
+ # Convert the Faraday response to expected format
325
+ { status: res.status, body: res.body, headers: res.headers }
326
+ end
327
+
328
+ unless response[:status] == 200
329
+ session[:error] = "Error #{response[:status]}: #{response[:body]}"
330
+ redirect "/authorized"
331
+ end
332
+
333
+ session[:notice] = "Post published successfully"
334
+ redirect "/authorized"
335
+ rescue StandardError => e
336
+ log_error(e)
337
+ session[:error] = "Publishing post failed: #{e.message}"
338
+ redirect "/authorized"
339
+ end
340
+
341
+ get "/logout" do
342
+ if session[:oauth_session_id]
343
+ # Revoke access tokens and clean up the stored session
344
+ settings.oauth_client.delete_session(session[:oauth_session_id], revoke: true)
345
+ end
346
+
347
+ session.clear
348
+ session[:notice] = "Successfully logged out"
349
+ redirect "/"
350
+ end
351
+ end
@@ -0,0 +1,11 @@
1
+ {
2
+ "client_id": "http://localhost",
3
+ "client_name": "AT Protocol OAuth Ruby Example",
4
+ "redirect_uris": ["http://127.0.0.1:9292/callback"],
5
+ "grant_types": ["authorization_code", "refresh_token"],
6
+ "response_types": ["code"],
7
+ "scope": "atproto repo:app.bsky.feed.post",
8
+ "token_endpoint_auth_method": "none",
9
+ "application_type": "web",
10
+ "dpop_bound_access_tokens": true
11
+ }