diff --git a/CHANGELOG.md b/CHANGELOG.md
index b8fe6c2b6..ad7e43877 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -16,6 +16,7 @@ All notable changes to this project will be documented in this file.
- Add last 24h plots to /sites view
- Add site pinning to /sites view
- Add support for JSON logger, via LOG_FORMAT=json environment variable
+- Add support for 2FA authentication
### Removed
- Removed the nested custom event property breakdown UI when filtering by a goal in Goal Conversions
diff --git a/lib/plausible/auth/totp.ex b/lib/plausible/auth/totp.ex
index a5cae9198..5854edb2f 100644
--- a/lib/plausible/auth/totp.ex
+++ b/lib/plausible/auth/totp.ex
@@ -18,19 +18,17 @@ defmodule Plausible.Auth.TOTP do
After initiation, user is expected to confirm valid setup with `enable/2`,
providing TOTP code from their authenticator app. After code validation
passes successfully, the `User.totp_enabled` flag is set to `true`.
-
Finally, the user must be immediately presented with a list of recovery codes
- generated with `generate_recovery_codes/1`. The codes should be presented
+ returned by the same call of `enable/2`. The codes should be presented
in copy/paste friendly form, ideally also with a print-friendly view option.
- The function can be run more than once, giving the user ability to regenerate
- codes from the final stage of setup if needed.
The `initiate/1` and `enable/1` functions can be safely called multiple
times, allowing user to abort and restart setup up to these stages.
## Management
- State of TOTP for a particular user can be chcecked by calling `enabled?/1`.
+ The state of TOTP for a particular user can be chcecked by calling
+ `enabled?/1` or `initiated?/1`.
TOTP can be disabled with `disable/2`. User is expected to provide their
current password for safety. Once disabled, all TOTP user settings are
@@ -38,9 +36,9 @@ defmodule Plausible.Auth.TOTP do
can be safely run more than once.
If the user needs to regenerate the recovery codes outside of setup procedure,
- they must do it via `generate_recovery_codes_protected/2`, providing
- their current password for safety. They must be warned that any existing
- recovery codes will be invalidated.
+ they must do it via `generate_recovery_codes/2`, providing their current
+ password for safety. They must be warned that any existing recovery codes
+ will be invalidated.
## Validation
@@ -65,6 +63,18 @@ defmodule Plausible.Auth.TOTP do
In case of recovery codes, each code is deleted immediately after use.
They are strictly one-time use only.
+ ## TOTP Token
+
+ TOTP token is an alternate method of authenticating user session.
+ It's main use case is "trust this device" functionality, where user
+ can decide to skip 2FA verification for a particular browser session
+ for next N days. The token should then be stored in an encrypted,
+ signed cookie with a proper expiration timestamp.
+
+ The token should be reset each time it either fails to match
+ or when other credentials (like password) are reset. This should
+ effectively invalidate all trusted devices for a given user.
+
"""
import Ecto.Changeset, only: [change: 2]
@@ -106,14 +116,15 @@ defmodule Plausible.Auth.TOTP do
user
|> change(
totp_enabled: false,
- totp_secret: secret
+ totp_secret: secret,
+ totp_token: nil
)
|> Repo.update!()
{:ok, user, %{totp_uri: totp_uri(user), secret: readable_secret(user)}}
end
- @spec enable(Auth.User.t(), String.t(), Keyword.t()) ::
+ @spec enable(Auth.User.t(), String.t() | :skip_verify, Keyword.t()) ::
{:ok, Auth.User.t(), %{recovery_codes: [String.t()]}}
| {:error, :invalid_code | :not_initiated}
def enable(user, code, opts \\ [])
@@ -122,26 +133,37 @@ defmodule Plausible.Auth.TOTP do
{:error, :not_initiated}
end
+ def enable(user, :skip_verify, _opts) do
+ do_enable(user)
+ end
+
def enable(user, code, opts) do
with {:ok, user} <- do_validate_code(user, code, opts) do
- {:ok, {user, recovery_codes}} =
- Repo.transaction(fn ->
- user =
- user
- |> change(totp_enabled: true)
- |> Repo.update!()
+ do_enable(user)
+ end
+ end
+
+ defp do_enable(user) do
+ {:ok, {user, recovery_codes}} =
+ Repo.transaction(fn ->
+ user =
+ user
+ |> change(
+ totp_enabled: true,
+ totp_token: generate_token()
+ )
+ |> Repo.update!()
- {:ok, recovery_codes} = do_generate_recovery_codes(user)
+ {:ok, recovery_codes} = do_generate_recovery_codes(user)
- {user, recovery_codes}
- end)
+ {user, recovery_codes}
+ end)
- user
- |> Email.two_factor_enabled_email()
- |> Plausible.Mailer.send()
+ user
+ |> Email.two_factor_enabled_email()
+ |> Plausible.Mailer.send()
- {:ok, user, %{recovery_codes: recovery_codes}}
- end
+ {:ok, user, %{recovery_codes: recovery_codes}}
end
@spec disable(Auth.User.t(), String.t()) :: {:ok, Auth.User.t()} | {:error, :invalid_password}
@@ -157,6 +179,7 @@ defmodule Plausible.Auth.TOTP do
user
|> change(
totp_enabled: false,
+ totp_token: nil,
totp_secret: nil,
totp_last_used_at: nil
)
@@ -173,6 +196,18 @@ defmodule Plausible.Auth.TOTP do
end
end
+ @spec reset_token(Auth.User.t()) :: Auth.User.t()
+ def reset_token(user) do
+ new_token =
+ if user.totp_enabled do
+ generate_token()
+ end
+
+ user
+ |> change(totp_token: new_token)
+ |> Repo.update!()
+ end
+
@spec generate_recovery_codes(Auth.User.t(), String.t()) ::
{:ok, [String.t()]} | {:error, :invalid_password | :not_enabled}
def generate_recovery_codes(%{totp_enabled: false}) do
@@ -303,4 +338,10 @@ defmodule Plausible.Auth.TOTP do
|> change(totp_last_used_at: now)
|> Repo.update!()
end
+
+ defp generate_token() do
+ 20
+ |> :crypto.strong_rand_bytes()
+ |> Base.encode64(padding: false)
+ end
end
diff --git a/lib/plausible/auth/user.ex b/lib/plausible/auth/user.ex
index d34431dd2..b0ecc5b1a 100644
--- a/lib/plausible/auth/user.ex
+++ b/lib/plausible/auth/user.ex
@@ -38,6 +38,7 @@ defmodule Plausible.Auth.User do
# Fields for TOTP authentication. See `Plausible.Auth.TOTP`.
field :totp_enabled, :boolean, default: false
field :totp_secret, Plausible.Auth.TOTP.EncryptedBinary
+ field :totp_token, :string
field :totp_last_used_at, :naive_datetime
embeds_one :grace_period, Plausible.Auth.GracePeriod, on_replace: :update
diff --git a/lib/plausible_web/components/generic.ex b/lib/plausible_web/components/generic.ex
index ffeb3fcd8..e1b35f468 100644
--- a/lib/plausible_web/components/generic.ex
+++ b/lib/plausible_web/components/generic.ex
@@ -32,7 +32,7 @@ defmodule PlausibleWeb.Components.Generic do
type={@type}
disabled={@disabled}
class={[
- "inline-flex items-center justify-center gap-x-2 rounded-md bg-indigo-600 px-3.5 py-2.5 text-sm font-semibold text-white shadow-sm hover:bg-indigo-700 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-600 disabled:bg-gray-400",
+ "inline-flex items-center justify-center gap-x-2 rounded-md bg-indigo-600 px-3.5 py-2.5 text-sm font-semibold text-white shadow-sm hover:bg-indigo-700 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-600 disabled:bg-gray-400 dark:disabled:text-white dark:disabled:text-gray-400 dark:disabled:bg-gray-700",
@class
]}
{@rest}
@@ -53,7 +53,7 @@ defmodule PlausibleWeb.Components.Generic do
<.link
href={@href}
class={[
- "inline-flex items-center justify-center gap-x-2 rounded-md bg-indigo-600 px-3.5 py-2.5 text-sm font-semibold text-white shadow-sm hover:bg-indigo-700 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-600 disabled:bg-gray-400",
+ "inline-flex items-center justify-center gap-x-2 rounded-md bg-indigo-600 px-3.5 py-2.5 text-sm font-semibold text-white shadow-sm hover:bg-indigo-700 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-600 disabled:bg-gray-400 dark:disabled:bg-gray-800",
@class
]}
{@rest}
@@ -248,6 +248,28 @@ defmodule PlausibleWeb.Components.Generic do
end
end
+ attr :class, :any, default: ""
+
+ def spinner(assigns) do
+ ~H"""
+
+ """
+ end
+
defp icon_class(link_assigns) do
if String.contains?(link_assigns[:class], "text-sm") do
["w-3 h-3"]
diff --git a/lib/plausible_web/components/two_factor.ex b/lib/plausible_web/components/two_factor.ex
new file mode 100644
index 000000000..2233ddd5a
--- /dev/null
+++ b/lib/plausible_web/components/two_factor.ex
@@ -0,0 +1,155 @@
+defmodule PlausibleWeb.Components.TwoFactor do
+ @moduledoc """
+ Reusable components specific to 2FA
+ """
+ use Phoenix.Component
+
+ attr :text, :string, required: true
+ attr :scale, :integer, default: 4
+
+ def qr_code(assigns) do
+ qr_code =
+ assigns.text
+ |> EQRCode.encode()
+ |> EQRCode.svg(%{width: 160})
+
+ assigns = assign(assigns, :code, qr_code)
+
+ ~H"""
+ <%= Phoenix.HTML.raw(@code) %>
+ """
+ end
+
+ attr :id, :string, default: "verify-button"
+ attr :form, :any, required: true
+ attr :field, :any, required: true
+ attr :class, :string, default: ""
+
+ def verify_2fa_input(assigns) do
+ ~H"""
+
- <%= if @subscription && @subscription.status in [Plausible.Billing.Subscription.Status.active(), Plausible.Billing.Subscription.Status.past_due()] do %>
-
-
- <%= if @subscription && @subscription.next_bill_date && @subscription.status in [Plausible.Billing.Subscription.Status.active(), Plausible.Billing.Subscription.Status.past_due()] do %>
-
+ <%= if @subscription && @subscription.status in [Plausible.Billing.Subscription.Status.active(), Plausible.Billing.Subscription.Status.past_due()] do %>
+
- <%= case @invoices do %>
- <% {:error, :no_invoices} -> %>
- <% {:error, :request_failed} -> %>
-
-
Invoices
-
-
- Something went wrong
-
-
- <% {:ok, invoice_list} when is_list(invoice_list) -> %>
-
-
Invoices
-
-
-
-
-
- Date
-
-
- Amount
-
-
- Invoice
-
-
-
- <%= for invoice <- format_invoices(invoice_list) do %>
-
-
-
- <%= invoice.date %>
-
-
- <%= invoice.currency <> invoice.amount %>
-
-
- <%= link("Link", to: invoice.url, target: "_blank") %>
-
-
-
+ <%= if @subscription && @subscription.next_bill_date && @subscription.status in [Plausible.Billing.Subscription.Status.active(), Plausible.Billing.Subscription.Status.past_due()] do %>
+
- <%= button("Revoke",
- to: "/settings/api-keys/#{api_key.id}",
- class: "text-red-600 hover:text-red-900",
- method: :delete,
- "data-confirm":
- "Are you sure you want to revoke this key? This action cannot be reversed."
- ) %>
-
+
+
API Keys
+
+
+
+
+
+
+
+ <%= if Enum.any?(@user.api_keys) do %>
+
+
+
+
+
+ Name
+
+
+ Key
+
+
+ Revoke
+
- <% end %>
-
-
-
- <% end %>
+
+
+ <%= for api_key <- @user.api_keys do %>
+
+ <%= button("Revoke",
+ to: "/settings/api-keys/#{api_key.id}",
+ class: "text-red-600 hover:text-red-900",
+ method: :delete,
+ "data-confirm":
+ "Are you sure you want to revoke this key? This action cannot be reversed."
+ ) %>
+
+
+ <% end %>
+
+
+
+ <% end %>
-
- + New API Key
-
+
+ + New API Key
+
+
-
-
-
-
Delete account
+
+
+
Delete account
+
+
+
+
+
+ Deleting your account removes all sites and stats you've collected
+
+
+ <%= if @subscription && @subscription.status == Plausible.Billing.Subscription.Status.active() do %>
+
+ Delete my account
+
+
+ Your account cannot be deleted because you have an active subscription. If you want to delete your account, please cancel your subscription first.
+
+ <% else %>
+ <%= link("Delete my account",
+ to: "/me",
+ class:
+ "inline-block mt-4 px-4 py-2 border border-gray-300 dark:border-gray-500 text-sm leading-5 font-medium rounded-md text-red-700 bg-white dark:bg-gray-800 hover:text-red-500 dark:hover:text-red-400 focus:outline-none focus:border-blue-300 focus:ring active:text-red-800 active:bg-gray-50 transition ease-in-out duration-150",
+ method: "delete",
+ data: [
+ confirm:
+ "Deleting your account will also delete all the sites and data that you own. This action cannot be reversed. Are you sure?"
+ ]
+ ) %>
+ <% end %>
- Deleting your account removes all sites and stats you've collected
-
+
+ Once disabled, verification codes from the authenticator application and current recovery codes will become invalid. 2FA will have to be setup from the start.
+
- <%= if @subscription && @subscription.status == Plausible.Billing.Subscription.Status.active() do %>
-
- Delete my account
-
-
- Your account cannot be deleted because you have an active subscription. If you want to delete your account, please cancel your subscription first.
-
- <% else %>
- <%= link("Delete my account",
- to: "/me",
- class:
- "inline-block mt-4 px-4 py-2 border border-gray-300 dark:border-gray-500 text-sm leading-5 font-medium rounded-md text-red-700 bg-white dark:bg-gray-800 hover:text-red-500 dark:hover:text-red-400 focus:outline-none focus:border-blue-300 focus:ring active:text-red-800 active:bg-gray-50 transition ease-in-out duration-150",
- method: "delete",
- data: [
- confirm:
- "Deleting your account will also delete all the sites and data that you own. This action cannot be reversed. Are you sure?"
- ]
- ) %>
- <% end %>
+
+ Can't access your authenticator application?
+
+ Use recovery code
+
+ <%= if full_build?() do %>
+ Lost your recovery codes?
+
+ Contact us
+
+ <% end %>
+
+
+
+ <% end %>
+
diff --git a/lib/plausible_web/templates/auth/verify_2fa_recovery_code.html.heex b/lib/plausible_web/templates/auth/verify_2fa_recovery_code.html.heex
new file mode 100644
index 000000000..8c893acf5
--- /dev/null
+++ b/lib/plausible_web/templates/auth/verify_2fa_recovery_code.html.heex
@@ -0,0 +1,59 @@
+
diff --git a/lib/plausible_web/templates/auth/verify_2fa_setup.html.heex b/lib/plausible_web/templates/auth/verify_2fa_setup.html.heex
new file mode 100644
index 000000000..d091e48cd
--- /dev/null
+++ b/lib/plausible_web/templates/auth/verify_2fa_setup.html.heex
@@ -0,0 +1,38 @@
+
+
+
+ Setup Two-Factor Authentication
+
+
+
+ <%= form_for @conn.params, Routes.auth_path(@conn, :verify_2fa_setup), [
+ id: "verify-2fa-form",
+ onsubmit: "document.getElementById('verify-button').disabled = true"
+ ], fn f -> %>
+ Enter the code from your authenticator application before it expires or wait for a new one.
+
+ <% end %>
+
+