Set up SES mail delivery and harden the mailing list (#120)

* setup basic SES email sending

* basic honeypot form form submission
This commit is contained in:
2026-11-09 16:38:55 +01:00
committed by GitHub
parent 5b3241ae1f
commit cae4e35a70
23 changed files with 731 additions and 64 deletions
+2
View File
@@ -7,6 +7,7 @@ defmodule Chesstrainer.Accounts do
alias Chesstrainer.Repo
alias Chesstrainer.Accounts.{User, UserToken, UserNotifier}
alias Chesstrainer.MailingList
## Database getters
@@ -207,6 +208,7 @@ defmodule Chesstrainer.Accounts do
with {:ok, query} <- UserToken.verify_change_email_token_query(token, context),
%UserToken{sent_to: email} <- Repo.one(query),
{:ok, user} <- Repo.update(User.email_changeset(user, %{email: email})),
{:ok, _subscription} <- MailingList.update_subscriber_email(user, email),
{_count, _result} <-
Repo.delete_all(from(UserToken, where: [user_id: ^user.id, context: ^context])) do
{:ok, user}
+1 -1
View File
@@ -9,7 +9,7 @@ defmodule Chesstrainer.Accounts.UserNotifier do
email =
new()
|> to(recipient)
|> from({Branding.name(), Branding.support_email()})
|> from({Branding.name(), Branding.mail_from()})
|> subject(subject)
|> text_body(body)
+8 -4
View File
@@ -8,10 +8,11 @@ defmodule Chesstrainer.Branding do
"""
@defaults [
name: "Lucid Chess",
wordmark: "LUCID",
name: "Inner Square Chess",
wordmark: "INNERSQUARE",
tagline: "Endgame Trainer",
support_email: "support@lucidchess.app"
support_email: "support@innersquare.app",
mail_from: "no-reply@innersquare.app"
]
@doc "The display name, e.g. `\"Lucid Chess\"`."
@@ -23,9 +24,12 @@ defmodule Chesstrainer.Branding do
@doc "The tagline appended to the home title, e.g. `\"Endgame Trainer\"`."
def tagline, do: get(:tagline)
@doc "The address shown in legal pages and used as the mailer `from`."
@doc "The support address shown in legal pages and used as the mailer reply-to."
def support_email, do: get(:support_email)
@doc "The From address used for outgoing mail."
def mail_from, do: get(:mail_from)
@doc "The home-page title, e.g. `\"Lucid Chess — Endgame Trainer\"`."
def home_title, do: "#{name()} — #{tagline()}"
+153 -14
View File
@@ -9,6 +9,9 @@ defmodule Chesstrainer.MailingList do
confirmed when the user's account is. A subscriber created from the landing
page has no user; one created from registration is linked to the user so
deleting the account also removes their address.
Unsubscribing sets `unsubscribed_at` instead of deleting the row, so the
address stays suppressed and is never emailed again unless it opts back in.
"""
import Ecto.Query, warn: false
@@ -17,6 +20,8 @@ defmodule Chesstrainer.MailingList do
alias Chesstrainer.MailingList.Subscriber
alias Chesstrainer.Repo
@confirmation_cooldown_seconds 10 * 60
@doc """
Requests a subscription from the landing-page form.
@@ -42,7 +47,8 @@ defmodule Chesstrainer.MailingList do
email = Ecto.Changeset.get_field(changeset, :email)
case Repo.get_by(Subscriber, email: email) do
%Subscriber{confirmed_at: confirmed_at} when not is_nil(confirmed_at) ->
%Subscriber{confirmed_at: confirmed_at, unsubscribed_at: nil}
when not is_nil(confirmed_at) ->
{:ok, :already_subscribed}
%Subscriber{} ->
@@ -75,20 +81,92 @@ defmodule Chesstrainer.MailingList do
@doc """
Confirms a subscription by email address.
Confirming also clears a previous unsubscribe, so an address that opted out
can rejoin only by going through a fresh confirmation.
Returns `{:error, :not_found}` when the address is not on the list.
"""
def confirm(email) when is_binary(email) do
case Repo.get_by(Subscriber, email: String.trim(email)) do
nil ->
{:error, :not_found}
nil -> {:error, :not_found}
%Subscriber{} = subscriber -> confirm_subscriber(subscriber)
end
end
%Subscriber{confirmed_at: nil} = subscriber ->
subscriber
|> Ecto.Changeset.change(confirmed_at: DateTime.utc_now(:second))
|> Repo.update()
@doc """
Unsubscribes an address from the mailing list.
The row is kept so the address remains suppressed. Idempotent.
"""
def unsubscribe(email) when is_binary(email) do
case Repo.get_by(Subscriber, email: String.trim(email)) do
nil -> {:error, :not_found}
%Subscriber{} = subscriber -> mark_unsubscribed(subscriber)
end
end
@doc """
Unsubscribes the address linked to the given user account.
"""
def unsubscribe_user(%User{} = user) do
case Repo.get_by(Subscriber, user_id: user.id) do
nil -> {:error, :not_found}
%Subscriber{} = subscriber -> mark_unsubscribed(subscriber)
end
end
@doc "Returns true when the user has an active mailing-list subscription."
def user_subscribed?(%User{} = user) do
Subscriber
|> where(
[s],
s.user_id == ^user.id and not is_nil(s.confirmed_at) and is_nil(s.unsubscribed_at)
)
|> Repo.exists?()
end
@doc """
Keeps a user's linked subscription in step with their account email.
Returns `{:ok, :no_subscription}` when the user was not on the list.
"""
def update_subscriber_email(%User{} = user, new_email) when is_binary(new_email) do
case Repo.get_by(Subscriber, user_id: user.id) do
nil ->
{:ok, :no_subscription}
%Subscriber{} = subscriber ->
{:ok, subscriber}
new_email = String.trim(new_email)
case Repo.get_by(Subscriber, email: new_email) do
# An anonymous row may already hold the new address. Remove it so the
# unique email constraint does not block the account email change,
# but keep its unsubscribe so moving an account email cannot opt an
# address back in.
%Subscriber{user_id: nil, unsubscribed_at: anonymous_unsubscribed_at} =
anonymous ->
Repo.delete!(anonymous)
changeset = Subscriber.changeset(subscriber, %{email: new_email})
changeset =
if anonymous_unsubscribed_at do
Ecto.Changeset.put_change(
changeset,
:unsubscribed_at,
subscriber.unsubscribed_at || anonymous_unsubscribed_at
)
else
changeset
end
Repo.update(changeset)
_other ->
subscriber
|> Subscriber.changeset(%{email: new_email})
|> Repo.update()
end
end
end
@@ -103,16 +181,71 @@ defmodule Chesstrainer.MailingList do
Subscriber
|> where([s], s.user_id == ^user.id and is_nil(s.confirmed_at))
|> Repo.update_all(set: [confirmed_at: now, updated_at: now])
|> Repo.update_all(set: [confirmed_at: now, unsubscribed_at: nil, updated_at: now])
end
@doc "Returns the number of confirmed addresses on the mailing list."
@doc "Returns the number of active addresses on the mailing list."
def count_confirmed_subscribers do
Subscriber
|> where([s], not is_nil(s.confirmed_at))
|> where([s], not is_nil(s.confirmed_at) and is_nil(s.unsubscribed_at))
|> Repo.aggregate(:count)
end
@doc """
Returns true when a confirmation email may be sent to this address.
Addresses without a subscriber row are allowed, as are addresses that have
not received a confirmation recently. This stops a repeated submission from
turning into an email flood.
"""
def confirmation_allowed?(email) when is_binary(email) do
case Repo.get_by(Subscriber, email: String.trim(email)) do
nil ->
true
%Subscriber{confirmation_sent_at: nil} ->
true
%Subscriber{confirmation_sent_at: sent_at} ->
DateTime.diff(DateTime.utc_now(:second), sent_at, :second) >=
@confirmation_cooldown_seconds
end
end
@doc "Records that a confirmation email was sent to this address."
def mark_confirmation_sent(email) when is_binary(email) do
case Repo.get_by(Subscriber, email: String.trim(email)) do
nil ->
:ok
%Subscriber{} = subscriber ->
subscriber
|> Ecto.Changeset.change(confirmation_sent_at: DateTime.utc_now(:second))
|> Repo.update()
end
end
defp confirm_subscriber(%Subscriber{} = subscriber) do
attrs =
if is_nil(subscriber.confirmed_at) do
%{confirmed_at: DateTime.utc_now(:second), unsubscribed_at: nil}
else
%{unsubscribed_at: nil}
end
subscriber
|> Ecto.Changeset.change(attrs)
|> Repo.update()
end
defp mark_unsubscribed(%Subscriber{unsubscribed_at: nil} = subscriber) do
subscriber
|> Ecto.Changeset.change(unsubscribed_at: DateTime.utc_now(:second))
|> Repo.update()
end
defp mark_unsubscribed(%Subscriber{} = subscriber), do: {:ok, subscriber}
defp insert_subscription(changeset, email) do
case Repo.insert(changeset) do
{:ok, _subscriber} ->
@@ -123,9 +256,15 @@ defmodule Chesstrainer.MailingList do
# above and this insert; the unique constraint decides, so re-read it.
if email_taken?(changeset) do
case Repo.get_by(Subscriber, email: email) do
%Subscriber{confirmed_at: nil} -> {:ok, :confirmation_required}
%Subscriber{} -> {:ok, :already_subscribed}
nil -> {:error, changeset}
%Subscriber{confirmed_at: confirmed_at, unsubscribed_at: nil}
when not is_nil(confirmed_at) ->
{:ok, :already_subscribed}
%Subscriber{} ->
{:ok, :confirmation_required}
nil ->
{:error, changeset}
end
else
{:error, changeset}
+2 -1
View File
@@ -33,7 +33,8 @@ defmodule Chesstrainer.MailingList.Notifier do
email =
new()
|> to(recipient)
|> from({Branding.name(), Branding.support_email()})
|> from({Branding.name(), Branding.mail_from()})
|> reply_to(Branding.support_email())
|> subject(subject)
|> text_body(body)
@@ -10,6 +10,8 @@ defmodule Chesstrainer.MailingList.Subscriber do
field :email, :string
field :source, Ecto.Enum, values: [:home, :registration], default: :home
field :confirmed_at, :utc_datetime
field :unsubscribed_at, :utc_datetime
field :confirmation_sent_at, :utc_datetime
belongs_to :user, User
timestamps(type: :utc_datetime)
@@ -13,6 +13,7 @@ defmodule ChesstrainerWeb.LandingComponents do
alias Chesstrainer.FEN
alias Chesstrainer.Themes
alias ChesstrainerWeb.Board.PositionText
alias ChesstrainerWeb.MailingListFormToken
@button_variants %{
nav: "nav-cta",
@@ -93,6 +94,19 @@ defmodule ChesstrainerWeb.LandingComponents do
<form action="/mailing-list" method="post" id="mailing-list-form" class="mailing-list-form">
<input type="hidden" name="_csrf_token" value={get_csrf_token()} />
<input type="hidden" name="subscriber[form_token]" value={MailingListFormToken.sign()} />
<div class="mailing-list-honeypot" aria-hidden="true">
<label for="mailing-list-company">Company</label>
<input
id="mailing-list-company"
type="text"
name="subscriber[company]"
tabindex="-1"
autocomplete="off"
/>
</div>
<label for="mailing-list-email">Email address</label>
<div class="mailing-list-row">
<input
@@ -3,45 +3,31 @@ defmodule ChesstrainerWeb.MailingListController do
alias Chesstrainer.MailingList
alias Chesstrainer.MailingList.Notifier
alias ChesstrainerWeb.MailingListFormToken
@return_to "/#mailing-list"
@token_salt "mailing_list_confirm"
@token_max_age 7 * 24 * 60 * 60
def create(conn, %{"subscriber" => %{"email" => email}}) when is_binary(email) do
email = String.trim(email)
def create(conn, %{"subscriber" => params}) when is_map(params) do
email = params["email"]
case MailingList.subscribe(email) do
{:ok, :already_subscribed} ->
conn
|> put_flash(:info, "You're already on the mailing list.")
|> redirect(to: @return_to)
cond do
honeypot_filled?(params) ->
fake_success(conn)
{:ok, :confirmation_required} ->
case send_confirmation(email) do
:ok ->
conn
|> put_flash(:info, "Check your inbox to confirm your subscription.")
|> redirect(to: @return_to)
not is_binary(email) ->
invalid_email(conn)
:error ->
conn
|> put_flash(:error, "We couldn't send the confirmation email. Please try again.")
|> redirect(to: @return_to)
end
MailingListFormToken.verify(params["form_token"]) != :ok ->
form_error(conn)
{:error, %Ecto.Changeset{}} ->
conn
|> put_flash(:error, "Enter a valid email address.")
|> redirect(to: @return_to)
true ->
subscribe(conn, email)
end
end
def create(conn, _params) do
conn
|> put_flash(:error, "Enter a valid email address.")
|> redirect(to: @return_to)
end
def create(conn, _params), do: invalid_email(conn)
def confirm(conn, %{"token" => token}) do
case Phoenix.Token.verify(
@@ -77,13 +63,63 @@ defmodule ChesstrainerWeb.MailingListController do
end
end
defp send_confirmation(email) do
defp subscribe(conn, email) do
email = String.trim(email)
case MailingList.subscribe(email) do
{:ok, :already_subscribed} ->
conn
|> put_flash(:info, "You're already on the mailing list.")
|> redirect(to: @return_to)
{:ok, :confirmation_required} ->
if MailingList.confirmation_allowed?(email) do
send_confirmation(conn, email)
else
fake_success(conn)
end
{:error, %Ecto.Changeset{}} ->
invalid_email(conn)
end
end
defp send_confirmation(conn, email) do
token = Phoenix.Token.sign(ChesstrainerWeb.Endpoint, @token_salt, email)
url = url(~p"/mailing-list/confirm/#{token}")
case Notifier.deliver_confirmation_instructions(email, url) do
{:ok, _email} -> :ok
{:error, _reason} -> :error
{:ok, _email} ->
_ = MailingList.mark_confirmation_sent(email)
conn
|> put_flash(:info, "Check your inbox to confirm your subscription.")
|> redirect(to: @return_to)
{:error, _reason} ->
conn
|> put_flash(:error, "We couldn't send the confirmation email. Please try again.")
|> redirect(to: @return_to)
end
end
defp honeypot_filled?(params), do: params["company"] not in [nil, ""]
defp fake_success(conn) do
conn
|> put_flash(:info, "Check your inbox to confirm your subscription.")
|> redirect(to: @return_to)
end
defp form_error(conn) do
conn
|> put_flash(:error, "Please refresh the page and try again.")
|> redirect(to: @return_to)
end
defp invalid_email(conn) do
conn
|> put_flash(:error, "Enter a valid email address.")
|> redirect(to: @return_to)
end
end
@@ -4,6 +4,7 @@ defmodule ChesstrainerWeb.UserLive.Profile do
alias Chesstrainer.Accounts
alias Chesstrainer.Accounts.Scope
alias Chesstrainer.Attempts
alias Chesstrainer.MailingList
@recent_attempts 25
@@ -159,6 +160,27 @@ defmodule ChesstrainerWeb.UserLive.Profile do
</p>
</section>
<section id="mailing-list-settings" class="space-y-3 rounded-lg border border-base-300 p-4">
<h2 class="settings-header">Mailing list</h2>
<p :if={@mailing_list_subscribed?} class="settings-subtitle">
You're subscribed to occasional endgame tips and site news.
</p>
<p :if={!@mailing_list_subscribed?} class="settings-subtitle">
You're not subscribed to the mailing list.
</p>
<.button
:if={@mailing_list_subscribed?}
id="unsubscribe-mailing-list"
variant="secondary"
phx-click="unsubscribe_mailing_list"
>
Unsubscribe
</.button>
</section>
<p id="settings-empty-state" class="text-sm text-base-content/60">
More site settings will appear here as they become available.
</p>
@@ -332,6 +354,24 @@ defmodule ChesstrainerWeb.UserLive.Profile do
end
end
def handle_event("unsubscribe_mailing_list", _params, socket) do
user = socket.assigns.current_scope.user
case MailingList.unsubscribe_user(user) do
{:ok, _subscriber} ->
{:noreply,
socket
|> assign(:mailing_list_subscribed?, false)
|> put_flash(:info, "You've been removed from the mailing list.")}
{:error, :not_found} ->
{:noreply,
socket
|> assign(:mailing_list_subscribed?, false)
|> put_flash(:info, "You're not on the mailing list.")}
end
end
def handle_event("delete_account", _params, socket) do
user = socket.assigns.current_scope.user
true = Accounts.sudo_mode?(user)
@@ -348,10 +388,16 @@ defmodule ChesstrainerWeb.UserLive.Profile do
case socket.assigns.live_action do
:account -> assign_account(socket)
:data -> assign_data(socket)
:settings -> assign_settings(socket)
_ -> socket
end
end
defp assign_settings(socket) do
user = socket.assigns.current_scope.user
assign(socket, :mailing_list_subscribed?, MailingList.user_subscribed?(user))
end
defp assign_account(socket) do
user = socket.assigns.current_scope.user
email_changeset = Accounts.change_user_email(user, %{}, validate_unique: false)
@@ -0,0 +1,38 @@
defmodule ChesstrainerWeb.MailingListFormToken do
@moduledoc """
Signed timestamp hidden in the mailing-list signup form.
Used as a timing check: submissions that arrive faster than a human could
plausibly fill the form are rejected. The timestamp is signed so a bot
cannot simply make one up.
"""
@salt "mailing_list_form"
@max_age 2 * 60 * 60
@min_seconds 2
@type verify_result :: :ok | :too_fast | :expired | :invalid
@doc "Signs the current time for the hidden form field."
def sign, do: sign(System.system_time(:second))
@doc false
def sign(signed_at) when is_integer(signed_at) do
Phoenix.Token.sign(ChesstrainerWeb.Endpoint, @salt, signed_at, signed_at: signed_at)
end
@doc "Checks a submitted form token."
@spec verify(term()) :: verify_result()
def verify(token) when is_binary(token) do
now = System.system_time(:second)
case Phoenix.Token.verify(ChesstrainerWeb.Endpoint, @salt, token, max_age: @max_age) do
{:ok, signed_at} when is_integer(signed_at) and now - signed_at >= @min_seconds -> :ok
{:ok, _signed_at} -> :too_fast
{:error, :expired} -> :expired
{:error, _reason} -> :invalid
end
end
def verify(_token), do: :invalid
end