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:
2026-11-06 12:06:32 +01:00
committed by GitHub
parent 2c5e290e66
commit dda588da06
14 changed files with 691 additions and 97 deletions
+7
View File
@@ -81,6 +81,13 @@ config :chesstrainer, Chesstrainer.Cache,
max_size: cache_max_size,
backup_time: cache_backup_time
# Guest puzzle limit: free puzzles per UTC day for anonymous visitors. The
# visitor is identified by a keyed hash of their address held in memory only.
# Enable TRUST_FORWARDED_FOR only behind a proxy that sets the header.
config :chesstrainer, Chesstrainer.GuestLimits,
limit: String.to_integer(System.get_env("GUEST_PUZZLE_LIMIT", "5")),
trust_forwarded_for: System.get_env("TRUST_FORWARDED_FOR") in ~w(true 1)
config :chesstrainer, ChesstrainerWeb.Endpoint,
http: [port: String.to_integer(System.get_env("PORT", "4000"))]
+38
View File
@@ -0,0 +1,38 @@
# Guest puzzles are capped per UTC day by a hashed address
`/guest-train` gives anonymous visitors 5 puzzles per UTC day. The budget is per
client address, but the address is never stored: the limiter keys an in-memory
ETS table by `HMAC-SHA256(boot_secret, "<gregorian_day>|<address>")`. The secret
is generated when the node boots, so digests are not stable across restarts and
cannot be correlated with anything else. The table is swept when the day rolls
over, and no entry is ever written to the database, a log, or a backup.
## Why a daily UTC reset
A fixed 00:00 UTC boundary makes the rule easy to state ("5 free puzzles a
day"), gives every visitor the same reset instant, and removes the need for
per-entry timestamps: the UTC date is part of the key, so yesterday's entries
simply stop matching. That also means the stored data's lifetime is bounded by
the calendar day.
## Why not an IP address
The raw address is never persisted; only the digest is, and only until the day
rolls over or the node restarts. This is abuse prevention with data
minimisation, not tracking, and needs no cookie or client-side storage. The
processing is disclosed in the privacy policy (see #87).
## Consequences
- Visitors behind one NAT share a budget. Masking to a subnet would make that
worse, so the full address is hashed.
- The budget lives in one node's memory: a restart resets it, and a second node
would keep its own. Move the counter to Postgres or Redis if that matters.
- The unit being metered is a puzzle load, not a move. A LiveView reconnect
re-runs the connected mount and therefore consumes one puzzle.
- Retry and review never consume a puzzle because they reuse the loaded
position.
- Signed-in visitors are redirected to `/train` and are never metered.
- Behind a proxy, set `TRUST_FORWARDED_FOR=1` and make sure the proxy overwrites
or appends `X-Forwarded-For`; otherwise every visitor shares the proxy's
budget. `GUEST_PUZZLE_LIMIT` changes the daily allowance.
+1
View File
@@ -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},
+14 -2
View File
@@ -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.
"""
+119
View File
@@ -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
+1 -1
View File
@@ -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.
+2 -2
View File
@@ -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
+2 -4
View File
@@ -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
+8 -1
View File
@@ -322,7 +322,7 @@ defmodule Chesstrainer.EndgamesTest do
end
end
describe "random_endgame/0" do
describe "random_endgame/1" do
test "returns nil when there are no endgames" do
assert Endgames.random_endgame() == nil
end
@@ -333,6 +333,13 @@ defmodule Chesstrainer.EndgamesTest do
assert Endgames.random_endgame().id in [kr.id, kq.id]
end
test "skips excluded endgames" do
kr = create_endgame!(@kr)
kq = create_endgame!(@kq)
assert Endgames.random_endgame(exclude_ids: [kr.id]).id == kq.id
end
end
describe "curated_endgames/1" do
+53
View File
@@ -0,0 +1,53 @@
defmodule Chesstrainer.GuestLimitsTest do
use ExUnit.Case, async: false
alias Chesstrainer.GuestLimits
@address {203, 0, 113, 7}
@other {198, 51, 100, 9}
@today ~D[2026-11-06]
setup do
GuestLimits.reset()
:ok
end
test "allows five puzzles a day and blocks the sixth" do
assert {:ok, 4} = GuestLimits.take(@address, @today)
assert {:ok, 3} = GuestLimits.take(@address, @today)
assert {:ok, 2} = GuestLimits.take(@address, @today)
assert {:ok, 1} = GuestLimits.take(@address, @today)
assert {:ok, 0} = GuestLimits.take(@address, @today)
assert {:limit_reached, retry_ms} = GuestLimits.take(@address, @today)
assert retry_ms > 0
end
test "resets on the next UTC day" do
for _ <- 1..5, do: assert({:ok, _} = GuestLimits.take(@address, @today))
assert {:limit_reached, _} = GuestLimits.take(@address, @today)
assert {:ok, 4} = GuestLimits.take(@address, ~D[2026-11-07])
end
test "tracks addresses independently" do
for _ <- 1..5, do: assert({:ok, _} = GuestLimits.take(@address, @today))
assert {:limit_reached, _} = GuestLimits.take(@address, @today)
assert {:ok, 4} = GuestLimits.take(@other, @today)
end
test "does not limit a missing address" do
assert {:ok, nil} = GuestLimits.take(nil, @today)
assert {:ok, nil} = GuestLimits.take(nil, @today)
end
test "reset clears spent budgets" do
for _ <- 1..5, do: assert({:ok, _} = GuestLimits.take(@address, @today))
assert {:limit_reached, _} = GuestLimits.take(@address, @today)
GuestLimits.reset()
assert {:ok, 4} = GuestLimits.take(@address, @today)
end
end
@@ -0,0 +1,178 @@
defmodule ChesstrainerWeb.EndgameLive.GuestTrainTest do
use ChesstrainerWeb.ConnCase
import Phoenix.LiveViewTest
import Chesstrainer.EndgamesFixtures
alias Chesstrainer.Attempts.Attempt
alias Chesstrainer.Endgames.Tablebase
alias Chesstrainer.Endgames.Tablebase.Cache, as: TablebaseCache
alias Chesstrainer.FEN
alias Chesstrainer.GuestLimits
alias Chesstrainer.Repo
@guest_address {127, 0, 0, 1}
setup do
GuestLimits.reset()
:ok
end
defp seed_tablebase(fen, opts) do
tablebase = %Tablebase{
category: Keyword.get(opts, :category, :win),
checkmate: Keyword.get(opts, :checkmate, false),
moves: Keyword.get(opts, :moves, [])
}
key = FEN.position_key(fen)
TablebaseCache.put(key, tablebase)
on_exit(fn -> TablebaseCache.delete(key) end)
end
defp grading_moves do
[%Tablebase.Move{uci: "d1d7", san: "Qd7+", category: :loss, dtz: -1}]
end
# Plays the move the seeded tablebase grades as optimal and completes the
# puzzle by checkmate on the follow-up position.
defp solve_current(view) do
endgame = :sys.get_state(view.pid).socket.assigns.endgame
after_fen = "8/8/8/8/8/8/8/8 b - - 0 1"
seed_tablebase(after_fen, checkmate: true, moves: [])
render_hook(view, "endgame_move_played", %{
"from" => "d1",
"to" => "d7",
"san" => "Qd7+",
"prev_fen" => endgame.fen,
"fen" => after_fen,
"endgame_id" => endgame.id
})
end
defp spend_puzzles(count) do
for _ <- 1..count do
assert {:ok, _remaining} = GuestLimits.take(@guest_address)
end
end
describe "access" do
test "lets an anonymous visitor play a random puzzle", %{conn: conn} do
endgame = endgame_fixture()
seed_tablebase(endgame.fen, moves: grading_moves())
{:ok, view, _html} = live(conn, ~p"/guest-train")
assert has_element?(view, "#endgame-board[data-endgame-id='#{endgame.id}']")
refute has_element?(view, "#difficulty-picker")
refute has_element?(view, "#session-bar")
assert render(view) =~ "A random endgame puzzle"
assert render(view) =~ "4 of 5 free puzzles left today"
end
test "redirects signed-in users to the difficulty picker", %{conn: conn} do
%{conn: conn} = register_and_log_in_user(%{conn: conn})
assert {:error, {:redirect, %{to: "/train"}}} = live(conn, ~p"/guest-train")
end
end
describe "without puzzles" do
test "shows an empty state", %{conn: conn} do
{:ok, view, _html} = live(conn, ~p"/guest-train")
assert render(view) =~ "No endgames are available yet"
refute has_element?(view, "#endgame-board")
end
end
describe "playing" do
test "solves a puzzle without recording an attempt", %{conn: conn} do
endgame = endgame_fixture()
seed_tablebase(endgame.fen, moves: grading_moves())
{:ok, view, _html} = live(conn, ~p"/guest-train")
solve_current(view)
assert render(view) =~ "Solved!"
assert has_element?(view, "#next-puzzle-button")
assert Repo.aggregate(Attempt, :count) == 0
end
test "next puzzle loads a different endgame", %{conn: conn} do
endgames =
for _ <- 1..2 do
endgame = endgame_fixture()
seed_tablebase(endgame.fen, moves: grading_moves())
endgame
end
{:ok, view, _html} = live(conn, ~p"/guest-train")
first = :sys.get_state(view.pid).socket.assigns.endgame
solve_current(view)
view |> element("#next-puzzle-button") |> render_click()
second = :sys.get_state(view.pid).socket.assigns.endgame
assert second.id != first.id
assert Enum.any?(endgames, &(&1.id == second.id))
assert :sys.get_state(view.pid).socket.assigns.guest_remaining == 3
end
test "trying again does not spend another puzzle", %{conn: conn} do
endgame = endgame_fixture()
seed_tablebase(endgame.fen, moves: grading_moves())
{:ok, view, _html} = live(conn, ~p"/guest-train")
solve_current(view)
view |> element("button", "Try again") |> render_click()
assert :sys.get_state(view.pid).socket.assigns.guest_remaining == 4
end
end
describe "daily budget" do
test "shows the sign-up wall once the budget is spent", %{conn: conn} do
endgame = endgame_fixture()
seed_tablebase(endgame.fen, moves: grading_moves())
spend_puzzles(4)
{:ok, view, _html} = live(conn, ~p"/guest-train")
assert :sys.get_state(view.pid).socket.assigns.guest_remaining == 0
assert render(view) =~ "Last free puzzle today"
solve_current(view)
view |> element("#next-puzzle-button") |> render_click()
assert has_element?(view, "#guest-limit")
assert render(view) =~ "used your 5 free puzzles today"
assert render(view) =~ "Sign up for a free account to keep training"
assert has_element?(view, "#guest-sign-up[href='/users/register']")
assert render(view) =~ "reset at 00:00 UTC"
refute has_element?(view, "#next-puzzle-button")
end
test "a fresh visit after the limit shows only the wall", %{conn: conn} do
spend_puzzles(5)
{:ok, view, _html} = live(conn, ~p"/guest-train")
assert has_element?(view, "#guest-limit")
refute has_element?(view, "#endgame-board")
assert render(view) =~ "used your 5 free puzzles today"
end
test "signed-in visitors do not spend the guest budget", %{conn: conn} do
%{conn: conn} = register_and_log_in_user(%{conn: conn})
assert {:error, {:redirect, %{to: "/train"}}} = live(conn, ~p"/guest-train")
assert {:ok, 4} = GuestLimits.take(@guest_address)
end
end
end
@@ -7,6 +7,8 @@ defmodule ChesstrainerWeb.EndgameLive.PlayerIndexTest do
alias Chesstrainer.Endgames
setup :register_and_log_in_user
test "groups endgames by Key and shows themes on expand", %{conn: conn} do
theme = theme_fixture(%{name: "Lucena"})
endgame = endgame_fixture()