Transactional mail, crawler metadata, and asset measurement (#179)

* Send transactional email from no-reply@mail.innersquare.app

Centralise the sender identity, reply-to address and SES configuration set in Chesstrainer.Mail so no notifier can drift. Add MAIL_REDIRECT_TO for smoke tests and a mix mail.check task that exercises the SES mailbox simulators, and document the setup in the deploy guide and .env.example.

* Tighten crawler metadata and keep play pages out of search

Canonical URLs no longer carry query strings, public pages get an OG image, WebSite JSON-LD and a per-page language, and the sitemap dates the landing page only. Play and guest-training routes are marked noindex so tens of thousands of near-identical pages stay out of the index.

* Measure built asset sizes with mix assets.sizes

Report raw, gzip and brotli sizes for built JS and CSS, and record the current numbers plus the board-code split recommendation in docs/assets.md.
This commit is contained in:
2026-11-17 10:29:45 +01:00
committed by GitHub
parent b33c5e334a
commit 37e0ac8e56
24 changed files with 666 additions and 44 deletions
+4
View File
@@ -7,6 +7,10 @@ MAILING_LIST_ENABLED=false
SES_REGION=eu-north-1 SES_REGION=eu-north-1
SES_ACCESS_KEY_ID=AKIA... SES_ACCESS_KEY_ID=AKIA...
SES_SECRET_ACCESS_KEY=... SES_SECRET_ACCESS_KEY=...
SES_CONFIGURATION_SET=my-first-configuration-set
# Optional: override the sender or send everything to one address while testing.
# MAIL_FROM=no-reply@mail.innersquare.app
# MAIL_REDIRECT_TO=you@example.com
TABLEBASE_PATH= TABLEBASE_PATH=
MATOMO_URL=https://analytics.owenrees.eu/ MATOMO_URL=https://analytics.owenrees.eu/
+1 -1
View File
@@ -15,7 +15,7 @@ config :chesstrainer, :branding,
wordmark: "INNERSQUARE", wordmark: "INNERSQUARE",
tagline: "Endgame Trainer", tagline: "Endgame Trainer",
support_email: "support@innersquare.app", support_email: "support@innersquare.app",
mail_from: "no-reply@innersquare.app" mail_from: "no-reply@mail.innersquare.app"
# Prelaunch gating. Production sets these from PRELAUNCH and # Prelaunch gating. Production sets these from PRELAUNCH and
# MAILING_LIST_ENABLED; dev and test use these defaults. # MAILING_LIST_ENABLED; dev and test use these defaults.
+18
View File
@@ -28,6 +28,24 @@ if mailing_list_enabled = System.get_env("MAILING_LIST_ENABLED") do
config :chesstrainer, :mailing_list_enabled, mailing_list_enabled in ~w(true 1) config :chesstrainer, :mailing_list_enabled, mailing_list_enabled in ~w(true 1)
end end
# Sender address override. The default lives in config/config.exs; this lets a
# deploy try a different From address (for example a new sending subdomain)
# without a rebuild.
if mail_from = System.get_env("MAIL_FROM") do
branding = Application.get_env(:chesstrainer, :branding, [])
config :chesstrainer, :branding, Keyword.put(branding, :mail_from, mail_from)
end
# SES configuration set stamped on every outgoing email. The set is what links
# a message to its SNS bounce and complaint notifications.
config :chesstrainer,
:ses_configuration_set,
System.get_env("SES_CONFIGURATION_SET", "my-first-configuration-set")
# Rewrite every recipient to one address while testing. Leave unset in normal
# operation; see `mix mail.check`.
config :chesstrainer, :mail_redirect_to, System.get_env("MAIL_REDIRECT_TO")
# Local Syzygy tablebases: set TABLEBASE_PATH to the directory holding the # Local Syzygy tablebases: set TABLEBASE_PATH to the directory holding the
# .rtbw/.rtbz files. When unset, the local backend stays disabled and lookups # .rtbw/.rtbz files. When unset, the local backend stays disabled and lookups
# fall back to Lichess. # fall back to Lichess.
+42
View File
@@ -141,6 +141,7 @@ MAILING_LIST_ENABLED=false
SES_REGION=eu-north-1 SES_REGION=eu-north-1
SES_ACCESS_KEY_ID=AKIA... SES_ACCESS_KEY_ID=AKIA...
SES_SECRET_ACCESS_KEY=... SES_SECRET_ACCESS_KEY=...
SES_CONFIGURATION_SET=my-first-configuration-set
MATOMO_URL=https://analytics.owenrees.eu/ MATOMO_URL=https://analytics.owenrees.eu/
MATOMO_SITE_ID=6 MATOMO_SITE_ID=6
@@ -162,6 +163,47 @@ pages and the guest trainer. Signed-in account and admin pages are excluded.
The privacy controls, Matomo server settings, retention, and opt-out behaviour The privacy controls, Matomo server settings, retention, and opt-out behaviour
are documented in `docs/analytics.md`. are documented in `docs/analytics.md`.
## Transactional email
Every outgoing email goes through `Chesstrainer.Mail`, which applies the same
house rules everywhere:
- **From**: `Inner Square Chess <no-reply@mail.innersquare.app>`. The address
lives on the `mail.` subdomain; SES verifies the parent domain, and subdomains
inherit that verification, so the subdomain does not need its own identity.
- **Reply-To**: `support@innersquare.app`. Replies reach a monitored inbox even
though the sender says `no-reply`.
- **SES configuration set**: `SES_CONFIGURATION_SET`, default
`my-first-configuration-set`. The set is what links a message to its SNS
bounce and complaint notifications. It must exist in `SES_REGION`.
Optional overrides:
```sh
MAIL_FROM=no-reply@mail.innersquare.app # try another sender without a rebuild
MAIL_REDIRECT_TO=you@example.com # rewrite every recipient (staging/smoke tests)
```
`MAIL_REDIRECT_TO` rewrites `to`, `cc` and `bcc` to one address, prefixes the
subject with the original recipients and adds an `X-Original-To` header, so a
redirected message explains itself. Leave it unset in normal operation.
Check delivery from the release environment:
```sh
bin/chesstrainer eval 'Mix.Task.run("mail.check", ["--to", "you@example.com"])'
```
or, in a checkout configured with the production SES variables,
`mix mail.check --to you@example.com`. The task sends to the given address plus
the SES mailbox simulators (`success@`, `bounce@`, `complaint@simulator...
amazonses.com`) so the configuration set's bounce and complaint path can be
exercised without touching a real inbox. Use `--no-simulators` to skip them.
DNS: the apex publishes DMARC (`p=quarantine`) with aggregate reports sent to
`dmarc@innersquare.app`, and `mail.innersquare.app` carries the custom MAIL FROM
SPF record and the SES feedback MX.
Generate the two secrets: Generate the two secrets:
```sh ```sh
+84
View File
@@ -0,0 +1,84 @@
# Asset bundle sizes
What the browser downloads, measured rather than guessed. Numbers below are
from the last production build (`mix assets.deploy`, minified and digested) and
were read with `mix assets.sizes`.
Re-measure after any asset change:
```sh
mix assets.deploy
mix assets.sizes
```
`mix assets.sizes` prints raw, gzip and brotli sizes for every built JS and CSS
file. Brotli shows as `-` when the `brotli` CLI is not installed.
## Current bundles
| File | Raw | Gzip |
| --- | ---: | ---: |
| `assets/js/app.js` (LiveView entry) | 219.7 KB | 69.2 KB |
| `assets/js/marketing.js` (controller pages) | 4.8 KB | 1.9 KB |
| `assets/css/app.css` | 94.2 KB | 17.3 KB |
Cached font files, served only when used: DM Sans variable 62.5 KB, DM Serif
Display 24.5 KB, DM Serif Display italic 24.4 KB, DM Sans italic 14.6 KB
(woff2, already compressed).
## What is in each bundle
`app.js` is a single entry loaded by every LiveView page. It contains:
| Part | Raw | Gzip |
| --- | ---: | ---: |
| `phoenix`, `phoenix_live_view`, `phoenix_html` | — | ~30 KB |
| `chessground` (`dist/chessground.min.js`) | 30.0 KB | 11.0 KB |
| `chess.js` (`dist/esm/chess.js`) | 107.1 KB | 23.9 KB |
| `topbar` | 4.3 KB | 1.5 KB |
| `nav`, `analytics`, hooks | ~8 KB | ~3 KB |
The library figures are the packages' own builds; esbuild's minification and
tree shaking mean the bundle total is smaller than the naive sum.
`marketing.js` is deliberately tiny: `phoenix_html`, the nav toggle and the
cookieless analytics loader. It has no LiveView, socket, hooks or topbar.
Controller pages (landing page, legal pages, 404) load it instead of `app.js`.
`app.css` is one Tailwind build for the whole site, including the three
chessground stylesheets (`chessground.base.css` 3.3 KB, `chessground.brown.css`
2.8 KB, `chessground.cburnett.css` 11.5 KB raw, ~4.7 KB gzipped together).
## Findings
1. **Board code is about half of `app.js` and most pages do not use it.**
chessground and chess.js are ~35 KB of the 69 KB gzip payload. They are
needed only by pages that render `ChessBoard`: guest training, play, review.
Profile, settings, the endgame list and every admin screen pay for them and
never instantiate a board.
2. **The marketing/public split is already right.** Public pages do not load
the LiveView runtime at all.
3. **Board CSS is in the global stylesheet.** ~4.7 KB gzipped of chess piece
and board styling reaches every page, including the landing page.
4. **Stale digested bundles accumulate.** `priv/static/assets` currently holds
three generations of `app-*.js` and `app-*.css`. They are not linked but do
bloat the release. `mix phx.digest.clean --age 0` (or deploying from a clean
build) removes them.
## Recommendation (not applied)
Split the board libraries out of the LiveView entry:
- Load `chessground` and `chess.js` with a dynamic `import()` inside
`assets/js/hooks/chessBoard.js` and build with esbuild `--splitting
--format=esm`. Pages without a board then never fetch the chunk; board pages
fetch it once, in parallel with the hook mounting.
- Expected result: `app.js` drops from ~69 KB to ~35 KB gzip on most
authenticated pages, with a separate ~35 KB board chunk fetched only where
needed.
- Move the chessground stylesheets into the board chunk's CSS (or a second CSS
entry loaded only on board pages) to take ~4.7 KB off every page.
- Set a budget in CI once the split lands: `app.js` ≤ 40 KB gzip, board chunk
≤ 40 KB gzip, `marketing.js` ≤ 2 KB gzip, `app.css` ≤ 20 KB gzip.
No build configuration was changed as part of this measurement.
+2 -7
View File
@@ -2,20 +2,15 @@ defmodule Chesstrainer.Accounts.UserNotifier do
import Swoosh.Email import Swoosh.Email
alias Chesstrainer.Branding alias Chesstrainer.Branding
alias Chesstrainer.Mailer alias Chesstrainer.Mail
# Delivers the email using the application mailer. # Delivers the email using the application mailer.
defp deliver(recipient, subject, body) do defp deliver(recipient, subject, body) do
email =
new() new()
|> to(recipient) |> to(recipient)
|> from({Branding.name(), Branding.mail_from()})
|> subject(subject) |> subject(subject)
|> text_body(body) |> text_body(body)
|> Mail.deliver()
with {:ok, _metadata} <- Mailer.deliver(email) do
{:ok, email}
end
end end
@doc """ @doc """
+1 -1
View File
@@ -12,7 +12,7 @@ defmodule Chesstrainer.Branding do
wordmark: "INNERSQUARE", wordmark: "INNERSQUARE",
tagline: "Endgame Trainer", tagline: "Endgame Trainer",
support_email: "support@innersquare.app", support_email: "support@innersquare.app",
mail_from: "no-reply@innersquare.app" mail_from: "no-reply@mail.innersquare.app"
] ]
@doc "The display name, e.g. `\"Lucid Chess\"`." @doc "The display name, e.g. `\"Lucid Chess\"`."
+82
View File
@@ -0,0 +1,82 @@
defmodule Chesstrainer.Mail do
@moduledoc """
House rules for every outgoing email.
Notifiers build the message body and hand it here, so the sender identity,
reply-to address, SES configuration set and the test redirect are applied in
exactly one place and no sender can forget them.
The From address lives on the `mail.` subdomain so transactional mail is
distinct from the addresses that receive mail on the apex domain. SES
verification of the parent domain covers the subdomain, so no separate
identity is required for the From header to be accepted.
"""
alias Chesstrainer.Branding
alias Chesstrainer.Mailer
@default_configuration_set "my-first-configuration-set"
@doc """
Applies the house rules and delivers the email.
Returns `{:ok, email}` so notifiers can report the message they sent.
"""
def deliver(%Swoosh.Email{} = email) do
email = prepare(email)
with {:ok, _metadata} <- Mailer.deliver(email) do
{:ok, email}
end
end
@doc """
Applies the house rules without delivering.
Exposed so tooling (such as `mix mail.check`) can inspect or send the exact
message the application would send.
"""
def prepare(%Swoosh.Email{} = email) do
email
|> Swoosh.Email.from({Branding.name(), Branding.mail_from()})
|> Swoosh.Email.reply_to(Branding.support_email())
|> Swoosh.Email.put_provider_option(:configuration_set_name, configuration_set())
|> redirect()
end
defp configuration_set do
Application.get_env(:chesstrainer, :ses_configuration_set, @default_configuration_set)
end
# Rewrites every recipient to one address so a staging or production smoke
# test can send through real SES without reaching users. The original
# recipients stay in the subject and in an `X-Original-To` header so the
# redirected message explains itself.
defp redirect(email) do
case Application.get_env(:chesstrainer, :mail_redirect_to) do
address when is_binary(address) and address != "" ->
originals = recipients(email)
require Logger
Logger.warning("mail redirect: #{Enum.join(originals, ", ")} -> #{address}")
%{email | to: [{"", address}], cc: [], bcc: []}
|> Swoosh.Email.header("X-Original-To", Enum.join(originals, ", "))
|> Swoosh.Email.subject("[→ #{Enum.join(originals, ", ")}] #{email.subject}")
_unset ->
email
end
end
defp recipients(email) do
[email.to, email.cc, email.bcc]
|> List.flatten()
|> Enum.reject(&is_nil/1)
|> Enum.map(fn
{_name, address} -> address
address when is_binary(address) -> address
end)
end
end
+2 -8
View File
@@ -6,7 +6,7 @@ defmodule Chesstrainer.MailingList.Notifier do
import Swoosh.Email import Swoosh.Email
alias Chesstrainer.Branding alias Chesstrainer.Branding
alias Chesstrainer.Mailer alias Chesstrainer.Mail
@doc """ @doc """
Delivers the confirmation email for a mailing-list subscription. Delivers the confirmation email for a mailing-list subscription.
@@ -30,16 +30,10 @@ defmodule Chesstrainer.MailingList.Notifier do
end end
defp deliver(recipient, subject, body) do defp deliver(recipient, subject, body) do
email =
new() new()
|> to(recipient) |> to(recipient)
|> from({Branding.name(), Branding.mail_from()})
|> reply_to(Branding.support_email())
|> subject(subject) |> subject(subject)
|> text_body(body) |> text_body(body)
|> Mail.deliver()
with {:ok, _metadata} <- Mailer.deliver(email) do
{:ok, email}
end
end end
end end
+1
View File
@@ -107,6 +107,7 @@ defmodule ChesstrainerWeb do
alias Phoenix.LiveView.JS alias Phoenix.LiveView.JS
alias Chesstrainer.Branding alias Chesstrainer.Branding
alias ChesstrainerWeb.Layouts alias ChesstrainerWeb.Layouts
alias ChesstrainerWeb.SEO
# Routes generation with the ~p sigil # Routes generation with the ~p sigil
unquote(verified_routes()) unquote(verified_routes())
+2 -1
View File
@@ -368,7 +368,8 @@ defmodule ChesstrainerWeb.Layouts do
matomo_url: url, matomo_url: url,
matomo_site_id: site_id && to_string(site_id), matomo_site_id: site_id && to_string(site_id),
analytics_enabled: analytics_enabled:
is_binary(url) and url != "" and site_id not in [nil, ""] and is_nil(user) is_binary(url) and byte_size(url) > 0 and is_binary(site_id) and byte_size(site_id) > 0 and
is_nil(user)
) )
~H""" ~H"""
@@ -1,5 +1,5 @@
<!DOCTYPE html> <!DOCTYPE html>
<html lang="en"> <html lang={assigns[:lang] || "en"}>
<head> <head>
<meta charset="utf-8" /> <meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" /> <meta name="viewport" content="width=device-width, initial-scale=1" />
@@ -30,7 +30,24 @@
content={assigns[:meta_description]} content={assigns[:meta_description]}
/> />
<meta :if={assigns[:canonical_url]} property="og:url" content={assigns[:canonical_url]} /> <meta :if={assigns[:canonical_url]} property="og:url" content={assigns[:canonical_url]} />
<meta :if={assigns[:meta_description]} name="twitter:card" content="summary" /> <meta
:if={assigns[:meta_description]}
property="og:image"
content={assigns[:og_image_url] || SEO.og_image_url()}
/>
<meta :if={assigns[:meta_description]} property="og:image:width" content="1200" />
<meta :if={assigns[:meta_description]} property="og:image:height" content="630" />
<meta
:if={assigns[:meta_description]}
property="og:image:alt"
content={"#{Branding.name()} — #{Branding.tagline()}"}
/>
<meta :if={assigns[:meta_description]} name="twitter:card" content="summary_large_image" />
<meta
:if={assigns[:meta_description]}
name="twitter:image"
content={assigns[:og_image_url] || SEO.og_image_url()}
/>
<meta <meta
:if={assigns[:meta_description]} :if={assigns[:meta_description]}
name="twitter:title" name="twitter:title"
@@ -73,6 +90,9 @@
> >
</script> </script>
<Layouts.theme_script /> <Layouts.theme_script />
<script :if={assigns[:json_ld]} type="application/ld+json">
<%= raw(assigns[:json_ld]) %>
</script>
</head> </head>
<body> <body>
<a <a
@@ -6,6 +6,7 @@ defmodule ChesstrainerWeb.PageController do
alias Chesstrainer.Branding alias Chesstrainer.Branding
alias Chesstrainer.DailyPuzzles alias Chesstrainer.DailyPuzzles
alias Chesstrainer.Endgames alias Chesstrainer.Endgames
alias ChesstrainerWeb.SEO
@description "Short, focused endgame puzzles against tablebase-perfect defence. " <> @description "Short, focused endgame puzzles against tablebase-perfect defence. " <>
"Learn to see the winning move and make the endgame your strongest phase." "Learn to see the winning move and make the endgame your strongest phase."
@@ -15,13 +16,15 @@ defmodule ChesstrainerWeb.PageController do
render_coming_soon(conn) render_coming_soon(conn)
else else
endgames = Endgames.curated_endgames() endgames = Endgames.curated_endgames()
canonical_url = SEO.canonical_url(conn)
conn conn
|> assign(:js_entry, ~p"/assets/js/marketing.js") |> assign(:js_entry, ~p"/assets/js/marketing.js")
|> assign(:page_title, Branding.home_title()) |> assign(:page_title, Branding.home_title())
|> assign(:title_suffix, "") |> assign(:title_suffix, "")
|> assign(:meta_description, @description) |> assign(:meta_description, @description)
|> assign(:canonical_url, current_url(conn)) |> assign(:canonical_url, canonical_url)
|> assign(:json_ld, SEO.json_ld(canonical_url))
|> assign(:mailing_list_enabled, mailing_list_enabled?()) |> assign(:mailing_list_enabled, mailing_list_enabled?())
|> render(:home, |> render(:home,
endgames: endgames, endgames: endgames,
@@ -43,7 +46,7 @@ defmodule ChesstrainerWeb.PageController do
:meta_description, :meta_description,
"How #{Branding.name()} collects, uses, and protects your personal data." "How #{Branding.name()} collects, uses, and protects your personal data."
) )
|> assign(:canonical_url, current_url(conn)) |> assign(:canonical_url, SEO.canonical_url(conn))
|> render(:privacy) |> render(:privacy)
end end
@@ -53,7 +56,7 @@ defmodule ChesstrainerWeb.PageController do
|> assign(:page_title, Branding.title("Terms & Conditions")) |> assign(:page_title, Branding.title("Terms & Conditions"))
|> assign(:title_suffix, "") |> assign(:title_suffix, "")
|> assign(:meta_description, "The terms that apply when you use #{Branding.name()}.") |> assign(:meta_description, "The terms that apply when you use #{Branding.name()}.")
|> assign(:canonical_url, current_url(conn)) |> assign(:canonical_url, SEO.canonical_url(conn))
|> render(:terms_conditions) |> render(:terms_conditions)
end end
@@ -66,7 +69,8 @@ defmodule ChesstrainerWeb.PageController do
:meta_description, :meta_description,
"Éditeur, hébergeur et informations légales de #{Branding.name()}." "Éditeur, hébergeur et informations légales de #{Branding.name()}."
) )
|> assign(:canonical_url, current_url(conn)) |> assign(:canonical_url, SEO.canonical_url(conn))
|> assign(:lang, "fr")
|> render(:mentions_legales) |> render(:mentions_legales)
end end
@@ -86,7 +90,7 @@ defmodule ChesstrainerWeb.PageController do
|> assign(:page_title, Branding.home_title()) |> assign(:page_title, Branding.home_title())
|> assign(:title_suffix, "") |> assign(:title_suffix, "")
|> assign(:meta_description, @description) |> assign(:meta_description, @description)
|> assign(:canonical_url, current_url(conn)) |> assign(:canonical_url, SEO.canonical_url(conn))
|> assign(:noindex, true) |> assign(:noindex, true)
|> assign(:mailing_list_enabled, mailing_list_enabled?()) |> assign(:mailing_list_enabled, mailing_list_enabled?())
|> render(:coming_soon) |> render(:coming_soon)
@@ -11,28 +11,37 @@ defmodule ChesstrainerWeb.SitemapController do
use ChesstrainerWeb, :controller use ChesstrainerWeb, :controller
def index(conn, _params) do def index(conn, _params) do
urls = [ # The landing page changes every day (daily puzzle, counts), so its
url(conn, ~p"/"), # lastmod is honest. The legal pages have no stored modification time, and
url(conn, ~p"/privacy"), # an invented lastmod is worse than none.
url(conn, ~p"/terms-conditions"), entries = [
url(conn, ~p"/mentions-legales") {url(conn, ~p"/"), Date.utc_today()},
{url(conn, ~p"/privacy"), nil},
{url(conn, ~p"/terms-conditions"), nil},
{url(conn, ~p"/mentions-legales"), nil}
] ]
conn conn
|> put_resp_content_type("application/xml") |> put_resp_content_type("application/xml")
|> send_resp(200, render_sitemap(urls)) |> send_resp(200, render_sitemap(entries))
end end
defp render_sitemap(urls) do defp render_sitemap(entries) do
entries = Enum.map_join(urls, &" <url><loc>#{escape(&1)}</loc></url>\n") urls =
Enum.map_join(entries, fn {loc, lastmod} ->
" <url><loc>#{escape(loc)}</loc>#{lastmod_entry(lastmod)}</url>\n"
end)
""" """
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"> <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
#{entries}</urlset> #{urls}</urlset>
""" """
end end
defp lastmod_entry(nil), do: ""
defp lastmod_entry(%Date{} = date), do: "<lastmod>#{Date.to_iso8601(date)}</lastmod>"
# Templates escape automatically; this response is built as a plain string, # Templates escape automatically; this response is built as a plain string,
# so XML-significant characters must be escaped here. # so XML-significant characters must be escaped here.
defp escape(value) do defp escape(value) do
+3 -1
View File
@@ -111,7 +111,9 @@ defmodule ChesstrainerWeb.Router do
end end
scope "/", ChesstrainerWeb do scope "/", ChesstrainerWeb do
pipe_through [:browser] # App surface: play pages, auth forms and guest training are reachable
# without a session but must never appear in search results.
pipe_through [:browser, :noindex]
live_session :current_user, live_session :current_user,
on_mount: [ on_mount: [
+49
View File
@@ -0,0 +1,49 @@
defmodule ChesstrainerWeb.SEO do
@moduledoc """
Absolute URLs and crawler metadata for controller-rendered pages.
Search engines need absolute URLs, so these helpers read the endpoint's
configured host rather than the request host (which is a proxy address).
Canonical URLs deliberately drop the query string: campaign parameters such
as `?utm_source=...` must not become canonical pages of their own.
"""
alias Chesstrainer.Branding
alias ChesstrainerWeb.Endpoint
@og_image "/images/og.png"
@logo "/apple-touch-icon.png"
@doc "The request path as an absolute canonical URL, without any query string."
def canonical_url(conn) do
Phoenix.VerifiedRoutes.unverified_url(conn, conn.request_path)
end
@doc "Absolute URL of the social share image."
def og_image_url, do: Endpoint.url() <> @og_image
@doc """
JSON-LD for the site, encoded as a string ready for a
`<script type="application/ld+json">` block.
"""
def json_ld(url) do
%{
"@context" => "https://schema.org",
"@graph" => [
%{
"@type" => "WebSite",
"name" => Branding.name(),
"url" => url
},
%{
"@type" => "Organization",
"name" => Branding.name(),
"url" => url,
"logo" => Endpoint.url() <> @logo
}
]
}
|> Jason.encode!()
end
end
+101
View File
@@ -0,0 +1,101 @@
defmodule Mix.Tasks.Assets.Sizes do
use Mix.Task
@shortdoc "Report raw, gzip and brotli sizes of built assets"
@moduledoc """
Prints the size of every built JavaScript and CSS file under
`priv/static/assets`, uncompressed and compressed, so bundle changes can be
measured rather than guessed.
mix assets.sizes
Run it after `mix assets.build` (development, unminified) or
`mix assets.deploy` (production, minified and digested). Production numbers
are the ones that matter: they are what the browser downloads.
Brotli sizes are shown as a dash when the `brotli` CLI is not installed.
"""
@assets_globs ["priv/static/assets/js/**/*.js", "priv/static/assets/css/**/*.css"]
@impl true
def run(_argv) do
files = @assets_globs |> Enum.flat_map(&Path.wildcard/1) |> Enum.sort()
if files == [] do
Mix.raise("no built assets found under priv/static/assets; run mix assets.build")
end
rows = Enum.map(files, &measure/1)
print(rows)
end
defp measure(path) do
contents = File.read!(path)
%{
path: Path.relative_to_cwd(path),
raw: byte_size(contents),
gzip: byte_size(:zlib.gzip(contents)),
brotli: brotli_size(path)
}
end
defp brotli_size(path) do
with executable when is_binary(executable) <- System.find_executable("brotli"),
{output, 0} <- System.cmd(executable, ["-q", "11", "-c", path], into: "") do
byte_size(output)
else
_unavailable -> nil
end
end
defp print(rows) do
widths = column_widths(rows)
header = [
pad("file", widths.path),
pad("raw", widths.raw, :right),
pad("gzip", widths.gzip, :right),
pad("brotli", widths.brotli, :right)
]
Mix.shell().info(Enum.join(header, " "))
Mix.shell().info(String.duplicate("-", Enum.sum(Map.values(widths)) + 6))
Enum.each(rows, &print_row(&1, widths))
end
defp print_row(row, widths) do
values = [
pad(row.path, widths.path),
pad(human(row.raw), widths.raw, :right),
pad(human(row.gzip), widths.gzip, :right),
pad(human(row.brotli), widths.brotli, :right)
]
Mix.shell().info(Enum.join(values, " "))
end
defp column_widths(rows) do
%{
path: rows |> Enum.map(&String.length(&1.path)) |> Enum.max(),
raw: rows |> Enum.map(&String.length(human(&1.raw))) |> Enum.max(),
gzip: rows |> Enum.map(&String.length(human(&1.gzip))) |> Enum.max(),
brotli: rows |> Enum.map(&String.length(human(&1.brotli))) |> Enum.max()
}
end
defp pad(value, width, align \\ :left) do
value = to_string(value)
case align do
:right -> String.pad_leading(value, width)
:left -> String.pad_trailing(value, width)
end
end
defp human(nil), do: "-"
defp human(bytes) when bytes < 1024, do: "#{bytes} B"
defp human(bytes), do: "#{Float.round(bytes / 1024, 1)} KB"
end
+84
View File
@@ -0,0 +1,84 @@
defmodule Mix.Tasks.Mail.Check do
use Mix.Task
@shortdoc "Send test email through the configured mailer and SES simulators"
@moduledoc """
Sends a test message through the application mailer, applying the same house
rules as real mail: From identity, Reply-To, and the SES configuration set.
mix mail.check --to you@example.com
By default it also sends to the SES mailbox simulator addresses so bounce and
complaint wiring can be exercised without touching a real inbox:
* `success@simulator.amazonses.com`
* `bounce@simulator.amazonses.com`
* `complaint@simulator.amazonses.com`
The simulators only do something when the mailer is the SES adapter. Pass
`--no-simulators` to send only to the given address.
If `MAIL_REDIRECT_TO` is set, every recipient is rewritten to that address
first (including the simulators), so this task cannot reach users even in
production.
"""
alias Chesstrainer.Mail
@simulators [
"success@simulator.amazonses.com",
"bounce@simulator.amazonses.com",
"complaint@simulator.amazonses.com"
]
@impl true
def run(argv) do
{opts, _args} = OptionParser.parse!(argv, strict: [to: :string, simulators: :boolean])
recipient =
opts[:to] ||
Mix.raise("pass the address to check: mix mail.check --to you@example.com")
Mix.Task.run("app.start")
targets = if opts[:simulators] == false, do: [recipient], else: [recipient | @simulators]
Mix.shell().info("adapter: #{inspect(adapter())}")
if redirect(), do: Mix.shell().info("redirect: every message goes to #{redirect()}")
Enum.each(targets, &send_message/1)
end
defp send_message(recipient) do
email =
Swoosh.Email.new()
|> Swoosh.Email.to(recipient)
|> Swoosh.Email.subject("Mail check #{DateTime.utc_now() |> DateTime.to_iso8601()}")
|> Swoosh.Email.text_body(
"This is a delivery check from the chess trainer. " <>
"If you can read it, the mailer, sender identity and configuration set are wired up."
)
|> Mail.prepare()
case Chesstrainer.Mailer.deliver(email) do
{:ok, metadata} ->
Mix.shell().info("sent #{recipient} #{format_metadata(metadata)}")
{:error, reason} ->
Mix.shell().error("failed #{recipient} #{inspect(reason)}")
end
end
defp format_metadata(%{id: id}) when is_binary(id), do: "(message id #{id})"
defp format_metadata(_metadata), do: ""
defp adapter do
:chesstrainer
|> Application.get_env(Chesstrainer.Mailer, [])
|> Keyword.get(:adapter)
end
defp redirect, do: Application.get_env(:chesstrainer, :mail_redirect_to)
end
Binary file not shown.

After

Width:  |  Height:  |  Size: 34 KiB

+72
View File
@@ -0,0 +1,72 @@
defmodule Chesstrainer.MailTest do
use ExUnit.Case, async: false
import Swoosh.TestAssertions
alias Chesstrainer.Branding
alias Chesstrainer.Mail
setup do
previous_redirect = Application.get_env(:chesstrainer, :mail_redirect_to)
previous_set = Application.get_env(:chesstrainer, :ses_configuration_set)
on_exit(fn ->
restore_env(:mail_redirect_to, previous_redirect)
restore_env(:ses_configuration_set, previous_set)
end)
:ok
end
defp simple_email(recipient \\ "player@example.com") do
Swoosh.Email.new()
|> Swoosh.Email.to(recipient)
|> Swoosh.Email.subject("Confirmation instructions")
|> Swoosh.Email.text_body("Hello")
end
test "sends from the no-reply address on the mail subdomain" do
{:ok, email} = Mail.deliver(simple_email())
assert email.from == {Branding.name(), "no-reply@mail.innersquare.app"}
assert email.reply_to == {"", "support@innersquare.app"}
end
test "stamps the SES configuration set on the provider options" do
{:ok, email} = Mail.deliver(simple_email())
assert email.provider_options[:configuration_set_name] == "my-first-configuration-set"
end
test "the configuration set can be overridden by config" do
Application.put_env(:chesstrainer, :ses_configuration_set, "staging-set")
{:ok, email} = Mail.deliver(simple_email())
assert email.provider_options[:configuration_set_name] == "staging-set"
end
test "redirects every recipient when a test address is configured" do
Application.put_env(:chesstrainer, :mail_redirect_to, "ops@example.com")
email = simple_email("player@example.com")
{:ok, sent} = Mail.deliver(email)
assert sent.to == [{"", "ops@example.com"}]
assert sent.bcc == []
assert sent.cc == []
assert sent.subject == "[→ player@example.com] Confirmation instructions"
assert {"X-Original-To", "player@example.com"} in sent.headers
end
test "delivers the message it returns" do
{:ok, email} = Mail.deliver(simple_email())
assert_email_sent(to: "player@example.com", subject: "Confirmation instructions")
assert email.to == [{"", "player@example.com"}]
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
@@ -86,7 +86,11 @@ defmodule ChesstrainerWeb.PageControllerTest do
{~s(meta[property="og:title"]), Branding.home_title()}, {~s(meta[property="og:title"]), Branding.home_title()},
{~s(meta[property="og:description"]), @description}, {~s(meta[property="og:description"]), @description},
{~s(meta[property="og:url"]), canonical}, {~s(meta[property="og:url"]), canonical},
{~s(meta[name="twitter:card"]), "summary"}, {~s(meta[property="og:image"]), ChesstrainerWeb.SEO.og_image_url()},
{~s(meta[property="og:image:width"]), "1200"},
{~s(meta[property="og:image:height"]), "630"},
{~s(meta[name="twitter:card"]), "summary_large_image"},
{~s(meta[name="twitter:image"]), ChesstrainerWeb.SEO.og_image_url()},
{~s(meta[name="twitter:title"]), Branding.home_title()}, {~s(meta[name="twitter:title"]), Branding.home_title()},
{~s(meta[name="twitter:description"]), @description} {~s(meta[name="twitter:description"]), @description}
] do ] do
@@ -94,6 +98,36 @@ defmodule ChesstrainerWeb.PageControllerTest do
end end
end end
test "canonical URL drops query parameters", %{conn: conn} do
html = conn |> get("/?utm_source=newsletter&utm_medium=email") |> html_response(200)
document = LazyHTML.from_document(html)
assert [canonical] =
LazyHTML.attribute(LazyHTML.query(document, ~s(link[rel="canonical"])), "href")
assert canonical == ChesstrainerWeb.Endpoint.url() <> "/"
assert LazyHTML.attribute(LazyHTML.query(document, ~s(meta[property="og:url"])), "content") ==
[canonical]
end
test "home page publishes WebSite structured data", %{conn: conn} do
html = conn |> get(~p"/") |> html_response(200)
document = LazyHTML.from_document(html)
json =
document
|> LazyHTML.query(~s(script[type="application/ld+json"]))
|> LazyHTML.text()
|> Jason.decode!()
assert json["@context"] == "https://schema.org"
types = Enum.map(json["@graph"], & &1["@type"])
assert "WebSite" in types
assert "Organization" in types
end
test "GET /privacy renders the privacy policy", %{conn: conn} do test "GET /privacy renders the privacy policy", %{conn: conn} do
html = conn |> get(~p"/privacy") |> html_response(200) html = conn |> get(~p"/privacy") |> html_response(200)
document = LazyHTML.from_document(html) document = LazyHTML.from_document(html)
@@ -150,6 +184,7 @@ defmodule ChesstrainerWeb.PageControllerTest do
document = LazyHTML.from_document(html) document = LazyHTML.from_document(html)
assert LazyHTML.text(LazyHTML.query(document, "h1")) == "Mentions légales" assert LazyHTML.text(LazyHTML.query(document, "h1")) == "Mentions légales"
assert html =~ ~s(lang="fr")
assert html =~ "Owen REES" assert html =~ "Owen REES"
assert html =~ "929" assert html =~ "929"
assert html =~ "293 B" assert html =~ "293 B"
@@ -11,12 +11,19 @@ defmodule ChesstrainerWeb.SitemapControllerTest do
assert body =~ ~s(<?xml version="1.0" encoding="UTF-8"?>) assert body =~ ~s(<?xml version="1.0" encoding="UTF-8"?>)
assert body =~ ~s(<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">) assert body =~ ~s(<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">)
assert body =~ "<loc>#{base_url}/</loc>" assert body =~ "<loc>#{base_url}/</loc>"
assert body =~ "<lastmod>#{Date.utc_today() |> Date.to_iso8601()}</lastmod>"
assert body =~ "<loc>#{base_url}/privacy</loc>" assert body =~ "<loc>#{base_url}/privacy</loc>"
assert body =~ "<loc>#{base_url}/terms-conditions</loc>" assert body =~ "<loc>#{base_url}/terms-conditions</loc>"
assert body =~ "<loc>#{base_url}/mentions-legales</loc>" assert body =~ "<loc>#{base_url}/mentions-legales</loc>"
assert length(:binary.matches(body, "<url>")) == 4 assert length(:binary.matches(body, "<url>")) == 4
end end
test "only dates the landing page", %{conn: conn} do
body = conn |> get(~p"/sitemap.xml") |> response(200)
assert length(:binary.matches(body, "<lastmod>")) == 1
end
test "is served as XML", %{conn: conn} do test "is served as XML", %{conn: conn} do
conn = get(conn, ~p"/sitemap.xml") conn = get(conn, ~p"/sitemap.xml")
@@ -59,6 +59,15 @@ defmodule ChesstrainerWeb.EndgameLive.GuestTrainTest do
end end
describe "access" do describe "access" do
test "is marked noindex for crawlers", %{conn: conn} do
endgame = endgame_fixture()
seed_tablebase(endgame.fen, moves: grading_moves())
conn = get(conn, ~p"/guest-train")
assert get_resp_header(conn, "x-robots-tag") == ["noindex, nofollow"]
end
test "lets an anonymous visitor play a random puzzle", %{conn: conn} do test "lets an anonymous visitor play a random puzzle", %{conn: conn} do
endgame = endgame_fixture() endgame = endgame_fixture()
seed_tablebase(endgame.fen, moves: grading_moves()) seed_tablebase(endgame.fen, moves: grading_moves())
@@ -135,6 +135,15 @@ defmodule ChesstrainerWeb.EndgameLive.PlayTest do
end end
describe "mount" do describe "mount" do
test "is marked noindex for crawlers", %{conn: conn} do
endgame = endgame_fixture()
seed_tablebase(endgame.fen)
conn = get(conn, ~p"/endgames/#{endgame.public_code}/play")
assert get_resp_header(conn, "x-robots-tag") == ["noindex, nofollow"]
end
test "renders the chessboard hook div and pushes init_board", %{conn: conn} do test "renders the chessboard hook div and pushes init_board", %{conn: conn} do
endgame = endgame_fixture(color: :white) endgame = endgame_fixture(color: :white)
seed_tablebase(endgame.fen) seed_tablebase(endgame.fen)