kaze 2.1.0 → 2.2.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 (66) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +69 -1
  3. data/README.md +42 -2
  4. data/lib/kaze/commands/app/base_stack.rb +14 -0
  5. data/lib/kaze/commands/app/hotwire_stack.rb +4 -1
  6. data/lib/kaze/commands/app/inertia_react_stack.rb +3 -1
  7. data/lib/kaze/commands/app/inertia_vue_stack.rb +3 -1
  8. data/lib/kaze/version.rb +1 -1
  9. data/stubs/default/app/forms/auth/login_form.rb +6 -1
  10. data/stubs/default/app/forms/auth/two_factor_challenge_form.rb +24 -0
  11. data/stubs/default/app/forms/confirm_two_factor_form.rb +5 -0
  12. data/stubs/default/app/forms/disable_two_factor_form.rb +7 -0
  13. data/stubs/default/app/models/concerns/two_factor_authenticatable.rb +112 -0
  14. data/stubs/default/app/models/session_guard.rb +8 -1
  15. data/stubs/default/app/models/two_factor_challenge.rb +55 -0
  16. data/stubs/default/app/models/user.rb +1 -0
  17. data/stubs/default/config/initializers/active_record_encryption.rb +20 -0
  18. data/stubs/default/config/routes.rb +9 -0
  19. data/stubs/default/db/migrate/20240101000001_add_two_factor_to_users.rb +15 -0
  20. data/stubs/default/test/integration/auth/rate_limiting_test.rb +64 -0
  21. data/stubs/default/test/integration/auth/two_factor_challenge_test.rb +114 -0
  22. data/stubs/default/test/integration/settings/two_factor_test.rb +104 -0
  23. data/stubs/default/test/models/two_factor_authenticatable_test.rb +143 -0
  24. data/stubs/default/test/test_helper.rb +16 -0
  25. data/stubs/hotwire/app/controllers/auth/authenticated_session_controller.rb +32 -1
  26. data/stubs/hotwire/app/controllers/auth/two_factor_challenge_controller.rb +59 -0
  27. data/stubs/hotwire/app/controllers/concerns/set_two_factor_challenge.rb +8 -0
  28. data/stubs/hotwire/app/controllers/settings/two_factor_controller.rb +48 -0
  29. data/stubs/hotwire/app/views/auth/forgot_password.html.erb +1 -1
  30. data/stubs/hotwire/app/views/auth/login.html.erb +1 -1
  31. data/stubs/hotwire/app/views/auth/register.html.erb +2 -2
  32. data/stubs/hotwire/app/views/auth/reset_password.html.erb +3 -3
  33. data/stubs/hotwire/app/views/auth/two_factor_challenge.html.erb +21 -0
  34. data/stubs/hotwire/app/views/auth/verify_email.html.erb +2 -2
  35. data/stubs/hotwire/app/views/layouts/_settings.html.erb +1 -0
  36. data/stubs/hotwire/app/views/layouts/_sidebar_user.html.erb +1 -1
  37. data/stubs/hotwire/app/views/settings/password/_update_password_form.html.erb +6 -6
  38. data/stubs/hotwire/app/views/settings/profile/_confirm_user_deletion_modal.html.erb +1 -1
  39. data/stubs/hotwire/app/views/settings/profile/_delete_user_form.html.erb +1 -1
  40. data/stubs/hotwire/app/views/settings/two_factor/_confirming.html.erb +20 -0
  41. data/stubs/hotwire/app/views/settings/two_factor/_disabled.html.erb +8 -0
  42. data/stubs/hotwire/app/views/settings/two_factor/_enabled.html.erb +29 -0
  43. data/stubs/hotwire/app/views/settings/two_factor/edit.html.erb +16 -0
  44. data/stubs/inertia-common/app/controllers/auth/authenticated_session_controller.rb +30 -1
  45. data/stubs/inertia-common/app/controllers/auth/two_factor_challenge_controller.rb +53 -0
  46. data/stubs/inertia-common/app/controllers/concerns/set_two_factor_challenge.rb +8 -0
  47. data/stubs/inertia-common/app/controllers/settings/two_factor_controller.rb +60 -0
  48. data/stubs/inertia-react-ts/app/javascript/Layouts/SettingsLayout.tsx +5 -1
  49. data/stubs/inertia-react-ts/app/javascript/Pages/Auth/ForgotPassword.tsx +2 -2
  50. data/stubs/inertia-react-ts/app/javascript/Pages/Auth/Register.tsx +1 -1
  51. data/stubs/inertia-react-ts/app/javascript/Pages/Auth/ResetPassword.tsx +3 -3
  52. data/stubs/inertia-react-ts/app/javascript/Pages/Auth/TwoFactorChallenge.tsx +71 -0
  53. data/stubs/inertia-react-ts/app/javascript/Pages/Auth/VerifyEmail.tsx +3 -3
  54. data/stubs/inertia-react-ts/app/javascript/Pages/Settings/Partials/DeleteUserForm.tsx +2 -2
  55. data/stubs/inertia-react-ts/app/javascript/Pages/Settings/Partials/UpdatePasswordForm.tsx +3 -3
  56. data/stubs/inertia-react-ts/app/javascript/Pages/Settings/TwoFactor.tsx +199 -0
  57. data/stubs/inertia-vue-ts/app/javascript/Layouts/SettingsLayout.vue +5 -1
  58. data/stubs/inertia-vue-ts/app/javascript/Pages/Auth/ForgotPassword.vue +2 -2
  59. data/stubs/inertia-vue-ts/app/javascript/Pages/Auth/Register.vue +1 -1
  60. data/stubs/inertia-vue-ts/app/javascript/Pages/Auth/ResetPassword.vue +3 -3
  61. data/stubs/inertia-vue-ts/app/javascript/Pages/Auth/TwoFactorChallenge.vue +60 -0
  62. data/stubs/inertia-vue-ts/app/javascript/Pages/Auth/VerifyEmail.vue +3 -3
  63. data/stubs/inertia-vue-ts/app/javascript/Pages/Settings/Partials/DeleteUserForm.vue +2 -2
  64. data/stubs/inertia-vue-ts/app/javascript/Pages/Settings/Partials/UpdatePasswordForm.vue +3 -3
  65. data/stubs/inertia-vue-ts/app/javascript/Pages/Settings/TwoFactor.vue +147 -0
  66. metadata +41 -1
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 701db9d43e1fa6af035b37096755ff20cad5d574ed2cf042d4ee9dad2b2513d0
4
- data.tar.gz: e52ef54c1289863cac8afc289b569d5cf991e1dd1c43faea861593ee6116151e
3
+ metadata.gz: c7ab421b0a7d20dbb30c5b0aaf56162163b146eda38f71a29be7a828aa1625b9
4
+ data.tar.gz: 992e0ec2554ad5b93feb3e88780e774333af09a047bc633cf59d4371e158c4ef
5
5
  SHA512:
6
- metadata.gz: 67c562979bb3627648c660bd1c3ce6b85f132ee54e2bc71477651ec8969ee731da08910f957b77cfaa61defe24d998c94172f292ebc67c87559f01b867ca0d2f
7
- data.tar.gz: 98f645b2b95a8141b2440ea180eae7092bf8d5b4b4f070f94fa420a03c790090eeee92b062a1b8fe53514e631593494a59d7ca341d530e5f26e06d38773f33ca
6
+ metadata.gz: 464c2bea1cbd7454d506daae0e0ea93860c03522a3c5d3a33008677452412668590cea894890c2467a0c2f624c1ca4acc50c7fa2e156354a8a4a9971924a7674
7
+ data.tar.gz: 9ab0ae727a1b18b1d5bdfb0c8b346d7e86a94338094b758fef7791a38cd91ed47d5be3c7c9e9807ed3d0f156ad7ef4c0e5c1156923b8303b005a24a2eb2f6ef6
data/CHANGELOG.md CHANGED
@@ -6,6 +6,72 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
6
6
 
7
7
  ## [Unreleased]
8
8
 
9
+ ## [2.2.0] - 2026-10-27
10
+
11
+ ### Added
12
+
13
+ - Rate limiting on the login and two factor forms. Six digits is small enough to guess given enough tries, so the challenge caps attempts at five a minute, keyed on the account being challenged rather than the address — moving between addresses buys no extra attempts. Login is capped at ten a minute, keyed on the email being tried, so one account under attack cannot lock anyone else out.
14
+
15
+ Rails counts these in the cache, and a generated application uses the null store in test, which accepts every write silently and would let a limit pass as working while doing nothing. The installer now switches the test environment to the memory store so the behaviour is real and testable; development and production already have real stores. `test_helper.rb` clears the cache between tests, since rate limits outlive the transaction a test is rolled back in and rolled-back ids get reused.
16
+
17
+ - A two factor settings page, at `/settings/two-factor` and in the settings sub-navigation, where two factor can be turned on and off. Turning it on shows a QR code to scan and the key to type if scanning is not possible, and is not finished until a code from the authenticator app is confirmed. Once on, the page lists the eight recovery codes and can regenerate them.
18
+
19
+ Turning it off asks for the current password. Removing a protection should take more than a session someone else may be holding.
20
+
21
+ - A two factor challenge in the login flow. Where a user has two factor enabled, a correct password no longer starts a session: it holds them in a challenge and asks for a code from their authenticator app, or one of their recovery codes. Users without two factor are unaffected and log straight in as before.
22
+
23
+ `SessionGuard#attempt` has been split, so `validate` checks credentials and returns the user without starting a session, and `attempt` is that plus `login`. `Auth::LoginForm` uses the first and exposes the user it found, leaving the controller to decide whether a second factor is still owed. A `TwoFactorChallenge` object holds the pending user in the session and nothing else, so an abandoned challenge grants nothing, and it expires after five minutes because a challenge left open is a password already given. The session id is rotated when the challenge completes, so a session fixed before the password was given cannot survive the second factor.
24
+
25
+ - The groundwork for two-factor authentication: a `TwoFactorAuthenticatable` concern on `User`, the columns it needs, and `rotp` and `rqrcode` as dependencies. Nothing is wired into the login flow or the settings area yet — that comes next — so this changes nothing a user can see.
26
+
27
+ Setup is two steps on purpose, as it is in Laravel's kits. `prepare_two_factor` generates a secret and eight single-use recovery codes, and `confirm_two_factor` only marks the account protected once the user has read a working code back. Walking away halfway leaves the account exactly as it was rather than locked out. Codes verify with a step of drift either side, so a slightly wrong clock or a code typed as it expired still works.
28
+
29
+ The secret and the recovery codes are encrypted at rest with Active Record Encryption. That normally needs three keys a generated application does not have, so a new `config/initializers/active_record_encryption.rb` derives them from `secret_key_base` — encrypted attributes work from the first boot with no extra setup. The trade-off is that rotating `secret_key_base` makes existing ciphertext unreadable; the initializer says so and points at `bin/rails db:encryption:init` for anyone who would rather manage the keys separately.
30
+
31
+ ### Fixed
32
+
33
+ - The first `bin/rails test` run of an Inertia application no longer fails to build its frontend. Vite Ruby builds assets on demand and guards that with a mutex, which only holds within a single process — but `test_helper.rb` runs the suite under `parallelize(workers: :number_of_processors)`, so every forked worker started its own `vite build` against the same manifest, and a worker that read the file while another was writing it died with `Unexpected end of JSON input`. The tests that followed reported the symptom rather than the cause: `Vite Ruby can't find entrypoints/application.tsx in the manifests`.
34
+
35
+ Only a first run is exposed, since afterwards there is nothing left to build — which is why this looked like a local flake for as long as it did, and why re-running always cleared it. A fresh checkout on CI is a first run every time, so CI was exposed on every build and had simply been winning the race; it started losing once the two factor work grew the suite. On a ten-core machine a cleared build failed two runs in three.
36
+
37
+ `test_helper.rb` now builds once in the parent process before the workers fork, which leaves them nothing to race over, and stops with the reason if that build fails rather than letting it surface three screens later as a missing entrypoint. The Hotwire stack has no Vite and is unaffected.
38
+
39
+ ### Documentation
40
+
41
+ - A README section on two factor authentication. The feature spans four pull requests and touches the login flow, the settings area and the database, and none of it was written down anywhere a user would look. The section covers the two-step setup, the challenge and the recovery codes, the password gate on turning it off, and the `TwoFactorAuthenticatable` concern for anyone driving it from their own code.
42
+
43
+ It also states the one consequence of deriving the encryption keys from `secret_key_base`: rotating that key makes existing two factor secrets unreadable, and anyone who had it turned on has to set it up again. That belongs in the README rather than only in a comment in the initializer, since the person who rotates a secret is not usually the person reading initializers.
44
+
45
+ ||||||| 1466c8e
46
+
47
+ ### Internal
48
+
49
+ - `bin/release` now promotes the changelog itself, and refuses to run when the ground is not safe. Cutting 2.1.1 showed the old script had drifted out of step with the project: it bumped `lib/kaze/version.rb` in one commit and left the `[Unreleased]` heading to be promoted in another, which puts a commit on master where the version and the newest changelog heading disagree — exactly what the gem's own test suite asserts against. Both now move in the same commit.
50
+
51
+ It also had no `set -e`, so a failed `git push` went on to tag the commit and publish the gem anyway. It now stops at the first failure, and checks before touching anything that the branch is master, the tree is clean, master and origin agree, the tag does not already exist, and `[Unreleased]` actually has something in it. The test suite runs before the push rather than after.
52
+
53
+ ## [2.1.1] - 2026-10-25
54
+
55
+ ### Fixed
56
+
57
+ - User-visible text now reads the same across the three stacks and within a page. Hotwire's login button said "Login" where React and Vue said "Log in", which is what prompted this — but the sweep found the real problem was that the 2.0.0 settings area introduced sentence case ("Profile information", "Delete account") while the auth pages kept the title case inherited from Breeze ("Reset Password", "Confirm Password"), so the two conventions met inside the same screen. The delete-account page had a "Delete account" heading directly above a "Delete Account" button.
58
+
59
+ Everything settles on sentence case, matching the settings area and Laravel's current kits: "Log in", "Log out", "Reset password", "Confirm password", "Current password", "New password", "Delete account", "Email password reset link", "Resend verification email", and the "Forgot password" and "Email verification" page titles. Mailer copy is left in title case — a different surface, and Laravel's reset email keeps it too.
60
+
61
+ ### Documentation
62
+
63
+ - Screenshots and badges in the README. A starter kit whose selling point is what it looks like had no picture of itself anywhere — someone evaluating Kaze had to install it to find out. Three captures of the real scaffolded application cover the sidebar shell, the settings area and both themes, at 48 KB in total and outside the gem's packaged files.
64
+
65
+ - A README section on the frontend. The 2.0.0 redesign is the largest change this project has had and the README described none of it — what shadcn/ui means here, that the primitives are yours to edit, how to add more with `npx shadcn@latest add`, the capitalised `@/Components` alias that will bite anyone hand-writing an import, the token and appearance systems, and why the Hotwire stack hand-rolls its own equivalents.
66
+
67
+ ### Internal
68
+
69
+ - A test suite for the gem itself, run by `rake test` and by a new `Gem Tests` job in CI. Until now the only automated coverage was the scaffolded applications' own tests, which exercise the stubs but never the code that copies them.
70
+
71
+ The bulk of it covers `kaze upgrade`, since that is the part that deletes files from a real application: that a directory is pruned only once empty, that one still holding someone else's work survives along with the file in it, that nothing above `app/` is ever touched, and that a path missing from the application is skipped rather than raised on. The rest pins the removal manifests — no listed path may still be shipped by the stubs, which would have `upgrade` delete a file the install puts straight back — and checks that `lib/kaze/version.rb` matches the newest changelog heading, so a release cannot ship a version the changelog does not describe.
72
+
73
+ The tests are excluded from the built gem.
74
+
9
75
  ## [2.1.0] - 2026-10-22
10
76
 
11
77
  ### Added
@@ -195,7 +261,9 @@ Together these take a freshly scaffolded Inertia application from seven npm advi
195
261
 
196
262
  Releases before 1.0.0 are not catalogued here. See the [tags](https://github.com/cuonggt/kaze/tags) for their history.
197
263
 
198
- [Unreleased]: https://github.com/cuonggt/kaze/compare/v2.1.0...HEAD
264
+ [Unreleased]: https://github.com/cuonggt/kaze/compare/v2.2.0...HEAD
265
+ [2.2.0]: https://github.com/cuonggt/kaze/compare/v2.1.1...v2.2.0
266
+ [2.1.1]: https://github.com/cuonggt/kaze/compare/v2.1.0...v2.1.1
199
267
  [2.1.0]: https://github.com/cuonggt/kaze/compare/v2.0.1...v2.1.0
200
268
  [2.0.1]: https://github.com/cuonggt/kaze/compare/v2.0.0...v2.0.1
201
269
  [2.0.0]: https://github.com/cuonggt/kaze/compare/v1.4.0...v2.0.0
data/README.md CHANGED
@@ -2,12 +2,24 @@
2
2
 
3
3
  # Kaze
4
4
 
5
+ [![Gem Version](https://img.shields.io/gem/v/kaze)](https://rubygems.org/gems/kaze)
6
+ [![Tests](https://github.com/cuonggt/kaze/actions/workflows/tests.yml/badge.svg)](https://github.com/cuonggt/kaze/actions/workflows/tests.yml)
7
+ [![License: MIT](https://img.shields.io/badge/license-MIT-blue)](LICENSE.md)
8
+
5
9
  Heavily inspired by [Laravel Breeze](https://github.com/laravel/breeze), this gem offers authentication and application starter kits to give you a head start building your new [Rails](https://rubyonrails.org) application. These kits automatically scaffold your application with the routes, controllers, and views you need to register and authenticate your application's users.
6
10
 
7
- [Kaze](https://github.com/cuonggt/kaze) is a opinionated minimal, simple implementation of all authentication features that a modern web application should have, including login, registration, password reset, email verification. In addition, Kaze includes a settings area where the user may update their name and email address, change their password, choose an appearance, and delete their account.
11
+ [Kaze](https://github.com/cuonggt/kaze) is an opinionated, minimal, simple implementation of all authentication features that a modern web application should have, including login, registration, password reset, email verification, and two factor authentication. In addition, Kaze includes a settings area where the user may update their name and email address, change their password, turn two factor authentication on and off, choose an appearance, and delete their account.
8
12
 
9
13
  Kaze provides scaffolding options based on [Hotwire](https://hotwired.dev) or [Inertia](https://inertiajs.com), with the choice of using Vue or React for the Inertia-based scaffolding.
10
14
 
15
+ ![Profile settings](/art/screenshots/settings-light.jpg)
16
+
17
+ | | |
18
+ |---|---|
19
+ | ![The same page in dark mode](/art/screenshots/settings-dark.jpg) | ![Logging in](/art/screenshots/login-light.jpg) |
20
+
21
+ The three stacks are built to the same design, so these are from the React one.
22
+
11
23
  ## Installation
12
24
 
13
25
  Before creating your first project powered by Kaze, make sure that your local machine has Ruby installed. Ruby can be installed in minutes via [mise](https://mise.jdx.dev).
@@ -36,7 +48,7 @@ Once the project has been created, you may scaffold your application using one o
36
48
 
37
49
  ## Kaze and Hotwire
38
50
 
39
- The default Kaze "stack" is the Hotwire stack. Hotwire is a powerful way to building dynamic, reactive, front-end UIs primarily using Ruby and ERB templates without using much JavaScript by sending HTML instead of JSON over the wire.
51
+ The default Kaze "stack" is the Hotwire stack. Hotwire is a powerful way to build dynamic, reactive, front-end UIs primarily using Ruby and ERB templates without using much JavaScript by sending HTML instead of JSON over the wire.
40
52
 
41
53
  The Hotwire stack may be installed by invoking the `kaze install` command with no other additional arguments inside your app directory. This command publishes the authentication, views, routes, controllers, and other resources to your application.
42
54
 
@@ -76,6 +88,34 @@ bin/dev
76
88
 
77
89
  Next, you may navigate to your application's `/login` or `/register` URLs in your web browser. All of Kaze's routes are defined within the `config/routes.rb` file.
78
90
 
91
+ ## The frontend
92
+
93
+ Both Inertia stacks are built on [shadcn/ui](https://ui.shadcn.com) — thirteen primitives apiece (button, input, label, checkbox, dialog, dropdown menu, separator, skeleton, sheet, tooltip, avatar, breadcrumb and sidebar), on Radix for React and [reka-ui](https://reka-ui.com) for Vue. shadcn copies source into a project rather than shipping a package, which is how Kaze already works, so these land in `app/javascript/Components/ui` and are yours to change.
94
+
95
+ A `components.json` comes with them, so you can add more:
96
+
97
+ ```
98
+ npx shadcn@latest add card
99
+ ```
100
+
101
+ One thing to know if you reach for that: Kaze uses a capitalised `@/Components`, which `components.json` already records. The CLI will follow it, but an import you write by hand as `@/components/ui/card` will resolve on macOS and fail on Linux.
102
+
103
+ Colour runs through design tokens — `bg-background`, `text-muted-foreground`, `border-sidebar-border` and so on, defined once per stylesheet as oklch variables — rather than per-element `dark:` pairs. Appearance is a user preference of light, dark or system, stored in `localStorage` and applied before first paint so the page never flashes the wrong theme; system follows the device and tracks it live. The application layout is a sidebar that collapses to icons and becomes a drawer on small screens, remembering its state in a cookie the server reads back.
104
+
105
+ There is no shadcn for Hotwire. That stack gets the same look from ViewComponents written against the same tokens, with the handful of [lucide](https://lucide.dev) icons the layouts need inlined into an `IconComponent`, since it carries no npm dependencies at all.
106
+
107
+ ## Two factor authentication
108
+
109
+ Two factor authentication is time-based one-time passwords, the kind an authenticator app generates. A user turns it on from `/settings/two-factor`, scans the QR code shown there — or types the key, if scanning is not possible — and the account is only protected once they have read a code back. Walking away from a half-finished setup leaves the account exactly as it was rather than locked out.
110
+
111
+ Once it is on, a correct password no longer signs anyone in on its own: it holds them at a challenge that asks for a code, or for one of the eight single-use recovery codes the settings page lists. Turning it off asks for the current password, so a session someone else is holding is not enough to undo it.
112
+
113
+ The secret and the recovery codes are encrypted in the database with Active Record Encryption. That normally needs three keys a generated application does not have, so Kaze ships a `config/initializers/active_record_encryption.rb` that derives them from `secret_key_base`. Nothing to configure, with one consequence worth knowing: **rotating `secret_key_base` makes existing secrets unreadable**, and anyone who has turned two factor on will need to set it up again. To manage the keys separately instead, run `bin/rails db:encryption:init` and move them into your credentials.
114
+
115
+ Both forms are rate limited — five attempts a minute on the challenge, ten on login. Rails counts these in the cache, so Kaze sets the test environment to the memory store, since the null store a generated application uses there would accept every write and let a limit look like it was working while it did nothing.
116
+
117
+ The model side lives in a `TwoFactorAuthenticatable` concern on `User`, next to `CanResetPassword`, if you want to drive it from your own code.
118
+
79
119
  ## Upgrading
80
120
 
81
121
  Kaze copies files into your application and does not own them afterwards, so re-running `kaze install` cannot know whether a file it no longer ships was left over from an older version or written by you. `kaze upgrade` resolves that by asking:
@@ -82,12 +82,26 @@ class Kaze::Commands::App::BaseStack
82
82
  Dir.children("#{Dir.pwd}/db/migrate").each { |file| replace_in_file(/ActiveRecord::Migration$/, "ActiveRecord::Migration[#{railsVersion}]", "#{Dir.pwd}/db/migrate/#{file}") }
83
83
  end
84
84
 
85
+ # Rate limiting counts attempts in the cache, and a generated application uses
86
+ # the null store in test -- which silently accepts every write, so a limit can
87
+ # never trip and could never be tested. Development and production already
88
+ # have real stores.
89
+ def enable_test_cache_store
90
+ path = "#{Dir.pwd}/config/environments/test.rb"
91
+
92
+ return unless File.exist?(path)
93
+
94
+ replace_in_file(/^ config\.cache_store = :null_store$/, ' config.cache_store = :memory_store', path)
95
+ end
96
+
85
97
  def install_tests
86
98
  ensure_directory_exists("#{Dir.pwd}/test/factories")
87
99
  ensure_directory_exists("#{Dir.pwd}/test/integration")
100
+ ensure_directory_exists("#{Dir.pwd}/test/models")
88
101
  FileUtils.copy_file("#{stubs_path}/default/test/test_helper.rb", "#{Dir.pwd}/test/test_helper.rb")
89
102
  FileUtils.copy_entry("#{stubs_path}/default/test/factories", "#{Dir.pwd}/test/factories")
90
103
  FileUtils.copy_entry("#{stubs_path}/default/test/integration", "#{Dir.pwd}/test/integration")
104
+ FileUtils.copy_entry("#{stubs_path}/default/test/models", "#{Dir.pwd}/test/models")
91
105
  end
92
106
 
93
107
  def ensure_directory_exists(path)
@@ -20,7 +20,7 @@ class Kaze::Commands::App::HotwireStack < Kaze::Commands::App::BaseStack
20
20
  def install
21
21
  # Gems...
22
22
  return unless remove_gems([ 'sprockets-rails', 'stimulus-rails' ])
23
- return unless install_gems([ 'propshaft', 'view_component', 'turbo-rails', 'dotenv', 'bcrypt' ])
23
+ return unless install_gems([ 'propshaft', 'view_component', 'turbo-rails', 'dotenv', 'bcrypt', 'rotp', 'rqrcode' ])
24
24
  return unless run_bundle_command("#{bundle_command} add tailwindcss-rails --version=\"~> 4.0\"").success?
25
25
  return unless install_gems([ 'hotwire-livereload' ], 'development')
26
26
  return unless install_gems([ 'factory_bot_rails', 'faker' ], 'development, test')
@@ -61,9 +61,12 @@ class Kaze::Commands::App::HotwireStack < Kaze::Commands::App::BaseStack
61
61
 
62
62
  # Tests...
63
63
  install_tests
64
+ enable_test_cache_store
64
65
 
65
66
  # Routes...
66
67
  FileUtils.copy_file("#{stubs_path}/default/config/routes.rb", "#{Dir.pwd}/config/routes.rb")
68
+ ensure_directory_exists("#{Dir.pwd}/config/initializers")
69
+ FileUtils.copy_file("#{stubs_path}/default/config/initializers/active_record_encryption.rb", "#{Dir.pwd}/config/initializers/active_record_encryption.rb")
67
70
 
68
71
  # Migrations...
69
72
  install_migrations
@@ -25,7 +25,7 @@ class Kaze::Commands::App::InertiaReactStack < Kaze::Commands::App::BaseStack
25
25
  def install
26
26
  # Gems...
27
27
  return unless remove_gems([ 'sprockets-rails', 'turbo-rails', 'stimulus-rails' ])
28
- return unless install_gems([ 'propshaft', 'inertia_rails', 'vite_rails', 'dotenv', 'bcrypt', 'js-routes' ])
28
+ return unless install_gems([ 'propshaft', 'inertia_rails', 'vite_rails', 'dotenv', 'bcrypt', 'rotp', 'rqrcode', 'js-routes' ])
29
29
  return unless run_bundle_command("#{bundle_command} add tailwindcss-rails --version=\"~> 4.0\"").success?
30
30
  return unless install_gems([ 'factory_bot_rails', 'faker' ], 'development, test')
31
31
 
@@ -64,6 +64,7 @@ class Kaze::Commands::App::InertiaReactStack < Kaze::Commands::App::BaseStack
64
64
 
65
65
  # Tests...
66
66
  install_tests
67
+ enable_test_cache_store
67
68
  FileUtils.copy_entry("#{stubs_path}/inertia-common/test/integration", "#{Dir.pwd}/test/integration")
68
69
 
69
70
  # Routes...
@@ -79,6 +80,7 @@ class Kaze::Commands::App::InertiaReactStack < Kaze::Commands::App::BaseStack
79
80
  FileUtils.copy_file("#{stubs_path}/inertia-common/config/vite.json", "#{Dir.pwd}/config/vite.json")
80
81
  ensure_directory_exists("#{Dir.pwd}/config/initializers")
81
82
  FileUtils.copy_file("#{stubs_path}/inertia-common/config/initializers/inertia_rails.rb", "#{Dir.pwd}/config/initializers/inertia_rails.rb")
83
+ FileUtils.copy_file("#{stubs_path}/default/config/initializers/active_record_encryption.rb", "#{Dir.pwd}/config/initializers/active_record_encryption.rb")
82
84
  FileUtils.copy_file("#{stubs_path}/inertia-react-ts/components.json", "#{Dir.pwd}/components.json")
83
85
  FileUtils.copy_file("#{stubs_path}/inertia-react-ts/tsconfig.json", "#{Dir.pwd}/tsconfig.json")
84
86
  FileUtils.copy_file("#{stubs_path}/inertia-react-ts/vite.config.ts", "#{Dir.pwd}/vite.config.ts")
@@ -26,7 +26,7 @@ class Kaze::Commands::App::InertiaVueStack < Kaze::Commands::App::BaseStack
26
26
  def install
27
27
  # Gems...
28
28
  return unless remove_gems([ 'sprockets-rails', 'turbo-rails', 'stimulus-rails' ])
29
- return unless install_gems([ 'propshaft', 'inertia_rails', 'vite_rails', 'dotenv', 'bcrypt', 'js-routes' ])
29
+ return unless install_gems([ 'propshaft', 'inertia_rails', 'vite_rails', 'dotenv', 'bcrypt', 'rotp', 'rqrcode', 'js-routes' ])
30
30
  return unless run_bundle_command("#{bundle_command} add tailwindcss-rails --version=\"~> 4.0\"").success?
31
31
  return unless install_gems([ 'factory_bot_rails', 'faker' ], 'development, test')
32
32
 
@@ -65,6 +65,7 @@ class Kaze::Commands::App::InertiaVueStack < Kaze::Commands::App::BaseStack
65
65
 
66
66
  # Tests...
67
67
  install_tests
68
+ enable_test_cache_store
68
69
  FileUtils.copy_entry("#{stubs_path}/inertia-common/test/integration", "#{Dir.pwd}/test/integration")
69
70
 
70
71
  # Routes...
@@ -80,6 +81,7 @@ class Kaze::Commands::App::InertiaVueStack < Kaze::Commands::App::BaseStack
80
81
  FileUtils.copy_file("#{stubs_path}/inertia-common/config/vite.json", "#{Dir.pwd}/config/vite.json")
81
82
  ensure_directory_exists("#{Dir.pwd}/config/initializers")
82
83
  FileUtils.copy_file("#{stubs_path}/inertia-common/config/initializers/inertia_rails.rb", "#{Dir.pwd}/config/initializers/inertia_rails.rb")
84
+ FileUtils.copy_file("#{stubs_path}/default/config/initializers/active_record_encryption.rb", "#{Dir.pwd}/config/initializers/active_record_encryption.rb")
83
85
  FileUtils.copy_file("#{stubs_path}/inertia-vue-ts/components.json", "#{Dir.pwd}/components.json")
84
86
  FileUtils.copy_file("#{stubs_path}/inertia-vue-ts/tsconfig.json", "#{Dir.pwd}/tsconfig.json")
85
87
  FileUtils.copy_file("#{stubs_path}/inertia-vue-ts/vite.config.ts", "#{Dir.pwd}/vite.config.ts")
data/lib/kaze/version.rb CHANGED
@@ -1,3 +1,3 @@
1
1
  module Kaze
2
- VERSION = '2.1.0'
2
+ VERSION = '2.2.0'
3
3
  end
@@ -1,12 +1,17 @@
1
1
  class Auth::LoginForm < ApplicationForm
2
2
  attr_accessor :email, :password, :remember
3
+ attr_reader :user
3
4
 
4
5
  validates :email, presence: true, email: true
5
6
  validates :password, presence: true
6
7
 
8
+ # Checks the credentials without logging anyone in, so the caller can decide
9
+ # whether a second factor is still owed.
7
10
  def authenticate
8
11
  return if invalid?
9
12
 
10
- errors.add(:email, message: 'These credentials do not match our records.') unless Current.auth.attempt({ email: @email, password: @password }, @remember)
13
+ @user = Current.auth.validate({ email: @email, password: @password })
14
+
15
+ errors.add(:email, message: 'These credentials do not match our records.') if @user.nil?
11
16
  end
12
17
  end
@@ -0,0 +1,24 @@
1
+ class Auth::TwoFactorChallengeForm < ApplicationForm
2
+ attr_accessor :code, :recovery_code
3
+
4
+ validate :code_or_recovery_code_present
5
+
6
+ # A recovery code is offered as the way in when the authenticator is not to
7
+ # hand, so whichever was filled in is the one that gets checked.
8
+ def authenticate(user)
9
+ return if invalid?
10
+
11
+ if recovery_code.present?
12
+ errors.add(:recovery_code, message: 'That recovery code is not valid.') unless user.consume_two_factor_recovery_code(recovery_code)
13
+ else
14
+ errors.add(:code, message: 'That code is not valid.') unless user.verify_two_factor_code(code)
15
+ end
16
+ end
17
+
18
+ private
19
+ def code_or_recovery_code_present
20
+ return if code.present? || recovery_code.present?
21
+
22
+ errors.add(:code, message: 'Enter the code from your authenticator app, or a recovery code.')
23
+ end
24
+ end
@@ -0,0 +1,5 @@
1
+ class ConfirmTwoFactorForm < ApplicationForm
2
+ attr_accessor :code
3
+
4
+ validates :code, presence: true
5
+ end
@@ -0,0 +1,7 @@
1
+ # Turning two factor off removes a protection, so it asks for the password. A
2
+ # stolen session should not be enough to undo it.
3
+ class DisableTwoFactorForm < ApplicationForm
4
+ attr_accessor :password
5
+
6
+ validates :password, presence: true, current_password: true
7
+ end
@@ -0,0 +1,112 @@
1
+ # Time-based one-time passwords, in the shape Laravel's starter kits use: a
2
+ # secret is generated first and only counts as enabled once the user has proved
3
+ # they can read codes from it, so nobody can lock themselves out by walking away
4
+ # from a half-finished setup.
5
+ module TwoFactorAuthenticatable
6
+ extend ActiveSupport::Concern
7
+
8
+ RECOVERY_CODE_COUNT = 8
9
+
10
+ # A window of one step either side, so a code is still accepted if the user's
11
+ # clock is a little out or they typed it as it was expiring.
12
+ DRIFT = 30
13
+
14
+ included do
15
+ encrypts :two_factor_secret
16
+ encrypts :two_factor_recovery_codes
17
+ end
18
+
19
+ def two_factor_enabled?
20
+ two_factor_secret.present? && two_factor_confirmed_at.present?
21
+ end
22
+
23
+ # A secret exists but has not been confirmed. Setup was started and not
24
+ # finished; the account is not protected yet.
25
+ def two_factor_pending?
26
+ two_factor_secret.present? && two_factor_confirmed_at.nil?
27
+ end
28
+
29
+ # Starts setup, replacing anything half-finished from a previous attempt.
30
+ def prepare_two_factor
31
+ update!(
32
+ two_factor_secret: ROTP::Base32.random,
33
+ two_factor_recovery_codes: generate_recovery_codes.to_json,
34
+ two_factor_confirmed_at: nil
35
+ )
36
+ end
37
+
38
+ def confirm_two_factor(code)
39
+ return false unless two_factor_pending? && verify_two_factor_code(code)
40
+
41
+ update!(two_factor_confirmed_at: Time.current)
42
+
43
+ true
44
+ end
45
+
46
+ def disable_two_factor
47
+ update!(two_factor_secret: nil, two_factor_recovery_codes: nil, two_factor_confirmed_at: nil)
48
+ end
49
+
50
+ def verify_two_factor_code(code)
51
+ return false if two_factor_secret.blank? || code.blank?
52
+
53
+ totp.verify(code.to_s.strip, drift_behind: DRIFT, drift_ahead: DRIFT).present?
54
+ end
55
+
56
+ # Recovery codes are single use. Returns false without consuming anything if
57
+ # the code is not one of ours.
58
+ def consume_two_factor_recovery_code(code)
59
+ return false if code.blank?
60
+
61
+ remaining = two_factor_recovery_codes_list
62
+ index = remaining.index(code.to_s.strip)
63
+
64
+ return false if index.nil?
65
+
66
+ remaining.delete_at(index)
67
+ update!(two_factor_recovery_codes: remaining.to_json)
68
+
69
+ true
70
+ end
71
+
72
+ def two_factor_recovery_codes_list
73
+ return [] if two_factor_recovery_codes.blank?
74
+
75
+ JSON.parse(two_factor_recovery_codes)
76
+ rescue JSON::ParserError
77
+ []
78
+ end
79
+
80
+ def regenerate_two_factor_recovery_codes
81
+ update!(two_factor_recovery_codes: generate_recovery_codes.to_json)
82
+ end
83
+
84
+ # What the authenticator app scans. The issuer is what the user will see
85
+ # listed in their app, so it is the application's name rather than a URL.
86
+ def two_factor_provisioning_uri(issuer: nil)
87
+ return nil if two_factor_secret.blank?
88
+
89
+ totp(issuer: issuer).provisioning_uri(email)
90
+ end
91
+
92
+ def two_factor_qr_code_svg(issuer: nil)
93
+ uri = two_factor_provisioning_uri(issuer: issuer)
94
+
95
+ return nil if uri.nil?
96
+
97
+ RQRCode::QRCode.new(uri).as_svg(viewbox: true, use_path: true, module_size: 4)
98
+ end
99
+
100
+ private
101
+ def totp(issuer: nil)
102
+ ROTP::TOTP.new(two_factor_secret, issuer: issuer || default_two_factor_issuer)
103
+ end
104
+
105
+ def default_two_factor_issuer
106
+ Rails.application.class.module_parent_name
107
+ end
108
+
109
+ def generate_recovery_codes
110
+ Array.new(RECOVERY_CODE_COUNT) { "#{SecureRandom.alphanumeric(10)}-#{SecureRandom.alphanumeric(10)}".downcase }
111
+ end
112
+ end
@@ -38,7 +38,7 @@ class SessionGuard
38
38
  end
39
39
 
40
40
  def attempt(credentials = {}, remember = false)
41
- @last_attempted = user = User.authenticate_by(credentials)
41
+ user = validate(credentials)
42
42
 
43
43
  return false if user.nil?
44
44
 
@@ -47,6 +47,13 @@ class SessionGuard
47
47
  true
48
48
  end
49
49
 
50
+ # Checks credentials and returns the user without starting a session. The two
51
+ # factor challenge needs this: a correct password is not enough to be logged
52
+ # in when a second factor is required.
53
+ def validate(credentials = {})
54
+ @last_attempted = User.authenticate_by(credentials)
55
+ end
56
+
50
57
  def login(user, remember = false)
51
58
  update_session(user.id)
52
59
 
@@ -0,0 +1,55 @@
1
+ # The gap between a correct password and a completed login. The user is not
2
+ # logged in while this is pending -- their id is held in the session and nothing
3
+ # else -- so an abandoned challenge grants nothing.
4
+ class TwoFactorChallenge
5
+ EXPIRES_IN = 5.minutes
6
+
7
+ USER_KEY = :two_factor_challenge_user_id
8
+ REMEMBER_KEY = :two_factor_challenge_remember
9
+ STARTED_KEY = :two_factor_challenge_started_at
10
+
11
+ def initialize(session)
12
+ @session = session
13
+ end
14
+
15
+ def start(user, remember: false)
16
+ @session[USER_KEY] = user.id
17
+ @session[REMEMBER_KEY] = remember
18
+ @session[STARTED_KEY] = Time.current.to_i
19
+ end
20
+
21
+ def pending?
22
+ !user.nil?
23
+ end
24
+
25
+ def user
26
+ return nil if @session[USER_KEY].nil?
27
+
28
+ if expired?
29
+ clear
30
+ return nil
31
+ end
32
+
33
+ @user ||= User.find_by(id: @session[USER_KEY])
34
+ end
35
+
36
+ def remember?
37
+ @session[REMEMBER_KEY].present?
38
+ end
39
+
40
+ def clear
41
+ @session.delete(USER_KEY)
42
+ @session.delete(REMEMBER_KEY)
43
+ @session.delete(STARTED_KEY)
44
+ @user = nil
45
+ end
46
+
47
+ private
48
+ # A challenge left open is a password already given, so it should not wait
49
+ # around indefinitely for the second factor.
50
+ def expired?
51
+ started_at = @session[STARTED_KEY]
52
+
53
+ started_at.nil? || Time.zone.at(started_at.to_i) < EXPIRES_IN.ago
54
+ end
55
+ end
@@ -1,5 +1,6 @@
1
1
  class User < ApplicationRecord
2
2
  include CanResetPassword
3
+ include TwoFactorAuthenticatable
3
4
  # include MustVerifyEmail
4
5
 
5
6
  has_secure_password
@@ -0,0 +1,20 @@
1
+ # Active Record Encryption needs three keys, and a generated application has
2
+ # none. Deriving them from secret_key_base means encrypted attributes work the
3
+ # moment the application boots, without a second set of secrets to manage.
4
+ #
5
+ # The consequence is that rotating secret_key_base makes existing ciphertext
6
+ # unreadable. To manage the keys separately instead, run
7
+ # `bin/rails db:encryption:init` and move them into your credentials.
8
+ Rails.application.configure do
9
+ generator = ActiveSupport::KeyGenerator.new(
10
+ Rails.application.secret_key_base,
11
+ hash_digest_class: OpenSSL::Digest::SHA256
12
+ )
13
+
14
+ config.active_record.encryption.primary_key =
15
+ generator.generate_key('active_record_encryption_primary_key', 32)
16
+ config.active_record.encryption.deterministic_key =
17
+ generator.generate_key('active_record_encryption_deterministic_key', 32)
18
+ config.active_record.encryption.key_derivation_salt =
19
+ generator.generate_key('active_record_encryption_key_derivation_salt', 32)
20
+ end
@@ -19,6 +19,9 @@ Rails.application.routes.draw do
19
19
  post 'verify-email', to: 'auth/email_verification_notification#create', as: :verification_send
20
20
  get 'verify-email/:id/:hash', to: 'auth/verified_email#create', as: :verification_verify
21
21
 
22
+ get 'two-factor-challenge', to: 'auth/two_factor_challenge#new', as: :two_factor_challenge
23
+ post 'two-factor-challenge', to: 'auth/two_factor_challenge#create', as: :two_factor_challenge_store
24
+
22
25
  post 'logout', to: 'auth/authenticated_session#destroy', as: :logout
23
26
 
24
27
  get 'dashboard', to: 'dashboard#index', as: :dashboard
@@ -33,6 +36,12 @@ Rails.application.routes.draw do
33
36
  get 'password', to: 'password#edit', as: :password_edit
34
37
  put 'password', to: 'password#update', as: :password_update
35
38
 
39
+ get 'two-factor', to: 'two_factor#edit', as: :two_factor_edit
40
+ post 'two-factor', to: 'two_factor#create', as: :two_factor_store
41
+ patch 'two-factor', to: 'two_factor#update', as: :two_factor_update
42
+ delete 'two-factor', to: 'two_factor#destroy', as: :two_factor_destroy
43
+ post 'two-factor/recovery-codes', to: 'two_factor#recovery_codes', as: :two_factor_recovery_codes
44
+
36
45
  get 'appearance', to: 'appearance#edit', as: :appearance_edit
37
46
  end
38
47
  end
@@ -0,0 +1,15 @@
1
+ class AddTwoFactorToUsers < ActiveRecord::Migration
2
+ def self.up
3
+ change_table :users, bulk: true do |table|
4
+ table.text :two_factor_secret
5
+ table.text :two_factor_recovery_codes
6
+ table.timestamp :two_factor_confirmed_at
7
+ end
8
+ end
9
+
10
+ def self.down
11
+ change_table :users, bulk: true do |table|
12
+ table.remove :two_factor_secret, :two_factor_recovery_codes, :two_factor_confirmed_at
13
+ end
14
+ end
15
+ end