From 79782dc778883034efcec0073fb07affdb84aa9b Mon Sep 17 00:00:00 2001 From: Owen Date: Mon, 9 Nov 2026 20:49:25 +0100 Subject: [PATCH] prelaunch env var prevents the site from being operational --- .env.example | 3 + config/config.exs | 5 ++ config/prod.exs | 6 +- config/runtime.exs | 8 ++ lib/chesstrainer_web.ex | 8 ++ lib/chesstrainer_web/components/layouts.ex | 80 +++++++++-------- .../controllers/health_controller.ex | 13 +++ .../controllers/mailing_list_controller.ex | 50 +++++++---- .../controllers/page_controller.ex | 53 ++++++++---- .../page_html/coming_soon.html.heex | 26 ++++++ .../controllers/page_html/home.html.heex | 2 +- .../controllers/robots_controller.ex | 20 +++-- .../controllers/user_session_controller.ex | 35 +++++--- lib/chesstrainer_web/live/user_live/login.ex | 16 +++- .../live/user_live/registration.ex | 36 ++++++-- lib/chesstrainer_web/plugs/prelaunch.ex | 57 +++++++++++++ lib/chesstrainer_web/router.ex | 19 ++++- lib/chesstrainer_web/user_auth.ex | 18 ++++ mise.toml | 4 + .../mailing_list_controller_test.exs | 21 ++++- .../controllers/page_controller_test.exs | 26 ++++++ .../controllers/robots_controller_test.exs | 17 +++- .../chesstrainer_web/plugs/prelaunch_test.exs | 85 +++++++++++++++++++ 23 files changed, 510 insertions(+), 98 deletions(-) create mode 100644 lib/chesstrainer_web/controllers/health_controller.ex create mode 100644 lib/chesstrainer_web/controllers/page_html/coming_soon.html.heex create mode 100644 lib/chesstrainer_web/plugs/prelaunch.ex create mode 100644 mise.toml create mode 100644 test/chesstrainer_web/plugs/prelaunch_test.exs diff --git a/.env.example b/.env.example index 5f024b9..847e58e 100644 --- a/.env.example +++ b/.env.example @@ -2,6 +2,9 @@ SECRET_KEY_BASE=... DATABASE_URL=... PHX_HOST=innersquare.app PORT=4000 +PRELAUNCH=true +MAILING_LIST_ENABLED=false SES_REGION=eu-north-1 SES_ACCESS_KEY_ID=AKIA... SES_SECRET_ACCESS_KEY=... +TABLEBASE_PATH= diff --git a/config/config.exs b/config/config.exs index 494f817..8b26f70 100644 --- a/config/config.exs +++ b/config/config.exs @@ -17,6 +17,11 @@ config :chesstrainer, :branding, support_email: "support@innersquare.app", mail_from: "no-reply@innersquare.app" +# Prelaunch gating. Production sets these from PRELAUNCH and +# MAILING_LIST_ENABLED; dev and test use these defaults. +config :chesstrainer, :prelaunch, false +config :chesstrainer, :mailing_list_enabled, true + config :chesstrainer, :scopes, user: [ default: true, diff --git a/config/prod.exs b/config/prod.exs index 1b96ae1..fa7a5a9 100644 --- a/config/prod.exs +++ b/config/prod.exs @@ -15,11 +15,15 @@ config :chesstrainer, ChesstrainerWeb.Endpoint, force_ssl: [ rewrite_on: [:x_forwarded_proto], exclude: [ - # paths: ["/health"], + paths: ["/health"], hosts: ["localhost", "127.0.0.1"] ] ] +# Fail closed in production: the mailing list stays off until SES production +# access is granted and MAILING_LIST_ENABLED is set explicitly. +config :chesstrainer, :mailing_list_enabled, false + # Configure Swoosh API Client config :swoosh, api_client: Swoosh.ApiClient.Req diff --git a/config/runtime.exs b/config/runtime.exs index 2c2846e..464887c 100644 --- a/config/runtime.exs +++ b/config/runtime.exs @@ -20,6 +20,14 @@ if System.get_env("PHX_SERVER") do config :chesstrainer, ChesstrainerWeb.Endpoint, server: true end +if prelaunch = System.get_env("PRELAUNCH") do + config :chesstrainer, :prelaunch, prelaunch in ~w(true 1) +end + +if mailing_list_enabled = System.get_env("MAILING_LIST_ENABLED") do + config :chesstrainer, :mailing_list_enabled, mailing_list_enabled in ~w(true 1) +end + # Local Syzygy tablebases: set TABLEBASE_PATH to the directory holding the # .rtbw/.rtbz files. When unset, the local backend stays disabled and lookups # fall back to Lichess. diff --git a/lib/chesstrainer_web.ex b/lib/chesstrainer_web.ex index 542ae0d..d0df354 100644 --- a/lib/chesstrainer_web.ex +++ b/lib/chesstrainer_web.ex @@ -19,6 +19,14 @@ defmodule ChesstrainerWeb do def static_paths, do: ~w(assets fonts images favicon.ico) + @doc "Whether the app is gated behind the prelaunch page." + def prelaunch?, do: Application.get_env(:chesstrainer, :prelaunch, false) + + @doc "Whether the mailing-list form and endpoint are open." + def mailing_list_enabled? do + Application.get_env(:chesstrainer, :mailing_list_enabled, true) + end + def router do quote do use Phoenix.Router, helpers: false diff --git a/lib/chesstrainer_web/components/layouts.ex b/lib/chesstrainer_web/components/layouts.ex index 268e639..5ae4e52 100644 --- a/lib/chesstrainer_web/components/layouts.ex +++ b/lib/chesstrainer_web/components/layouts.ex @@ -63,11 +63,17 @@ defmodule ChesstrainerWeb.Layouts do doc: "the current [scope](https://phoenix.hexdocs.pm/scopes.html)" def navbar(assigns) do + user = signed_in_user(assigns.current_scope) + nav_links = nav_links(assigns.current_scope) + prelaunch = ChesstrainerWeb.prelaunch?() + assigns = assigns - |> assign(:nav_links, nav_links(assigns.current_scope)) + |> assign(:nav_links, nav_links) |> assign(:start_href, start_href(assigns.current_scope)) - |> assign(:user, signed_in_user(assigns.current_scope)) + |> assign(:user, user) + |> assign(:prelaunch, prelaunch) + |> assign(:show_nav, not prelaunch or not is_nil(user) or nav_links != []) ~H"""
@@ -80,41 +86,47 @@ defmodule ChesstrainerWeb.Layouts do
diff --git a/lib/chesstrainer_web/controllers/health_controller.ex b/lib/chesstrainer_web/controllers/health_controller.ex new file mode 100644 index 0000000..2796852 --- /dev/null +++ b/lib/chesstrainer_web/controllers/health_controller.ex @@ -0,0 +1,13 @@ +defmodule ChesstrainerWeb.HealthController do + @moduledoc """ + Lightweight health check used by deploys and uptime monitors. + """ + + use ChesstrainerWeb, :controller + + def index(conn, _params) do + conn + |> put_resp_content_type("text/plain") + |> send_resp(200, "ok") + end +end diff --git a/lib/chesstrainer_web/controllers/mailing_list_controller.ex b/lib/chesstrainer_web/controllers/mailing_list_controller.ex index f6456be..6391c8f 100644 --- a/lib/chesstrainer_web/controllers/mailing_list_controller.ex +++ b/lib/chesstrainer_web/controllers/mailing_list_controller.ex @@ -10,24 +10,16 @@ defmodule ChesstrainerWeb.MailingListController do @token_max_age 7 * 24 * 60 * 60 def create(conn, %{"subscriber" => params}) when is_map(params) do - email = params["email"] - - cond do - honeypot_filled?(params) -> - fake_success(conn) - - not is_binary(email) -> - invalid_email(conn) - - MailingListFormToken.verify(params["form_token"]) != :ok -> - form_error(conn) - - true -> - subscribe(conn, email) + if mailing_list_enabled?() do + create_subscription(conn, params) + else + closed(conn) end end - def create(conn, _params), do: invalid_email(conn) + def create(conn, _params) do + if mailing_list_enabled?(), do: invalid_email(conn), else: closed(conn) + end def confirm(conn, %{"token" => token}) do case Phoenix.Token.verify( @@ -63,6 +55,24 @@ defmodule ChesstrainerWeb.MailingListController do end end + defp create_subscription(conn, params) do + email = params["email"] + + cond do + honeypot_filled?(params) -> + fake_success(conn) + + not is_binary(email) -> + invalid_email(conn) + + MailingListFormToken.verify(params["form_token"]) != :ok -> + form_error(conn) + + true -> + subscribe(conn, email) + end + end + defp subscribe(conn, email) do email = String.trim(email) @@ -122,4 +132,14 @@ defmodule ChesstrainerWeb.MailingListController do |> put_flash(:error, "Enter a valid email address.") |> redirect(to: @return_to) end + + defp closed(conn) do + conn + |> put_flash(:info, "The mailing list isn't open yet.") + |> redirect(to: @return_to) + end + + defp mailing_list_enabled? do + Application.get_env(:chesstrainer, :mailing_list_enabled, true) + end end diff --git a/lib/chesstrainer_web/controllers/page_controller.ex b/lib/chesstrainer_web/controllers/page_controller.ex index d69471c..89deb2a 100644 --- a/lib/chesstrainer_web/controllers/page_controller.ex +++ b/lib/chesstrainer_web/controllers/page_controller.ex @@ -11,22 +11,27 @@ defmodule ChesstrainerWeb.PageController do "Learn to see the winning move and make the endgame your strongest phase." def home(conn, _params) do - endgames = Endgames.curated_endgames() + if prelaunch?() do + render_coming_soon(conn) + else + endgames = Endgames.curated_endgames() - conn - |> assign(:js_entry, ~p"/assets/js/marketing.js") - |> assign(:page_title, Branding.home_title()) - |> assign(:title_suffix, "") - |> assign(:meta_description, @description) - |> assign(:canonical_url, current_url(conn)) - |> render(:home, - endgames: endgames, - active_endgame: DailyPuzzles.today(), - puzzle_count: Endgames.count_endgames(), - user_count: Attempts.count_users_with_attempts(), - logged_in_count: Accounts.count_logged_in_users(), - today: Date.utc_today() - ) + conn + |> assign(:js_entry, ~p"/assets/js/marketing.js") + |> assign(:page_title, Branding.home_title()) + |> assign(:title_suffix, "") + |> assign(:meta_description, @description) + |> assign(:canonical_url, current_url(conn)) + |> assign(:mailing_list_enabled, mailing_list_enabled?()) + |> render(:home, + endgames: endgames, + active_endgame: DailyPuzzles.today(), + puzzle_count: Endgames.count_endgames(), + user_count: Attempts.count_users_with_attempts(), + logged_in_count: Accounts.count_logged_in_users(), + today: Date.utc_today() + ) + end end def privacy(conn, _params) do @@ -61,4 +66,22 @@ defmodule ChesstrainerWeb.PageController do |> assign(:noindex, true) |> render(:not_found) end + + defp render_coming_soon(conn) do + conn + |> assign(:js_entry, ~p"/assets/js/marketing.js") + |> assign(:page_title, Branding.home_title()) + |> assign(:title_suffix, "") + |> assign(:meta_description, @description) + |> assign(:canonical_url, current_url(conn)) + |> assign(:noindex, true) + |> assign(:mailing_list_enabled, mailing_list_enabled?()) + |> render(:coming_soon) + end + + defp prelaunch?, do: Application.get_env(:chesstrainer, :prelaunch, false) + + defp mailing_list_enabled? do + Application.get_env(:chesstrainer, :mailing_list_enabled, true) + end end diff --git a/lib/chesstrainer_web/controllers/page_html/coming_soon.html.heex b/lib/chesstrainer_web/controllers/page_html/coming_soon.html.heex new file mode 100644 index 0000000..4386f08 --- /dev/null +++ b/lib/chesstrainer_web/controllers/page_html/coming_soon.html.heex @@ -0,0 +1,26 @@ + +
+
+
+
+ <.icon_spark /> Endgame training, coming soon +
+

+ Master the endgame. +

+

+ Short, focused endgame puzzles against tablebase-perfect defence. We're putting the finishing touches on the trainer. +

+
+ <.pill_button variant={:primary} href="#mailing-list">Join the list +
+
+
+
+
+ <.board_preview /> +
+
+ + <.mailing_list_signup :if={@mailing_list_enabled} /> +
diff --git a/lib/chesstrainer_web/controllers/page_html/home.html.heex b/lib/chesstrainer_web/controllers/page_html/home.html.heex index 5a3cfe8..2e4f095 100644 --- a/lib/chesstrainer_web/controllers/page_html/home.html.heex +++ b/lib/chesstrainer_web/controllers/page_html/home.html.heex @@ -70,7 +70,7 @@ --%> - <.mailing_list_signup /> + <.mailing_list_signup :if={@mailing_list_enabled} /> <%!--
diff --git a/lib/chesstrainer_web/controllers/robots_controller.ex b/lib/chesstrainer_web/controllers/robots_controller.ex index 62e0062..b3e0b90 100644 --- a/lib/chesstrainer_web/controllers/robots_controller.ex +++ b/lib/chesstrainer_web/controllers/robots_controller.ex @@ -9,15 +9,25 @@ defmodule ChesstrainerWeb.RobotsController do use ChesstrainerWeb, :controller def index(conn, _params) do - body = """ - User-agent: * - Allow: / + body = + if prelaunch?() do + """ + User-agent: * + Disallow: / + """ + else + """ + User-agent: * + Allow: / - Sitemap: #{url(conn, ~p"/sitemap.xml")} - """ + Sitemap: #{url(conn, ~p"/sitemap.xml")} + """ + end conn |> put_resp_content_type("text/plain") |> send_resp(200, body) end + + defp prelaunch?, do: Application.get_env(:chesstrainer, :prelaunch, false) end diff --git a/lib/chesstrainer_web/controllers/user_session_controller.ex b/lib/chesstrainer_web/controllers/user_session_controller.ex index 81ed66e..def9622 100644 --- a/lib/chesstrainer_web/controllers/user_session_controller.ex +++ b/lib/chesstrainer_web/controllers/user_session_controller.ex @@ -5,20 +5,28 @@ defmodule ChesstrainerWeb.UserSessionController do alias ChesstrainerWeb.UserAuth def create(conn, %{"user" => user_params}) do + authenticate(conn, user_params, ~p"/users/log-in", nil) + end + + def create_admin(conn, %{"user" => user_params}) do + if ChesstrainerWeb.prelaunch?() do + authenticate(conn, user_params, ~p"/admin/log-in", ~p"/admin/endgames") + else + authenticate(conn, user_params, ~p"/users/log-in", nil) + end + end + + defp authenticate(conn, user_params, failure_path, success_path) do %{"email" => login, "password" => password} = user_params case Accounts.get_user_by_login_and_password(login, password) do nil -> - # In order to prevent user enumeration attacks, don't disclose whether - # the email or username is registered. - conn - |> put_flash(:error, "Invalid email, username or password") - |> put_flash(:email, String.slice(login, 0, 160)) - |> redirect(to: ~p"/users/log-in") + invalid_credentials(conn, login, failure_path) user -> if user.confirmed_at do conn + |> maybe_put_return_to(success_path) |> put_flash(:info, "Welcome back!") |> UserAuth.log_in_user(user, user_params) else @@ -30,14 +38,21 @@ defmodule ChesstrainerWeb.UserSessionController do # In order to prevent user enumeration attacks, report the same error # as invalid credentials. - conn - |> put_flash(:error, "Invalid email, username or password") - |> put_flash(:email, String.slice(login, 0, 160)) - |> redirect(to: ~p"/users/log-in") + invalid_credentials(conn, login, failure_path) end end end + defp invalid_credentials(conn, login, path) do + conn + |> put_flash(:error, "Invalid email, username or password") + |> put_flash(:email, String.slice(login, 0, 160)) + |> redirect(to: path) + end + + defp maybe_put_return_to(conn, nil), do: conn + defp maybe_put_return_to(conn, path), do: put_session(conn, :user_return_to, path) + def update_password(conn, %{"user" => user_params}) do user = conn.assigns.current_scope.user true = Accounts.sudo_mode?(user) diff --git a/lib/chesstrainer_web/live/user_live/login.ex b/lib/chesstrainer_web/live/user_live/login.ex index c086b26..6429d92 100644 --- a/lib/chesstrainer_web/live/user_live/login.ex +++ b/lib/chesstrainer_web/live/user_live/login.ex @@ -11,7 +11,7 @@ defmodule ChesstrainerWeb.UserLive.Login do <%= if @current_scope do %> You need to reauthenticate to perform sensitive actions on your account. <% else %> -

+

Don't have an account? <.link navigate={~p"/users/register"} class="font-semibold text-primary-text hover:underline" @@ -25,7 +25,7 @@ defmodule ChesstrainerWeb.UserLive.Login do :let={f} for={@form} id="login_form_password" - action={~p"/users/log-in"} + action={@login_action} phx-submit="submit_password" phx-trigger-action={@trigger_submit} > @@ -73,8 +73,18 @@ defmodule ChesstrainerWeb.UserLive.Login do get_in(socket.assigns, [:current_scope, Access.key(:user), Access.key(:email)]) form = to_form(%{"email" => email}, as: "user") + prelaunch = ChesstrainerWeb.prelaunch?() - {:ok, assign(socket, form: form, trigger_submit: false)} + login_action = + if prelaunch, do: ~p"/admin/log-in", else: ~p"/users/log-in" + + {:ok, + assign(socket, + form: form, + trigger_submit: false, + prelaunch: prelaunch, + login_action: login_action + )} end @impl true diff --git a/lib/chesstrainer_web/live/user_live/registration.ex b/lib/chesstrainer_web/live/user_live/registration.ex index 059031e..2d942ef 100644 --- a/lib/chesstrainer_web/live/user_live/registration.ex +++ b/lib/chesstrainer_web/live/user_live/registration.ex @@ -74,19 +74,40 @@ defmodule ChesstrainerWeb.UserLive.Registration do end @impl true - def mount(_params, _session, %{assigns: %{current_scope: %{user: user}}} = socket) - when not is_nil(user) do + def mount(_params, _session, socket) do + if prelaunch?() do + {:ok, redirect(socket, to: ~p"/")} + else + do_mount(socket) + end + end + + @impl true + def handle_event("save", %{"user" => user_params}, socket) do + if prelaunch?() do + {:noreply, push_navigate(socket, to: ~p"/")} + else + save_registration(socket, user_params) + end + end + + def handle_event("validate", %{"user" => user_params}, socket) do + changeset = Accounts.change_user_registration(%User{}, user_params, validate_unique: false) + {:noreply, assign_form(socket, Map.put(changeset, :action, :validate))} + end + + defp do_mount(%{assigns: %{current_scope: %{user: user}}} = socket) + when not is_nil(user) do {:ok, redirect(socket, to: ChesstrainerWeb.UserAuth.signed_in_path(socket))} end - def mount(_params, _session, socket) do + defp do_mount(socket) do changeset = Accounts.change_user_registration(%User{}, %{}, validate_unique: false) {:ok, assign_form(socket, changeset), temporary_assigns: [form: nil]} end - @impl true - def handle_event("save", %{"user" => user_params}, socket) do + defp save_registration(socket, user_params) do case Accounts.register_user(user_params) do {:ok, user} -> if user.mailing_list, do: MailingList.subscribe_user(user) @@ -110,10 +131,7 @@ defmodule ChesstrainerWeb.UserLive.Registration do end end - def handle_event("validate", %{"user" => user_params}, socket) do - changeset = Accounts.change_user_registration(%User{}, user_params, validate_unique: false) - {:noreply, assign_form(socket, Map.put(changeset, :action, :validate))} - end + defp prelaunch?, do: Application.get_env(:chesstrainer, :prelaunch, false) defp assign_form(socket, %Ecto.Changeset{} = changeset) do form = to_form(changeset, as: "user") diff --git a/lib/chesstrainer_web/plugs/prelaunch.ex b/lib/chesstrainer_web/plugs/prelaunch.ex new file mode 100644 index 0000000..94624a7 --- /dev/null +++ b/lib/chesstrainer_web/plugs/prelaunch.ex @@ -0,0 +1,57 @@ +defmodule ChesstrainerWeb.Plugs.Prelaunch do + @moduledoc """ + Redirects every non-public route to the home page while the app is gated. + + The allowlist is deliberately small: legal pages, the mailing list, auth + entry points, admin, crawler files, health, and the static/LiveView plumbing. + Everything else redirects to `/` with `X-Robots-Tag: noindex, nofollow`. + + Set `PRELAUNCH=true` to enable the gate. + """ + + import Plug.Conn + + @allowed_exact ~w( + / + /privacy + /terms-conditions + /health + /robots.txt + /sitemap.xml + /favicon.ico + ) + + @allowed_prefixes ~w( + /mailing-list + /users/log-out + /users/confirm + /users/reset-password + /users/settings + /admin + /live + /assets + /fonts + /images + /dev + ) + + def init(opts), do: opts + + def call(conn, _opts) do + if enabled?() and not allowed?(conn.request_path) do + conn + |> put_resp_header("x-robots-tag", "noindex, nofollow") + |> Phoenix.Controller.redirect(to: "/") + |> halt() + else + conn + end + end + + defp enabled?, do: Application.get_env(:chesstrainer, :prelaunch, false) + + defp allowed?(path) do + path in @allowed_exact or + Enum.any?(@allowed_prefixes, &String.starts_with?(path, &1)) + end +end diff --git a/lib/chesstrainer_web/router.ex b/lib/chesstrainer_web/router.ex index abe16de..54d8deb 100644 --- a/lib/chesstrainer_web/router.ex +++ b/lib/chesstrainer_web/router.ex @@ -10,6 +10,7 @@ defmodule ChesstrainerWeb.Router do plug :put_root_layout, html: {ChesstrainerWeb.Layouts, :root} plug :protect_from_forgery plug :put_secure_browser_headers + plug ChesstrainerWeb.Plugs.Prelaunch plug :fetch_current_scope_for_user end @@ -34,13 +35,17 @@ defmodule ChesstrainerWeb.Router do get "/terms-conditions", PageController, :terms_conditions post "/mailing-list", MailingListController, :create get "/mailing-list/confirm/:token", MailingListController, :confirm + post "/admin/log-in", UserSessionController, :create_admin end scope "/admin", ChesstrainerWeb do pipe_through [:browser, :noindex, :require_admin_user] live_session :endgames, - on_mount: [{ChesstrainerWeb.UserAuth, :require_admin}] do + on_mount: [ + {ChesstrainerWeb.UserAuth, :enforce_prelaunch}, + {ChesstrainerWeb.UserAuth, :require_admin} + ] do live "/endgames", EndgameLive.Index, :index live "/endgames/new", EndgameLive.Form, :new live "/endgames/:id", EndgameLive.Show, :show @@ -76,7 +81,10 @@ defmodule ChesstrainerWeb.Router do pipe_through [:browser, :require_authenticated_user] live_session :require_authenticated_user, - on_mount: [{ChesstrainerWeb.UserAuth, :require_authenticated}] do + on_mount: [ + {ChesstrainerWeb.UserAuth, :enforce_prelaunch}, + {ChesstrainerWeb.UserAuth, :require_authenticated} + ] do live "/endgames", EndgameLive.PlayerIndex, :index live "/train", EndgameLive.Train, :train live "/users/profile", UserLive.Profile, :account @@ -95,11 +103,15 @@ defmodule ChesstrainerWeb.Router do pipe_through [:browser] live_session :current_user, - on_mount: [{ChesstrainerWeb.UserAuth, :mount_current_scope}] do + on_mount: [ + {ChesstrainerWeb.UserAuth, :enforce_prelaunch}, + {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 + live "/admin/log-in", UserLive.Login, :new live "/users/reset-password", UserLive.ResetPassword, :new live "/users/reset-password/:token", UserLive.ResetPassword, :edit end @@ -115,6 +127,7 @@ defmodule ChesstrainerWeb.Router do scope "/", ChesstrainerWeb do pipe_through :seo + get "/health", HealthController, :index get "/robots.txt", RobotsController, :index get "/sitemap.xml", SitemapController, :index end diff --git a/lib/chesstrainer_web/user_auth.ex b/lib/chesstrainer_web/user_auth.ex index dbc3a28..7e104c9 100644 --- a/lib/chesstrainer_web/user_auth.ex +++ b/lib/chesstrainer_web/user_auth.ex @@ -212,6 +212,24 @@ defmodule ChesstrainerWeb.UserAuth do live "/profile", ProfileLive, :index end """ + @prelaunch_allowed_views [ + ChesstrainerWeb.UserLive.Login, + ChesstrainerWeb.UserLive.ResetPassword, + ChesstrainerWeb.UserLive.Profile, + ChesstrainerWeb.EndgameLive.Index, + ChesstrainerWeb.EndgameLive.Form, + ChesstrainerWeb.EndgameLive.Show + ] + + def on_mount(:enforce_prelaunch, _params, _session, socket) do + if Application.get_env(:chesstrainer, :prelaunch, false) and + socket.view not in @prelaunch_allowed_views do + {:halt, Phoenix.LiveView.redirect(socket, to: ~p"/")} + else + {:cont, socket} + end + end + def on_mount(:mount_current_scope, _params, session, socket) do {:cont, mount_current_scope(socket, session)} end diff --git a/mise.toml b/mise.toml new file mode 100644 index 0000000..561e857 --- /dev/null +++ b/mise.toml @@ -0,0 +1,4 @@ +[tools] +erlang = "28.5" +elixir = "1.19.5-otp-28" +rust = "1.98.1" diff --git a/test/chesstrainer_web/controllers/mailing_list_controller_test.exs b/test/chesstrainer_web/controllers/mailing_list_controller_test.exs index b2a1de7..0d4463d 100644 --- a/test/chesstrainer_web/controllers/mailing_list_controller_test.exs +++ b/test/chesstrainer_web/controllers/mailing_list_controller_test.exs @@ -1,5 +1,5 @@ defmodule ChesstrainerWeb.MailingListControllerTest do - use ChesstrainerWeb.ConnCase, async: true + use ChesstrainerWeb.ConnCase, async: false alias Chesstrainer.MailingList alias Chesstrainer.MailingList.Subscriber @@ -169,6 +169,22 @@ defmodule ChesstrainerWeb.MailingListControllerTest do assert redirected_to(conn) == "/#mailing-list" assert Phoenix.Flash.get(conn.assigns.flash, :error) =~ "valid email address" end + + test "rejects signups when the mailing list is disabled", %{conn: conn} do + previous = Application.get_env(:chesstrainer, :mailing_list_enabled) + on_exit(fn -> restore_env(:mailing_list_enabled, previous) end) + Application.put_env(:chesstrainer, :mailing_list_enabled, false) + + conn = + post(conn, ~p"/mailing-list", + subscriber: %{email: "player@example.com", form_token: form_token()} + ) + + assert redirected_to(conn) == "/#mailing-list" + assert Phoenix.Flash.get(conn.assigns.flash, :info) =~ "isn't open yet" + refute_received {:email, _email} + assert Repo.aggregate(Subscriber, :count) == 0 + end end describe "GET /mailing-list/confirm/:token" do @@ -227,4 +243,7 @@ defmodule ChesstrainerWeb.MailingListControllerTest do defp form_token do MailingListFormToken.sign(System.system_time(:second) - 5) end + + defp restore_env(key, nil), do: Application.delete_env(:chesstrainer, key) + defp restore_env(key, value), do: Application.put_env(:chesstrainer, key, value) end diff --git a/test/chesstrainer_web/controllers/page_controller_test.exs b/test/chesstrainer_web/controllers/page_controller_test.exs index e72c266..bbd96c5 100644 --- a/test/chesstrainer_web/controllers/page_controller_test.exs +++ b/test/chesstrainer_web/controllers/page_controller_test.exs @@ -180,6 +180,29 @@ defmodule ChesstrainerWeb.PageControllerTest do assert LazyHTML.text(LazyHTML.query(document, ".rating-note strong")) == "0" end + test "renders the coming soon page while prelaunch is on", %{conn: conn} do + previous = Application.get_env(:chesstrainer, :prelaunch) + on_exit(fn -> restore_env(:prelaunch, previous) end) + Application.put_env(:chesstrainer, :prelaunch, true) + + html = conn |> get(~p"/") |> html_response(200) + + assert html =~ "coming soon" + assert html =~ "Master the" + refute html =~ "Try today" + end + + test "hides the mailing list when it is disabled", %{conn: conn} do + previous = Application.get_env(:chesstrainer, :mailing_list_enabled) + on_exit(fn -> restore_env(:mailing_list_enabled, previous) end) + Application.put_env(:chesstrainer, :mailing_list_enabled, false) + + html = conn |> get(~p"/") |> html_response(200) + + refute html =~ ~s(id="mailing-list-form") + refute html =~ "Join the list" + end + test "renders the mailing list signup form", %{conn: conn} do html = conn |> get(~p"/") |> html_response(200) document = LazyHTML.from_document(html) @@ -305,4 +328,7 @@ defmodule ChesstrainerWeb.PageControllerTest do assert html =~ "Browse puzzles" assert html =~ ~s(href="/endgames") end + + defp restore_env(key, nil), do: Application.delete_env(:chesstrainer, key) + defp restore_env(key, value), do: Application.put_env(:chesstrainer, key, value) end diff --git a/test/chesstrainer_web/controllers/robots_controller_test.exs b/test/chesstrainer_web/controllers/robots_controller_test.exs index 0f0adfe..c8eb6b0 100644 --- a/test/chesstrainer_web/controllers/robots_controller_test.exs +++ b/test/chesstrainer_web/controllers/robots_controller_test.exs @@ -1,5 +1,5 @@ defmodule ChesstrainerWeb.RobotsControllerTest do - use ChesstrainerWeb.ConnCase, async: true + use ChesstrainerWeb.ConnCase, async: false alias ChesstrainerWeb.Endpoint @@ -18,5 +18,20 @@ defmodule ChesstrainerWeb.RobotsControllerTest do assert [content_type] = get_resp_header(conn, "content-type") assert content_type =~ "text/plain" end + + test "disallows crawlers while prelaunch is on", %{conn: conn} do + previous = Application.get_env(:chesstrainer, :prelaunch) + on_exit(fn -> restore_env(:prelaunch, previous) end) + Application.put_env(:chesstrainer, :prelaunch, true) + + body = conn |> get(~p"/robots.txt") |> response(200) + + assert body =~ "User-agent: *" + assert body =~ "Disallow: /" + refute body =~ "Allow: /" + end end + + defp restore_env(key, nil), do: Application.delete_env(:chesstrainer, key) + defp restore_env(key, value), do: Application.put_env(:chesstrainer, key, value) end diff --git a/test/chesstrainer_web/plugs/prelaunch_test.exs b/test/chesstrainer_web/plugs/prelaunch_test.exs new file mode 100644 index 0000000..43acc04 --- /dev/null +++ b/test/chesstrainer_web/plugs/prelaunch_test.exs @@ -0,0 +1,85 @@ +defmodule ChesstrainerWeb.Plugs.PrelaunchTest do + use ChesstrainerWeb.ConnCase, async: false + + import Chesstrainer.AccountsFixtures + import Phoenix.LiveViewTest + + alias Chesstrainer.Accounts.User + alias Chesstrainer.Repo + + setup do + previous = Application.get_env(:chesstrainer, :prelaunch) + on_exit(fn -> restore_env(:prelaunch, previous) end) + Application.put_env(:chesstrainer, :prelaunch, true) + :ok + end + + test "allows the public pages, legal pages, health, and admin login", %{conn: conn} do + assert conn |> get(~p"/") |> html_response(200) + assert conn |> get(~p"/privacy") |> html_response(200) + assert conn |> get(~p"/terms-conditions") |> html_response(200) + assert conn |> get(~p"/health") |> response(200) + assert conn |> get(~p"/admin/log-in") |> html_response(200) + end + + test "hides public auth links and start training", %{conn: conn} do + html = conn |> get(~p"/") |> html_response(200) + + refute html =~ ">Log in<" + refute html =~ ">Register<" + refute html =~ "Start training" + end + + test "the hidden admin login uses the admin form action", %{conn: conn} do + html = conn |> get(~p"/admin/log-in") |> html_response(200) + + assert html =~ ~s(action="/admin/log-in") + refute html =~ "Sign up" + end + + test "pauses the public login route", %{conn: conn} do + assert conn |> get(~p"/users/log-in") |> redirected_to() == "/" + end + + test "admin login redirects to the admin area", %{conn: conn} do + user = + user_fixture() + |> Ecto.Changeset.change(role: :admin) + |> Repo.update!() + + conn = + post(conn, ~p"/admin/log-in", + user: %{email: user.email, password: "hello world!", remember_me: "true"} + ) + + assert redirected_to(conn) == "/admin/endgames" + end + + test "redirects blocked routes to the home page", %{conn: conn} do + conn = get(conn, ~p"/train") + + assert redirected_to(conn) == "/" + assert get_resp_header(conn, "x-robots-tag") == ["noindex, nofollow"] + end + + test "redirects registration and unknown pages", %{conn: conn} do + assert conn |> get(~p"/users/register") |> redirected_to() == "/" + assert conn |> get("/definitely-not-a-page") |> redirected_to() == "/" + end + + test "blocks direct registration LiveView requests", %{conn: conn} do + assert {:error, {:redirect, %{to: "/"}}} = live(conn, ~p"/users/register") + end + + test "blocks registration reached through LiveView navigation", %{conn: conn} do + {:ok, view, _html} = live(conn, ~p"/admin/log-in") + + assert {:error, {:redirect, %{to: "/"}}} = + live_redirect(view, to: ~p"/users/register") + + assert Repo.aggregate(User, :count) == 0 + end + + defp restore_env(key, nil), do: Application.delete_env(:chesstrainer, key) + defp restore_env(key, value), do: Application.put_env(:chesstrainer, key, value) +end