mirror of
https://github.com/TheRealOwenRees/chess-endgame-trainer.git
synced 2026-11-18 03:32:06 +00:00
Feature/guest trainer (#89)
* add anonymous guest training with a daily puzzle limit - /guest-train serves random endgames with no difficulty picker; signed-in visitors are redirected to /train - guests get 5 puzzles per UTC day, keyed by an in-memory HMAC of the client address; the raw address is never stored or logged - a sign-up wall replaces the next puzzle once the budget is spent - move the endgame library behind auth so guests cannot browse it - privacy disclosure tracked in #87 * remove chess-test endpoint and liveview
This commit is contained in:
@@ -16,6 +16,7 @@ defmodule Chesstrainer.Application do
|
||||
{Phoenix.PubSub, name: Chesstrainer.PubSub},
|
||||
# Start a worker by calling: Chesstrainer.Worker.start_link(arg)
|
||||
# {Chesstrainer.Worker, arg},
|
||||
Chesstrainer.GuestLimits,
|
||||
# Start to serve requests, typically the last entry
|
||||
ChesstrainerWeb.Endpoint,
|
||||
{Registry, keys: :unique, name: Chesstrainer.CacheRegistry},
|
||||
|
||||
@@ -23,11 +23,23 @@ defmodule Chesstrainer.Endgames do
|
||||
|
||||
@doc """
|
||||
Returns a random endgame, or `nil` when none exist.
|
||||
|
||||
`:exclude_ids` (default `[]`) skips endgames by id — used to avoid repeating
|
||||
the puzzle just played.
|
||||
"""
|
||||
def random_endgame do
|
||||
Repo.one(from e in Endgame, order_by: fragment("RANDOM()"), limit: 1)
|
||||
def random_endgame(opts \\ []) do
|
||||
exclude_ids = Keyword.get(opts, :exclude_ids, [])
|
||||
|
||||
Endgame
|
||||
|> skip_ids(exclude_ids)
|
||||
|> order_by([e], fragment("RANDOM()"))
|
||||
|> limit(1)
|
||||
|> Repo.one()
|
||||
end
|
||||
|
||||
defp skip_ids(query, []), do: query
|
||||
defp skip_ids(query, ids), do: where(query, [e], e.id not in ^ids)
|
||||
|
||||
@doc """
|
||||
Returns the number of stored endgames, each of which is played as a puzzle.
|
||||
"""
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
defmodule Chesstrainer.GuestLimits do
|
||||
@moduledoc """
|
||||
Daily puzzle budget for anonymous visitors.
|
||||
|
||||
Each visitor gets a fixed number of puzzles per UTC day. Visitors are
|
||||
identified by an HMAC of their client address — the address itself is never
|
||||
stored, logged, or persisted. The digest lives only in ETS, is scoped to the
|
||||
current UTC date, and is swept away when the day rolls over. The HMAC secret
|
||||
is generated at boot, so digests are not stable across restarts.
|
||||
|
||||
Budgets reset for everyone at 00:00 UTC: the date is part of the key, so a
|
||||
new day simply starts a new entry.
|
||||
"""
|
||||
|
||||
use GenServer
|
||||
|
||||
@table :guest_limits
|
||||
@default_limit 5
|
||||
@sweep_interval :timer.minutes(10)
|
||||
|
||||
@typedoc "An IPv4/IPv6 address, or `nil` when the socket has no peer data."
|
||||
@type address :: :inet.ip_address() | nil
|
||||
|
||||
@doc "Starts the limiter."
|
||||
def start_link(opts \\ []), do: GenServer.start_link(__MODULE__, opts, name: __MODULE__)
|
||||
|
||||
@doc """
|
||||
Consumes one puzzle from `address`'s budget for `today`.
|
||||
|
||||
Returns `{:ok, remaining}` with the puzzles left today, or
|
||||
`{:limit_reached, retry_in_ms}` when the budget is spent. A `nil` address is
|
||||
not limited and returns `{:ok, nil}`.
|
||||
"""
|
||||
@spec take(address, Date.t()) ::
|
||||
{:ok, non_neg_integer | nil} | {:limit_reached, non_neg_integer}
|
||||
def take(address, today \\ Date.utc_today()) do
|
||||
GenServer.call(__MODULE__, {:take, address, today})
|
||||
end
|
||||
|
||||
@doc "Clears every budget. Intended for tests."
|
||||
def reset, do: GenServer.call(__MODULE__, :reset)
|
||||
|
||||
@doc "The daily puzzle allowance for a guest."
|
||||
def limit, do: config() |> Keyword.get(:limit, @default_limit)
|
||||
|
||||
@doc """
|
||||
Whether to read the client address from `X-Forwarded-For`.
|
||||
|
||||
Enable only behind a proxy that overwrites or appends the header.
|
||||
"""
|
||||
def trust_forwarded_for?, do: config() |> Keyword.get(:trust_forwarded_for, false)
|
||||
|
||||
defp config, do: Application.get_env(:chesstrainer, __MODULE__, [])
|
||||
|
||||
@impl true
|
||||
def init(opts) do
|
||||
:ets.new(@table, [:named_table, :set])
|
||||
Process.send_after(self(), :sweep, @sweep_interval)
|
||||
|
||||
{:ok,
|
||||
%{
|
||||
limit: Keyword.get(opts, :limit, limit()),
|
||||
secret: :crypto.strong_rand_bytes(32)
|
||||
}}
|
||||
end
|
||||
|
||||
@impl true
|
||||
def handle_call({:take, nil, _today}, _from, state), do: {:reply, {:ok, nil}, state}
|
||||
|
||||
def handle_call({:take, address, today}, _from, state) do
|
||||
day = Date.to_gregorian_days(today)
|
||||
key = key(state.secret, day, address)
|
||||
|
||||
case count(key, day) do
|
||||
used when used >= state.limit ->
|
||||
{:reply, {:limit_reached, ms_until_utc_midnight()}, state}
|
||||
|
||||
used ->
|
||||
:ets.insert(@table, {key, day, used + 1})
|
||||
{:reply, {:ok, state.limit - used - 1}, state}
|
||||
end
|
||||
end
|
||||
|
||||
def handle_call(:reset, _from, state) do
|
||||
:ets.delete_all_objects(@table)
|
||||
{:reply, :ok, state}
|
||||
end
|
||||
|
||||
@impl true
|
||||
def handle_info(:sweep, state) do
|
||||
sweep(Date.to_gregorian_days(Date.utc_today()))
|
||||
Process.send_after(self(), :sweep, @sweep_interval)
|
||||
{:noreply, state}
|
||||
end
|
||||
|
||||
defp count(key, day) do
|
||||
case :ets.lookup(@table, key) do
|
||||
[{^key, ^day, used}] -> used
|
||||
_ -> 0
|
||||
end
|
||||
end
|
||||
|
||||
defp key(secret, day, address) do
|
||||
:crypto.mac(:hmac, :sha256, secret, [Integer.to_string(day), "|", address_binary(address)])
|
||||
end
|
||||
|
||||
defp address_binary(address) when is_tuple(address), do: :erlang.term_to_binary(address)
|
||||
|
||||
defp sweep(day) do
|
||||
:ets.select_delete(@table, [{{:_, :"$1", :_}, [{:<, :"$1", day}], [true]}])
|
||||
end
|
||||
|
||||
defp ms_until_utc_midnight do
|
||||
now = DateTime.utc_now()
|
||||
midnight = now |> DateTime.to_date() |> Date.add(1) |> DateTime.new!(~T[00:00:00], "Etc/UTC")
|
||||
|
||||
max(DateTime.diff(midnight, now, :millisecond), 0)
|
||||
end
|
||||
end
|
||||
@@ -151,7 +151,7 @@ defmodule ChesstrainerWeb.Layouts do
|
||||
|
||||
# Signed-in users start a puzzle session; visitors browse the public list.
|
||||
defp start_href(%{user: %{}}), do: ~p"/train"
|
||||
defp start_href(_scope), do: ~p"/endgames"
|
||||
defp start_href(_scope), do: ~p"/guest-train"
|
||||
|
||||
@doc """
|
||||
Renders the site-wide footer.
|
||||
|
||||
@@ -12,8 +12,8 @@ defmodule ChesstrainerWeb.Endpoint do
|
||||
]
|
||||
|
||||
socket "/live", Phoenix.LiveView.Socket,
|
||||
websocket: [connect_info: [session: @session_options]],
|
||||
longpoll: [connect_info: [session: @session_options]]
|
||||
websocket: [connect_info: [:peer_data, :x_headers, session: @session_options]],
|
||||
longpoll: [connect_info: [:peer_data, :x_headers, session: @session_options]]
|
||||
|
||||
# Serve at "/" the static files from "priv/static" directory.
|
||||
#
|
||||
|
||||
@@ -1,87 +0,0 @@
|
||||
defmodule ChesstrainerWeb.ChessTestLive do
|
||||
use ChesstrainerWeb, :live_view
|
||||
|
||||
@impl true
|
||||
def mount(_params, _session, socket) do
|
||||
{:ok, assign(socket, last_move: "None yet", san: "None yet", move_list: [])}
|
||||
end
|
||||
|
||||
@impl true
|
||||
def render(assigns) do
|
||||
~H"""
|
||||
<div class="mx-auto max-w-2xl p-6">
|
||||
<h1 class="text-2xl font-bold mb-4">Chessground LiveView Test</h1>
|
||||
|
||||
<form phx-submit="load_fen" class="mb-6 flex gap-2 bg-gray-50 p-4 rounded-lg shadow-sm">
|
||||
<div class="flex-1">
|
||||
<input
|
||||
type="text"
|
||||
name="fen"
|
||||
placeholder="Paste FEN string here (e.g., rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1)"
|
||||
class="w-full px-3 py-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 font-mono text-sm"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<button
|
||||
type="submit"
|
||||
class="px-4 py-2 bg-blue-600 text-white font-medium rounded-md hover:bg-blue-700 transition"
|
||||
>
|
||||
Load FEN
|
||||
</button>
|
||||
</form>
|
||||
|
||||
<div class="bg-gray-100 p-4 rounded mb-4 flex justify-between items-center shadow-sm">
|
||||
<div>
|
||||
<p class="text-sm text-gray-600 font-semibold">Last Played Move:</p>
|
||||
<p class="text-lg font-mono text-blue-600">{@last_move}</p>
|
||||
<p class="text-lg font-mono text-blue-600">{@san}</p>
|
||||
<p class="text-lg font-mono text-emerald-600">
|
||||
{if length(@move_list) == 0 do
|
||||
"No Moves"
|
||||
else
|
||||
Enum.reverse(@move_list) |> Enum.join(", ")
|
||||
end}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="flex justify-center bg-gray-200 p-4 rounded-xl shadow-inner">
|
||||
<div
|
||||
id="chessground-board"
|
||||
phx-hook="ChessBoard"
|
||||
phx-update="ignore"
|
||||
class="w-[400px] h-[400px]"
|
||||
>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
"""
|
||||
end
|
||||
|
||||
@impl true
|
||||
def handle_event("load_fen", %{"fen" => fen}, socket) do
|
||||
clean_fen = String.trim(fen)
|
||||
|
||||
{:noreply,
|
||||
socket
|
||||
|> assign(:last_move, "Position Loaded")
|
||||
|> assign(:san, "None yet")
|
||||
|> assign(:move_list, [])
|
||||
|> push_event("set_fen", %{fen: clean_fen})}
|
||||
end
|
||||
|
||||
@impl true
|
||||
def handle_event(
|
||||
"move_played",
|
||||
%{"from" => from, "to" => to, "fen" => _fen, "san" => san},
|
||||
socket
|
||||
) do
|
||||
current_moves = socket.assigns.move_list
|
||||
|
||||
{:noreply,
|
||||
socket
|
||||
|> assign(:last_move, "#{from} ➔ #{to}")
|
||||
|> assign(:san, san)
|
||||
|> assign(:move_list, [san | current_moves])}
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,266 @@
|
||||
defmodule ChesstrainerWeb.EndgameLive.GuestTrain do
|
||||
@moduledoc """
|
||||
Public training: play random endgame puzzles without an account.
|
||||
|
||||
There is no difficulty selection and no session — each puzzle is drawn from
|
||||
the whole pool and "Next puzzle" draws another. Anonymous visitors get a
|
||||
daily budget of puzzles (see `Chesstrainer.GuestLimits`); when it runs out the
|
||||
page asks them to sign up. Signed-in visitors are sent to `/train`, where they
|
||||
can pick a difficulty. Move grading, opponent replies and review come from
|
||||
`ChesstrainerWeb.EndgameLive.PlayCore`.
|
||||
"""
|
||||
|
||||
use ChesstrainerWeb, :live_view
|
||||
|
||||
alias Chesstrainer.Endgames
|
||||
alias Chesstrainer.GuestLimits
|
||||
alias ChesstrainerWeb.EndgameLive.PlayCore
|
||||
alias ChesstrainerWeb.PlayComponents
|
||||
|
||||
@impl true
|
||||
def render(assigns) do
|
||||
~H"""
|
||||
<Layouts.app flash={@flash}>
|
||||
<.header>
|
||||
Train
|
||||
<:subtitle>
|
||||
<%= if @endgame do %>
|
||||
A random endgame puzzle — {@endgame.color
|
||||
|> Atom.to_string()
|
||||
|> String.capitalize()} to move, rating {round(@endgame.rating)}.
|
||||
<% else %>
|
||||
Random endgame puzzles.
|
||||
<% end %>
|
||||
<span
|
||||
:if={@guest_remaining != nil}
|
||||
id="guest-remaining"
|
||||
class="mt-1 block text-xs text-muted"
|
||||
>
|
||||
{remaining_label(@guest_remaining, @limit)}
|
||||
</span>
|
||||
<span class="mt-1 block text-xs text-muted">
|
||||
<.link navigate={~p"/users/register"}>Create a free account</.link>
|
||||
to track your rating and train at your level.
|
||||
</span>
|
||||
</:subtitle>
|
||||
</.header>
|
||||
|
||||
<section
|
||||
:if={@limit_reached}
|
||||
id="guest-limit"
|
||||
class="rounded-xl border border-hairline bg-canvas-raised p-6"
|
||||
>
|
||||
<h2 class="text-lg font-semibold">
|
||||
You've used your {@limit} free puzzles today
|
||||
</h2>
|
||||
<p class="mt-1 text-sm text-muted">
|
||||
Sign up for a free account to keep training. Your rating is tracked, so
|
||||
the puzzles match your level.
|
||||
</p>
|
||||
<p class="mt-1 text-sm text-muted">
|
||||
Free guest puzzles reset at 00:00 UTC (in {format_wait(@limit_reached)}).
|
||||
</p>
|
||||
<div class="mt-4 flex flex-wrap gap-2">
|
||||
<.button id="guest-sign-up" navigate={~p"/users/register"} variant="primary">
|
||||
<.icon name="hero-user-plus" /> Sign up free
|
||||
</.button>
|
||||
<.button navigate={~p"/users/log-in"}>Log in</.button>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<PlayComponents.play_surface
|
||||
:if={@endgame}
|
||||
session={is_nil(@limit_reached)}
|
||||
endgame={@endgame}
|
||||
status={@status}
|
||||
blocked_reason={@blocked_reason}
|
||||
best_move={@best_move}
|
||||
plies={@plies}
|
||||
line={@line}
|
||||
reviewing={@reviewing}
|
||||
review_index={@review_index}
|
||||
review_tablebase={@review_tablebase}
|
||||
review_blocked={@review_blocked}
|
||||
awaiting_reply={@awaiting_reply}
|
||||
last_grade={@last_grade}
|
||||
awaiting_best_line={@awaiting_best_line}
|
||||
/>
|
||||
|
||||
<p :if={@loading} class="text-base-content/70">Picking a random puzzle…</p>
|
||||
|
||||
<p
|
||||
:if={not @loading and is_nil(@endgame) and is_nil(@limit_reached)}
|
||||
class="text-base-content/70"
|
||||
>
|
||||
No endgames are available yet. Please check back soon.
|
||||
</p>
|
||||
</Layouts.app>
|
||||
"""
|
||||
end
|
||||
|
||||
@impl true
|
||||
def mount(_params, _session, socket) do
|
||||
socket = assign(socket, :limit, GuestLimits.limit())
|
||||
|
||||
cond do
|
||||
signed_in?(socket) ->
|
||||
{:ok, redirect(socket, to: ~p"/train")}
|
||||
|
||||
connected?(socket) ->
|
||||
take_puzzle(socket, client_address(socket))
|
||||
|
||||
true ->
|
||||
{:ok,
|
||||
socket
|
||||
|> assign(:loading, true)
|
||||
|> assign(:endgame, nil)
|
||||
|> assign(:guest_remaining, nil)
|
||||
|> assign(:limit_reached, nil)
|
||||
|> assign(:guest_address, nil)}
|
||||
end
|
||||
end
|
||||
|
||||
@impl true
|
||||
def handle_event("next_puzzle", _params, socket) do
|
||||
case GuestLimits.take(socket.assigns.guest_address) do
|
||||
{:ok, remaining} ->
|
||||
endgame =
|
||||
Endgames.random_endgame(exclude_ids: [socket.assigns.endgame.id]) ||
|
||||
Endgames.random_endgame()
|
||||
|
||||
case endgame do
|
||||
nil ->
|
||||
{:noreply, put_flash(socket, :info, "No more puzzles are available right now.")}
|
||||
|
||||
endgame ->
|
||||
{:noreply,
|
||||
socket
|
||||
|> assign(:guest_remaining, remaining)
|
||||
|> PlayCore.init(endgame, page_title: "Train")}
|
||||
end
|
||||
|
||||
{:limit_reached, retry_ms} ->
|
||||
{:noreply,
|
||||
socket
|
||||
|> assign(:guest_remaining, nil)
|
||||
|> assign(:limit_reached, retry_ms)}
|
||||
end
|
||||
end
|
||||
|
||||
def handle_event("endgame_move_played", params, socket),
|
||||
do: PlayCore.move_played(socket, params)
|
||||
|
||||
def handle_event("opponent_reply_applied", params, socket),
|
||||
do: PlayCore.opponent_reply_applied(socket, params)
|
||||
|
||||
def handle_event("chess_fen_invalid", params, socket),
|
||||
do: PlayCore.fen_invalid(socket, params)
|
||||
|
||||
def handle_event("reset", _params, socket), do: PlayCore.reset(socket)
|
||||
|
||||
def handle_event("review", _params, socket), do: PlayCore.review(socket)
|
||||
|
||||
def handle_event("review_prev", _params, socket), do: PlayCore.review_prev(socket)
|
||||
|
||||
def handle_event("review_next", _params, socket), do: PlayCore.review_next(socket)
|
||||
|
||||
def handle_event("review_step", %{"index" => index}, socket),
|
||||
do: PlayCore.review_step(socket, index)
|
||||
|
||||
def handle_event("play_best_line", _params, socket), do: PlayCore.play_best_line(socket)
|
||||
|
||||
def handle_event("best_line_move_applied", params, socket),
|
||||
do: PlayCore.best_line_move_applied(socket, params)
|
||||
|
||||
def handle_event("back_to_game", _params, socket), do: PlayCore.back_to_game(socket)
|
||||
|
||||
defp take_puzzle(socket, address) do
|
||||
case GuestLimits.take(address) do
|
||||
{:ok, remaining} ->
|
||||
socket =
|
||||
socket
|
||||
|> assign(:loading, false)
|
||||
|> assign(:guest_address, address)
|
||||
|> assign(:guest_remaining, remaining)
|
||||
|> assign(:limit_reached, nil)
|
||||
|
||||
{:ok, load_random_endgame(socket)}
|
||||
|
||||
{:limit_reached, retry_ms} ->
|
||||
{:ok,
|
||||
socket
|
||||
|> assign(:loading, false)
|
||||
|> assign(:guest_address, address)
|
||||
|> assign(:guest_remaining, nil)
|
||||
|> assign(:limit_reached, retry_ms)
|
||||
|> assign(:endgame, nil)}
|
||||
end
|
||||
end
|
||||
|
||||
defp load_random_endgame(socket) do
|
||||
case Endgames.random_endgame() do
|
||||
nil -> assign(socket, :endgame, nil)
|
||||
endgame -> PlayCore.init(socket, endgame, page_title: "Train")
|
||||
end
|
||||
end
|
||||
|
||||
defp client_address(socket) do
|
||||
if GuestLimits.trust_forwarded_for?() do
|
||||
forwarded_address(socket) || peer_address(socket)
|
||||
else
|
||||
peer_address(socket)
|
||||
end
|
||||
end
|
||||
|
||||
defp peer_address(socket) do
|
||||
case get_connect_info(socket, :peer_data) do
|
||||
%{address: address} -> address
|
||||
_ -> nil
|
||||
end
|
||||
end
|
||||
|
||||
defp forwarded_address(socket) do
|
||||
with headers when is_list(headers) <- get_connect_info(socket, :x_headers),
|
||||
{_, value} <- List.keyfind(headers, "x-forwarded-for", 0),
|
||||
address when address != nil <- parse_address(value) do
|
||||
address
|
||||
else
|
||||
_ -> nil
|
||||
end
|
||||
end
|
||||
|
||||
# The rightmost entry is the one our own proxy appended.
|
||||
defp parse_address(value) do
|
||||
value
|
||||
|> String.split(",")
|
||||
|> List.last()
|
||||
|> to_string()
|
||||
|> String.trim()
|
||||
|> String.to_charlist()
|
||||
|> :inet.parse_address()
|
||||
|> case do
|
||||
{:ok, address} -> address
|
||||
{:error, _} -> nil
|
||||
end
|
||||
end
|
||||
|
||||
defp signed_in?(socket) do
|
||||
case socket.assigns.current_scope do
|
||||
%{user: %{}} -> true
|
||||
_ -> false
|
||||
end
|
||||
end
|
||||
|
||||
defp remaining_label(0, _limit), do: "Last free puzzle today"
|
||||
|
||||
defp remaining_label(remaining, limit),
|
||||
do: "#{remaining} of #{limit} free puzzles left today"
|
||||
|
||||
defp format_wait(ms) when is_integer(ms) do
|
||||
minutes = max(div(ms + 59_999, 60_000), 1)
|
||||
hours = div(minutes, 60)
|
||||
mins = rem(minutes, 60)
|
||||
|
||||
if hours > 0, do: "#{hours}h #{mins}m", else: "#{mins}m"
|
||||
end
|
||||
end
|
||||
@@ -21,10 +21,6 @@ defmodule ChesstrainerWeb.Router do
|
||||
pipe_through :browser
|
||||
|
||||
get "/", PageController, :home
|
||||
|
||||
live "/chess-test", ChessTestLive
|
||||
|
||||
live "/endgames", EndgameLive.PlayerIndex, :index
|
||||
end
|
||||
|
||||
scope "/admin", ChesstrainerWeb do
|
||||
@@ -68,6 +64,7 @@ defmodule ChesstrainerWeb.Router do
|
||||
|
||||
live_session :require_authenticated_user,
|
||||
on_mount: [{ChesstrainerWeb.UserAuth, :require_authenticated}] do
|
||||
live "/endgames", EndgameLive.PlayerIndex, :index
|
||||
live "/train", EndgameLive.Train, :train
|
||||
live "/users/settings", UserLive.Settings, :edit
|
||||
live "/users/settings/confirm-email/:token", UserLive.Settings, :confirm_email
|
||||
@@ -81,6 +78,7 @@ defmodule ChesstrainerWeb.Router do
|
||||
|
||||
live_session :current_user,
|
||||
on_mount: [{ChesstrainerWeb.UserAuth, :mount_current_scope}] do
|
||||
live "/guest-train", EndgameLive.GuestTrain, :play
|
||||
live "/endgames/:public_code/play", EndgameLive.Play, :play
|
||||
live "/users/register", UserLive.Registration, :new
|
||||
live "/users/log-in", UserLive.Login, :new
|
||||
|
||||
Reference in New Issue
Block a user