monkrb 0.27.0 → 0.28.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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: c96fd07ece5e995917d27464123a215fe1227351c1ef4b143546f24a22bfa7f2
4
- data.tar.gz: b2bf65af91c657498c20cb498263ccb5638d81d692b92a15b252209e87a845aa
3
+ metadata.gz: 2c71bb2b19d026499b94a976131d9aab3b2b8f44cb084294c3d9adbd8183b602
4
+ data.tar.gz: 864671c305178391d29f1b6c40e27d43afa324cdb6cf63c141c8064b99080ab4
5
5
  SHA512:
6
- metadata.gz: ab820ddae9c4333e6bb29e54335abc2aab42a0f395e1c8d3b822beb412dbfa8d243b85aa72b3f32540ab64178544e4d8b5b6913ba171c68a47cdbac66e8e9c43
7
- data.tar.gz: b0f80afc56f0de798c29d525d78c2365f4fda4470f1d791f1803de9b091a971247a9be0b894f044b5334d916c4b05240bfc67de67176ed66492cdb12a5fc340b
6
+ metadata.gz: 89e9b69d99e2ccf1458716025529f37b7b23b6ca906b96e80d6fab0bb558186d8ed0fa5160836829f59a97f86b83ff77f78ca691183a0de69618fc0c2d9b5724
7
+ data.tar.gz: 9f17f7c2b658d1e0e8cbbd7ab65057998c31e1ff1b0cf5f9f1bad4f8ae472579ef3610021afa7b2bc13d31acd637d8aee3e9185baba467ff1051bb3d1a81f483
data/CHANGELOG.md CHANGED
@@ -4,6 +4,61 @@ All notable changes to this project are documented here. Format is loosely
4
4
  [Keep a Changelog](https://keepachangelog.com/); versions are as released
5
5
  in `lib/monk/version.rb`.
6
6
 
7
+ ## 0.28.0 - 2026-11-24
8
+
9
+ A smoother first sign-in, from walking a real app's invitation and
10
+ sign-up flows on phones. Upgrading an app with auth takes a few steps:
11
+ [`upgrading.md`](docs/guides/upgrading.md#028).
12
+
13
+ ### Added
14
+
15
+ - **A 6-digit sign-in code beside the magic link**, for where a link
16
+ can't work: the installed app on an iPhone (Mail opens links in
17
+ Safari), or a page opened in a chat app's built-in browser.
18
+ `Monk::Auth.redeem_code(email, code)` redeems the same login token as
19
+ the link; five wrong codes use it up, and ten for one address in an
20
+ hour lock that address's codes until the hour is up. The scaffold's
21
+ login page becomes the code form, with `POST /auth/code`, and the
22
+ mail's subject starts with the code
23
+ ([`auth.md`](docs/guides/auth.md#signing-in-with-a-code)).
24
+ - **Sessions renewed by use**: once less than half of `session_ttl` is
25
+ left, a request moves it to now + `session_ttl` and reissues the
26
+ cookies, one write per session per half TTL. `session_max_age:` caps a
27
+ session's whole life
28
+ ([`auth.md`](docs/guides/auth.md#sessions-renewed-by-use)).
29
+ - **The installed iPhone app's own session.** Add to Home Screen copies
30
+ Safari's session into the app, so logging out in one ended both.
31
+ `register.js` now asks `POST /auth/own` once, on the app's first
32
+ launch, and `own_session!` (`Monk::Auth.split`) gives it a session of
33
+ its own ([`auth.md`](docs/guides/auth.md#the-installed-iphone-apps-own-session)).
34
+ - **`redirect_allowlist` takes Regexps**, matched against the whole
35
+ path, and an allowed path may carry a query string.
36
+ `Monk::Auth.allowed_redirect?(path)` makes the same check for a route,
37
+ and `Monk::Auth.redirect_for(token)` says where an expired or used
38
+ link was going ([`auth.md`](docs/guides/auth.md#where-a-login-returns)).
39
+ - **Helping people install the app.** `register.js` sets
40
+ `data-pwa-standalone`, `data-pwa-platform`, `data-pwa-installable` and
41
+ `data-pwa-in-app` on `<html>`, and emits `monk-pwa:installable` and
42
+ `monk-pwa:installed`. `<%= monk_install %>` renders an install banner
43
+ with an iOS sheet (Share, then Add to Home Screen), unstyled, every
44
+ text overridable. `pwa.md` shows how an app can add an "Open in your
45
+ browser" button for chat apps' built-in browsers
46
+ ([`pwa.md`](docs/guides/pwa.md#helping-people-install)).
47
+
48
+ ### Changed
49
+
50
+ - **`Monk::Auth.request_login` returns `{ token:, code: }`**, not the
51
+ token alone, and strips and downcases the address.
52
+ - **`deliver:` is always called with `redirect_to:` and `code:`** too,
53
+ beside `email:, link:, token:`.
54
+ - **Web push outlives an idle session.** A subscription counts until its
55
+ session is revoked, or expired for longer than
56
+ `Monk::Auth.configure(expired_retention:)` (90 days by default), and
57
+ `Monk::Auth.sweep!` keeps expired sessions that long. Logging out still
58
+ stops notifications at once
59
+ ([`push.md`](docs/guides/push.md#subscriptions-belong-to-sessions)).
60
+ - New migration `add_login_codes` for auth.
61
+
7
62
  ## 0.27.0 - 2026-11-23
8
63
 
9
64
  ### Added
data/README.md CHANGED
@@ -21,7 +21,7 @@ bin/server # -> http://localhost:9292/hello
21
21
  monk add --list # the modules you can add: postgres, auth, jobs, live...
22
22
  ```
23
23
 
24
- `monk new` scaffolds the app's own `Gemfile` with `gem "monkrb", "~> 0.27", require: "monk"`.
24
+ `monk new` scaffolds the app's own `Gemfile` with `gem "monkrb", "~> 0.28", require: "monk"`.
25
25
 
26
26
  `monk new` writes a working app: an HTML home page, a `/hello` route and a `/api/hello` JSON route, `public/`, its tests, a `SETUP.md`, and an `AGENTS.md` for coding agents. The app's own code goes under `app/`: `app/app.rb` and `app/routes/` for routes, `app/views/`, and one directory per role (`models/`, `presenters/`, `helpers/`, `mailers/`, `broadcasts/`, `jobs/`).
27
27
 
@@ -63,14 +63,14 @@ Everything beyond the core is opt-in (`require "monk"` alone loads none of it).
63
63
  | Logging | request log per environment, `Monk::Log.debug`/`info`/`warn`/`error` | — | [`logging.md`](docs/guides/logging.md) |
64
64
  | Persistence | `Monk::Persistence::Pg`: raw `pg`, per-Ractor connections, hash-based `Model` | `require "monk/persistence/pg"` (+ `.../pg/model`); needs the `pg` gem | [`persistence.md`](docs/guides/persistence.md) |
65
65
  | Migrations | plain `.sql` up/down pairs, `Migrator` | `require "monk/persistence/pg/migrator"`; needs the `pg` gem | [`migrations.md`](docs/guides/migrations.md) |
66
- | Auth and sessions | `Monk::Auth`: passwordless tokens, Bearer or cookie + CSRF, a per-address login-email rate limit, nightly cleanup with jobs | `require "monk/auth"`; needs the `pg` gem and a registered Postgres connection | [`auth.md`](docs/guides/auth.md) |
66
+ | Auth and sessions | `Monk::Auth`: passwordless login by email link or 6-digit code, sessions renewed by use, Bearer or cookie + CSRF, a per-address login-email rate limit, nightly cleanup with jobs | `require "monk/auth"`; needs the `pg` gem and a registered Postgres connection | [`auth.md`](docs/guides/auth.md) |
67
67
  | Email | `Monk::Mail`: text/HTML email over SMTP or a local relay, one `MAIL_URL`, sent from any worker Ractor, or from a background job with `deliver_later` | `require "monk/mail"`; `deliver_later` is there once `monk/jobs` is loaded too; SMTP needs the `net-smtp` gem | [`mail.md`](docs/guides/mail.md) |
68
68
  | Background jobs | `Monk::Jobs`: a queue in Postgres, run by `bin/jobs` on worker Ractors; retries with backoff, scheduled jobs, recurring jobs on a cron schedule (UTC), enqueue inside the app's own transaction, `drain!` for tests | `require "monk/jobs"` (+ `require "monk/jobs/runtime"` in the job process); needs the `pg` gem and a registered Postgres connection | [`jobs.md`](docs/guides/jobs.md) |
69
69
  | WebSocket | `Monk::WebSocket`: RFC 6455 server as its own process, Redis or Postgres fan-out | `require "monk/websocket"`; fan-out: `require "monk/websocket/redis_fanout"` (+ the `redis` gem) or `require "monk/websocket/pg_fanout"` (+ the `pg` gem) | [`websocket.md`](docs/guides/websocket.md) |
70
70
  | Live updates | `Monk::Live`: server-rendered HTML patches pushed to open tabs | `require "monk/live"`; needs the WebSocket server and, across processes, Redis or Postgres | [`live.md`](docs/guides/live.md) |
71
71
  | Presence | `Monk::Presence`: whether a signed-in person has a page open and visible (online), only hidden ones (away), or none (offline, with when they were last seen), across tabs, devices and WebSocket processes; an `on_change` hook in `bin/server` | `require "monk/presence"`; needs auth, the WebSocket server and Postgres; away needs Live | [`presence.md`](docs/guides/presence.md) |
72
72
  | File storage | `Monk::Storage`: files by key in any S3-compatible bucket (Hetzner, R2, B2, AWS), local files in development and test; browser uploads and downloads through signed links, never through a worker Ractor | `require "monk/storage"`; no gem needed | [`storage.md`](docs/guides/storage.md) |
73
- | Installable app | `Monk::Pwa`: a web app manifest, icons and a service worker (`/sw.js`), checked at boot and linked by `<%= monk_head %>`, so the app installs on a Home Screen or as a desktop app | `require "monk/pwa"`; no gem needed | [`pwa.md`](docs/guides/pwa.md) |
73
+ | Installable app | `Monk::Pwa`: a web app manifest, icons and a service worker (`/sw.js`), checked at boot and linked by `<%= monk_head %>`, so the app installs on a Home Screen or as a desktop app; `<%= monk_install %>` invites people to | `require "monk/pwa"`; no gem needed | [`pwa.md`](docs/guides/pwa.md) |
74
74
  | Web push | `Monk::Push`: notifications to the devices where a signed-in person turned them on, encrypted and signed by Monk itself (RFC 8291, VAPID), one job per device; subscriptions tied to auth sessions | `require "monk/push"`; needs auth, jobs and Postgres, and pwa's service worker | [`push.md`](docs/guides/push.md) |
75
75
  | Scaffolding | `monk new` and `monk add`: one generator per module, for a new app or an existing one; text or `--json` output; `monk add deploy` for Docker Compose and Caddy on one host | — (the `monk` command: `monk new NAME --with ...`, `monk add MODULE`, `monk add --list`) | [`scaffolding.md`](docs/guides/scaffolding.md) |
76
76
 
@@ -7,19 +7,28 @@ module Monk
7
7
  # memoizing current_subject on it is exempt from the app's
8
8
  # shareability constraints -- nothing here needs Ractor.make_shareable.
9
9
  module Helpers
10
- # With a session cookie, also mends the csrf_token cookie when it
11
- # doesn't match the session: after AUTH_SECRET changes (a restored
12
- # backup, a rotated secret) the session still verifies, since it's
13
- # stored as a plain hash, but the cookie was signed with the old
14
- # secret, and every require_csrf! route, logout included, would be
15
- # a 403 until the browser's cookies were cleared.
10
+ # Renews a session in use (Monk::Auth.verified_session's renew:),
11
+ # and with a session cookie reissues both cookies when it did.
12
+ # Otherwise it still mends the csrf_token cookie when it doesn't
13
+ # match the session: after AUTH_SECRET changes (a restored backup, a
14
+ # rotated secret) the session still verifies, since it's stored as a
15
+ # plain hash, but the cookie was signed with the old secret, and
16
+ # every require_csrf! route, logout included, would be a 403 until
17
+ # the browser's cookies were cleared.
16
18
  def current_subject
17
19
  return @current_subject if defined?(@current_subject)
18
- return @current_subject = Monk::Auth.verify(bearer_token) if bearer_token
20
+
21
+ if bearer_token
22
+ return @current_subject = Monk::Auth.verified_session(bearer_token, renew: true)&.fetch(:subject)
23
+ end
19
24
 
20
25
  token = session_cookie_token
21
- session = Monk::Auth.verified_session(token)
22
- reissue_csrf_cookie(token, session[:expires_at]) if session
26
+ session = Monk::Auth.verified_session(token, renew: true)
27
+ if session&.dig(:renewed)
28
+ set_session_cookie(token: token, expires_at: session[:expires_at])
29
+ elsif session
30
+ reissue_csrf_cookie(token, session[:expires_at])
31
+ end
23
32
  @current_subject = session&.fetch(:subject)
24
33
  end
25
34
 
@@ -83,6 +92,29 @@ module Monk
83
92
  nil
84
93
  end
85
94
 
95
+ # Gives this browser its own session: splits the cookie's session
96
+ # (Monk::Auth.split) and sets the cookies for the new one, leaving
97
+ # the old one to whoever else holds it. The subject, or nil without
98
+ # a valid session cookie. For the installed iPhone app, which
99
+ # register.js has call Monk::Auth::OWN_PATH once; call require_csrf!
100
+ # first:
101
+ # post("/auth/own") { require_csrf!; own_session! || halt(401); json(ok: true) }
102
+ def own_session!
103
+ session = Monk::Auth.split(session_cookie_token)
104
+ return nil unless session
105
+
106
+ set_session_cookie(session)
107
+ @current_subject = session[:subject]
108
+ end
109
+
110
+ # For the layout's <%= monk_head %>: where register.js asks for the
111
+ # installed app's own session.
112
+ def head_tags
113
+ return super unless Monk::Auth.config
114
+
115
+ super + [%(<meta name="monk-auth-own-url" content="#{h(Monk::Auth::OWN_PATH)}">)]
116
+ end
117
+
86
118
  private
87
119
 
88
120
  def bearer_token
@@ -4,8 +4,8 @@
4
4
 
5
5
  module Monk
6
6
  module Auth
7
- # Sends a magic link from bin/jobs instead of the login request. The
8
- # token is created here, right before it's sent, so the raw token is
7
+ # Sends a magic link, and its sign-in code, from bin/jobs instead of
8
+ # the login request. The token is created here, right before it's sent, so the raw token is
9
9
  # never stored anywhere -- not even in the job queue, which pointing
10
10
  # deliver: at Monk::Mail.deliver_later would do
11
11
  # (docs/adr/0014-mail-from-jobs-and-login-links-created-in-the-job.md).
@@ -28,8 +28,11 @@ module Monk
28
28
  never_retry Monk::InvalidRedirectError
29
29
 
30
30
  def self.perform(email, redirect_to = nil)
31
- token = Monk::Auth.request_login(email, redirect_to: redirect_to)
32
- Monk::Auth.deliver_link(email: email, link: Monk::Auth.login_link(token), token: token)
31
+ login = Monk::Auth.request_login(email, redirect_to: redirect_to)
32
+ Monk::Auth.deliver_link(
33
+ email: email, link: Monk::Auth.login_link(login[:token]), token: login[:token],
34
+ redirect_to: redirect_to, code: login[:code],
35
+ )
33
36
  end
34
37
  end
35
38
  end
data/lib/monk/auth.rb CHANGED
@@ -20,6 +20,11 @@ module Monk
20
20
  module Auth
21
21
  REQUIRED_CONFIG_KEYS = %i[db_name secret login_ttl session_ttl].freeze
22
22
  MIN_SECRET_LENGTH = 32
23
+ EXPIRED_RETENTION = 90 * 86_400
24
+
25
+ # The scaffold's route giving the installed iPhone app its own session
26
+ # (own_session!), named to register.js by monk_head.
27
+ OWN_PATH = "/auth/own".freeze
23
28
 
24
29
  # The login-email rate limit: records a request unless one was recorded
25
30
  # for the address less than $2 seconds ago. One statement, so racing
@@ -32,11 +37,59 @@ module Monk
32
37
  RETURNING 1
33
38
  SQL
34
39
 
40
+ # The sign-in code (redeem_code): wrong guesses at one token before it
41
+ # is used up, and at one address, across its tokens, per hour.
42
+ MAX_CODE_ATTEMPTS = 5
43
+ MAX_CODE_FAILURES_PER_HOUR = 10
44
+ CODE_FORMAT = /\A\d{6}\z/
45
+
46
+ CODE_LOCKED_SQL = <<~SQL.freeze
47
+ SELECT 1 FROM login_requests
48
+ WHERE email = $1 AND code_failures >= $2 AND code_failures_since > now() - interval '1 hour'
49
+ SQL
50
+
51
+ # A wrong code: one more attempt at the token, which the
52
+ # MAX_CODE_ATTEMPTS-th uses up. Only while it's unused, so a guess
53
+ # racing a successful redeem changes nothing.
54
+ CODE_MISS_SQL = <<~SQL.freeze
55
+ UPDATE login_tokens SET code_attempts = code_attempts + 1,
56
+ used_at = CASE WHEN code_attempts + 1 >= $2 THEN $3::timestamptz ELSE used_at END
57
+ WHERE id = $1 AND used_at IS NULL
58
+ SQL
59
+
60
+ # And one more failure for the address, in a window that starts at its
61
+ # first failure and lasts an hour. A new row's requested_at is
62
+ # -infinity: counting a failure doesn't hold back the next login email.
63
+ CODE_FAILURE_SQL = <<~SQL.freeze
64
+ INSERT INTO login_requests (email, requested_at, code_failures, code_failures_since)
65
+ VALUES ($1, '-infinity', 1, now())
66
+ ON CONFLICT (email) DO UPDATE SET
67
+ code_failures = CASE WHEN login_requests.code_failures_since > now() - interval '1 hour'
68
+ THEN login_requests.code_failures + 1 ELSE 1 END,
69
+ code_failures_since = CASE WHEN login_requests.code_failures_since > now() - interval '1 hour'
70
+ THEN login_requests.code_failures_since ELSE now() END
71
+ SQL
72
+
73
+ # Renewal by use: only while the row still ends before $3 (now plus
74
+ # half the TTL), so two requests arriving together write once.
75
+ RENEW_SESSION_SQL = <<~SQL.freeze
76
+ UPDATE sessions SET expires_at = $2 WHERE id = $1 AND expires_at < $3 AND revoked_at IS NULL
77
+ RETURNING expires_at
78
+ SQL
79
+
80
+ # split: the new session copies the old one's life exactly.
81
+ SPLIT_SESSION_SQL = <<~SQL.freeze
82
+ INSERT INTO sessions (subject, token_hash, expires_at, created_at)
83
+ SELECT subject, $2, expires_at, created_at FROM sessions WHERE token_hash = $1
84
+ RETURNING subject, expires_at
85
+ SQL
86
+
35
87
  SWEEP_BATCH_SIZE = 10_000
36
88
 
37
89
  # sweep!'s statements, one batch each. Tokens and sessions expire by
38
90
  # the app's clock, as redeem and verify check them; login requests by
39
- # the database's, as allow_login_request? does.
91
+ # the database's, as allow_login_request? does. Sessions go only once
92
+ # expired for longer than expired_retention.
40
93
  SWEEP_LOGIN_TOKENS_SQL = <<~SQL.freeze
41
94
  DELETE FROM login_tokens WHERE id IN (SELECT id FROM login_tokens WHERE expires_at < $1 LIMIT $2)
42
95
  SQL
@@ -45,7 +98,8 @@ module Monk
45
98
  SQL
46
99
  SWEEP_LOGIN_REQUESTS_SQL = <<~SQL.freeze
47
100
  DELETE FROM login_requests WHERE email IN (
48
- SELECT email FROM login_requests WHERE requested_at < now() - $1::int * interval '1 second' LIMIT $2
101
+ SELECT email FROM login_requests WHERE requested_at < now() - $1::int * interval '1 second'
102
+ AND (code_failures_since IS NULL OR code_failures_since < now() - interval '1 hour') LIMIT $2
49
103
  )
50
104
  SQL
51
105
 
@@ -72,15 +126,22 @@ module Monk
72
126
  # route, but builds links to it: login_link below, and so
73
127
  # Monk::Auth::SendLoginLink. login_request_interval: is the seconds
74
128
  # allow_login_request? makes an address wait between login emails.
129
+ # session_max_age: caps a session's whole life, in seconds from its
130
+ # creation, however much it's used (nil: no cap). expired_retention:
131
+ # is the seconds an expired session is kept before sweep! deletes it
132
+ # (90 days): Monk::Push still notifies through it until then.
75
133
  def configure(
76
134
  db_name: nil, secret: nil, login_ttl: nil, session_ttl: nil, redirect_allowlist: [], secure: true,
77
- deliver: nil, callback_path: "/auth/callback", login_request_interval: 60
135
+ deliver: nil, callback_path: "/auth/callback", login_request_interval: 60, session_max_age: nil,
136
+ expired_retention: EXPIRED_RETENTION
78
137
  )
79
138
  config = {
80
139
  db_name: db_name, secret: checked_secret(secret), login_ttl: login_ttl, session_ttl: session_ttl,
81
- redirect_allowlist: redirect_allowlist, secure: secure, deliver: deliver,
140
+ redirect_allowlist: checked_redirect_allowlist(redirect_allowlist), secure: secure, deliver: deliver,
82
141
  callback_path: checked_callback_path(callback_path),
83
142
  login_request_interval: checked_login_request_interval(login_request_interval),
143
+ session_max_age: checked_session_max_age(session_max_age),
144
+ expired_retention: checked_expired_retention(expired_retention),
84
145
  }
85
146
 
86
147
  REQUIRED_CONFIG_KEYS.each do |key|
@@ -103,22 +164,60 @@ module Monk
103
164
  @config = nil
104
165
  end
105
166
 
167
+ # A login token for `email` (stripped and downcased), redeemable once
168
+ # within login_ttl, by its link (redeem) or its code (redeem_code):
169
+ # { token:, code: }. Only hashes are stored: send both right away.
106
170
  def request_login(email, redirect_to: nil)
107
171
  ensure_configured!
108
- if redirect_to && !config[:redirect_allowlist].include?(redirect_to)
172
+ email = normalized_email(email)
173
+ if redirect_to && !allowed_redirect?(redirect_to)
109
174
  raise Monk::InvalidRedirectError, "#{redirect_to.inspect} is not in Monk::Auth's redirect_allowlist"
110
175
  end
111
176
 
112
177
  raw = SecureRandom.urlsafe_base64(32)
178
+ code = format("%06d", SecureRandom.random_number(1_000_000))
113
179
 
114
180
  LoginToken.create(
115
181
  email: email,
116
182
  token_hash: hash_token(raw),
183
+ code_hash: hash_code(code),
117
184
  redirect_to: redirect_to,
118
185
  expires_at: Time.now + config[:login_ttl],
119
186
  )
120
187
 
121
- raw
188
+ { token: raw, code: code }
189
+ end
190
+
191
+ # Whether request_login(redirect_to:) accepts `path`: it starts with
192
+ # a single "/" (never "//" or "/\", which a browser reads as another
193
+ # host), and the part before any "?" is a String entry of
194
+ # redirect_allowlist, or matched whole by a Regexp entry. A route
195
+ # checks it before enqueueing SendLoginLink, where an
196
+ # InvalidRedirectError would fail unseen in the job.
197
+ #
198
+ # halt(422) if redirect_to && !Monk::Auth.allowed_redirect?(redirect_to)
199
+ def allowed_redirect?(path)
200
+ ensure_configured!
201
+ return false unless path.is_a?(String) && path.start_with?("/")
202
+ return false if path.start_with?("//", "/\\")
203
+
204
+ path_only = path.split("?", 2).first
205
+ config[:redirect_allowlist].any? do |entry|
206
+ entry.is_a?(Regexp) ? entry.match?(path_only) : entry == path_only
207
+ end
208
+ end
209
+
210
+ # Where a login token was going (its redirect_to), whether or not it
211
+ # has expired or been used; nil for an unknown token or one with no
212
+ # redirect_to. Only whoever holds the token learns it: a callback
213
+ # sends an expired link back to its page instead of a dead end.
214
+ #
215
+ # redirect("#{Monk::Auth.redirect_for(params[:token]) || "/"}?expired=1")
216
+ def redirect_for(raw)
217
+ ensure_configured!
218
+ return nil if raw.nil? || raw.empty?
219
+
220
+ LoginToken.where(token_hash: hash_token(raw)).first&.fetch(:redirect_to)
122
221
  end
123
222
 
124
223
  # The login-email rate limit, for the login route to check before it
@@ -179,12 +278,15 @@ module Monk
179
278
  # `link` is usually login_link(token), above. An app may build its
180
279
  # own instead, from a trusted origin, never from request headers.
181
280
  # `token` is passed through for a deliver: that wants it (an SMS
182
- # body instead of a link, say); most won't need it.
183
- def deliver_link(email:, link:, token: nil)
281
+ # body instead of a link, say); most won't need it. `redirect_to`
282
+ # (where the link returns, e.g. an invitation) and `code` (the
283
+ # sign-in code) let the mail say more; deliver: is always called with
284
+ # all five keywords.
285
+ def deliver_link(email:, link:, token: nil, redirect_to: nil, code: nil)
184
286
  ensure_configured!
185
287
 
186
288
  if config[:deliver]
187
- config[:deliver].call(email: email, link: link, token: token)
289
+ config[:deliver].call(email: email, link: link, token: token, redirect_to: redirect_to, code: code)
188
290
  elsif Monk.env.development?
189
291
  log_dev_link(link, subject: email)
190
292
  else
@@ -240,14 +342,33 @@ module Monk
240
342
  return nil unless row
241
343
  return nil if row[:expires_at] <= Time.now
242
344
 
243
- claimed = LoginToken.claim({ id: row[:id], used_at: nil }, used_at: Time.now)
244
- return nil unless claimed
345
+ start_session(row)
346
+ end
245
347
 
246
- session_raw = SecureRandom.urlsafe_base64(32)
247
- expires_at = Time.now + config[:session_ttl]
248
- Session.create(subject: row[:email], token_hash: hash_token(session_raw), expires_at: expires_at)
348
+ # As redeem, for the 6-digit code sent beside the link: a session,
349
+ # or nil. Only the address's newest token counts, so asking for a new
350
+ # code retires the previous one. A wrong code counts against the
351
+ # token (the MAX_CODE_ATTEMPTS-th uses it up) and against the
352
+ # address: past MAX_CODE_FAILURES_PER_HOUR, every code for it is
353
+ # refused until the hour is up, so asking for new codes doesn't buy
354
+ # more guesses. The link keeps working.
355
+ def redeem_code(email, code)
356
+ ensure_configured!
357
+ return nil unless email.is_a?(String) && code.is_a?(String) && code.match?(CODE_FORMAT)
249
358
 
250
- { token: session_raw, subject: row[:email], expires_at: expires_at, redirect_to: row[:redirect_to] }
359
+ email = normalized_email(email)
360
+ return nil if email.empty?
361
+
362
+ row = LoginToken.where({ email: email }, order: { created_at: :desc, id: :desc }, limit: 1).first
363
+ return nil unless row && row[:used_at].nil? && row[:expires_at] > Time.now && row[:code_hash]
364
+ return nil if code_locked?(email)
365
+
366
+ unless OpenSSL.secure_compare(hash_code(code), row[:code_hash])
367
+ count_code_failure(row[:id], email)
368
+ return nil
369
+ end
370
+
371
+ start_session(row)
251
372
  end
252
373
 
253
374
  def verify(raw)
@@ -257,16 +378,45 @@ module Monk
257
378
  # As #verify, with when the session expires: {subject:, expires_at:},
258
379
  # or nil. The helpers use it to reissue a CSRF cookie that lives as
259
380
  # long as its session.
260
- def verified_session(raw)
381
+ #
382
+ # renew: true (the helpers, on every HTTP request) also renews a
383
+ # session in use: once less than half of session_ttl is left, its
384
+ # expires_at moves to now + session_ttl (never past session_max_age
385
+ # from its creation), and the result says renewed: true so the
386
+ # caller reissues its cookies. One UPDATE per session per half TTL,
387
+ # never per request. #verify (the WebSocket's check) never writes.
388
+ def verified_session(raw, renew: false)
261
389
  ensure_configured!
262
390
  return nil if raw.nil? || raw.empty?
263
391
 
264
392
  row = Session.where(token_hash: hash_token(raw)).first
265
393
  return nil unless row
266
394
  return nil if row[:revoked_at]
267
- return nil if row[:expires_at] <= Time.now
268
395
 
269
- { subject: row[:subject], expires_at: row[:expires_at] }
396
+ now = Time.now
397
+ return nil if row[:expires_at] <= now
398
+
399
+ ends_at = config[:session_max_age] && (row[:created_at] + config[:session_max_age])
400
+ return nil if ends_at && ends_at <= now
401
+
402
+ session = { subject: row[:subject], expires_at: row[:expires_at] }
403
+ renew ? renewed(row, session, now, ends_at) : session
404
+ end
405
+
406
+ # A second session for a valid session's subject, with the same
407
+ # created_at and expires_at (so it never outlives session_max_age):
408
+ # {token:, subject:, expires_at:}, or nil. The installed iPhone app
409
+ # starts with Safari's session, copied once at Add to Home Screen;
410
+ # after a split, logging out in one no longer ends the other.
411
+ def split(raw)
412
+ ensure_configured!
413
+ return nil unless verified_session(raw)
414
+
415
+ token = SecureRandom.urlsafe_base64(32)
416
+ row = Monk::Persistence::Pg.checkout(config[:db_name]) do |conn|
417
+ conn.exec_params(SPLIT_SESSION_SQL, [hash_token(raw), hash_token(token)]).first
418
+ end
419
+ { token: token, subject: row["subject"], expires_at: row["expires_at"] }
270
420
  end
271
421
 
272
422
  def revoke(raw)
@@ -286,8 +436,9 @@ module Monk
286
436
  rows.size
287
437
  end
288
438
 
289
- # Deletes expired login tokens and sessions, and login requests older
290
- # than login_request_interval; returns how many of each. At most
439
+ # Deletes expired login tokens, sessions expired for longer than
440
+ # expired_retention, and login requests older than
441
+ # login_request_interval; returns how many of each. At most
291
442
  # batch_size rows per statement, so a large backlog (the first sweep of
292
443
  # an app that never swept) holds no lock for long. Run nightly by
293
444
  # Monk::Auth::Sweep. Deliberately not grown onto Model: a `<` comparison
@@ -303,7 +454,7 @@ module Monk
303
454
  now = Time.now
304
455
  {
305
456
  login_tokens: delete_in_batches(conn, SWEEP_LOGIN_TOKENS_SQL, [now], batch_size),
306
- sessions: delete_in_batches(conn, SWEEP_SESSIONS_SQL, [now], batch_size),
457
+ sessions: delete_in_batches(conn, SWEEP_SESSIONS_SQL, [now - config[:expired_retention]], batch_size),
307
458
  login_requests: delete_in_batches(
308
459
  conn, SWEEP_LOGIN_REQUESTS_SQL, [config[:login_request_interval]], batch_size,
309
460
  ),
@@ -355,6 +506,54 @@ module Monk
355
506
  end.join("\n")
356
507
  end
357
508
 
509
+ # Uses up a login token (link or code) and opens a session for its
510
+ # address; nil if the other way, or another request, got there first.
511
+ def start_session(row)
512
+ claimed = LoginToken.claim({ id: row[:id], used_at: nil }, used_at: Time.now)
513
+ return nil unless claimed
514
+
515
+ session_raw = SecureRandom.urlsafe_base64(32)
516
+ expires_at = Time.now + config[:session_ttl]
517
+ Session.create(subject: row[:email], token_hash: hash_token(session_raw), expires_at: expires_at)
518
+
519
+ { token: session_raw, subject: row[:email], expires_at: expires_at, redirect_to: row[:redirect_to] }
520
+ end
521
+
522
+ # session with expires_at moved and renewed: true, when it was due
523
+ # and this request got there first; session as it was otherwise.
524
+ def renewed(row, session, now, ends_at)
525
+ ttl = config[:session_ttl]
526
+ return session if row[:expires_at] >= now + (ttl / 2.0)
527
+
528
+ new_expires_at = [now + ttl, ends_at].compact.min
529
+ return session if new_expires_at <= row[:expires_at]
530
+
531
+ updated = Monk::Persistence::Pg.checkout(config[:db_name]) do |conn|
532
+ conn.exec_params(RENEW_SESSION_SQL, [row[:id], new_expires_at, now + (ttl / 2.0)]).ntuples.positive?
533
+ end
534
+ updated ? session.merge(expires_at: new_expires_at, renewed: true) : session
535
+ end
536
+
537
+ def code_locked?(email)
538
+ Monk::Persistence::Pg.checkout(config[:db_name]) do |conn|
539
+ conn.exec_params(CODE_LOCKED_SQL, [email, MAX_CODE_FAILURES_PER_HOUR]).ntuples.positive?
540
+ end
541
+ end
542
+
543
+ def count_code_failure(token_id, email)
544
+ Monk::Persistence::Pg.checkout(config[:db_name]) do |conn|
545
+ conn.exec_params(CODE_MISS_SQL, [token_id, MAX_CODE_ATTEMPTS, Time.now])
546
+ conn.exec_params(CODE_FAILURE_SQL, [email])
547
+ end
548
+ end
549
+
550
+ # The same normalization as allow_login_request?'s.
551
+ def normalized_email(email) = email.strip.downcase
552
+
553
+ # Keyed by the auth secret: six digits are trivial to try offline
554
+ # against a plain hash.
555
+ def hash_code(code) = OpenSSL::HMAC.hexdigest("SHA256", config[:secret], code)
556
+
358
557
  def ensure_configured!
359
558
  return if @config
360
559
 
@@ -378,6 +577,19 @@ module Monk
378
577
  secret
379
578
  end
380
579
 
580
+ # Strings (exact paths) and Regexps. Each Regexp is anchored here,
581
+ # \A(?:...)\z, so it must match the whole path: one written without
582
+ # \z would otherwise let "/invite/x/../admin" through.
583
+ def checked_redirect_allowlist(entries)
584
+ unless entries.is_a?(Array) && entries.all? { |entry| entry.is_a?(String) || entry.is_a?(Regexp) }
585
+ raise Monk::InvalidAuthConfigError,
586
+ "Monk::Auth.configure(redirect_allowlist:) is an Array of paths (Strings) and patterns (Regexps), " \
587
+ "got #{entries.inspect}"
588
+ end
589
+
590
+ entries.map { |entry| entry.is_a?(Regexp) ? /\A(?:#{entry})\z/ : entry }
591
+ end
592
+
381
593
  def checked_callback_path(path)
382
594
  unless path.is_a?(String) && path.start_with?("/")
383
595
  raise Monk::InvalidAuthConfigError,
@@ -398,6 +610,21 @@ module Monk
398
610
  end
399
611
  end
400
612
 
613
+ def checked_expired_retention(seconds)
614
+ return seconds if seconds.is_a?(Integer) && !seconds.negative?
615
+
616
+ raise Monk::InvalidAuthConfigError, "Monk::Auth.configure(expired_retention:) must be an Integer of " \
617
+ "seconds, 0 or more, got #{seconds.inspect}"
618
+ end
619
+
620
+ def checked_session_max_age(seconds)
621
+ return nil if seconds.nil?
622
+ return seconds if seconds.is_a?(Integer) && seconds.positive?
623
+
624
+ raise Monk::InvalidAuthConfigError, "Monk::Auth.configure(session_max_age:) must be nil (no cap) or a " \
625
+ "positive Integer of seconds, got #{seconds.inspect}"
626
+ end
627
+
401
628
  def checked_login_request_interval(seconds)
402
629
  unless seconds.is_a?(Integer) && seconds.positive?
403
630
  raise Monk::InvalidAuthConfigError, "Monk::Auth.configure(login_request_interval:) must be a positive " \
@@ -4,12 +4,14 @@ Monk::Generator.define(:auth) do
4
4
  installed_if "config/auth.rb"
5
5
  depends_on :postgres, :mail
6
6
 
7
- copy "config/auth.rb", "app/mailers/auth_mailer.rb", role: :wiring
7
+ copy "config/auth.rb", role: :wiring
8
+ copy "app/mailers/auth_mailer.rb", role: :wiring, app_name: true
8
9
  copy "app/views/mail/magic_link.erb", "app/views/auth/login.erb", role: :view
9
10
  copy "app/routes/auth.rb", role: :example
10
11
  copy "test/auth_test.rb", role: :test
11
12
  migration "create_auth_tables"
12
13
  migration "create_login_requests"
14
+ migration "add_login_codes"
13
15
 
14
16
  env :development, { "AUTH_SECRET" => "change-me-dev-secret" }
15
17
  env :test, { "AUTH_SECRET" => "change-me-test-secret" }