devise-webauthn 0.2.1 → 0.3.0

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 (38) hide show
  1. checksums.yaml +4 -4
  2. data/.github/dependabot.yml +6 -0
  3. data/.github/workflows/ruby.yml +6 -2
  4. data/.rubocop.yml +1 -0
  5. data/Appraisals +18 -4
  6. data/CHANGELOG.md +50 -8
  7. data/Gemfile +2 -2
  8. data/Gemfile.lock +3 -5
  9. data/README.md +158 -5
  10. data/app/assets/javascript/devise/webauthn.js +179 -0
  11. data/app/controllers/devise/passkeys_controller.rb +6 -1
  12. data/app/controllers/devise/second_factor_webauthn_credentials_controller.rb +31 -4
  13. data/config/locales/en.yml +6 -0
  14. data/devise-webauthn.gemspec +1 -1
  15. data/gemfiles/devise_5_0.gemfile +26 -0
  16. data/gemfiles/rails_7_1.gemfile +3 -2
  17. data/gemfiles/rails_7_2.gemfile +3 -2
  18. data/gemfiles/rails_8_0.gemfile +3 -2
  19. data/gemfiles/rails_8_1.gemfile +3 -2
  20. data/gemfiles/rails_edge.gemfile +2 -1
  21. data/lib/devise/strategies/database_authenticatable.rb +1 -0
  22. data/lib/devise/strategies/webauthn_two_factor_authenticatable.rb +11 -5
  23. data/lib/devise/webauthn/engine.rb +6 -0
  24. data/lib/devise/webauthn/helpers/credentials_helper.rb +21 -36
  25. data/lib/devise/webauthn/routes.rb +1 -1
  26. data/lib/devise/webauthn/test/authenticator_helpers.rb +42 -0
  27. data/lib/devise/webauthn/version.rb +1 -1
  28. data/lib/generators/devise/webauthn/controllers_generator.rb +5 -1
  29. data/lib/generators/devise/webauthn/install/install_generator.rb +2 -2
  30. data/lib/generators/devise/webauthn/javascript/javascript_configuration_generator.rb +64 -0
  31. data/lib/generators/devise/webauthn/templates/controllers/second_factor_webauthn_credentials_controller.rb.tt +48 -0
  32. data/lib/generators/devise/webauthn/templates/controllers/two_factor_authentications_controller.rb.tt +13 -0
  33. data/lib/generators/devise/webauthn/views_generator.rb +2 -0
  34. data/lib/generators/devise/webauthn/webauthn_credential_model/templates/webauthn_credential_migration.rb.erb +17 -0
  35. data/lib/generators/devise/webauthn/webauthn_credential_model/webauthn_credential_model_generator.rb +15 -9
  36. metadata +10 -5
  37. data/lib/generators/devise/webauthn/stimulus/stimulus_generator.rb +0 -24
  38. data/lib/generators/devise/webauthn/stimulus/templates/webauthn_credentials_controller.js +0 -31
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 8083a823cce7edf858475a062ea009193c3a86cf9b4a821db1dd2715430580d4
4
- data.tar.gz: df00de569113a642c13f87cc4f6c93836acb5c5df1ef1cecfe492b01247a17aa
3
+ metadata.gz: aaa4817ea2af9200fa03ddf48357462fee35e64624b14d0de881b7805af7a34d
4
+ data.tar.gz: 88b7affbb03be29d61834f20924db27ecd8623c0f7c5463ce59554ebd727dcd7
5
5
  SHA512:
6
- metadata.gz: ce764390d121fc68bd1732d655700ccae382ced384a24f350256f2bb633910d0038972637a8e9f4f5e512d0e13030c53851f7288733fb233e8d86fe00ab5c8b8
7
- data.tar.gz: d2072d245253437be40005c81b9879f22f0a7c0fa3e0e3cd39b9b03f812aa05cdcd7404cbd4123afac473785364472f3e025dbdf025ae3f74af117854dcbca38
6
+ metadata.gz: 963eaa9ff4ce30759da2bb0b90fd2e8af1118c3c51caad4b574b7e28873033cdf16cdc9a91c29d21a4be2676e78255665df5db50d524c29a9321dfc864490a78
7
+ data.tar.gz: 758cb30bc99014c144ad7b8467cb9a24da62c7c0a1c7db1b7565436973ab145041ad3ac8eabf1951b648e56caa5682459ec0ebaf5f0fd21f0b8b07341c95b30a
@@ -0,0 +1,6 @@
1
+ version: 2
2
+ updates:
3
+ - package-ecosystem: "github-actions"
4
+ directory: "/"
5
+ schedule:
6
+ interval: "weekly"
@@ -8,7 +8,7 @@ jobs:
8
8
 
9
9
  steps:
10
10
  - name: Check out repository code
11
- uses: actions/checkout@v5
11
+ uses: actions/checkout@v6
12
12
 
13
13
  - name: Set up Ruby
14
14
  uses: ruby/setup-ruby@v1
@@ -36,8 +36,12 @@ jobs:
36
36
  - rails_8_0
37
37
  - rails_7_2
38
38
  - rails_7_1
39
+ - devise_5_0
39
40
 
40
41
  exclude:
42
+ - ruby: 3.2
43
+ gemfile: rails_edge
44
+
41
45
  - ruby: 3.1
42
46
  gemfile: rails_edge
43
47
  - ruby: 3.1
@@ -69,7 +73,7 @@ jobs:
69
73
 
70
74
  steps:
71
75
  - name: Check out repository code
72
- uses: actions/checkout@v5
76
+ uses: actions/checkout@v6
73
77
 
74
78
  - name: Set up Ruby
75
79
  uses: ruby/setup-ruby@v1
data/.rubocop.yml CHANGED
@@ -7,6 +7,7 @@ AllCops:
7
7
  NewCops: enable
8
8
  Exclude:
9
9
  - "spec/internal/**/*"
10
+ - "spec/tmp/**/*"
10
11
  - "vendor/**/*"
11
12
  - "gemfiles/**/*"
12
13
  - "lib/devise/strategies/database_authenticatable.rb"
data/Appraisals CHANGED
@@ -5,19 +5,19 @@ appraise "rails-edge" do
5
5
  end
6
6
 
7
7
  appraise "rails-8_1" do
8
- gem "rails", "~> 8.1"
8
+ gem "rails", "~> 8.1.x"
9
9
  end
10
10
 
11
11
  appraise "rails-8_0" do
12
- gem "rails", "~> 8.0"
12
+ gem "rails", "~> 8.0.x"
13
13
  end
14
14
 
15
15
  appraise "rails-7_2" do
16
- gem "rails", "~> 7.2"
16
+ gem "rails", "~> 7.2.x"
17
17
  end
18
18
 
19
19
  appraise "rails-7_1" do
20
- gem "rails", "~> 7.1"
20
+ gem "rails", "~> 7.1.x"
21
21
 
22
22
  gem "capybara", "~> 3.39"
23
23
  gem "importmap-rails", "~> 2.0"
@@ -27,3 +27,17 @@ appraise "rails-7_1" do
27
27
  gem "rspec-rails", "~> 7.1"
28
28
  gem "sqlite3", "~> 1.7"
29
29
  end
30
+
31
+ appraise "devise-5_0" do
32
+ gem "devise", "~> 5.0.0.rc"
33
+
34
+ gem "rails", ">= 7.1"
35
+ gem "capybara", "~> 3.39"
36
+ gem "importmap-rails", "~> 2.0"
37
+ gem "pry-byebug", "~> 3.10"
38
+ install_if "-> { RUBY_VERSION < \"3.0\" }" do
39
+ gem "rack", "~> 2.2"
40
+ end
41
+ gem "rspec-rails", ">= 7.1"
42
+ gem "sqlite3", ">= 1.6", "!= 1.7.0", "!= 1.7.1", "!= 1.7.2", "!= 1.7.3"
43
+ end
data/CHANGELOG.md CHANGED
@@ -2,31 +2,73 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ ## [v0.3.0](https://github.com/cedarcode/devise-webauthn/compare/v0.2.2...v0.3.0/) - 2026-01-16
6
+
7
+ ### Added
8
+
9
+ - WebAuthn JavaScript is now bundled as engine assets using custom HTML elements (`<webauthn-create>`, `<webauthn-get>`) instead of generating a Stimulus controller into the host application. [#84](https://github.com/cedarcode/devise-webauthn/pull/84) [@santiagorodriguez96]
10
+ - Add endpoint to `SecondFactorWebauthnCredentialsController` for "upgrading" second factor webauthn credentials (i. e., security keys) to passkeys. [#80](https://github.com/cedarcode/devise-webauthn/pull/80) [@nicolastemciuc]
11
+
12
+ ### Changed
13
+
14
+ - Loosen `devise` upper constraint to allow for v5. [#94](https://github.com/cedarcode/devise-webauthn/pull/94) [@santiagorodriguez96]
15
+ - BREAKING!: Our [Form helpers](https://github.com/cedarcode/devise-webauthn/blob/355a6836315439f71265bb368bff4e8067033072/lib/devise/webauthn/helpers/credentials_helper.rb#L7-L58) now use the bundled WebAuthn JS asset now instead of the Stimulus controllers, so they expect it to be included in your application. [#84](https://github.com/cedarcode/devise-webauthn/pull/84) [@santiagorodriguez96]
16
+ - Previously generated Stimulus controller for handling WebAuthn client logic are no longer generated.
17
+ - Stimulus is no longer needed for this engine to work.
18
+ - Make helpers for generating WebAuthn options public methods. [#106](https://github.com/cedarcode/devise-webauthn/pull/106) [@santiagorodriguez96]
19
+
20
+ ### Fixed
21
+
22
+ - Fix `Remember me` checkbox not honored when going through the 2FA challenge flow. [#87](https://github.com/cedarcode/devise-webauthn/pull/87) [@santiagorodriguez96]
23
+
24
+ ## [v0.2.2](https://github.com/cedarcode/devise-webauthn/compare/v0.2.1...v0.2.2/) - 2025-12-11
25
+
26
+ ### Added
27
+
28
+ - Update controllers and views generators to generate 2FA-related controllers and views. [#75](https://github.com/cedarcode/devise-webauthn/pull/75) [@santiagorodriguez96]
29
+ - Add flash messages when removing credentials. [#78](https://github.com/cedarcode/devise-webauthn/pull/78) [@nicolastemciuc]
30
+
31
+ ### Changed
32
+
33
+ - Generate webauthn credentials table with not null constraints in attributes that must be present. [#70](https://github.com/cedarcode/devise-webauthn/pull/70) [@santiagorodriguez96]
34
+
5
35
  ## [v0.2.1](https://github.com/cedarcode/devise-webauthn/compare/v0.2.0...v0.2.1/) - 2025-12-10
6
36
 
7
- - Add form helpers for security key registration and 2FA authentication.
8
- - Fix incorrect call to `resource_name` instead of using passed `resource` param in `login_with_security_key_button` helper.
9
- - Fix `NoMethodError` when calling `second_factor_enabled?` on resources without 2FA.
10
- - Avoid assuming `email` as the authentication key of the resource in form helpers.
37
+ ### Added
38
+
39
+ - Add form helpers for security key registration and 2FA authentication. [#52](https://github.com/cedarcode/devise-webauthn/pull/52) [@santiagorodriguez96]
40
+
41
+ ### Fixed
42
+
43
+ - Fix incorrect call to `resource_name` instead of using passed `resource` param in `login_with_security_key_button` helper. [#65](https://github.com/cedarcode/devise-webauthn/pull/65) [@santiagorodriguez96]
44
+ - Fix `NoMethodError` when calling `second_factor_enabled?` on resources without 2FA. [#62](https://github.com/cedarcode/devise-webauthn/pull/62) [@nicolastemciuc]
45
+ - Avoid assuming `email` as the authentication key of the resource in form helpers. [#66](https://github.com/cedarcode/devise-webauthn/pull/66) [@santiagorodriguez96]
11
46
 
12
47
  ## [v0.2.0](https://github.com/cedarcode/devise-webauthn/compare/v0.1.2...v0.2.0/) - 2025-12-03
13
48
 
14
- - Add new `webauthn_two_factor_authenticatable` module for enabling 2FA using WebAuthn credentials.
49
+ ### Added
50
+
51
+ - Add new `webauthn_two_factor_authenticatable` module for enabling 2FA using WebAuthn credentials. [#49](https://github.com/cedarcode/devise-webauthn/pull/49) [@santiagorodriguez96]
15
52
 
16
53
  ## [v0.1.2](https://github.com/cedarcode/devise-webauthn/compare/v0.1.1...v0.1.2/) - 2025-12-03
17
54
 
18
55
  ### Fixed
19
56
 
20
- - Fixed sign in with passkey for resources with name different from "User"
57
+ - Fixed sign in with passkey for resources with name different from "User". [#47](https://github.com/cedarcode/devise-webauthn/pull/47) [@joaquintomas2003], [@santiagorodriguez96]
21
58
 
22
59
  ## [v0.1.1](https://github.com/cedarcode/devise-webauthn/compare/v0.1.0...v0.1.1/) - 2025-11-13
23
60
 
24
61
  ### Changed
25
62
 
26
- - Updated gemspec metadata.
63
+ - Updated gemspec metadata. [#43](https://github.com/cedarcode/devise-webauthn/pull/43) [@joaquintomas2003]
27
64
 
28
65
  ## [v0.1.0](https://github.com/cedarcode/devise-webauthn/compare/v0.0.0...v0.1.0/) - 2025-11-12
29
66
 
30
67
  ### Initial release
31
68
 
32
- - Provides passkey authentication for apps using Devise.
69
+ - Provides passkey authentication for apps using Devise. [@joaquintomas2003], [@nicolastemciuc], [@RenzoMinelli], [@santiagorodriguez96]
70
+
71
+ [@RenzoMinelli]: https://github.com/RenzoMinelli
72
+ [@joaquintomas2003]: https://github.com/joaquintomas2003
73
+ [@nicolastemciuc]: https://github.com/nicolastemciuc
74
+ [@santiagorodriguez96]: https://github.com/santiagorodriguez96
data/Gemfile CHANGED
@@ -7,9 +7,10 @@ git_source(:github) { |repo_name| "https://github.com/#{repo_name}" }
7
7
  # Specify your gem's dependencies in devise-webauthn.gemspec
8
8
  gemspec
9
9
 
10
- gem "appraisal", "~> 2.5"
10
+ gem "appraisal", "~> 2.5", require: false
11
11
  gem "capybara", "~> 3.40"
12
12
  gem "combustion", "~> 1.3"
13
+ gem "devise", "~> 4.9"
13
14
  gem "importmap-rails", "~> 2.2"
14
15
  gem "propshaft", "~> 1.2"
15
16
  gem "pry-byebug", "~> 3.11"
@@ -21,4 +22,3 @@ gem "rubocop-rails", "~> 2.32"
21
22
  gem "rubocop-rspec", "~> 3.6"
22
23
  gem "selenium-webdriver"
23
24
  gem "sqlite3", "~> 2.7"
24
- gem "stimulus-rails", "~> 1.3"
data/Gemfile.lock CHANGED
@@ -1,8 +1,8 @@
1
1
  PATH
2
2
  remote: .
3
3
  specs:
4
- devise-webauthn (0.2.1)
5
- devise (~> 4.9)
4
+ devise-webauthn (0.3.0)
5
+ devise (>= 4.9)
6
6
  webauthn (~> 3.0)
7
7
 
8
8
  GEM
@@ -303,8 +303,6 @@ GEM
303
303
  websocket (~> 1.0)
304
304
  sqlite3 (2.7.3)
305
305
  mini_portile2 (~> 2.8.0)
306
- stimulus-rails (1.3.4)
307
- railties (>= 6.0.0)
308
306
  stringio (3.1.7)
309
307
  thor (1.4.0)
310
308
  timeout (0.4.3)
@@ -345,6 +343,7 @@ DEPENDENCIES
345
343
  appraisal (~> 2.5)
346
344
  capybara (~> 3.40)
347
345
  combustion (~> 1.3)
346
+ devise (~> 4.9)
348
347
  devise-webauthn!
349
348
  importmap-rails (~> 2.2)
350
349
  propshaft (~> 1.2)
@@ -357,7 +356,6 @@ DEPENDENCIES
357
356
  rubocop-rspec (~> 3.6)
358
357
  selenium-webdriver
359
358
  sqlite3 (~> 2.7)
360
- stimulus-rails (~> 1.3)
361
359
 
362
360
  BUNDLED WITH
363
361
  2.7.1
data/README.md CHANGED
@@ -6,9 +6,7 @@ Devise::Webauthn is a [Devise](https://github.com/heartcombo/devise) extension t
6
6
  ## Requirements
7
7
 
8
8
  - **Ruby**: 2.7+
9
- - **Stimulus Rails**: This gem requires [stimulus-rails](https://github.com/hotwired/stimulus-rails) to be installed and configured in your application.
10
- > **Note:** Stimulus Rails is needed for the generated code to work out of the box.
11
- > If you prefer not to have this dependency, you’ll need to manually implement the JavaScript logic for WebAuthn interactions.
9
+ - **JavaScript**: This gem includes WebAuthn JavaScript as custom HTML elements. You'll need to import the JavaScript file in your application.
12
10
 
13
11
  ## Installation
14
12
 
@@ -31,7 +29,7 @@ Or install it yourself as:
31
29
  First, ensure you have Devise set up in your Rails application. For a full guide on setting up Devise, refer to the [Devise documentation](https://github.com/heartcombo/devise?tab=readme-ov-file#getting-started).
32
30
  Then, follow these steps to integrate Devise::Webauthn:
33
31
  1. **Run Devise::Webauthn Generator:**
34
- Run the generator to set up necessary configurations, migrations, and Stimulus controller:
32
+ Run the generator to set up necessary configurations and migrations:
35
33
  ```bash
36
34
  $ bin/rails generate devise:webauthn:install
37
35
  ```
@@ -45,7 +43,7 @@ Then, follow these steps to integrate Devise::Webauthn:
45
43
  - Create the WebAuthn initializer (`config/initializers/webauthn.rb`)
46
44
  - Generate the `WebauthnCredential` model and migration
47
45
  - Add `webauthn_id` field to your devise model (e.g., `User`)
48
- - Install the Stimulus controller
46
+ - Configure JavaScript loading for your application (see [JavaScript Setup](#javascript-setup))
49
47
 
50
48
  2. **Run Migrations:**
51
49
  After running the generator, execute the migrations to update your database schema:
@@ -76,6 +74,29 @@ Then, follow these steps to integrate Devise::Webauthn:
76
74
  end
77
75
  ```
78
76
 
77
+ 5. **Include bundled WebAuthn JavaScript in your application:**
78
+ The install generator automatically configures JavaScript loading based on your setup:
79
+
80
+ **For importmap-rails:**
81
+ - Adds `pin "devise/webauthn", to: "devise/webauthn.js"` to `config/importmap.rb`
82
+ - Adds `import "devise/webauthn"` to `app/javascript/application.js`
83
+
84
+ **For node setups (esbuild, Bun, etc.):**
85
+ - Adds `<%= javascript_include_tag "devise/webauthn" %>` to your application layout
86
+
87
+ If the automatic setup doesn't work for your configuration, you can manually include the JavaScript:
88
+ ```erb
89
+ <%= javascript_include_tag "devise/webauthn" %>
90
+ ```
91
+
92
+ #### Behavior
93
+
94
+ When the form is submitted:
95
+ 1. The default form submission is prevented
96
+ 2. The browser's WebAuthn prompt is triggered with the provided options
97
+ 3. Upon successful authentication, the credential response is stored in the hidden input
98
+ 4. The form is submitted with the credential data
99
+
79
100
  ## How It Works
80
101
 
81
102
  ### Passkey authentication
@@ -138,6 +159,90 @@ To add a passkeys creation form:
138
159
  <% end %>
139
160
  ```
140
161
 
162
+ ### Handling unsupported WebAuthn
163
+
164
+ The custom elements check for WebAuthn API support when they connect to the DOM. If the browser doesn't support WebAuthn, a `webauthn:unsupported` event is dispatched and the form submission handler is not attached.
165
+
166
+ ```javascript
167
+ document.addEventListener('webauthn:unsupported', (event) => {
168
+ const { action } = event.detail; // 'create' or 'get'
169
+
170
+ // Hide the WebAuthn form and show a message
171
+ hideWebauthnFormWithMessage('Your browser does not support WebAuthn');
172
+ });
173
+ ```
174
+
175
+ ### Customizing Javascript Error Handling
176
+
177
+ By default, WebAuthn errors during registration or authentication are displayed using the browser's `alert()` dialog. You can customize this behavior by listening to the `webauthn:prompt:error` event.
178
+
179
+ #### Listening for WebAuthn Errors
180
+
181
+ The custom elements dispatch a `webauthn:prompt:error` event whenever an error occurs during the WebAuthn prompt interaction (registration or authentication). You can listen for this event and provide custom error handling:
182
+
183
+ ```javascript
184
+ document.addEventListener('webauthn:prompt:error', (event) => {
185
+ event.preventDefault(); // Prevent the default alert
186
+
187
+ const { error, action } = event.detail;
188
+
189
+ // Your custom error handling
190
+ console.error(`WebAuthn ${action} failed:`, error);
191
+ showFlashMessage(error.message, 'error');
192
+ });
193
+ ```
194
+
195
+ #### Event Details
196
+
197
+ The event includes the following information in `event.detail`:
198
+ - `error`: The error object thrown during the WebAuthn operation
199
+ - `action`: Either `"create"` (for registration) or `"get"` (for authentication)
200
+
201
+ #### Handling Specific Error Types
202
+
203
+ WebAuthn operations can fail for various reasons. Here are some common error types you might want to handle:
204
+
205
+ ```javascript
206
+ document.addEventListener('webauthn:prompt:error', (event) => {
207
+ event.preventDefault();
208
+
209
+ const { error, action } = event.detail;
210
+
211
+ switch (error.name) {
212
+ case 'NotAllowedError':
213
+ // User cancelled the operation or timeout
214
+ showFlashMessage('Operation cancelled or timed out', 'warning');
215
+ break;
216
+
217
+ default:
218
+ // Generic error message
219
+ showFlashMessage(`Authentication error: ${error.message}`, 'error');
220
+ }
221
+ });
222
+ ```
223
+
224
+ #### Different Handling for Registration vs Authentication
225
+
226
+ You can provide different error handling based on whether the error occurred during registration or authentication:
227
+
228
+ ```javascript
229
+ document.addEventListener('webauthn:prompt:error', (event) => {
230
+ event.preventDefault();
231
+
232
+ const { error, action } = event.detail;
233
+
234
+ if (action === 'create') {
235
+ // Handle registration errors
236
+ handleRegistrationError(error);
237
+ } else if (action === 'get') {
238
+ // Handle authentication errors
239
+ handleAuthenticationError(error);
240
+ }
241
+ });
242
+ ```
243
+
244
+ **Note:** If you don't call `event.preventDefault()`, the default `alert()` will still be shown.
245
+
141
246
  ### Customizing Controllers
142
247
  Similar to [controllers customization on Devise](https://github.com/heartcombo/devise?tab=readme-ov-file#configuring-controllers), you can customize the Devise::Webauthn controllers.
143
248
 
@@ -155,6 +260,54 @@ devise_for :users, controllers: {
155
260
 
156
261
  3. Change or extend the generated controllers as needed.
157
262
 
263
+ ### Manually implementing WebAuthn forms
264
+
265
+ The gem provides two custom HTML elements for WebAuthn operations. While the [form helpers](#helper-methods) handle this automatically, you can use these elements directly for custom implementations.
266
+
267
+ #### `<webauthn-create>`
268
+
269
+ Used for registering new credentials (passkeys or security keys).
270
+
271
+ ```html
272
+ <form action="/passkeys" method="post">
273
+ <webauthn-create data-options-json="<%= create_passkey_options(@user).to_json %>">
274
+ <input type="hidden" name="public_key_credential" data-webauthn-target="response">
275
+ <input type="text" name="name" placeholder="Passkey name">
276
+ <button type="submit">Create Passkey</button>
277
+ </webauthn-create>
278
+ </form>
279
+ ```
280
+
281
+ **Requirements:**
282
+ - Must be wrapped in a `<form>` element
283
+ - The form's action should point to the appropriate endpoint – you can use the provided url helpers:
284
+ - For creating passkeys: `passkeys_path(resource_name)`
285
+ - For creating 2FA security keys: `second_factor_webauthn_credentials_path(resource_name)`
286
+ - Requires a `data-options-json` attribute containing JSON-serialized WebAuthn creation options
287
+ - Must contain a hidden input with `data-webauthn-target="response"` to store the credential response
288
+ - Must contain the submit button — the element intercepts form submission, calls the WebAuthn API, stores the credential in the hidden input, and then re-submits the form
289
+
290
+ #### `<webauthn-get>`
291
+
292
+ Used for authenticating with existing credentials.
293
+
294
+ ```html
295
+ <form action="/users/sign_in" method="post">
296
+ <webauthn-get data-options-json="<%= passkey_authentication_options.to_json %>">
297
+ <input type="hidden" name="public_key_credential" data-webauthn-target="response">
298
+ <button type="submit">Sign in with Passkey</button>
299
+ </webauthn-get>
300
+ </form>
301
+ ```
302
+
303
+ **Requirements:**
304
+ - Must be wrapped in a `<form>` element
305
+ - The form's action should point to the appropriate endpoint – you can use the provided url helpers:
306
+ - For passkey sign-in: `session_path(resource_name)`
307
+ - For 2FA with WebAuthn: `two_factor_authentication_path(resource_name)`
308
+ - Requires a `data-options-json` attribute containing JSON-serialized WebAuthn request options
309
+ - Must contain a hidden input with `data-webauthn-target="response"` to store the credential response
310
+ - Must contain the submit button — the element intercepts form submission, calls the WebAuthn API, stores the credential in the hidden input, and then re-submits the form
158
311
 
159
312
  ## Development
160
313
 
@@ -0,0 +1,179 @@
1
+ function isWebAuthnSupported() {
2
+ return !!(
3
+ navigator.credentials &&
4
+ navigator.credentials.create &&
5
+ navigator.credentials.get &&
6
+ window.PublicKeyCredential
7
+ );
8
+ }
9
+
10
+ export class WebauthnCreateElement extends HTMLElement {
11
+ connectedCallback() {
12
+ this.style.display = 'contents';
13
+
14
+ if (!isWebAuthnSupported()) {
15
+ this.handleWebauthnUnsupported();
16
+ return;
17
+ }
18
+
19
+ this.closest('form').addEventListener('submit', async (event) => {
20
+ event.preventDefault();
21
+
22
+ try {
23
+ const options = JSON.parse(this.getAttribute('data-options-json'));
24
+ const publicKey = PublicKeyCredential.parseCreationOptionsFromJSON(options);
25
+ const credential = await navigator.credentials.create({ publicKey });
26
+
27
+ this.querySelector('[data-webauthn-target="response"]').value = await this.stringifyRegistrationCredentialWithGracefullyHandlingAuthenticatorIssues(credential);
28
+
29
+ this.closest('form').submit();
30
+ } catch (error) {
31
+ this.handleError(error);
32
+ }
33
+ });
34
+ }
35
+
36
+ handleError(error) {
37
+ const event = new CustomEvent('webauthn:prompt:error', {
38
+ detail: { error, action: 'create' },
39
+ bubbles: true,
40
+ cancelable: true
41
+ });
42
+
43
+ // If no listener prevents default, show alert
44
+ if (this.dispatchEvent(event)) {
45
+ alert(error.message || error);
46
+ }
47
+ }
48
+
49
+ handleWebauthnUnsupported() {
50
+ this.dispatchEvent(new CustomEvent('webauthn:unsupported', {
51
+ detail: { action: 'create' },
52
+ bubbles: true
53
+ }));
54
+ }
55
+
56
+ // Stringifies registration credentials gracefully handling malformed ones (e.g., due to issues with
57
+ // certain authenticators like 1Password).
58
+ // It first tries to stringify them normally, and if the credential cannot be stringified (because its
59
+ // malformed), it attempts a workaround to convert the malformed credential into a valid format. This
60
+ // workaround was introduced for 1Password and might fail for other authenticators.
61
+ //
62
+ // Authenticators that return a proper credential should not affected by this workaround!
63
+ async stringifyRegistrationCredentialWithGracefullyHandlingAuthenticatorIssues(credential) {
64
+ try {
65
+ return JSON.stringify(credential);
66
+ } catch (e) {
67
+ console.warn("Authenticator returned a malformed credential, attempting to fix it. Error was:", e);
68
+ }
69
+
70
+ const response = credential.response;
71
+ const publicKey = response.getPublicKey ? await response.getPublicKey() : null;
72
+
73
+ return JSON.stringify({
74
+ type: credential.type,
75
+ id: credential.id,
76
+ rawId: credential.id,
77
+ authenticatorAttachment: credential.authenticatorAttachment,
78
+ clientExtensionResults: await credential.getClientExtensionResults(),
79
+ response: {
80
+ attestationObject: toBase64Url(response.attestationObject),
81
+ authenticatorData: toBase64Url(response.authenticatorData),
82
+ clientDataJSON: toBase64Url(response.clientDataJSON),
83
+ publicKey: toBase64Url(publicKey),
84
+ publicKeyAlgorithm: response.getPublicKeyAlgorithm(),
85
+ transports: response.getTransports(),
86
+ },
87
+ });
88
+ }
89
+ }
90
+
91
+ export class WebauthnGetElement extends HTMLElement {
92
+ connectedCallback() {
93
+ this.style.display = 'contents';
94
+
95
+ if (!isWebAuthnSupported()) {
96
+ this.handleWebauthnUnsupported();
97
+ return;
98
+ }
99
+
100
+ this.closest('form').addEventListener('submit', async (event) => {
101
+ event.preventDefault();
102
+
103
+ try {
104
+ const options = JSON.parse(this.getAttribute('data-options-json'));
105
+ const publicKey = PublicKeyCredential.parseRequestOptionsFromJSON(options);
106
+ const credential = await navigator.credentials.get({ publicKey });
107
+
108
+ this.querySelector('[data-webauthn-target="response"]').value = await this.stringifyAuthenticationCredentialWithGracefullyHandlingAuthenticatorIssues(credential);
109
+
110
+ this.closest('form').submit();
111
+ } catch (error) {
112
+ this.handleError(error);
113
+ }
114
+ });
115
+ }
116
+
117
+ handleError(error) {
118
+ const event = new CustomEvent('webauthn:prompt:error', {
119
+ detail: { error, action: 'get' },
120
+ bubbles: true,
121
+ cancelable: true
122
+ });
123
+
124
+ // If no listener prevents default, show alert
125
+ if (this.dispatchEvent(event)) {
126
+ alert(error.message || error);
127
+ }
128
+ }
129
+
130
+ handleWebauthnUnsupported() {
131
+ this.dispatchEvent(new CustomEvent('webauthn:unsupported', {
132
+ detail: { action: 'get' },
133
+ bubbles: true
134
+ }));
135
+ }
136
+
137
+ // Stringifies authentication credentials gracefully handling malformed ones (e.g., due to issues with
138
+ // certain authenticators like 1Password).
139
+ // It first tries to stringify them normally, and if the credential cannot be stringified (because its
140
+ // malformed), it attempts a workaround to convert the malformed credential into a valid format. This
141
+ // workaround was introduced for 1Password and might fail for other authenticators.
142
+ //
143
+ // Authenticators that return a proper credential should not affected by this workaround!
144
+ async stringifyAuthenticationCredentialWithGracefullyHandlingAuthenticatorIssues(credential) {
145
+ try {
146
+ return JSON.stringify(credential);
147
+ } catch (e) {
148
+ console.warn("Authenticator returned a malformed credential, attempting to fix it. Error was:", e);
149
+ }
150
+
151
+ const response = credential.response;
152
+
153
+ return JSON.stringify({
154
+ type: credential.type,
155
+ id: credential.id,
156
+ rawId: credential.id,
157
+ authenticatorAttachment: credential.authenticatorAttachment,
158
+ clientExtensionResults: await credential.getClientExtensionResults(),
159
+ response: {
160
+ authenticatorData: toBase64Url(response.authenticatorData),
161
+ clientDataJSON: toBase64Url(response.clientDataJSON),
162
+ signature: toBase64Url(response.signature),
163
+ userHandle: response.userHandle ? toBase64Url(response.userHandle) : null,
164
+ },
165
+ });
166
+ }
167
+ }
168
+
169
+ function toBase64Url(buffer) {
170
+ if (!buffer) return null;
171
+
172
+ const binary = String.fromCharCode(...new Uint8Array(buffer));
173
+ const base64 = btoa(binary);
174
+
175
+ return base64.replaceAll("+", "-").replaceAll("/", "_");
176
+ }
177
+
178
+ customElements.define('webauthn-create', WebauthnCreateElement);
179
+ customElements.define('webauthn-get', WebauthnGetElement);
@@ -23,7 +23,12 @@ module Devise
23
23
  end
24
24
 
25
25
  def destroy
26
- resource.passkeys.destroy(params[:id])
26
+ if resource.passkeys.destroy(params[:id])
27
+ set_flash_message! :notice, :passkey_deleted
28
+ else
29
+ set_flash_message! :alert, :passkey_deletion_failed, scope: :"devise.failure"
30
+ end
31
+
27
32
  redirect_to after_update_path
28
33
  end
29
34