Admin panel, login throttling, and Cloudflare edge hardening (#150)

* Document the remote shell for production user management

* add sitemap to footer links

* remove border under theme selection

* Add admin theme and user management (#144)

Add /admin/themes CRUD and /admin/users list/detail with role and plan editing, guarded by a shared Policy module. Include last-super-admin and self-role protections plus structured id-only admin logs.

Also add admin invitations, confirmation resends and password-reset emails, which work in development through the Swoosh mailbox before SES is configured.

* Rate-limit password logins and emit auth events (#142)

Add a two-bucket login throttle (5 failures per login, 10 per IP in a 15-minute window) and a shared client-address helper for controllers and LiveViews. Blocked attempts skip the database and bcrypt.

Log auth.login.failed and auth.login.throttled warnings with boot-scoped HMAC addresses only, and stop repeated confirmation emails on unconfirmed login attempts.

* Harden the production login edge for Cloudflare

Document the layered login defence: the app throttle is primary, Caddy must pass Cloudflare's CF-Connecting-IP to the app, and Cloudflare edge rate limiting covers request floods.

Update the reference Caddyfile to accept only Cloudflare ranges and reject direct-to-origin traffic, and document the exact Cloudflare dashboard rules.

* Document 10-second Cloudflare rate-limit window

Cloudflare may only offer a 10-second period. Keep the edge rule at 10 login POSTs per 10 seconds per IP and rely on the app's 15-minute login/address throttle for credential guessing.

* Document Cloudflare limits for LiveView registration

Registration submits over the shared LiveView socket, so a Cloudflare rule on POST /users/register will not count account creations. Note the app-level throttle/Turnstile options instead.

* Document current Cloudflare free-plan edge controls

Record the production setup: Cloudflare-only Caddy origins, Bot Fight Mode, and the 10-second login flood rule (10 POSTs per 10 seconds, 10-second block). Clarify that the application's 15-minute throttle remains the real credential lockout.

* Auto-refresh Cloudflare CIDRs for Caddy

Move the origin allowlist into a generated cloudflare-ranges.caddy imported by Caddy. Add an hourly systemd timer and script that fetch Cloudflare's v4/v6 lists, reject malformed responses, validate the candidate Caddyfile, and reload Caddy only when the ranges change. Restore the previous file on validation or reload failure.

* Document Cloudflare CIDR refresher setup and operations

Record the installed paths, permissions, timer checks, manual run, update procedure, and the direct-on-VPS setup fallback when the deploy directory is absent.
This commit is contained in:
2026-11-11 21:27:59 +01:00
committed by GitHub
parent 202b9b1f6a
commit 624ddab644
45 changed files with 3602 additions and 70 deletions
@@ -0,0 +1,114 @@
defmodule ChesstrainerWeb.Admin.ThemeLive.Form do
use ChesstrainerWeb, :live_view
alias Chesstrainer.Accounts.Policy
alias Chesstrainer.Themes
alias Chesstrainer.Themes.Theme
@category_options [
{"Endgame", "endgame"},
{"Opening", "opening"},
{"Tactic", "tactic"}
]
@impl true
def render(assigns) do
~H"""
<Layouts.app flash={@flash}>
<Layouts.admin_nav current_scope={@current_scope} />
<.header>
{@page_title}
<:subtitle>
Themes group endgames for filtering. Names must be unique within a category,
ignoring case.
</:subtitle>
</.header>
<.form for={@form} id="theme-form" phx-change="validate" phx-submit="save">
<.input field={@form[:name]} type="text" label="Name" autocomplete="off" required />
<.input
field={@form[:category]}
type="select"
label="Category"
options={@category_options}
/>
<footer>
<.button phx-disable-with="Saving..." variant="primary">Save theme</.button>
<.button navigate={~p"/admin/themes"}>Cancel</.button>
</footer>
</.form>
</Layouts.app>
"""
end
@impl true
def mount(params, _session, socket) do
{:ok, apply_action(socket, socket.assigns.live_action, params)}
end
defp apply_action(socket, :new, _params) do
theme = %Theme{}
socket
|> assign(:page_title, "New theme")
|> assign(:theme, theme)
|> assign(:category_options, @category_options)
|> assign(:form, to_form(Themes.change_theme(theme)))
end
defp apply_action(socket, :edit, %{"id" => id}) do
theme = Themes.get_theme!(id)
socket
|> assign(:page_title, "Edit theme")
|> assign(:theme, theme)
|> assign(:category_options, @category_options)
|> assign(:form, to_form(Themes.change_theme(theme)))
end
@impl true
def handle_event("validate", %{"theme" => theme_params}, socket) do
changeset =
socket.assigns.theme
|> Themes.change_theme(theme_params)
|> Map.put(:action, :validate)
{:noreply, assign(socket, :form, to_form(changeset, action: :validate))}
end
def handle_event("save", %{"theme" => theme_params}, socket) do
if Policy.can?(socket.assigns.current_scope, :manage_themes) do
save_theme(socket, socket.assigns.live_action, theme_params)
else
{:noreply, put_flash(socket, :error, "You are not authorized to manage themes.")}
end
end
defp save_theme(socket, :new, theme_params) do
case Themes.create_theme(theme_params) do
{:ok, _theme} ->
{:noreply,
socket
|> put_flash(:info, "Theme created successfully.")
|> push_navigate(to: ~p"/admin/themes")}
{:error, %Ecto.Changeset{} = changeset} ->
{:noreply, assign(socket, :form, to_form(changeset, action: :insert))}
end
end
defp save_theme(socket, :edit, theme_params) do
case Themes.update_theme(socket.assigns.theme, theme_params) do
{:ok, _theme} ->
{:noreply,
socket
|> put_flash(:info, "Theme updated successfully.")
|> push_navigate(to: ~p"/admin/themes")}
{:error, %Ecto.Changeset{} = changeset} ->
{:noreply, assign(socket, :form, to_form(changeset, action: :insert))}
end
end
end
@@ -0,0 +1,160 @@
defmodule ChesstrainerWeb.Admin.ThemeLive.Index do
use ChesstrainerWeb, :live_view
alias Chesstrainer.Accounts.Policy
alias Chesstrainer.Themes
@category_options [
{"All categories", ""},
{"Endgame", "endgame"},
{"Opening", "opening"},
{"Tactic", "tactic"}
]
@impl true
def render(assigns) do
~H"""
<Layouts.app flash={@flash} wide>
<Layouts.admin_nav current_scope={@current_scope} />
<.header>
Themes
<:subtitle>
Themes group endgames for filtering and puzzle selection. Deleting a theme detaches
it from every endgame and leaves the endgames intact.
</:subtitle>
<:actions>
<.button variant="primary" navigate={~p"/admin/themes/new"}>
<.icon name="hero-plus" /> New theme
</.button>
</:actions>
</.header>
<.form
for={@filter_form}
id="theme-admin-filter-form"
phx-change="filter"
class="mb-6 flex flex-col gap-3 sm:flex-row sm:items-end"
>
<div class="flex-1 [&>div]:mb-0">
<.input
field={@filter_form[:search]}
type="text"
label="Search by name"
autocomplete="off"
phx-debounce="200"
placeholder="Theme name…"
/>
</div>
<div class="[&>div]:mb-0 sm:w-56">
<.input
field={@filter_form[:category]}
type="select"
label="Category"
options={@category_options}
/>
</div>
</.form>
<p :if={@themes == []} class="text-base-content/70">
<%= if @has_filters do %>
No themes match these filters.
<% else %>
No themes yet. Themes power endgame filtering and puzzle selection, so start by
creating one and attaching it to an endgame.
<% end %>
</p>
<table :if={@themes != []} class={table_class()}>
<thead>
<tr>
<th>Name</th>
<th>Category</th>
<th>Used by</th>
<th><span class="sr-only">Actions</span></th>
</tr>
</thead>
<tbody id="themes">
<tr :for={{theme, usage_count} <- @themes} id={"theme-#{theme.id}"}>
<td>{theme.name}</td>
<td>{theme.category}</td>
<td>
<span id={"theme-usage-#{theme.id}"}>{usage_label(usage_count)}</span>
</td>
<td class="w-0 font-semibold">
<div class="flex gap-4">
<.link navigate={~p"/admin/themes/#{theme.id}/edit"}>Edit</.link>
<.link
phx-click="delete"
phx-value-id={theme.id}
data-confirm={
"Delete #{theme.name}? Used by #{usage_label(usage_count)}. " <>
"The endgames will be kept and simply detached."
}
>
Delete
</.link>
</div>
</td>
</tr>
</tbody>
</table>
</Layouts.app>
"""
end
@impl true
def mount(_params, _session, socket) do
{:ok,
socket
|> assign(:page_title, "Themes")
|> assign(:search, "")
|> assign(:category, "")
|> assign(:has_filters, false)
|> assign(:category_options, @category_options)
|> assign(:filter_form, to_form(%{"search" => "", "category" => ""}))
|> load_themes()}
end
@impl true
def handle_event("filter", params, socket) do
search = Map.get(params, "search", socket.assigns.search)
category = Map.get(params, "category", socket.assigns.category)
{:noreply,
socket
|> assign(:search, search)
|> assign(:category, category)
|> assign(:has_filters, String.trim(search) != "" or category != "")
|> load_themes()}
end
def handle_event("delete", %{"id" => id}, socket) do
if Policy.can?(socket.assigns.current_scope, :manage_themes) do
theme = Themes.get_theme!(id)
{:ok, _theme} = Themes.delete_theme(theme)
socket =
socket
|> put_flash(:info, "Theme deleted. Attached endgames were kept.")
|> load_themes()
{:noreply, socket}
else
{:noreply, put_flash(socket, :error, "You are not authorized to manage themes.")}
end
end
defp load_themes(socket) do
themes =
Themes.list_themes_for_admin(
search: socket.assigns.search,
category: socket.assigns.category
)
assign(socket, :themes, themes)
end
defp usage_label(1), do: "1 endgame"
defp usage_label(count), do: "#{count} endgames"
end