Compare commits

..
7 Commits
44 changed files with 2030 additions and 113 deletions
+6
View File
@@ -2,6 +2,12 @@ SECRET_KEY_BASE=...
DATABASE_URL=... DATABASE_URL=...
PHX_HOST=innersquare.app PHX_HOST=innersquare.app
PORT=4000 PORT=4000
PRELAUNCH=true
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=...
TABLEBASE_PATH=
MATOMO_URL=https://analytics.owenrees.eu/
MATOMO_SITE_ID=6
+5 -1
View File
@@ -31,8 +31,12 @@ chesstrainer-*.tar
# Ignore ETS table backups # Ignore ETS table backups
/priv/static/backups/ /priv/static/backups/
# Ignore digested assets cache. # Ignore digested assets cache and generated digests.
/priv/static/cache_manifest.json /priv/static/cache_manifest.json
/priv/static/favicon-*.ico
/priv/static/fonts/*-*.woff2
/priv/static/images/*-*.svg
/priv/static/images/*.svg.gz
# In case you use Node.js/npm, you want to ignore these. # In case you use Node.js/npm, you want to ignore these.
npm-debug.log npm-debug.log
+5
View File
@@ -17,6 +17,11 @@ config :chesstrainer, :branding,
support_email: "support@innersquare.app", support_email: "support@innersquare.app",
mail_from: "no-reply@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, config :chesstrainer, :scopes,
user: [ user: [
default: true, default: true,
+5 -1
View File
@@ -15,11 +15,15 @@ config :chesstrainer, ChesstrainerWeb.Endpoint,
force_ssl: [ force_ssl: [
rewrite_on: [:x_forwarded_proto], rewrite_on: [:x_forwarded_proto],
exclude: [ exclude: [
# paths: ["/health"], paths: ["/health"],
hosts: ["localhost", "127.0.0.1"] 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 # Configure Swoosh API Client
config :swoosh, api_client: Swoosh.ApiClient.Req config :swoosh, api_client: Swoosh.ApiClient.Req
+11 -5
View File
@@ -20,6 +20,14 @@ if System.get_env("PHX_SERVER") do
config :chesstrainer, ChesstrainerWeb.Endpoint, server: true config :chesstrainer, ChesstrainerWeb.Endpoint, server: true
end 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 # 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.
@@ -140,11 +148,9 @@ if config_env() == :prod do
config :chesstrainer, ChesstrainerWeb.Endpoint, config :chesstrainer, ChesstrainerWeb.Endpoint,
url: [host: host, port: 443, scheme: "https"], url: [host: host, port: 443, scheme: "https"],
http: [ http: [
# Enable IPv6 and bind on all interfaces. # The release runs behind Caddy, so bind to loopback and let the proxy
# Set it to {0, 0, 0, 0, 0, 0, 0, 1} for local network only access. # handle public traffic.
# See the documentation on https://bandit.hexdocs.pm/Bandit.html#t:options/0 ip: {127, 0, 0, 1}
# for details about using IPv6 vs IPv4 and loopback vs public addresses.
ip: {0, 0, 0, 0, 0, 0, 0, 0}
], ],
secret_key_base: secret_key_base secret_key_base: secret_key_base
+15
View File
@@ -0,0 +1,15 @@
# Reference block for the shared Caddyfile.
#
# This file is not installed automatically. On the shared VPS, add this block
# to the existing Caddy config by hand, then validate and reload Caddy.
#
# The app listens on loopback only; Caddy is the public entry point.
innersquare.app {
encode zstd gzip
reverse_proxy 127.0.0.1:4100
}
www.innersquare.app {
redir https://innersquare.app{uri} permanent
}
+436
View File
@@ -0,0 +1,436 @@
# Production deployment
Phoenix release on the shared Ubuntu VPS, behind Caddy, with Postgres in Docker.
```text
Internet
└─ Caddy :443
└─ Phoenix release 127.0.0.1:4100
└─ Postgres 127.0.0.1:5432
```
## Pinned versions
| Thing | Version |
|---|---|
| OS | Ubuntu 24.04.5 LTS, x86_64 |
| glibc | 2.39 |
| Erlang | 28.5 |
| Elixir | 1.19.5-otp-28 |
| Rust | 1.98.1 |
| Postgres | `postgres:18.0`, pinned directly in the unified compose |
| Caddy | 2.11.9 |
| Docker | 29.9.3 |
| Docker Compose | v5.7.0 |
| GitHub runner | `ubuntu-24.04` |
The release ships its own ERTS. The host needs the runtime libraries for the
Rust NIF (`libstdc++6`), OpenSSL, and CA certificates.
## Host prerequisites
A new Ubuntu 24.04 VPS needs:
- Docker Engine and the Compose plugin
- Caddy
- `curl`, `ca-certificates`, `libstdc++6`, `openssl`
- DNS and TLS for the domain
- A non-root deploy user with SSH access
Install the host libraries:
```sh
sudo apt update
sudo apt install -y curl ca-certificates libstdc++6 openssl
```
Install Docker and Caddy from their official repositories. The Caddy install
commands already used for the static site are in `deploy/static/README.md`.
Firewall:
```sh
sudo ufw allow OpenSSH
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp
sudo ufw enable
```
Do **not** open `4100` or `5432`. Phoenix binds to loopback, and Postgres is
published only on `127.0.0.1`.
DNS:
- `A`/`AAAA` for `innersquare.app` and `www` point at the VPS.
- Do not remove the existing mail records:
- root MX records for `support@innersquare.app`
- SES DKIM CNAMEs
- the `mail.innersquare.app` custom MAIL FROM MX/TXT records
- DMARC at `_dmarc.innersquare.app`
## Shared-host choices
- **Port 4100** is used for Phoenix because another BEAM process already owns
`4000` on this VPS.
- **Postgres runs as `chesstrainer-db`** in the VPS's unified
`docker-compose.yml` on `127.0.0.1:5432`; that port is free. The image
version is pinned directly in that file.
- **Caddy is shared and managed manually.** This repo ships a reference block
in `deploy/Caddyfile`; it is never installed automatically.
- The Postgres volume is named `chesstrainer_pgdata`, so it cannot collide with
other Docker projects.
## Directory layout
```text
/opt/chesstrainer/
├── releases/
│ ├── 20261109120000/
│ └── 20261109153000/
├── current -> releases/20261109153000
└── src/ # optional checkout of this repo / deploy scripts
```
`/etc/chesstrainer/env` is the application environment file, owned by
`root:root` with mode `0600`.
`/etc/chesstrainer/postgres.env` holds the Postgres container credentials,
also `root:root` and `0600`.
The app runs as the dedicated `chesstrainer` system user. It must own
`/opt/chesstrainer` so it can write `priv/static/backups`.
## Copy the deploy artifacts
Run these commands from a checkout of this repo on the VPS, or copy the
`deploy/` directory to `/opt/chesstrainer/src/deploy`.
```sh
sudo install -d -o root -g root /opt/chesstrainer/src/deploy
sudo cp -a deploy/. /opt/chesstrainer/src/deploy/
```
If you prefer to keep the checkout elsewhere, use that path in the commands
below.
## Application env file
`/etc/chesstrainer/env`:
```sh
SECRET_KEY_BASE=...
DATABASE_URL=ecto://chesstrainer:...@127.0.0.1:5432/chesstrainer_prod
PHX_HOST=innersquare.app
PORT=4100
POOL_SIZE=10
TRUST_FORWARDED_FOR=true
PRELAUNCH=true
MAILING_LIST_ENABLED=false
SES_REGION=eu-north-1
SES_ACCESS_KEY_ID=AKIA...
SES_SECRET_ACCESS_KEY=...
MATOMO_URL=https://analytics.owenrees.eu/
MATOMO_SITE_ID=6
# Optional:
# TABLEBASE_PATH=/path/to/syzygy
# RELEASE_COOKIE=...
```
The production endpoint binds to `127.0.0.1` only. Caddy is the public
entry point.
Generate the two secrets:
```sh
openssl rand -base64 64 # SECRET_KEY_BASE
openssl rand -hex 32 # Postgres password
```
### Secret key base
`SECRET_KEY_BASE` is required in production; the release raises at boot without
it. It signs cookies, session tokens, LiveView tokens, and mailing-list
confirmation links.
Generate it with `mix phx.gen.secret` or:
```sh
openssl rand -base64 64
```
Keep it stable. Rotating it signs every user out and invalidates outstanding
confirmation and unsubscribe links. Never reuse the dev/test value or commit it.
Verify it is set without printing it:
```sh
sudo awk -F= '/^SECRET_KEY_BASE=/{print length($2)}' /etc/chesstrainer/env
```
## Postgres env file
`/etc/chesstrainer/postgres.env`:
```sh
POSTGRES_USER=chesstrainer
POSTGRES_PASSWORD=...
POSTGRES_DB=chesstrainer_prod
```
Postgres 18 stores data under `/var/lib/postgresql/18/docker`, so the
Compose volume mounts the parent:
```yaml
volumes:
- chesstrainer_pgdata:/var/lib/postgresql
```
## First-time setup
Run as root or with sudo:
```sh
useradd --system --user-group \
--home-dir /opt/chesstrainer \
--create-home \
--shell /usr/sbin/nologin \
chesstrainer
install -d -o chesstrainer -g chesstrainer /opt/chesstrainer/releases
install -d -o chesstrainer -g chesstrainer /opt/chesstrainer/src
install -d -m 755 /etc/chesstrainer
install -m 600 /dev/null /etc/chesstrainer/env
install -m 600 /dev/null /etc/chesstrainer/postgres.env
chown root:root /etc/chesstrainer/env /etc/chesstrainer/postgres.env
```
Edit both files with `sudoedit` and set the generated secrets and
`DATABASE_URL`.
## Unified Compose: add Postgres
Add the `chesstrainer-db` service and `chesstrainer_pgdata` volume from
`deploy/postgres.compose.yml` to the VPS's existing unified
`docker-compose.yml`. Do not run the reference file as a separate project.
The image is pinned directly in the unified compose:
```yaml
image: postgres:18.0
```
For an immutable pin, replace it with the exact digest:
```yaml
image: postgres:18.0@sha256:...
```
There is no `POSTGRES_IMAGE` environment variable involved.
Because `postgres.env` is root-owned `0600`, run Compose with `sudo`:
```sh
sudo docker compose -f <UNIFIED_COMPOSE> config >/dev/null
sudo docker compose -f <UNIFIED_COMPOSE> up -d chesstrainer-db
sudo docker compose -f <UNIFIED_COMPOSE> ps chesstrainer-db
sudo docker compose -f <UNIFIED_COMPOSE> logs --tail=50 chesstrainer-db
```
Verify the database:
```sh
sudo docker compose -f <UNIFIED_COMPOSE> exec -T chesstrainer-db \
psql -U chesstrainer -d chesstrainer_prod -c 'select 1;'
```
To change the Postgres version:
```sh
# edit the image: line in the unified compose
sudo docker compose -f <UNIFIED_COMPOSE> pull chesstrainer-db
sudo docker compose -f <UNIFIED_COMPOSE> up -d chesstrainer-db
```
## systemd unit
From the deploy artifact copy:
```sh
sudo install -o root -g root -m 644 /opt/chesstrainer/src/deploy/chesstrainer.service \
/etc/systemd/system/chesstrainer.service
sudo systemctl daemon-reload
sudo systemctl enable chesstrainer
```
The unit includes `ConditionPathExists=/opt/chesstrainer/current/bin/server`, so
it is safe to enable before the first release. systemd skips it until a release
is in place.
## Caddy
On the current VPS the Caddyfile is a single file with no imports. Add the block
from `deploy/Caddyfile` by hand:
```caddy
innersquare.app {
encode zstd gzip
reverse_proxy 127.0.0.1:4100
}
www.innersquare.app {
redir https://innersquare.app{uri} permanent
}
```
If a new VPS uses imports, put the block in its own site file instead.
Do **not** switch Caddy until a release is running and verified on
`127.0.0.1:4100`. Before that, keep the static coming-soon site live.
Validate and reload:
```sh
sudo caddy validate --config /etc/caddy/Caddyfile
sudo systemctl reload caddy
```
Do not let a deploy overwrite the shared Caddyfile.
## Building a release
Build on a machine matching Ubuntu 24.04 / glibc 2.39, or let CI do it.
The release tarball is the contents of the release directory:
```sh
export MIX_ENV=prod
mix deps.get --only prod
mix assets.deploy
mix release
tar -czf chesstrainer-release.tar.gz -C _build/prod/rel/chesstrainer .
```
`mix assets.deploy` runs `compile` first so the generated LiveView colocated
CSS exists.
## First deploy and Caddy switch
Upload the tarball:
```sh
scp chesstrainer-release.tar.gz <VPS_USER>@<VPS_HOST>:/tmp/
```
On the VPS:
```sh
sudo /opt/chesstrainer/src/deploy/activate /tmp/chesstrainer-release.tar.gz
```
The script:
1. Extracts into `/opt/chesstrainer/releases/<timestamp>`
2. Fixes ownership
3. Flips `/opt/chesstrainer/current`
4. Restarts `chesstrainer.service`
5. Migrations run via `ExecStartPre`
6. Polls `/health`
7. Rolls back to the previous release on failure
8. Prunes old releases, keeping 5 by default
Verify locally before touching Caddy:
```sh
curl -i http://127.0.0.1:4100/health
curl -i http://127.0.0.1:4100/
sudo journalctl -u chesstrainer -n 100 --no-pager
```
Then add the Caddy block and reload. Verify publicly:
```sh
curl -I https://innersquare.app/
curl -I https://innersquare.app/privacy
curl -I https://innersquare.app/terms-conditions
```
## Subsequent deploys
```sh
scp chesstrainer-release.tar.gz <VPS_USER>@<VPS_HOST>:/tmp/
ssh <VPS_USER>@<VPS_HOST>
sudo /opt/chesstrainer/src/deploy/activate /tmp/chesstrainer-release.tar.gz
```
Optional overrides:
```sh
RELEASE_ID=20261109120000 \
HEALTH_URL=http://127.0.0.1:4100/health \
KEEP_RELEASES=5 \
sudo -E /opt/chesstrainer/src/deploy/activate /tmp/chesstrainer-release.tar.gz
```
## Rollback
```sh
sudo /opt/chesstrainer/src/deploy/rollback
```
Or target a specific release:
```sh
sudo /opt/chesstrainer/src/deploy/rollback 20261109120000
```
The script flips `current`, restarts the service, and checks `/health`.
## Logs and health
```sh
sudo systemctl status chesstrainer
sudo journalctl -u chesstrainer -n 100 --no-pager
curl -i http://127.0.0.1:4100/health
```
`/health` returns JSON with `status`, `db`, `tablebase`, and `process`.
It returns 200 for `ok`/`degraded` and 503 for `down`. A missing local tablebase
reports `degraded` but still 200 because Lichess fallback is available.
## Backups
Take a logical backup of the production database:
```sh
sudo docker compose -f <UNIFIED_COMPOSE> \
exec -T chesstrainer-db pg_dump -U chesstrainer chesstrainer_prod \
| gzip > /var/backups/chesstrainer-$(date -u +%Y%m%d%H%M%S).sql.gz
```
Example nightly entry in root's crontab (`sudo crontab -e`):
```cron
15 3 * * * docker compose -f /home/owen/docker-compose.yml exec -T chesstrainer-db pg_dump -U chesstrainer chesstrainer_prod | gzip > /var/backups/chesstrainer-$(date +\%Y\%m\%d).sql.gz
```
Keep `/var/backups` outside `/opt/chesstrainer/releases` and copy backups off
the VPS regularly.
## New VPS checklist
1. Ubuntu 24.04, DNS pointed at the VPS, firewall allows 22/80/443.
2. Docker, Compose, Caddy, and runtime libraries installed.
3. `chesstrainer` user, `/opt/chesstrainer` layout, root-owned env files.
4. `chesstrainer-db` merged into the unified compose and healthy.
5. systemd unit installed and enabled; `ConditionPathExists` keeps it skipped
until a release exists.
6. Release built on a matching Ubuntu runner and activated.
7. `/health` and `/` verified on `127.0.0.1:4100`.
8. Caddy block added, validated, reloaded.
9. Public `/`, `/privacy`, `/terms-conditions`, and `/health` verified.
10. Backups scheduled and tested.
+87
View File
@@ -0,0 +1,87 @@
#!/usr/bin/env bash
set -euo pipefail
# Activate a timestamped release on the VPS.
#
# Usage:
# sudo deploy/activate /tmp/chesstrainer-20261109.tar.gz
#
# Environment overrides:
# APP_USER, APP_ROOT, SERVICE, HEALTH_URL, KEEP_RELEASES, RELEASE_ID
if [[ "${EUID:-$(id -u)}" -ne 0 ]]; then
echo "activate: run with sudo" >&2
exit 1
fi
TARBALL="${1:-}"
if [[ -z "$TARBALL" || ! -f "$TARBALL" ]]; then
echo "usage: sudo $0 /path/to/chesstrainer-release.tar.gz" >&2
exit 1
fi
APP_USER="${APP_USER:-chesstrainer}"
APP_ROOT="${APP_ROOT:-/opt/chesstrainer}"
SERVICE="${SERVICE:-chesstrainer}"
HEALTH_URL="${HEALTH_URL:-http://127.0.0.1:4100/health}"
KEEP_RELEASES="${KEEP_RELEASES:-5}"
RELEASE_ID="${RELEASE_ID:-$(date -u +%Y%m%d%H%M%S)}"
if [[ ! "$RELEASE_ID" =~ ^[A-Za-z0-9._-]+$ ]]; then
echo "activate: RELEASE_ID may contain only letters, digits, dot, underscore and dash" >&2
exit 1
fi
if [[ ! "$KEEP_RELEASES" =~ ^[0-9]+$ ]] || [[ "$KEEP_RELEASES" -lt 1 ]]; then
echo "activate: KEEP_RELEASES must be a positive integer" >&2
exit 1
fi
health_check() {
curl --fail --silent --show-error \
--retry 10 --retry-delay 2 --retry-connrefused \
"$HEALTH_URL" >/dev/null
}
install -d -o "$APP_USER" -g "$APP_USER" "$APP_ROOT/releases"
PREVIOUS="$(readlink -f "$APP_ROOT/current" 2>/dev/null || true)"
RELEASE_DIR="$APP_ROOT/releases/$RELEASE_ID"
echo "activate: extracting $TARBALL -> $RELEASE_DIR"
install -d -o "$APP_USER" -g "$APP_USER" "$RELEASE_DIR"
tar -xzf "$TARBALL" -C "$RELEASE_DIR"
chown -R "$APP_USER:$APP_USER" "$RELEASE_DIR"
echo "activate: pointing current at $RELEASE_DIR"
ln -sfn "$RELEASE_DIR" "$APP_ROOT/current"
if systemctl restart "$SERVICE" && health_check; then
echo "activate: $RELEASE_ID is live"
if [[ "$KEEP_RELEASES" -gt 0 ]]; then
find "$APP_ROOT/releases" -mindepth 1 -maxdepth 1 -type d -printf '%T@ %p\n' \
| sort -nr \
| tail -n +"$((KEEP_RELEASES + 1))" \
| cut -d' ' -f2- \
| while read -r old_release; do
[[ -z "$old_release" ]] && continue
[[ "$old_release" == "$(readlink -f "$APP_ROOT/current")" ]] && continue
echo "activate: pruning $old_release"
rm -rf -- "$old_release"
done
fi
exit 0
fi
echo "activate: health check failed" >&2
if [[ -n "$PREVIOUS" && -d "$PREVIOUS" ]]; then
echo "activate: rolling back to $PREVIOUS" >&2
ln -sfn "$PREVIOUS" "$APP_ROOT/current"
systemctl restart "$SERVICE" || true
health_check || echo "activate: rollback health check also failed" >&2
fi
exit 1
+20
View File
@@ -0,0 +1,20 @@
[Unit]
Description=Inner Square Chess (Phoenix)
After=network.target docker.service
Wants=network.target
ConditionPathExists=/opt/chesstrainer/current/bin/server
[Service]
Type=simple
User=chesstrainer
Group=chesstrainer
EnvironmentFile=/etc/chesstrainer/env
WorkingDirectory=/opt/chesstrainer/current
ExecStartPre=/opt/chesstrainer/current/bin/migrate
ExecStart=/opt/chesstrainer/current/bin/server
Restart=always
RestartSec=5
SyslogIdentifier=chesstrainer
[Install]
WantedBy=multi-user.target
+26
View File
@@ -0,0 +1,26 @@
# Reference only. Merge the service and volume below into the VPS's unified
# docker-compose.yml. Do not run this file as a separate Compose project.
#
# Pin the Postgres image directly in the unified file. Replace the tag with
# an exact digest if you want immutable image pinning:
# image: postgres:18.0@sha256:...
services:
chesstrainer-db:
container_name: chesstrainer-db
image: postgres:18.0
restart: unless-stopped
env_file: /etc/chesstrainer/postgres.env
ports:
- "127.0.0.1:5432:5432"
volumes:
- chesstrainer_pgdata:/var/lib/postgresql
healthcheck:
test: ["CMD-SHELL", "pg_isready -U $$POSTGRES_USER -d $$POSTGRES_DB"]
interval: 5s
timeout: 5s
retries: 10
volumes:
chesstrainer_pgdata:
name: chesstrainer_pgdata
+58
View File
@@ -0,0 +1,58 @@
#!/usr/bin/env bash
set -euo pipefail
# Roll back to a previous release.
#
# Usage:
# sudo deploy/rollback # most recent previous release
# sudo deploy/rollback 20261109120000 # release id under /opt/chesstrainer/releases
# sudo deploy/rollback /opt/chesstrainer/releases/20261109120000
if [[ "${EUID:-$(id -u)}" -ne 0 ]]; then
echo "rollback: run with sudo" >&2
exit 1
fi
APP_ROOT="${APP_ROOT:-/opt/chesstrainer}"
SERVICE="${SERVICE:-chesstrainer}"
HEALTH_URL="${HEALTH_URL:-http://127.0.0.1:4100/health}"
health_check() {
curl --fail --silent --show-error \
--retry 10 --retry-delay 2 --retry-connrefused \
"$HEALTH_URL" >/dev/null
}
CURRENT="$(readlink -f "$APP_ROOT/current" 2>/dev/null || true)"
if [[ $# -gt 0 ]]; then
case "$1" in
/*) TARGET="$1" ;;
*) TARGET="$APP_ROOT/releases/$1" ;;
esac
else
TARGET="$(
find "$APP_ROOT/releases" -mindepth 1 -maxdepth 1 -type d -printf '%T@ %p\n' \
| sort -nr \
| cut -d' ' -f2- \
| while read -r release; do
if [[ "$release" != "$CURRENT" ]]; then
echo "$release"
break
fi
done
)"
fi
if [[ -z "$TARGET" || ! -d "$TARGET" ]]; then
echo "rollback: no previous release found" >&2
exit 1
fi
echo "rollback: pointing current at $TARGET"
ln -sfn "$TARGET" "$APP_ROOT/current"
systemctl restart "$SERVICE"
health_check
echo "rollback: $TARGET is live"
+2 -1
View File
@@ -1,6 +1,7 @@
__SITE_ADDRESS__ { __SITE_ADDRESS__ {
root * /var/www/innersquare root * /var/www/innersquare
encode zstd gzip encode zstd gzip
try_files {path}.html {path}
file_server file_server
header { header {
@@ -14,6 +15,6 @@ __SITE_ADDRESS__ {
@immutable path /fonts/* /favicon.ico @immutable path /fonts/* /favicon.ico
header @immutable Cache-Control "public, max-age=31536000, immutable" header @immutable Cache-Control "public, max-age=31536000, immutable"
@html path / /index.html @html path / /index.html /privacy /terms-conditions
header @html Cache-Control "no-cache" header @html Cache-Control "no-cache"
} }
+30 -3
View File
@@ -7,6 +7,9 @@ newsletter form, and no JavaScript — just static files and Caddy.
``` ```
deploy/static/ deploy/static/
├── index.html # page + inline CSS; uses the app's real brand tokens ├── index.html # page + inline CSS; uses the app's real brand tokens
├── privacy.html # privacy policy, served at /privacy
├── terms-conditions.html # terms, served at /terms-conditions
├── legal.css # shared styles for the legal pages
├── fonts/ # DM Sans + DM Serif Display woff2 files ├── fonts/ # DM Sans + DM Serif Display woff2 files
├── favicon.ico # copied from priv/static ├── favicon.ico # copied from priv/static
├── Caddyfile # site block template; rendered by deploy.sh --caddy ├── Caddyfile # site block template; rendered by deploy.sh --caddy
@@ -14,6 +17,9 @@ deploy/static/
└── README.md └── README.md
``` ```
The Caddyfile uses `try_files {path}.html {path}` so `/privacy` and
`/terms-conditions` serve the matching `.html` files without a redirect.
## Preview locally ## Preview locally
```sh ```sh
@@ -21,6 +27,26 @@ python3 -m http.server 8080 --directory deploy/static
# open http://localhost:8080 # open http://localhost:8080
``` ```
Python maps URLs directly to files, so it serves `/privacy.html` and
`/terms-conditions.html` but not the extensionless `/privacy` or
`/terms-conditions` links. Those depend on Caddy's `try_files`.
To preview the exact production routing, run the Caddyfile locally:
```sh
sed -e 's#__SITE_ADDRESS__#:8098#' \
-e 's#/var/www/innersquare#/srv#' \
deploy/static/Caddyfile > /tmp/Caddyfile.local
docker run --rm -it -p 8098:8098 \
-v "$PWD/deploy/static:/srv:ro" \
-v /tmp/Caddyfile.local:/etc/caddy/Caddyfile:ro \
caddy:2-alpine \
caddy run --config /etc/caddy/Caddyfile --adapter caddyfile
```
Then open `http://localhost:8098/`, `/privacy` and `/terms-conditions`.
The page is deliberately light-only — it uses the brand's paper palette The page is deliberately light-only — it uses the brand's paper palette
regardless of the visitor's OS theme. It references `/fonts/...` and regardless of the visitor's OS theme. It references `/fonts/...` and
`/favicon.ico` from the site root, so preview it at the root (as above), not `/favicon.ico` from the site root, so preview it at the root (as above), not
@@ -77,7 +103,7 @@ Pass `--caddy` and a `SITE_ADDRESS` to have the script add or update the site
block: block:
```sh ```sh
SITE_ADDRESS="innersquarechess.com, www.innersquarechess.com" \ SITE_ADDRESS="innersquare.app, www.innersquare.app" \
VPS_HOST=203.0.113.10 \ VPS_HOST=203.0.113.10 \
VPS_USER=ubuntu \ VPS_USER=ubuntu \
./deploy/static/deploy.sh --caddy ./deploy/static/deploy.sh --caddy
@@ -110,7 +136,7 @@ the main Caddyfile:
```sh ```sh
REMOTE_CADDYFILE=/etc/caddy/conf.d/innersquare.caddy \ REMOTE_CADDYFILE=/etc/caddy/conf.d/innersquare.caddy \
SITE_ADDRESS=innersquarechess.com \ SITE_ADDRESS=innersquare.app \
VPS_HOST=203.0.113.10 \ VPS_HOST=203.0.113.10 \
VPS_USER=ubuntu \ VPS_USER=ubuntu \
./deploy/static/deploy.sh --caddy ./deploy/static/deploy.sh --caddy
@@ -126,7 +152,8 @@ Optional overrides: `SSH_PORT`, `WEB_ROOT` (default `/var/www/innersquare`),
## What this page deliberately does not do ## What this page deliberately does not do
- **No newsletter signup** — that waits on real mail delivery (#84) and the - **No newsletter signup** — that waits on real mail delivery (#84) and the
gated app (#116). gated app (#116). The legal pages are linked from the footer so the public
site has a privacy policy and terms while the signup is still gated.
- **No analytics, cookies, or JavaScript.** - **No analytics, cookies, or JavaScript.**
- **No indexing** — `robots.txt` is absent and Caddy sends - **No indexing** — `robots.txt` is absent and Caddy sends
`X-Robots-Tag: noindex, nofollow` plus the page has a robots meta tag. `X-Robots-Tag: noindex, nofollow` plus the page has a robots meta tag.
+15
View File
@@ -454,6 +454,17 @@
font-size: 11px; font-size: 11px;
} }
.footer-links {
display: flex;
gap: 18px;
color: var(--color-muted);
font-size: 12px;
}
.footer-links a:hover {
color: var(--color-body);
}
@media (max-width: 900px) { @media (max-width: 900px) {
.hero { .hero {
grid-template-columns: 1fr; grid-template-columns: 1fr;
@@ -685,6 +696,10 @@
</a> </a>
<p>Short, focused endgame training.</p> <p>Short, focused endgame training.</p>
</div> </div>
<nav class="footer-links" aria-label="Legal">
<a href="/privacy">Privacy</a>
<a href="/terms-conditions">Terms</a>
</nav>
<small>&copy; 2026 Inner Square Chess</small> <small>&copy; 2026 Inner Square Chess</small>
</footer> </footer>
</body> </body>
+277
View File
@@ -0,0 +1,277 @@
@font-face {
font-family: "DM Sans";
font-style: normal;
font-weight: 100 1000;
font-display: swap;
src: url("/fonts/dm-sans-variable.woff2") format("woff2");
}
@font-face {
font-family: "DM Serif Display";
font-style: normal;
font-weight: 400;
font-display: swap;
src: url("/fonts/dm-serif-display.woff2") format("woff2");
}
@font-face {
font-family: "DM Serif Display";
font-style: italic;
font-weight: 400;
font-display: swap;
src: url("/fonts/dm-serif-display-italic.woff2") format("woff2");
}
:root {
--ink: #17352d;
--ink-soft: #587068;
--paper: #f4f0e6;
--cream: #fffcf4;
--mint: #b9d7c9;
--coral: #ef755d;
--coral-dark: #d95d48;
--line: rgba(23, 53, 45, 0.15);
--color-canvas: var(--paper);
--color-canvas-raised: var(--cream);
--color-body: var(--ink);
--color-muted: var(--ink-soft);
--color-hairline: var(--line);
--color-deep: var(--ink);
--color-on-deep: var(--paper);
--color-coral: var(--coral);
--color-coral-text: #b8432c;
color-scheme: light;
}
*,
*::before,
*::after {
box-sizing: border-box;
}
html {
scroll-behavior: smooth;
}
body {
min-width: 320px;
min-height: 100vh;
min-height: 100dvh;
margin: 0;
display: flex;
flex-direction: column;
background: var(--color-canvas);
color: var(--color-body);
font-family: "DM Sans", system-ui, -apple-system, "Segoe UI", sans-serif;
-webkit-font-smoothing: antialiased;
}
a {
color: inherit;
text-decoration: none;
}
:focus-visible {
outline: 2px solid var(--color-coral-text);
outline-offset: 2px;
}
main {
flex: 1 0 auto;
overflow: hidden;
}
.nav-wrap {
width: min(1180px, calc(100% - 48px));
height: 92px;
margin: 0 auto;
display: flex;
align-items: center;
justify-content: space-between;
border-bottom: 1px solid var(--color-hairline);
}
.brand {
display: inline-flex;
align-items: center;
gap: 10px;
font-size: 16px;
font-weight: 700;
letter-spacing: 0.18em;
}
.brand-mark {
display: grid;
place-items: center;
width: 35px;
height: 35px;
border-radius: 50%;
background: var(--color-deep);
color: var(--color-on-deep);
font-size: 21px;
letter-spacing: 0;
}
.status {
display: inline-flex;
align-items: center;
gap: 8px;
padding: 8px 14px;
border: 1px solid var(--color-hairline);
border-radius: 999px;
color: var(--color-muted);
font-size: 11px;
font-weight: 700;
letter-spacing: 0.1em;
text-transform: uppercase;
white-space: nowrap;
}
.status::before {
content: "";
width: 7px;
height: 7px;
border-radius: 50%;
background: var(--color-coral);
}
.legal {
width: min(760px, calc(100% - 48px));
margin: 0 auto;
padding: 84px 0 120px;
}
.legal h1 {
max-width: none;
margin: 0;
font-family: "DM Serif Display", Georgia, serif;
font-size: clamp(42px, 5vw, 62px);
font-weight: 400;
letter-spacing: -0.035em;
line-height: 1.02;
}
.legal-meta {
margin-top: 14px;
color: var(--color-muted);
font-size: 13px;
}
.legal h2 {
margin: 42px 0 12px;
font-family: "DM Serif Display", Georgia, serif;
font-size: 26px;
font-weight: 400;
letter-spacing: -0.02em;
line-height: 1.15;
}
.legal p,
.legal li {
color: var(--color-muted);
font-size: 15px;
line-height: 1.75;
}
.legal p + p {
margin-top: 12px;
}
.legal ul {
display: grid;
gap: 8px;
margin: 12px 0 0 20px;
list-style: disc;
}
.legal strong {
color: var(--color-body);
font-weight: 600;
}
.legal a {
color: var(--color-coral-text);
text-decoration: underline;
text-underline-offset: 2px;
}
.legal a:hover {
opacity: 0.75;
}
.site-footer {
width: min(1180px, calc(100% - 48px));
margin: 0 auto;
padding: 44px 0;
display: flex;
align-items: center;
justify-content: space-between;
gap: 30px;
border-top: 1px solid var(--color-hairline);
}
.footer-brand {
display: flex;
flex-direction: column;
gap: 12px;
}
.footer-brand p {
margin: 0;
color: var(--color-muted);
font-size: 13px;
}
.site-footer > small {
color: var(--color-muted);
font-size: 11px;
}
.footer-links {
display: flex;
gap: 18px;
color: var(--color-muted);
font-size: 12px;
}
.footer-links a:hover {
color: var(--color-body);
}
@media (max-width: 650px) {
.nav-wrap,
.site-footer {
width: calc(100% - 36px);
}
.nav-wrap {
height: 74px;
}
.status {
padding: 7px 10px;
font-size: 9px;
}
.legal {
width: calc(100% - 36px);
padding: 56px 0 84px;
}
.legal h1 {
font-size: clamp(34px, 11vw, 44px);
}
.legal h2 {
margin-top: 34px;
font-size: 23px;
}
.site-footer {
flex-direction: column;
align-items: flex-start;
gap: 24px;
}
}
+196
View File
@@ -0,0 +1,196 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Privacy Policy — Inner Square Chess</title>
<meta
name="description"
content="How Inner Square Chess collects, uses, and protects your personal information."
/>
<meta name="robots" content="noindex, nofollow" />
<meta name="theme-color" content="#f4f0e6" />
<meta property="og:type" content="website" />
<meta property="og:site_name" content="Inner Square Chess" />
<meta property="og:title" content="Privacy Policy — Inner Square Chess" />
<meta
property="og:description"
content="How Inner Square Chess collects, uses, and protects your personal information."
/>
<meta name="twitter:card" content="summary" />
<link rel="icon" href="/favicon.ico" />
<link rel="stylesheet" href="/legal.css" />
</head>
<body>
<header>
<nav class="nav-wrap" aria-label="Main navigation">
<a class="brand" href="/" aria-label="Inner Square Chess home">
<span class="brand-mark" aria-hidden="true">♞</span>
<span>INNERSQUARE</span>
</a>
<span class="status">Launching soon</span>
</nav>
</header>
<main id="main-content">
<article class="legal">
<h1>Privacy Policy</h1>
<p class="legal-meta">Last updated: 6 November 2026</p>
<p>
Inner Square Chess is an endgame training site. This policy explains what
information we collect when you use it, why we collect it, and the choices
you have. It covers the website and every page under it, including the
guest trainer.
</p>
<h2>What we collect</h2>
<ul>
<li>
<strong>Account details.</strong>
If you register, we store your username, email address, and a hashed
password. We never store passwords in plain text.
</li>
<li>
<strong>Training activity.</strong>
We record the puzzles you attempt and whether you solved them, so we can
show your progress and keep the daily puzzle meaningful.
</li>
<li>
<strong>Mailing list email.</strong>
If you join the mailing list — using the form on the home page or the
checkbox when registering — we store your email address and where you
signed up, so we can send you occasional updates. You can ask to be
removed at any time.
</li>
<li>
<strong>Technical data.</strong>
Our hosting and server infrastructure may keep standard request logs
(IP address, browser, timestamps) for security and troubleshooting.
These logs are rotated regularly.
</li>
<li>
<strong>Messages you send us.</strong>
If you contact us, we keep the message and our reply for as long as
needed to help you.
</li>
</ul>
<h2>Cookies and local storage</h2>
<p>
We use a small number of cookies and local storage entries that are
required for the site to work:
</p>
<ul>
<li>a session cookie that keeps you signed in;</li>
<li>a CSRF token that protects forms from cross-site requests;</li>
<li>a colour-mode preference stored in your browser.</li>
</ul>
<p>
We do not use advertising cookies, third-party analytics, or cross-site
tracking. You can clear these entries at any time in your browser
settings; doing so will sign you out and reset your colour mode.
</p>
<h2>How we use your information</h2>
<ul>
<li>To create and secure your account and sign you in.</li>
<li>To run the trainer and remember your progress.</li>
<li>To send service emails, such as confirmation and password reset links.</li>
<li>To send occasional endgame tips and site news, if you opted in.</li>
<li>To keep the site available, prevent abuse, and fix faults.</li>
<li>To respond when you ask for help.</li>
</ul>
<p>
We rely on our contract with you to provide the service, our legitimate
interests in keeping it secure and improving it, and your consent where we
ask for it. You can withdraw consent at any time.
</p>
<h2>Guest puzzle limit</h2>
<p>
Visitors who use the guest trainer without an account get a limited number
of free puzzles per UTC day. To enforce that limit and prevent abuse, we
identify each visitor by a keyed hash (HMAC-SHA256) of their IP address.
The limiter itself never stores, logs, or shares the raw address.
</p>
<p>
The hash exists only in the memory of the server that handled your request.
It is tied to the current UTC day, stops being usable at 00:00 UTC, and is
deleted by a periodic sweep shortly afterwards; it is also discarded when
the server restarts. It is never written to a database, a log, or a
backup, and no cookie or other client-side storage is involved. Signed-in
accounts are not metered this way.
</p>
<p>
We process this hash on the basis of our legitimate interests
(Article 6(1)(f) GDPR) in keeping the service available and preventing
abuse of the free tier. We do not share it with anyone. You have the right
to object to this processing; to do so, contact us using the address below.
</p>
<h2>Sharing</h2>
<p>
We do not sell your personal information. We share it only with providers
who help us run the site — for example hosting, database, and email
delivery providers — and only as far as they need it to perform that work.
We may also disclose information where the law requires it or to protect
the rights and safety of our users.
</p>
<h2>Retention</h2>
<p>
We keep account and training data while your account is open. If you
delete your account, we remove your personal information within a
reasonable period, except where we must keep records for legal, security,
or accounting reasons.
</p>
<h2>Your rights</h2>
<p>
Depending on where you live, you may have the right to access, correct,
delete, restrict, or export your personal information, and to object to
some uses of it. To make a request, contact us using the address below. If
you are in the UK or EU and are unhappy with our response, you can complain
to your local data protection authority.
</p>
<h2>Children</h2>
<p>
The service is not directed at children under 13, and we do not knowingly
collect their personal information. If you believe a child has created an
account, contact us and we will remove it.
</p>
<h2>Changes</h2>
<p>
We may update this policy as the service changes. When we do, we will
change the date at the top of this page and, for significant changes,
notify signed-in users by email or on the site.
</p>
<h2>Contact</h2>
<p>
Questions about this policy or your data can be sent to
<a href="mailto:support@innersquare.app">support@innersquare.app</a>.
</p>
</article>
</main>
<footer class="site-footer">
<div class="footer-brand">
<a class="brand" href="/" aria-label="Inner Square Chess home">
<span class="brand-mark" aria-hidden="true">♞</span>
<span>INNERSQUARE</span>
</a>
<p>Short, focused endgame training.</p>
</div>
<nav class="footer-links" aria-label="Legal">
<a href="/privacy">Privacy</a>
<a href="/terms-conditions">Terms</a>
</nav>
<small>&copy; 2026 Inner Square Chess</small>
</footer>
</body>
</html>
+170
View File
@@ -0,0 +1,170 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Terms &amp; Conditions — Inner Square Chess</title>
<meta
name="description"
content="The terms that apply when you use Inner Square Chess."
/>
<meta name="robots" content="noindex, nofollow" />
<meta name="theme-color" content="#f4f0e6" />
<meta property="og:type" content="website" />
<meta property="og:site_name" content="Inner Square Chess" />
<meta property="og:title" content="Terms &amp; Conditions — Inner Square Chess" />
<meta
property="og:description"
content="The terms that apply when you use Inner Square Chess."
/>
<meta name="twitter:card" content="summary" />
<link rel="icon" href="/favicon.ico" />
<link rel="stylesheet" href="/legal.css" />
</head>
<body>
<header>
<nav class="nav-wrap" aria-label="Main navigation">
<a class="brand" href="/" aria-label="Inner Square Chess home">
<span class="brand-mark" aria-hidden="true">♞</span>
<span>INNERSQUARE</span>
</a>
<span class="status">Launching soon</span>
</nav>
</header>
<main id="main-content">
<article class="legal">
<h1>Terms &amp; Conditions</h1>
<p class="legal-meta">Last updated: 6 November 2026</p>
<p>
These terms govern your use of Inner Square Chess. By browsing the site,
using the guest trainer, or creating an account, you agree to them. If you
do not agree, please do not use the service.
</p>
<h2>The service</h2>
<p>
Inner Square Chess provides short endgame puzzles and training tools. Some
features are available without an account; others, such as saved progress
and the full puzzle list, require you to register. We may add, change, or
remove features over time.
</p>
<p>
The guest trainer is limited to a fixed number of puzzles per UTC day,
which we may change. The limit is enforced as described in our
<a href="/privacy">Privacy Policy</a>.
</p>
<h2>Accounts</h2>
<ul>
<li>You must be at least 13 years old to create an account.</li>
<li>Give accurate information and keep it up to date.</li>
<li>Keep your password private and tell us promptly about unauthorised use.</li>
<li>You are responsible for activity that happens under your account.</li>
<li>Do not share, sell, or transfer your account to someone else.</li>
</ul>
<h2>Acceptable use</h2>
<p>You agree not to:</p>
<ul>
<li>break the law or infringe anyone else's rights;</li>
<li>interfere with the site, its servers, or other users;</li>
<li>attempt to gain access to accounts or data that are not yours;</li>
<li>scrape, crawl, or bulk-download the site without our permission;</li>
<li>copy, resell, or redistribute the service or its content;</li>
<li>use the service to send spam or malicious code.</li>
</ul>
<h2>Our content and your licence</h2>
<p>
The site, its design, text, and software are owned by Inner Square Chess or
its licensors and are protected by copyright and other laws. We grant you a
personal, non-exclusive, non-transferable licence to use the service for
your own training. You may not reproduce, modify, distribute, or create
derivative works from our content without written permission.
</p>
<p>
Chess positions and puzzle data are drawn from public sources and
tablebase material. You may use the training output for your own study,
but not to build a competing product.
</p>
<h2>Your data</h2>
<p>
You keep ownership of the information you provide. You give us permission
to store and use it as described in our <a href="/privacy">Privacy Policy</a>
so that we can run the service.
</p>
<h2>Paid plans</h2>
<p>
Some features may be offered as part of a paid plan. Prices, billing
periods, and cancellation terms will be shown before you purchase. Unless
the law requires otherwise, payments are non-refundable once a billing
period has started. We may change prices with reasonable notice.
</p>
<h2>Availability and changes</h2>
<p>
We aim to keep the site available, but we do not guarantee uninterrupted
access. Maintenance, faults, or circumstances outside our control may
interrupt it. We may suspend or discontinue the service, in whole or in
part, with reasonable notice where practical.
</p>
<h2>Disclaimer</h2>
<p>
Inner Square Chess is an educational tool. We do not promise that using it
will improve your rating or results, and puzzle solutions are provided for
training purposes only. The service is provided "as is" to the extent
permitted by law.
</p>
<h2>Limitation of liability</h2>
<p>
To the extent permitted by law, Inner Square Chess is not liable for
indirect or consequential losses, loss of data, or loss of profits arising
from your use of the service. Nothing in these terms limits liability that
cannot be limited by law, including for death, personal injury, or fraud.
</p>
<h2>Termination</h2>
<p>
You may stop using the service and delete your account at any time. We may
suspend or close an account that breaches these terms, that we reasonably
believe is being misused, or where we are required to do so by law.
</p>
<h2>Governing law</h2>
<p>
These terms are governed by the laws of France. Any dispute will be handled
by the courts of France, unless the law where you live gives you the right
to bring it elsewhere.
</p>
<h2>Contact</h2>
<p>
Questions about these terms can be sent to
<a href="mailto:support@innersquare.app">support@innersquare.app</a>.
</p>
</article>
</main>
<footer class="site-footer">
<div class="footer-brand">
<a class="brand" href="/" aria-label="Inner Square Chess home">
<span class="brand-mark" aria-hidden="true">♞</span>
<span>INNERSQUARE</span>
</a>
<p>Short, focused endgame training.</p>
</div>
<nav class="footer-links" aria-label="Legal">
<a href="/privacy">Privacy</a>
<a href="/terms-conditions">Terms</a>
</nav>
<small>&copy; 2026 Inner Square Chess</small>
</footer>
</body>
</html>
+62
View File
@@ -0,0 +1,62 @@
defmodule Chesstrainer.Health do
@moduledoc """
Runtime health snapshot for deploy smoke tests and uptime monitors.
The database is the only hard dependency. Tablebase status is informational:
local Syzygy files are preferred, but falling back to Lichess is not an
outage, so a missing or broken local cache reports `degraded` with HTTP 200.
"""
alias Chesstrainer.Endgames.Tablebase.Local
alias Chesstrainer.Repo
@type status :: %{
status: String.t(),
db: String.t(),
tablebase: String.t(),
process: String.t()
}
@doc "Returns the current health status."
@spec status() :: status()
def status do
db = if database_up?(), do: "ok", else: "down"
tablebase = tablebase_status()
overall =
cond do
db == "down" -> "down"
tablebase == "local" -> "ok"
true -> "degraded"
end
%{status: overall, db: db, tablebase: tablebase, process: "ok"}
end
defp database_up? do
case Application.get_env(:chesstrainer, :health_database_check) do
fun when is_function(fun, 0) -> fun.()
_ -> default_database_up?()
end
end
defp default_database_up? do
case Repo.query("SELECT 1") do
{:ok, _result} -> true
_ -> false
end
rescue
_ -> false
catch
_, _ -> false
end
defp tablebase_status do
case Local.check() do
{:ok, largest} when largest > 0 -> "local"
{:ok, _largest} -> "fallback"
{:error, :not_configured} -> "not_configured"
{:error, _reason} -> "fallback"
end
end
end
+30
View File
@@ -0,0 +1,30 @@
defmodule Chesstrainer.Release do
@moduledoc """
Used for executing DB release tasks when run in production without Mix
installed.
"""
@app :chesstrainer
def migrate do
load_app()
for repo <- repos() do
{:ok, _, _} = Ecto.Migrator.with_repo(repo, &Ecto.Migrator.run(&1, :up, all: true))
end
end
def rollback(repo, version) do
load_app()
{:ok, _, _} = Ecto.Migrator.with_repo(repo, &Ecto.Migrator.run(&1, :down, to: version))
end
defp repos do
Application.fetch_env!(@app, :ecto_repos)
end
defp load_app do
# Many platforms require SSL when connecting to the database
Application.ensure_all_started(:ssl)
Application.ensure_loaded(@app)
end
end
+8
View File
@@ -19,6 +19,14 @@ defmodule ChesstrainerWeb do
def static_paths, do: ~w(assets fonts images favicon.ico) 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 def router do
quote do quote do
use Phoenix.Router, helpers: false use Phoenix.Router, helpers: false
+14 -2
View File
@@ -63,11 +63,17 @@ defmodule ChesstrainerWeb.Layouts do
doc: "the current [scope](https://phoenix.hexdocs.pm/scopes.html)" doc: "the current [scope](https://phoenix.hexdocs.pm/scopes.html)"
def navbar(assigns) do def navbar(assigns) do
user = signed_in_user(assigns.current_scope)
nav_links = nav_links(assigns.current_scope)
prelaunch = ChesstrainerWeb.prelaunch?()
assigns = assigns =
assigns assigns
|> assign(:nav_links, nav_links(assigns.current_scope)) |> assign(:nav_links, nav_links)
|> assign(:start_href, start_href(assigns.current_scope)) |> 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""" ~H"""
<header> <header>
@@ -80,6 +86,7 @@ defmodule ChesstrainerWeb.Layouts do
<div class="nav-right"> <div class="nav-right">
<.colour_mode_toggle /> <.colour_mode_toggle />
<%= if @show_nav do %>
<button <button
class="menu-button" class="menu-button"
type="button" type="button"
@@ -107,14 +114,19 @@ defmodule ChesstrainerWeb.Layouts do
</div> </div>
</details> </details>
<% else %> <% else %>
<%= if !@prelaunch do %>
<.link href={~p"/users/log-in"}>Log in</.link> <.link href={~p"/users/log-in"}>Log in</.link>
<.link href={~p"/users/register"}>Register</.link> <.link href={~p"/users/register"}>Register</.link>
<% end %> <% end %>
<% end %>
<%= if !@prelaunch do %>
<.pill_button variant={:nav} href={@start_href}> <.pill_button variant={:nav} href={@start_href}>
Start training <.icon_arrow /> Start training <.icon_arrow />
</.pill_button> </.pill_button>
<% end %>
</div> </div>
<% end %>
</div> </div>
</nav> </nav>
</header> </header>
@@ -0,0 +1,17 @@
defmodule ChesstrainerWeb.HealthController do
@moduledoc """
JSON health check used by deploys and uptime monitors.
"""
use ChesstrainerWeb, :controller
def index(conn, _params) do
health = Chesstrainer.Health.status()
status = if health.status == "down", do: :service_unavailable, else: :ok
conn
|> put_resp_header("x-robots-tag", "noindex")
|> put_status(status)
|> json(health)
end
end
@@ -10,24 +10,16 @@ defmodule ChesstrainerWeb.MailingListController do
@token_max_age 7 * 24 * 60 * 60 @token_max_age 7 * 24 * 60 * 60
def create(conn, %{"subscriber" => params}) when is_map(params) do def create(conn, %{"subscriber" => params}) when is_map(params) do
email = params["email"] if mailing_list_enabled?() do
create_subscription(conn, params)
cond do else
honeypot_filled?(params) -> closed(conn)
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
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 def confirm(conn, %{"token" => token}) do
case Phoenix.Token.verify( case Phoenix.Token.verify(
@@ -63,6 +55,24 @@ defmodule ChesstrainerWeb.MailingListController do
end end
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 defp subscribe(conn, email) do
email = String.trim(email) email = String.trim(email)
@@ -122,4 +132,14 @@ defmodule ChesstrainerWeb.MailingListController do
|> put_flash(:error, "Enter a valid email address.") |> put_flash(:error, "Enter a valid email address.")
|> redirect(to: @return_to) |> redirect(to: @return_to)
end 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 end
@@ -11,6 +11,9 @@ defmodule ChesstrainerWeb.PageController do
"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."
def home(conn, _params) do def home(conn, _params) do
if prelaunch?() do
render_coming_soon(conn)
else
endgames = Endgames.curated_endgames() endgames = Endgames.curated_endgames()
conn conn
@@ -19,6 +22,7 @@ defmodule ChesstrainerWeb.PageController do
|> assign(:title_suffix, "") |> assign(:title_suffix, "")
|> assign(:meta_description, @description) |> assign(:meta_description, @description)
|> assign(:canonical_url, current_url(conn)) |> assign(:canonical_url, current_url(conn))
|> assign(:mailing_list_enabled, mailing_list_enabled?())
|> render(:home, |> render(:home,
endgames: endgames, endgames: endgames,
active_endgame: DailyPuzzles.today(), active_endgame: DailyPuzzles.today(),
@@ -28,6 +32,7 @@ defmodule ChesstrainerWeb.PageController do
today: Date.utc_today() today: Date.utc_today()
) )
end end
end
def privacy(conn, _params) do def privacy(conn, _params) do
conn conn
@@ -61,4 +66,22 @@ defmodule ChesstrainerWeb.PageController do
|> assign(:noindex, true) |> assign(:noindex, true)
|> render(:not_found) |> render(:not_found)
end 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 end
@@ -0,0 +1,26 @@
<Layouts.flash_group flash={@flash} />
<main id="main-content" tabindex="-1">
<section class="hero">
<div class="hero-copy">
<div class="eyebrow">
<.icon_spark /> Endgame training, coming soon
</div>
<h1>
Master the <em>endgame.</em>
</h1>
<p>
Short, focused endgame puzzles against tablebase-perfect defence. We're putting the finishing touches on the trainer.
</p>
<div :if={@mailing_list_enabled} class="hero-actions">
<.pill_button variant={:primary} href="#mailing-list">Join the list</.pill_button>
</div>
</div>
<div class="board-stage" id="trainer">
<div class="coral-orbit" />
<div class="mint-orbit" />
<.board_preview />
</div>
</section>
<.mailing_list_signup :if={@mailing_list_enabled} />
</main>
@@ -70,7 +70,7 @@
</div> </div>
</section> --%> </section> --%>
<.mailing_list_signup /> <.mailing_list_signup :if={@mailing_list_enabled} />
<%!-- <section class="progress-banner" id="progress"> <%!-- <section class="progress-banner" id="progress">
<div> <div>
@@ -9,15 +9,25 @@ defmodule ChesstrainerWeb.RobotsController do
use ChesstrainerWeb, :controller use ChesstrainerWeb, :controller
def index(conn, _params) do def index(conn, _params) do
body = """ body =
if prelaunch?() do
"""
User-agent: *
Disallow: /
"""
else
"""
User-agent: * User-agent: *
Allow: / Allow: /
Sitemap: #{url(conn, ~p"/sitemap.xml")} Sitemap: #{url(conn, ~p"/sitemap.xml")}
""" """
end
conn conn
|> put_resp_content_type("text/plain") |> put_resp_content_type("text/plain")
|> send_resp(200, body) |> send_resp(200, body)
end end
defp prelaunch?, do: Application.get_env(:chesstrainer, :prelaunch, false)
end end
@@ -5,20 +5,28 @@ defmodule ChesstrainerWeb.UserSessionController do
alias ChesstrainerWeb.UserAuth alias ChesstrainerWeb.UserAuth
def create(conn, %{"user" => user_params}) do 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 %{"email" => login, "password" => password} = user_params
case Accounts.get_user_by_login_and_password(login, password) do case Accounts.get_user_by_login_and_password(login, password) do
nil -> nil ->
# In order to prevent user enumeration attacks, don't disclose whether invalid_credentials(conn, login, failure_path)
# 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")
user -> user ->
if user.confirmed_at do if user.confirmed_at do
conn conn
|> maybe_put_return_to(success_path)
|> put_flash(:info, "Welcome back!") |> put_flash(:info, "Welcome back!")
|> UserAuth.log_in_user(user, user_params) |> UserAuth.log_in_user(user, user_params)
else else
@@ -30,14 +38,21 @@ defmodule ChesstrainerWeb.UserSessionController do
# In order to prevent user enumeration attacks, report the same error # In order to prevent user enumeration attacks, report the same error
# as invalid credentials. # as invalid credentials.
invalid_credentials(conn, login, failure_path)
end
end
end
defp invalid_credentials(conn, login, path) do
conn conn
|> put_flash(:error, "Invalid email, username or password") |> put_flash(:error, "Invalid email, username or password")
|> put_flash(:email, String.slice(login, 0, 160)) |> put_flash(:email, String.slice(login, 0, 160))
|> redirect(to: ~p"/users/log-in") |> redirect(to: path)
end
end
end 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 def update_password(conn, %{"user" => user_params}) do
user = conn.assigns.current_scope.user user = conn.assigns.current_scope.user
true = Accounts.sudo_mode?(user) true = Accounts.sudo_mode?(user)
+13 -3
View File
@@ -11,7 +11,7 @@ defmodule ChesstrainerWeb.UserLive.Login do
<%= if @current_scope do %> <%= if @current_scope do %>
You need to reauthenticate to perform sensitive actions on your account. You need to reauthenticate to perform sensitive actions on your account.
<% else %> <% else %>
<p class="settings-subtitle my-4"> <p :if={!@prelaunch} class="settings-subtitle my-4">
Don't have an account? <.link Don't have an account? <.link
navigate={~p"/users/register"} navigate={~p"/users/register"}
class="font-semibold text-primary-text hover:underline" class="font-semibold text-primary-text hover:underline"
@@ -25,7 +25,7 @@ defmodule ChesstrainerWeb.UserLive.Login do
:let={f} :let={f}
for={@form} for={@form}
id="login_form_password" id="login_form_password"
action={~p"/users/log-in"} action={@login_action}
phx-submit="submit_password" phx-submit="submit_password"
phx-trigger-action={@trigger_submit} 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)]) get_in(socket.assigns, [:current_scope, Access.key(:user), Access.key(:email)])
form = to_form(%{"email" => email}, as: "user") 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 end
@impl true @impl true
@@ -74,19 +74,40 @@ defmodule ChesstrainerWeb.UserLive.Registration do
end end
@impl true @impl true
def mount(_params, _session, %{assigns: %{current_scope: %{user: user}}} = socket) 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 when not is_nil(user) do
{:ok, redirect(socket, to: ChesstrainerWeb.UserAuth.signed_in_path(socket))} {:ok, redirect(socket, to: ChesstrainerWeb.UserAuth.signed_in_path(socket))}
end end
def mount(_params, _session, socket) do defp do_mount(socket) do
changeset = Accounts.change_user_registration(%User{}, %{}, validate_unique: false) changeset = Accounts.change_user_registration(%User{}, %{}, validate_unique: false)
{:ok, assign_form(socket, changeset), temporary_assigns: [form: nil]} {:ok, assign_form(socket, changeset), temporary_assigns: [form: nil]}
end end
@impl true defp save_registration(socket, user_params) do
def handle_event("save", %{"user" => user_params}, socket) do
case Accounts.register_user(user_params) do case Accounts.register_user(user_params) do
{:ok, user} -> {:ok, user} ->
if user.mailing_list, do: MailingList.subscribe_user(user) if user.mailing_list, do: MailingList.subscribe_user(user)
@@ -110,10 +131,7 @@ defmodule ChesstrainerWeb.UserLive.Registration do
end end
end end
def handle_event("validate", %{"user" => user_params}, socket) do defp prelaunch?, do: Application.get_env(:chesstrainer, :prelaunch, false)
changeset = Accounts.change_user_registration(%User{}, user_params, validate_unique: false)
{:noreply, assign_form(socket, Map.put(changeset, :action, :validate))}
end
defp assign_form(socket, %Ecto.Changeset{} = changeset) do defp assign_form(socket, %Ecto.Changeset{} = changeset) do
form = to_form(changeset, as: "user") form = to_form(changeset, as: "user")
+57
View File
@@ -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
+16 -3
View File
@@ -10,6 +10,7 @@ defmodule ChesstrainerWeb.Router do
plug :put_root_layout, html: {ChesstrainerWeb.Layouts, :root} plug :put_root_layout, html: {ChesstrainerWeb.Layouts, :root}
plug :protect_from_forgery plug :protect_from_forgery
plug :put_secure_browser_headers plug :put_secure_browser_headers
plug ChesstrainerWeb.Plugs.Prelaunch
plug :fetch_current_scope_for_user plug :fetch_current_scope_for_user
end end
@@ -34,13 +35,17 @@ defmodule ChesstrainerWeb.Router do
get "/terms-conditions", PageController, :terms_conditions get "/terms-conditions", PageController, :terms_conditions
post "/mailing-list", MailingListController, :create post "/mailing-list", MailingListController, :create
get "/mailing-list/confirm/:token", MailingListController, :confirm get "/mailing-list/confirm/:token", MailingListController, :confirm
post "/admin/log-in", UserSessionController, :create_admin
end end
scope "/admin", ChesstrainerWeb do scope "/admin", ChesstrainerWeb do
pipe_through [:browser, :noindex, :require_admin_user] pipe_through [:browser, :noindex, :require_admin_user]
live_session :endgames, 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", EndgameLive.Index, :index
live "/endgames/new", EndgameLive.Form, :new live "/endgames/new", EndgameLive.Form, :new
live "/endgames/:id", EndgameLive.Show, :show live "/endgames/:id", EndgameLive.Show, :show
@@ -76,7 +81,10 @@ defmodule ChesstrainerWeb.Router do
pipe_through [:browser, :require_authenticated_user] pipe_through [:browser, :require_authenticated_user]
live_session :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 "/endgames", EndgameLive.PlayerIndex, :index
live "/train", EndgameLive.Train, :train live "/train", EndgameLive.Train, :train
live "/users/profile", UserLive.Profile, :account live "/users/profile", UserLive.Profile, :account
@@ -95,11 +103,15 @@ defmodule ChesstrainerWeb.Router do
pipe_through [:browser] pipe_through [:browser]
live_session :current_user, 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 "/guest-train", EndgameLive.GuestTrain, :play
live "/endgames/:public_code/play", EndgameLive.Play, :play live "/endgames/:public_code/play", EndgameLive.Play, :play
live "/users/register", UserLive.Registration, :new live "/users/register", UserLive.Registration, :new
live "/users/log-in", UserLive.Login, :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", UserLive.ResetPassword, :new
live "/users/reset-password/:token", UserLive.ResetPassword, :edit live "/users/reset-password/:token", UserLive.ResetPassword, :edit
end end
@@ -115,6 +127,7 @@ defmodule ChesstrainerWeb.Router do
scope "/", ChesstrainerWeb do scope "/", ChesstrainerWeb do
pipe_through :seo pipe_through :seo
get "/health", HealthController, :index
get "/robots.txt", RobotsController, :index get "/robots.txt", RobotsController, :index
get "/sitemap.xml", SitemapController, :index get "/sitemap.xml", SitemapController, :index
end end
+18
View File
@@ -212,6 +212,24 @@ defmodule ChesstrainerWeb.UserAuth do
live "/profile", ProfileLive, :index live "/profile", ProfileLive, :index
end 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 def on_mount(:mount_current_scope, _params, session, socket) do
{:cont, mount_current_scope(socket, session)} {:cont, mount_current_scope(socket, session)}
end end
+4
View File
@@ -0,0 +1,4 @@
[tools]
erlang = "28.5"
elixir = "1.19.5-otp-28"
rust = "1.98.1"
+1
View File
@@ -91,6 +91,7 @@ defmodule Chesstrainer.MixProject do
"assets.setup": ["tailwind.install --if-missing", "esbuild.install --if-missing"], "assets.setup": ["tailwind.install --if-missing", "esbuild.install --if-missing"],
"assets.build": ["compile", "tailwind chesstrainer", "esbuild chesstrainer"], "assets.build": ["compile", "tailwind chesstrainer", "esbuild chesstrainer"],
"assets.deploy": [ "assets.deploy": [
"compile",
"tailwind chesstrainer --minify", "tailwind chesstrainer --minify",
"esbuild chesstrainer --minify", "esbuild chesstrainer --minify",
"phx.digest" "phx.digest"
+5
View File
@@ -0,0 +1,5 @@
#!/bin/sh
set -eu
cd -P -- "$(dirname -- "$0")"
exec ./chesstrainer eval Chesstrainer.Release.migrate
+1
View File
@@ -0,0 +1 @@
call "%~dp0\chesstrainer" eval Chesstrainer.Release.migrate
+5
View File
@@ -0,0 +1,5 @@
#!/bin/sh
set -eu
cd -P -- "$(dirname -- "$0")"
PHX_SERVER=true exec ./chesstrainer start
+2
View File
@@ -0,0 +1,2 @@
set PHX_SERVER=true
call "%~dp0\chesstrainer" start
@@ -0,0 +1,62 @@
defmodule ChesstrainerWeb.HealthControllerTest do
use ChesstrainerWeb.ConnCase, async: false
describe "GET /health" do
test "returns ok with all four fields", %{conn: conn} do
conn = get(conn, ~p"/health")
body = json_response(conn, 200)
assert body["status"] == "ok"
assert body["db"] == "ok"
assert body["tablebase"] == "local"
assert body["process"] == "ok"
assert get_resp_header(conn, "x-robots-tag") == ["noindex"]
end
test "returns degraded when local tablebases are not configured", %{conn: conn} do
previous = Application.get_env(:chesstrainer, :tablebase_path)
on_exit(fn -> restore_env(:tablebase_path, previous) end)
Application.delete_env(:chesstrainer, :tablebase_path)
conn = get(conn, ~p"/health")
body = json_response(conn, 200)
assert body["status"] == "degraded"
assert body["db"] == "ok"
assert body["tablebase"] == "not_configured"
assert body["process"] == "ok"
end
test "returns degraded when local tablebases are misconfigured", %{conn: conn} do
previous = Application.get_env(:chesstrainer, :tablebase_path)
on_exit(fn -> restore_env(:tablebase_path, previous) end)
Application.put_env(:chesstrainer, :tablebase_path, "/definitely/not/a/tablebase")
conn = get(conn, ~p"/health")
body = json_response(conn, 200)
assert body["status"] == "degraded"
assert body["db"] == "ok"
assert body["tablebase"] == "fallback"
assert body["process"] == "ok"
end
test "returns 503 when the database is down", %{conn: conn} do
previous = Application.get_env(:chesstrainer, :health_database_check)
on_exit(fn -> restore_env(:health_database_check, previous) end)
Application.put_env(:chesstrainer, :health_database_check, fn -> false end)
conn = get(conn, ~p"/health")
body = json_response(conn, 503)
assert body["status"] == "down"
assert body["db"] == "down"
assert body["tablebase"] == "local"
assert body["process"] == "ok"
assert get_resp_header(conn, "x-robots-tag") == ["noindex"]
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
@@ -1,5 +1,5 @@
defmodule ChesstrainerWeb.MailingListControllerTest do defmodule ChesstrainerWeb.MailingListControllerTest do
use ChesstrainerWeb.ConnCase, async: true use ChesstrainerWeb.ConnCase, async: false
alias Chesstrainer.MailingList alias Chesstrainer.MailingList
alias Chesstrainer.MailingList.Subscriber alias Chesstrainer.MailingList.Subscriber
@@ -169,6 +169,22 @@ defmodule ChesstrainerWeb.MailingListControllerTest do
assert redirected_to(conn) == "/#mailing-list" assert redirected_to(conn) == "/#mailing-list"
assert Phoenix.Flash.get(conn.assigns.flash, :error) =~ "valid email address" assert Phoenix.Flash.get(conn.assigns.flash, :error) =~ "valid email address"
end 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 end
describe "GET /mailing-list/confirm/:token" do describe "GET /mailing-list/confirm/:token" do
@@ -227,4 +243,7 @@ defmodule ChesstrainerWeb.MailingListControllerTest do
defp form_token do defp form_token do
MailingListFormToken.sign(System.system_time(:second) - 5) MailingListFormToken.sign(System.system_time(:second) - 5)
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 end
@@ -180,6 +180,29 @@ defmodule ChesstrainerWeb.PageControllerTest do
assert LazyHTML.text(LazyHTML.query(document, ".rating-note strong")) == "0" assert LazyHTML.text(LazyHTML.query(document, ".rating-note strong")) == "0"
end 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 test "renders the mailing list signup form", %{conn: conn} do
html = conn |> get(~p"/") |> html_response(200) html = conn |> get(~p"/") |> html_response(200)
document = LazyHTML.from_document(html) document = LazyHTML.from_document(html)
@@ -305,4 +328,7 @@ defmodule ChesstrainerWeb.PageControllerTest do
assert html =~ "Browse puzzles" assert html =~ "Browse puzzles"
assert html =~ ~s(href="/endgames") assert html =~ ~s(href="/endgames")
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 end
@@ -1,5 +1,5 @@
defmodule ChesstrainerWeb.RobotsControllerTest do defmodule ChesstrainerWeb.RobotsControllerTest do
use ChesstrainerWeb.ConnCase, async: true use ChesstrainerWeb.ConnCase, async: false
alias ChesstrainerWeb.Endpoint alias ChesstrainerWeb.Endpoint
@@ -18,5 +18,20 @@ defmodule ChesstrainerWeb.RobotsControllerTest do
assert [content_type] = get_resp_header(conn, "content-type") assert [content_type] = get_resp_header(conn, "content-type")
assert content_type =~ "text/plain" assert content_type =~ "text/plain"
end 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
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 end
@@ -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