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.
@@ -5,8 +5,11 @@ module Monk
5
5
  module Push
6
6
  # Push's statements on push_subscriptions (and, read-only, auth's
7
7
  # sessions). A subscription counts -- gets notifications, makes its
8
- # subject subscribed -- only while its session is neither revoked nor
9
- # expired, and while the browser's own expirationTime hasn't passed.
8
+ # subject subscribed -- until its session is revoked, or expired for
9
+ # longer than Monk::Auth's expired_retention (the $2 of each statement
10
+ # using LIVE), and while the browser's own expirationTime hasn't
11
+ # passed: logging out stops it at once, an idle person keeps being
12
+ # notified.
10
13
  # Module functions over a db_name, each reaching Postgres through
11
14
  # Monk::Persistence::Pg in whatever Ractor calls it, as the job workers
12
15
  # do.
@@ -14,7 +17,8 @@ module Monk
14
17
  ARRAY = Ractor.make_shareable(PG::TextEncoder::Array.new)
15
18
 
16
19
  LIVE = <<~SQL.freeze
17
- s.revoked_at IS NULL AND s.expires_at > now() AND (p.expires_at IS NULL OR p.expires_at > now())
20
+ s.revoked_at IS NULL AND s.expires_at > now() - $2::int * interval '1 second'
21
+ AND (p.expires_at IS NULL OR p.expires_at > now())
18
22
  SQL
19
23
 
20
24
  # Only for a valid session: no row when the cookie's session is
@@ -51,9 +55,10 @@ module Monk
51
55
  DELETE_SQL = "DELETE FROM push_subscriptions WHERE id = $1".freeze
52
56
  SUCCEEDED_SQL = "UPDATE push_subscriptions SET last_success_at = now() WHERE id = $1".freeze
53
57
 
54
- # What no longer counts: a revoked session's rows, an expired
55
- # session's (if Monk::Auth.sweep! hasn't taken the session yet), and
56
- # those past the browser's expirationTime. $1 is the batch size.
58
+ # What no longer counts: a revoked session's rows, one expired past
59
+ # expired_retention (if Monk::Auth.sweep! hasn't taken the session
60
+ # yet), and those past the browser's expirationTime. $1 is the batch
61
+ # size.
57
62
  SWEEP_SQL = <<~SQL.freeze
58
63
  DELETE FROM push_subscriptions WHERE id IN (
59
64
  SELECT p.id FROM push_subscriptions p JOIN sessions s ON s.id = p.session_id
@@ -76,18 +81,18 @@ module Monk
76
81
  end
77
82
 
78
83
  def for_subject(db_name, subject)
79
- checkout(db_name) { |conn| conn.exec_params(FOR_SUBJECT_SQL, [subject]).map { |row| record(row) } }
84
+ checkout(db_name) { |conn| conn.exec_params(FOR_SUBJECT_SQL, [subject, retention]).map { |row| record(row) } }
80
85
  end
81
86
 
82
87
  def find(db_name, id)
83
- checkout(db_name) { |conn| conn.exec_params(BY_ID_SQL, [id]).map { |row| record(row) }.first }
88
+ checkout(db_name) { |conn| conn.exec_params(BY_ID_SQL, [id, retention]).map { |row| record(row) }.first }
84
89
  end
85
90
 
86
91
  # { subject => true/false } for every subject given.
87
92
  def subscribed(db_name, subjects)
88
93
  subjects = subjects.map(&:to_s).uniq
89
94
  found = checkout(db_name) do |conn|
90
- conn.exec_params(SUBSCRIBED_SQL, [ARRAY.encode(subjects)]).map { |row| row["subject"] }
95
+ conn.exec_params(SUBSCRIBED_SQL, [ARRAY.encode(subjects), retention]).map { |row| row["subject"] }
91
96
  end
92
97
  subjects.to_h { |subject| [subject, found.include?(subject)] }
93
98
  end
@@ -105,7 +110,7 @@ module Monk
105
110
  checkout(db_name) do |conn|
106
111
  total = 0
107
112
  loop do
108
- deleted = conn.exec_params(SWEEP_SQL, [batch_size]).cmd_tuples
113
+ deleted = conn.exec_params(SWEEP_SQL, [batch_size, retention]).cmd_tuples
109
114
  total += deleted
110
115
  break total if deleted < batch_size
111
116
  end
@@ -118,6 +123,8 @@ module Monk
118
123
  end
119
124
 
120
125
  def checkout(db_name, &) = Monk::Persistence::Pg.checkout(db_name, &)
126
+
127
+ def retention = Monk::Auth.config.fetch(:expired_retention)
121
128
  end
122
129
  end
123
130
  end
data/lib/monk/push.rb CHANGED
@@ -112,8 +112,9 @@ module Monk
112
112
  Delivery.options(ttl: ttl, urgency: urgency, topic: topic),)
113
113
  end
114
114
 
115
- # Deletes subscriptions that no longer count: a revoked or expired
116
- # session's, and those past the browser's expirationTime. Returns how
115
+ # Deletes subscriptions that no longer count: a revoked session's, one
116
+ # expired past Monk::Auth's expired_retention, and those past the
117
+ # browser's expirationTime. Returns how
117
118
  # many. Run nightly by Monk::Push::Sweep.
118
119
  def sweep!(batch_size: 1000)
119
120
  unless batch_size.is_a?(Integer) && batch_size.positive?
@@ -0,0 +1,21 @@
1
+ // What register.js tells the page about where it runs, as pure functions
2
+ // (test/js/pwa_platform.test.js).
3
+
4
+ // iPadOS reports itself as a Mac: a Mac with a touch screen is an iPad.
5
+ export function platform(userAgent, maxTouchPoints) {
6
+ if (/iPad|iPhone|iPod/.test(userAgent) || (/Macintosh/.test(userAgent) && maxTouchPoints > 1)) return "ios";
7
+ if (/Android/.test(userAgent)) return "android";
8
+ return "other";
9
+ }
10
+
11
+ // A chat or social app's built-in browser, guessed from its user agent:
12
+ // it can't install the app. WhatsApp's, on iOS, can't be told from Safari.
13
+ const IN_APP = /Instagram|FBAN|FBAV|FB_IAB|LinkedInApp|\bLine\/|TikTok|musical_ly|BytedanceWebview|Telegram/;
14
+
15
+ export const inApp = (userAgent) => IN_APP.test(userAgent);
16
+
17
+ // The install banner: on iOS, where Add to Home Screen is the way (the
18
+ // sheet says how), or on Android once Chrome offered its own prompt; never
19
+ // in the installed app itself, nor on a desktop.
20
+ export const showInstall = ({ platform, standalone, installable }) =>
21
+ !standalone && (platform === "ios" || (platform === "android" && installable));
@@ -5,13 +5,60 @@
5
5
  // monk-pwa:registered { scope }
6
6
  // monk-pwa:unsupported { reason: "no-service-worker" | "insecure" }
7
7
  // monk-pwa:failed { message }
8
+ // monk-pwa:own-session { status }
9
+ // monk-pwa:installable {} the browser offered to install the app
10
+ // monk-pwa:installed {}
11
+ //
12
+ // And where it runs, on <html>, for CSS to show the right thing:
13
+ // data-pwa-standalone "true" in the installed app, "false" in a tab
14
+ // data-pwa-platform "ios", "android" or "other"
15
+ // data-pwa-installable present once the browser offered to install
16
+ // data-pwa-in-app present in a chat or social app's built-in browser
17
+ // <%= monk_install %>'s banner is shown on iOS, or on Android once
18
+ // installable, and never in the app nor on a desktop; its button opens the browser's prompt, or on iOS the
19
+ // sheet saying how to Add to Home Screen.
8
20
  //
9
21
  // updateViaCache: "none" makes the browser check /sw.js itself on every
10
22
  // navigation, never from its HTTP cache, so an edited worker is picked up
11
23
  // on the next page load.
24
+ //
25
+ // With auth, the installed app on an iPhone also asks once for its own
26
+ // session (Monk::Auth's own_session!, at the meta's URL): Add to Home
27
+ // Screen copies Safari's cookies, so the app starts with Safari's very
28
+ // session, and logging out in one would end both.
29
+
30
+ import { platform, inApp, showInstall } from "./platform.js";
12
31
 
13
32
  const emit = (name, detail = {}) => document.dispatchEvent(new CustomEvent(`monk-pwa:${name}`, { detail }));
14
33
 
34
+ const root = document.documentElement;
35
+ root.dataset.pwaStandalone = String(standalone());
36
+ root.dataset.pwaPlatform = platform(navigator.userAgent, navigator.maxTouchPoints);
37
+ if (inApp(navigator.userAgent)) root.dataset.pwaInApp = "";
38
+
39
+ // Chrome's own install prompt, kept for the banner's button.
40
+ let installPrompt = null;
41
+ addEventListener("beforeinstallprompt", (event) => {
42
+ event.preventDefault();
43
+ installPrompt = event;
44
+ root.dataset.pwaInstallable = "";
45
+ showBanners();
46
+ emit("installable");
47
+ });
48
+ addEventListener("appinstalled", () => {
49
+ installPrompt = null;
50
+ delete root.dataset.pwaInstallable;
51
+ showBanners();
52
+ emit("installed");
53
+ });
54
+ document.addEventListener("click", (event) => {
55
+ const button = event.target.closest("[data-monk-install]");
56
+ if (button) install(button);
57
+ });
58
+ showBanners();
59
+
60
+ ownSession();
61
+
15
62
  if (!window.isSecureContext) {
16
63
  // Service workers need https, or localhost: a phone opening the dev
17
64
  // server at http://192.168.x.x gets none.
@@ -40,6 +87,52 @@ function standalone() {
40
87
  return navigator.standalone === true || modes.some((mode) => matchMedia(`(display-mode: ${mode})`).matches);
41
88
  }
42
89
 
90
+ // navigator.standalone is iOS's alone: Android's installed app shares
91
+ // Chrome's cookies, so it has nothing to split. Remembered once the
92
+ // server answered (a 401 or 404 too: no session, or no route, to split),
93
+ // so a first launch offline tries again on the next one.
94
+ function ownSession() {
95
+ const DONE = "monk-pwa:own-session";
96
+ const url = document.querySelector('meta[name="monk-auth-own-url"]')?.content;
97
+ if (!url || navigator.standalone !== true) return;
98
+ try {
99
+ if (localStorage.getItem(DONE) === "1") return;
100
+ } catch {
101
+ return; // no localStorage: it would ask on every launch
102
+ }
103
+
104
+ const csrf = document.cookie.split("; ").find((pair) => pair.startsWith("csrf_token="))?.slice("csrf_token=".length);
105
+ fetch(url, { method: "POST", credentials: "same-origin", headers: csrf ? { "x-csrf-token": csrf } : {} })
106
+ .then((response) => {
107
+ if (!response.ok && response.status !== 401 && response.status !== 404) return;
108
+ localStorage.setItem(DONE, "1");
109
+ emit("own-session", { status: response.status });
110
+ })
111
+ .catch((error) => console.warn("monk-pwa: asking for the app's own session failed", error));
112
+ }
113
+
114
+ function showBanners() {
115
+ const show = showInstall({
116
+ platform: root.dataset.pwaPlatform,
117
+ standalone: root.dataset.pwaStandalone === "true",
118
+ installable: installPrompt !== null,
119
+ });
120
+ document.querySelectorAll("[data-monk-install-banner]").forEach((banner) => { banner.hidden = !show; });
121
+ }
122
+
123
+ // On iOS always the sheet: Add to Home Screen is the only way there.
124
+ function install(button) {
125
+ if (installPrompt && root.dataset.pwaPlatform !== "ios") {
126
+ const prompt = installPrompt;
127
+ installPrompt = null;
128
+ prompt.prompt();
129
+ showBanners(); // Chrome's prompt is good for one go
130
+ return;
131
+ }
132
+ const banner = button.closest("[data-monk-install-banner]");
133
+ (banner ?? document).querySelector("[data-monk-install-sheet]")?.showModal();
134
+ }
135
+
43
136
  function tellWorkerThisIsTheApp() {
44
137
  navigator.serviceWorker.ready
45
138
  .then((registration) => registration.active?.postMessage({ monkPwa: { standalone: true } }))
@@ -20,6 +20,44 @@ module Monk
20
20
  %(<script type="module" src="#{h(asset_path("#{Pwa::CLIENT_PATH}/register.js"))}"></script>),
21
21
  ].compact
22
22
  end
23
+
24
+ # iOS's own Share and Add to Home Screen glyphs, for the sheet's
25
+ # steps; currentColor, so they take the app's text colour.
26
+ SHARE_ICON = '<svg class="monk-install__icon" viewBox="0 0 24 24" width="20" height="20" aria-hidden="true" ' \
27
+ 'fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" ' \
28
+ 'stroke-linejoin="round">' \
29
+ '<path d="M12 3v12M7.5 7.5 12 3l4.5 4.5"/><path d="M8 10H6v11h12V10h-2"/></svg>'.freeze
30
+ ADD_ICON = '<svg class="monk-install__icon" viewBox="0 0 24 24" width="20" height="20" aria-hidden="true" ' \
31
+ 'fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round">' \
32
+ '<rect x="3.5" y="3.5" width="17" height="17" rx="4"/><path d="M12 8v8M8 12h8"/></svg>'.freeze
33
+
34
+ # A banner inviting people to install the app, for a layout or a page:
35
+ # <%= monk_install %>
36
+ # Hidden until register.js shows it: on iOS, where its button opens
37
+ # a sheet saying how to Add to Home Screen, or once the browser
38
+ # offered its own prompt (Android's Chrome), which the button opens;
39
+ # never in the installed app, nor on a desktop. BEM classes and no
40
+ # styles: the app styles it. Every text can be overridden (another
41
+ # language, say); the app's name is the manifest's.
42
+ def monk_install(text: nil, button: "Install", share: "Tap Share", add: "then Add to Home Screen",
43
+ close: "OK")
44
+ return raw("") unless Monk::Pwa.configured?
45
+
46
+ text ||= "Install #{Monk::Pwa.manifest["name"]} on your device."
47
+ raw(<<~HTML.chomp)
48
+ <div class="monk-install" data-monk-install-banner hidden>
49
+ <p class="monk-install__text">#{h(text)}</p>
50
+ <button type="button" class="monk-install__button" data-monk-install>#{h(button)}</button>
51
+ <dialog class="monk-install__sheet" data-monk-install-sheet>
52
+ <ol class="monk-install__steps">
53
+ <li class="monk-install__step">#{h(share)} #{SHARE_ICON}</li>
54
+ <li class="monk-install__step">#{h(add)} #{ADD_ICON}</li>
55
+ </ol>
56
+ <form method="dialog"><button class="monk-install__close">#{h(close)}</button></form>
57
+ </dialog>
58
+ </div>
59
+ HTML
60
+ end
23
61
  end
24
62
  end
25
63
  end
@@ -2,22 +2,27 @@
2
2
 
3
3
  **Where:** `config/auth.rb` (settings, `callback_path:`),
4
4
  `app/routes/auth.rb` (the routes, commented: block `auth-routes`),
5
- `app/mailers/auth_mailer.rb` (sends the link), `app/views/auth/login.erb`
6
- (the login page), `app/views/mail/magic_link.erb` (the email's HTML).
5
+ `app/mailers/auth_mailer.rb` (sends the link and the code),
6
+ `app/views/auth/login.erb` (the login page, then the code form),
7
+ `app/views/mail/magic_link.erb` (the email's HTML).
7
8
 
8
- **Main calls:** `Monk::Auth.request_login(email)` returns a token;
9
- `Monk::Auth.login_link(token)` builds its link;
10
- `Monk::Auth.deliver_link(email:, link:, token:)` sends it;
11
- `Monk::Auth.redeem(token)` returns a session or nil. In routes:
12
- `set_session_cookie(session)`, `current_subject` (nil when logged out),
13
- `require_user!` (halts 401), `require_csrf!`, `log_out!`. With jobs:
9
+ **Main calls:** `Monk::Auth.request_login(email)` returns
10
+ `{ token:, code: }`; `Monk::Auth.login_link(token)` builds the link;
11
+ `Monk::Auth.deliver_link(email:, link:, token:, code:)` sends both;
12
+ `Monk::Auth.redeem(token)` and `Monk::Auth.redeem_code(email, code)`
13
+ return a session or nil. In routes: `set_session_cookie(session)`,
14
+ `current_subject` (nil when logged out; renews a session in use),
15
+ `require_user!` (halts 401), `require_csrf!`, `log_out!`, `own_session!`
16
+ (the installed iPhone app's own session, `POST /auth/own`). With jobs:
14
17
  `Monk::Auth::SendLoginLink.enqueue(email)`. Rate limit, in the login
15
18
  route before sending: `halt(429) unless Monk::Auth.allow_login_request?(email)`
16
19
  (one per address per `login_request_interval:`). `Monk::Auth.sweep!`
17
20
  deletes expired rows; with jobs, `Monk::Auth::Sweep` runs it nightly
18
- (`config/recurring.rb`).
21
+ (`config/recurring.rb`); expired sessions are kept for
22
+ `expired_retention:` (90 days), since push still reaches them.
19
23
 
20
- **Test:** `test/auth_test.rb` sends a link to `log/test.log` and redeems it.
24
+ **Test:** `test/auth_test.rb` sends a link and code to `log/test.log` and
25
+ redeems each.
21
26
  A test that asks for links calls `Monk::Auth.clear_login_requests!` in
22
27
  `teardown`, or its next request for the same address gets a 429.
23
28
 
@@ -28,7 +33,11 @@ A test that asks for links calls `Monk::Auth.clear_login_requests!` in
28
33
  - Never point `deliver:` at `Monk::Mail.deliver_later`: the link, token
29
34
  included, would sit in the job queue. Use `SendLoginLink` instead.
30
35
  - Links come from `Monk::Settings[:public_url]`, never from request headers.
31
- - A `redirect_to` must be listed in `redirect_allowlist`.
36
+ - A `redirect_to` must be allowed by `redirect_allowlist` (exact paths, or
37
+ Regexps matching the whole path). With jobs, check
38
+ `Monk::Auth.allowed_redirect?(path)` before enqueueing `SendLoginLink`.
39
+ - `deliver:` is called with `email:, link:, token:, redirect_to:, code:`:
40
+ take what you don't use with `**`.
32
41
  - A cookie-authenticated POST calls `require_csrf!`, and sends the token:
33
42
  a form with `<%= csrf_field %>`, `fetch` with the `x-csrf-token` header
34
43
  (the `csrf_token` cookie's value).
@@ -8,15 +8,19 @@ module AuthMailer
8
8
  # Monk::Auth.deliver_link. The HTML part is
9
9
  # app/views/mail/magic_link.erb. Swap the body for SMS or any other
10
10
  # channel; see docs/guides/auth.md.
11
- MAGIC_LINK = lambda do |email:, link:, token:|
11
+ #
12
+ # The subject starts with the code, so a phone's notification shows it
13
+ # and Safari can offer it on the login page.
14
+ MAGIC_LINK = lambda do |email:, link:, code:, **|
12
15
  # Development only (a no-op elsewhere): the link on the console, plus a
13
16
  # QR code for a phone if rqrcode is in the Gemfile.
14
17
  Monk::Auth.log_dev_link(link, subject: email)
15
18
  Monk::Mail.deliver(
16
19
  to: email,
17
- subject: "Your login link",
18
- text: "Here's your login link:\n\n#{link}\n\nIf you didn't ask for it, you can ignore this email.",
19
- html: Monk::Mail.render("mail/magic_link", link: link),
20
+ subject: "#{code} is your {{app}} code",
21
+ text: "Your login code: #{code}\n\nOr log in with this link:\n\n#{link}\n\n" \
22
+ "If you didn't ask for it, you can ignore this email.",
23
+ html: Monk::Mail.render("mail/magic_link", link: link, code: code),
20
24
  )
21
25
  end
22
26
  end
@@ -1,15 +1,16 @@
1
- # Logging in by email link (monk add auth). Monk::Auth makes and checks the
1
+ # Logging in by email link or code (monk add auth). Monk::Auth makes and checks the
2
2
  # tokens and sessions; these routes are the app's own, because they carry
3
3
  # its decisions: the rate limit, where to go after logging in, JSON or HTML.
4
4
  #
5
- # monk:example auth-routes -- log in by email link, log out, a page for logged-in users.
5
+ # monk:example auth-routes -- log in by email link or code, log out, a page for logged-in users.
6
6
  # # Before going live: keep the rate limit (without one, anyone can make this
7
7
  # # app send mail to any address), and list your redirects in config/auth.rb.
8
8
  # class App
9
9
  # get("/login") { @title = "Log in"; render "auth/login" }
10
10
  #
11
11
  # # The form in app/views/auth/login.erb; a failed submit renders it
12
- # # again with the error and its status.
12
+ # # again with the error and its status. Once sent, the page asks for
13
+ # # the code from the email ("Send a new code" posts here again).
13
14
  # post("/auth/request") do
14
15
  # @title = "Log in"
15
16
  # email = params[:email].to_s.strip.downcase
@@ -24,15 +25,32 @@
24
25
  # halt(429, render("auth/login"))
25
26
  # end
26
27
  #
27
- # # Sent here, in the request. With jobs, replace these two lines with
28
+ # # Sent here, in the request. With jobs, replace these lines with
28
29
  # # Monk::Auth::SendLoginLink.enqueue(email): the token is then made and
29
30
  # # sent in bin/jobs, and never stored.
30
- # token = Monk::Auth.request_login(email)
31
- # Monk::Auth.deliver_link(email: email, link: Monk::Auth.login_link(token), token: token)
32
- # @sent = true
31
+ # login = Monk::Auth.request_login(email)
32
+ # Monk::Auth.deliver_link(
33
+ # email: email, link: Monk::Auth.login_link(login[:token]), token: login[:token], code: login[:code],
34
+ # )
35
+ # @email = email
33
36
  # render "auth/login"
34
37
  # end
35
38
  #
39
+ # # The code from the email, typed on the page that asked for it: works
40
+ # # where the link wouldn't, like the installed app on an iPhone or a
41
+ # # chat app's built-in browser.
42
+ # post("/auth/code") do
43
+ # @title = "Log in"
44
+ # @email = params[:email].to_s.strip.downcase
45
+ # session = Monk::Auth.redeem_code(@email, params[:code].to_s.strip)
46
+ # unless session
47
+ # @error = "That code is wrong or has expired."
48
+ # halt(422, render("auth/login"))
49
+ # end
50
+ # set_session_cookie(session)
51
+ # redirect(session[:redirect_to] || "/")
52
+ # end
53
+ #
36
54
  # # The link in the email: callback_path in config/auth.rb.
37
55
  # get("/auth/callback/:token") do
38
56
  # session = Monk::Auth.redeem(params[:token]) || halt(401, "This link has expired or was already used.")
@@ -48,6 +66,16 @@
48
66
  # redirect "/login", flash: "You're logged out."
49
67
  # end
50
68
  #
69
+ # # The installed app on an iPhone starts with Safari's session (Add to
70
+ # # Home Screen copies the cookies): register.js asks here once, on its
71
+ # # first launch, for a session of its own (monk_head names this path,
72
+ # # Monk::Auth::OWN_PATH), so logging out in one doesn't end the other.
73
+ # post("/auth/own") do
74
+ # require_csrf!
75
+ # own_session! || halt(401)
76
+ # json(ok: true)
77
+ # end
78
+ #
51
79
  # get("/me") { json(email: require_user!) }
52
80
  # end
53
81
  # monk:end
@@ -1,14 +1,28 @@
1
1
  <h1>Log in</h1>
2
2
 
3
- <%# A plain form: POST /auth/request (app/routes/auth.rb) renders this page
4
- again, with @sent once the link is on its way, or with @error and a
5
- 422 or 429. %>
6
- <% if @sent %>
7
- <p>Check your email for the link.</p>
3
+ <%# Plain forms. POST /auth/request (app/routes/auth.rb) renders this page
4
+ again with @email once the email is on its way, or with @error and a
5
+ 422 or 429; POST /auth/code with @email and @error for a wrong code. %>
6
+ <% if @email %>
7
+ <p>We sent a code and a link to <strong><%= @email %></strong>.</p>
8
+ <% if @error %><p role="alert"><%= @error %></p><% end %>
9
+ <form id="login-code" method="post" action="/auth/code">
10
+ <input type="hidden" name="email" value="<%= @email %>">
11
+ <label>Code
12
+ <input name="code" inputmode="numeric" autocomplete="one-time-code" pattern="[0-9]{6}" maxlength="6"
13
+ required autofocus>
14
+ </label>
15
+ <button>Log in</button>
16
+ </form>
17
+ <form method="post" action="/auth/request">
18
+ <input type="hidden" name="email" value="<%= @email %>">
19
+ <button>Send a new code</button>
20
+ </form>
21
+ <p><a href="/login">Wrong address?</a></p>
8
22
  <% else %>
9
23
  <% if @error %><p role="alert"><%= @error %></p><% end %>
10
24
  <form id="login" method="post" action="/auth/request">
11
25
  <label>Email <input type="email" name="email" value="<%= params[:email] %>" required autocomplete="email"></label>
12
- <button>Send me a login link</button>
26
+ <button>Send me a login code</button>
13
27
  </form>
14
28
  <% end %>
@@ -1,3 +1,4 @@
1
- <p>Here's your login link:</p>
2
- <p><a href="<%= locals[:link] %>">Log in</a></p>
1
+ <p>Your login code:</p>
2
+ <p style="font-size: 1.5em; letter-spacing: 0.2em;"><strong><%= locals[:code] %></strong></p>
3
+ <p>Or log in with this link: <a href="<%= locals[:link] %>">Log in</a></p>
3
4
  <p>If you didn't ask for it, you can ignore this email.</p>
@@ -17,8 +17,10 @@ Monk::Auth.configure(
17
17
  db_name: :primary,
18
18
  secret: ENV.fetch("AUTH_SECRET"),
19
19
  login_ttl: 600, # seconds a login token stays redeemable
20
- session_ttl: 1_209_600, # seconds a session stays valid (14 days)
21
- redirect_allowlist: [], # paths request_login(redirect_to:) is allowed to target
20
+ session_ttl: 1_209_600, # seconds a session stays valid unused (14 days); renewed while it's used
21
+ session_max_age: nil, # seconds a session can last however much it's used (nil: no cap)
22
+ expired_retention: 7_776_000, # seconds an expired session is kept (90 days): push still reaches it
23
+ redirect_allowlist: [], # paths (Strings) and patterns (Regexps, matched whole) a login may return to
22
24
  callback_path: "/auth/callback", # your route redeeming a token: GET "#{callback_path}/:token"
23
25
  login_request_interval: 60, # seconds an address waits between login emails (allow_login_request?)
24
26
  secure: !Monk.env.development?, # Secure cookie flag; off in dev so plain-http testing works (Safari drops it)
@@ -0,0 +1,5 @@
1
+ ALTER TABLE login_requests DROP COLUMN code_failures_since;
2
+ ALTER TABLE login_requests DROP COLUMN code_failures;
3
+ DROP INDEX login_tokens_email_created_at;
4
+ ALTER TABLE login_tokens DROP COLUMN code_attempts;
5
+ ALTER TABLE login_tokens DROP COLUMN code_hash;
@@ -0,0 +1,16 @@
1
+ -- Monk::Auth's sign-in code (Monk 0.28): a 6-digit code beside the magic
2
+ -- link, redeeming the same login token (Monk::Auth.redeem_code).
3
+
4
+ -- An HMAC of the code, keyed by AUTH_SECRET (six digits are trivial to
5
+ -- try offline from a plain hash), and the wrong guesses at it: the fifth
6
+ -- uses the token up.
7
+ ALTER TABLE login_tokens ADD COLUMN code_hash TEXT;
8
+ ALTER TABLE login_tokens ADD COLUMN code_attempts INTEGER NOT NULL DEFAULT 0;
9
+
10
+ -- redeem_code checks an address's newest token.
11
+ CREATE INDEX login_tokens_email_created_at ON login_tokens (email, created_at);
12
+
13
+ -- Wrong codes per address, across its tokens: past 10 in an hour,
14
+ -- redeem_code refuses the address until the hour is up.
15
+ ALTER TABLE login_requests ADD COLUMN code_failures INTEGER NOT NULL DEFAULT 0;
16
+ ALTER TABLE login_requests ADD COLUMN code_failures_since TIMESTAMPTZ;
@@ -1,9 +1,11 @@
1
1
  ## auth
2
2
 
3
- Logging in by email link. `config/auth.rb` configures Monk::Auth,
4
- `app/mailers/auth_mailer.rb` sends the link through mail, and two
5
- migrations create the `login_tokens`, `sessions` and `login_requests`
6
- tables: run `bin/setup_db` and
3
+ Logging in by email link, or by the 6-digit code sent with it (which works
4
+ where the link wouldn't: the installed app on an iPhone, a chat app's
5
+ built-in browser). `config/auth.rb` configures Monk::Auth,
6
+ `app/mailers/auth_mailer.rb` sends the link and code through mail, and
7
+ three migrations create the `login_tokens`, `sessions` and
8
+ `login_requests` tables: run `bin/setup_db` and
7
9
  `DB_NAME={{app}}_test bin/setup_db` (postgres, above).
8
10
 
9
11
  ### Before production
@@ -19,23 +21,26 @@ reads it with `ENV.fetch`: unset, the app doesn't boot.
19
21
  minute (`login_request_interval:` in `config/auth.rb`), counted in
20
22
  `login_requests`, so across every `bin/server` process. A limit across
21
23
  addresses (per IP, say) is up to the app.
24
+ - **Wrong codes.** Five wrong codes use a login up; ten for one address
25
+ in an hour lock its codes until the hour is up (the link still works).
22
26
  - **Cleanup.** With jobs (`monk add jobs`), `bin/jobs` deletes expired
23
- sessions and login tokens every night (`monk_auth_sweep` in
24
- `config/recurring.rb`). Without jobs, run `Monk::Auth.sweep!` on a
25
- schedule of your own.
27
+ login tokens, and sessions expired for longer than `expired_retention:`
28
+ (90 days), every night (`monk_auth_sweep` in `config/recurring.rb`).
29
+ Without jobs, run `Monk::Auth.sweep!` on a schedule of your own.
26
30
 
27
31
  ### Check it works
28
32
 
29
- 1. `bundle exec rake test` runs `test/auth_test.rb`: a link is sent (to
30
- `log/test.log`) and redeemed into a session.
33
+ 1. `bundle exec rake test` runs `test/auth_test.rb`: a link and code are
34
+ sent (to `log/test.log`) and each redeems into a session.
31
35
  2. By hand: the login routes are commented out in `app/routes/auth.rb`,
32
36
  block `auth-routes`. Uncomment them and restart `bin/server`. Then:
33
37
  - http://localhost:9292/me answers `401`: nobody is logged in.
34
- - http://localhost:9292/login: enter an email. In development the link
35
- is printed, not sent: in `bin/server`'s console, or in `bin/jobs`'
36
- when a job sends it (`Monk::Auth::SendLoginLink`), and in
37
- `log/development.log` either way. Open it: it logs you in and goes
38
- back to `/`.
38
+ - http://localhost:9292/login: enter an email. In development the mail
39
+ is printed, not sent: on `bin/server`'s console, or `bin/jobs`' when
40
+ a job sends it (`Monk::Auth::SendLoginLink`), and in
41
+ `log/development.log` either way. Type the code from its subject
42
+ into the page, or open its link: either logs you in and goes back
43
+ to `/`.
39
44
  - http://localhost:9292/me now shows your email.
40
45
  - To log out, from the browser's console on any page of the app:
41
46
 
@@ -1,8 +1,8 @@
1
1
  require_relative "test_helper"
2
2
 
3
- # Monk::Auth works end to end without any route: a login link is created,
4
- # sent by config/auth.rb's deliver: (AuthMailer, to log/test.log here), and
5
- # redeemed into a session. SETUP.md, auth.
3
+ # Monk::Auth works end to end without any route: a login link and code are
4
+ # created, sent by config/auth.rb's deliver: (AuthMailer, to log/test.log
5
+ # here), and redeemed into a session. SETUP.md, auth.
6
6
  class AuthTest < Minitest::Test
7
7
  # Lifts the login-email rate limit, so the next test can ask for a link
8
8
  # for the same address at once.
@@ -12,12 +12,25 @@ class AuthTest < Minitest::Test
12
12
 
13
13
  def test_a_login_link_is_sent_and_redeems_into_a_session
14
14
  email = "login-check-#{rand(1_000_000)}@example.test"
15
- token = Monk::Auth.request_login(email)
15
+ login = Monk::Auth.request_login(email)
16
16
 
17
- Monk::Auth.deliver_link(email: email, link: Monk::Auth.login_link(token), token: token)
17
+ Monk::Auth.deliver_link(
18
+ email: email, link: Monk::Auth.login_link(login[:token]), token: login[:token], code: login[:code],
19
+ )
20
+
21
+ log = File.read(File.expand_path("../log/test.log", __dir__))
22
+ assert_includes log, Monk::Auth.login_link(login[:token])
23
+ assert_includes log, "#{login[:code]} is your"
24
+ session = Monk::Auth.redeem(login[:token])
25
+ assert_equal email, Monk::Auth.verify(session[:token])
26
+ end
27
+
28
+ def test_the_code_redeems_into_a_session_too
29
+ email = "code-check-#{rand(1_000_000)}@example.test"
30
+ login = Monk::Auth.request_login(email)
31
+
32
+ session = Monk::Auth.redeem_code(email, login[:code])
18
33
 
19
- assert_includes File.read(File.expand_path("../log/test.log", __dir__)), Monk::Auth.login_link(token)
20
- session = Monk::Auth.redeem(token)
21
34
  assert_equal email, Monk::Auth.verify(session[:token])
22
35
  end
23
36
  end
@@ -1,6 +1,6 @@
1
1
  source "https://rubygems.org"
2
2
 
3
- gem "monkrb", "~> 0.27", require: "monk"
3
+ gem "monkrb", "~> 0.28", require: "monk"
4
4
  gem "rackup"
5
5
  gem "webrick"
6
6
  gem "kino"
@@ -12,8 +12,9 @@ device and returns how many; `Monk::Push.subscribed(subjects)` gives
12
12
  `subscribed?(subject)` for one.
13
13
 
14
14
  **How it works:** a subscription belongs to the auth session it was made
15
- in: logging out, a revoked session or an expired one stops its
16
- notifications. A device that has gone (the push service answers 404/410)
15
+ in: logging out or a revoked session stops its notifications at once. An
16
+ expired session's keep coming for `expired_retention:` (config/auth.rb,
17
+ 90 days), so an idle person is still notified. A device that has gone (the push service answers 404/410)
17
18
  is deleted by its job. `Monk::Push::Sweep` clears the rest nightly
18
19
  (`config/recurring.rb`).
19
20
 
@@ -9,8 +9,12 @@ JSON with `name`, `short_name`, `start_url`, an installable `display`, a
9
9
  `icons/apple-touch-icon.png`; otherwise the boot fails with
10
10
  `Monk::Pwa::InvalidManifestError`. `<%= monk_head %>` links the manifest
11
11
  and the icon, and loads `/_monk/pwa/register.js`, which registers `/sw.js`
12
- and reports `monk-pwa:registered`, `monk-pwa:unsupported` or
13
- `monk-pwa:failed` on `document`.
12
+ and reports `monk-pwa:registered`, `monk-pwa:unsupported`,
13
+ `monk-pwa:failed`, `monk-pwa:installable` and `monk-pwa:installed` on
14
+ `document`. It also sets `data-pwa-standalone`, `data-pwa-platform`
15
+ (`ios`/`android`/`other`), `data-pwa-installable` and `data-pwa-in-app`
16
+ on `<html>`, for CSS. `<%= monk_install %>` renders an install banner
17
+ (hidden until it applies; BEM classes, no styles).
14
18
 
15
19
  **Test:** `test/pwa_test.rb` requests the manifest, its icons and
16
20
  `sw.js`, and checks a page links them.