mirror of
https://github.com/TheRealOwenRees/chess-endgame-trainer.git
synced 2026-11-18 11:42:07 +00:00
Compare commits
70
Commits
c95173cda8
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2759b34296 | ||
|
|
e6f08e0ca6 | ||
|
|
946fc38756 | ||
|
|
80cb033077 | ||
|
|
7209923de7
|
||
|
|
f4ff1e00fb
|
||
|
|
514c6ac924
|
||
|
|
e0b446bbfb | ||
|
|
fa1fef7b62 | ||
|
|
37e0ac8e56 | ||
|
|
b33c5e334a | ||
|
|
aebb2aecfb | ||
|
|
8934d191ad | ||
|
|
021e412167 | ||
|
|
0563b5aca2 | ||
|
|
0ae4c5b6fd | ||
|
|
b41c8bf1a6 | ||
|
|
69b89f68ef | ||
|
|
f27e16af1d | ||
|
|
fddb94e2bd | ||
|
|
20b53dae6f | ||
|
|
9e76045862 | ||
|
|
624ddab644 | ||
|
|
202b9b1f6a | ||
|
|
f8897fa5ae | ||
|
|
73ba25afe3 | ||
|
|
be57f21729
|
||
|
|
ee687dfb2d
|
||
|
|
fa90e1102d
|
||
|
|
2821f8e984
|
||
|
|
fda52dd2e7
|
||
|
|
7463784e03
|
||
|
|
f024bc608d
|
||
|
|
f12ae0b81f
|
||
|
|
8b25020737
|
||
|
|
56d51347b9
|
||
|
|
4c39f231f1
|
||
|
|
b1767e5fbc
|
||
|
|
3a849ddff0
|
||
|
|
79782dc778
|
||
|
|
9d3dd426db
|
||
|
|
cae4e35a70 | ||
|
|
5b3241ae1f | ||
|
|
805c2f1150 | ||
|
|
8df7ac982c
|
||
|
|
aa9c882b08
|
||
|
|
eaf72a7686
|
||
|
|
924a3e08dc
|
||
|
|
b54fb0a6d7
|
||
|
|
46bc27f614
|
||
|
|
f2d886d602
|
||
|
|
64a9210580
|
||
|
|
5c8d2494b6
|
||
|
|
1003ec203a
|
||
|
|
f9340fb57b
|
||
|
|
c71f465487 | ||
|
|
f5efcde5ca
|
||
|
|
bf176ebd42
|
||
|
|
785e403370
|
||
|
|
b17f346b25 | ||
|
|
bd8be4d10d | ||
|
|
6a4288bb6c
|
||
|
|
dda588da06 | ||
|
|
2c5e290e66
|
||
|
|
2f3f39a21d
|
||
|
|
8d1876b13b
|
||
|
|
0453e97897
|
||
|
|
1b44dae378
|
||
|
|
84eee4057e
|
||
|
|
55d2e2a913
|
@@ -0,0 +1,19 @@
|
||||
SECRET_KEY_BASE=...
|
||||
DATABASE_URL=...
|
||||
PHX_HOST=innersquare.app
|
||||
PORT=4000
|
||||
PRELAUNCH=true
|
||||
MAILING_LIST_ENABLED=false
|
||||
SES_REGION=eu-north-1
|
||||
SES_ACCESS_KEY_ID=AKIA...
|
||||
SES_SECRET_ACCESS_KEY=...
|
||||
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
|
||||
# Optional: directory of local Syzygy .rtbw/.rtbz files. Ignored by the test
|
||||
# suite, which always uses the committed 3-piece fixtures.
|
||||
TABLEBASE_PATH=
|
||||
|
||||
MATOMO_URL=https://analytics.owenrees.eu/
|
||||
MATOMO_SITE_ID=6
|
||||
@@ -0,0 +1,137 @@
|
||||
name: CI
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
push:
|
||||
branches: [main]
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: ci-${{ github.workflow }}-${{ github.ref }}
|
||||
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
|
||||
|
||||
jobs:
|
||||
test:
|
||||
name: Test
|
||||
runs-on: ubuntu-24.04
|
||||
env:
|
||||
MIX_ENV: test
|
||||
|
||||
services:
|
||||
postgres:
|
||||
image: postgres:18.6
|
||||
env:
|
||||
POSTGRES_USER: postgres
|
||||
POSTGRES_PASSWORD: postgres
|
||||
ports:
|
||||
- 5432:5432
|
||||
options: >-
|
||||
--health-cmd "pg_isready -U postgres"
|
||||
--health-interval 5s
|
||||
--health-timeout 5s
|
||||
--health-retries 10
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 #v7.0.1
|
||||
- uses: jdx/mise-action@b44d12e7d0d8ee7461bb893e1b1993500433185b #v5.2.7
|
||||
|
||||
- uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 #v6.1.0
|
||||
with:
|
||||
path: |
|
||||
deps
|
||||
~/.cargo/registry
|
||||
~/.cargo/git
|
||||
key: ${{ runner.os }}-mix-test-${{ hashFiles('mix.lock', 'mise.toml') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-mix-test-
|
||||
|
||||
- run: mix local.hex --force
|
||||
- run: mix local.rebar --force
|
||||
- run: mix deps.get
|
||||
- run: mix format --check-formatted
|
||||
- run: mix precommit
|
||||
|
||||
build-release:
|
||||
name: Build release
|
||||
needs: test
|
||||
runs-on: ubuntu-24.04
|
||||
env:
|
||||
MIX_ENV: prod
|
||||
SECRET_KEY_BASE: build-only-secret-key-base-build-only-secret-key-base-build-only-secret-key-base
|
||||
DATABASE_URL: ecto://postgres:postgres@127.0.0.1:5432/chesstrainer_build
|
||||
SES_REGION: eu-north-1
|
||||
SES_ACCESS_KEY_ID: build
|
||||
SES_SECRET_ACCESS_KEY: build
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 #v7.0.1
|
||||
- uses: jdx/mise-action@b44d12e7d0d8ee7461bb893e1b1993500433185b #v5.2.7
|
||||
|
||||
- uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 #v6.1.0
|
||||
with:
|
||||
path: |
|
||||
deps
|
||||
~/.cargo/registry
|
||||
~/.cargo/git
|
||||
assets/node_modules
|
||||
key: ${{ runner.os }}-mix-prod-${{ hashFiles('mix.lock', 'mise.toml', 'assets/package-lock.json') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-mix-prod-
|
||||
|
||||
- run: mix local.hex --force
|
||||
- run: mix local.rebar --force
|
||||
- run: npm ci --prefix assets --no-audit --no-fund
|
||||
- run: mix deps.get --only prod
|
||||
- run: mix assets.setup
|
||||
- run: mix assets.deploy
|
||||
- run: mix release
|
||||
- run: tar -czf chesstrainer-release.tar.gz -C _build/prod/rel/chesstrainer .
|
||||
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: chesstrainer-release
|
||||
path: chesstrainer-release.tar.gz
|
||||
retention-days: 7
|
||||
|
||||
deploy:
|
||||
name: Deploy
|
||||
needs: build-release
|
||||
if: github.ref == 'refs/heads/main' && (github.event_name == 'push' || github.event_name == 'workflow_dispatch')
|
||||
runs-on: ubuntu-24.04
|
||||
environment: production
|
||||
concurrency:
|
||||
group: production
|
||||
cancel-in-progress: false
|
||||
|
||||
steps:
|
||||
- uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 #v8.0.2
|
||||
with:
|
||||
name: chesstrainer-release
|
||||
|
||||
- name: Install SSH key
|
||||
run: |
|
||||
mkdir -p ~/.ssh
|
||||
printf '%s\n' "${{ secrets.VPS_SSH_KEY }}" > ~/.ssh/id_ed25519
|
||||
chmod 600 ~/.ssh/id_ed25519
|
||||
printf '%s\n' "${{ secrets.VPS_KNOWN_HOSTS }}" > ~/.ssh/known_hosts
|
||||
chmod 644 ~/.ssh/known_hosts
|
||||
|
||||
- name: Upload release
|
||||
run: |
|
||||
scp -i ~/.ssh/id_ed25519 -o BatchMode=yes \
|
||||
chesstrainer-release.tar.gz \
|
||||
"${{ secrets.VPS_USER }}@${{ secrets.VPS_HOST }}:/tmp/chesstrainer-release.tar.gz"
|
||||
|
||||
- name: Activate release
|
||||
run: |
|
||||
ssh -i ~/.ssh/id_ed25519 -o BatchMode=yes \
|
||||
"${{ secrets.VPS_USER }}@${{ secrets.VPS_HOST }}" \
|
||||
'sudo -n /opt/chesstrainer/src/deploy/activate /tmp/chesstrainer-release.tar.gz'
|
||||
|
||||
- name: Public smoke test
|
||||
run: |
|
||||
curl -fsS https://innersquare.app/health
|
||||
curl -fsS -o /dev/null https://innersquare.app/
|
||||
+5
-1
@@ -31,8 +31,12 @@ chesstrainer-*.tar
|
||||
# Ignore ETS table backups
|
||||
/priv/static/backups/
|
||||
|
||||
# Ignore digested assets cache.
|
||||
# Ignore digested assets cache and generated digests.
|
||||
/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.
|
||||
npm-debug.log
|
||||
|
||||
+31
-1
@@ -24,7 +24,7 @@ _Avoid_: Random puzzle, featured puzzle
|
||||
**Attempt**:
|
||||
A recorded playthrough of a puzzle by a user, ending solved or failed; a
|
||||
per-user record, distinct from an endgame's global attempt and solve counts.
|
||||
_Avoid_: Run, session, game
|
||||
_Avoid_: Run, game
|
||||
|
||||
**Theme**:
|
||||
A label describing an endgame's technique or goal, such as "mate in 2", "Lucena" or
|
||||
@@ -64,6 +64,12 @@ _Avoid_: Permission, access level
|
||||
A user's subscription tier — `free` or `premium` — independent of their role.
|
||||
_Avoid_: Tier, subscription, membership
|
||||
|
||||
**Mailing list**:
|
||||
Email addresses that opted in to occasional product updates, collected from the
|
||||
landing-page form or the registration checkbox; a subscriber need not have an
|
||||
account.
|
||||
_Avoid_: Newsletter, subscription (reserved for the premium plan)
|
||||
|
||||
## Play
|
||||
|
||||
**Winning side**:
|
||||
@@ -93,6 +99,20 @@ The decisive zeroing move — a promotion — that ends a conversion-type puzzle
|
||||
The terminal condition short of mate at which a puzzle counts as solved:
|
||||
promotion (still winning) for conversion puzzles, mate otherwise.
|
||||
|
||||
**Session**:
|
||||
One continuous spell of puzzle play, begun by choosing a difficulty, that
|
||||
carries a start time and a rating baseline for the timer and rating-gain
|
||||
monitor. Ephemeral — it lives only in the running LiveView, never persisted.
|
||||
_Avoid_: Run, game, attempt
|
||||
|
||||
**Repeat window**:
|
||||
The minimum interval before the same endgame may be served to the same user
|
||||
again. Selection skips endgames attempted inside the window; only when nothing
|
||||
else is available does the least recently attempted endgame come back. It is
|
||||
independent of the rating window, which decides whether a replay may move a
|
||||
rating.
|
||||
_Avoid_: Cooldown (reserved for tablebase rate-limiting), due date
|
||||
|
||||
## Ratings
|
||||
|
||||
**Rating**:
|
||||
@@ -115,6 +135,16 @@ A measure of how erratic a competitor's recent results are, used by some rating
|
||||
systems; the trainer deliberately does not track it.
|
||||
_Avoid_: Variance, inconsistency
|
||||
|
||||
**Difficulty**:
|
||||
A choice — `easy`, `medium` or `hard` — that biases which puzzles are served
|
||||
relative to the current user's rating: `medium` centres on the user's rating,
|
||||
`easy` below it, `hard` above it. Candidates are weighted by how close their
|
||||
rating is to that centre, so a session draws mostly from near the target but the
|
||||
whole library stays reachable. The spread is a configured constant. It is a
|
||||
property of a session, not of an endgame — the same endgame is easy for one user
|
||||
and hard for another.
|
||||
_Avoid_: Level, rank, tier
|
||||
|
||||
## Infrastructure
|
||||
|
||||
**Tablebase**:
|
||||
|
||||
@@ -21,9 +21,21 @@ mix tablebase.fetch --path /path/to/syzygy/3-4-5 # once per host (~939 MB)
|
||||
export TABLEBASE_PATH=/path/to/syzygy/3-4-5 # set per environment
|
||||
```
|
||||
|
||||
On the production VPS the directory is `/opt/chesstrainer/tablebases`, owned by
|
||||
the `chesstrainer` user. Set `TABLEBASE_PATH` in `/etc/chesstrainer/env` and
|
||||
restart the service; the value is read at boot.
|
||||
|
||||
See [docs/tablebases.md](docs/tablebases.md) for the full reference — dev vs
|
||||
VPS paths, `mix tablebase.check`, and boot logging.
|
||||
|
||||
## Logging
|
||||
|
||||
Production logs are one JSON object per line so they can be filtered with
|
||||
`journalctl` and `jq`; development and test keep the readable formatter. See
|
||||
[docs/logging.md](docs/logging.md) for the line shape, redaction rules and the
|
||||
background-work audit, and [`deploy/README.md`](deploy/README.md) for the VPS
|
||||
runbook.
|
||||
|
||||
## Learn more
|
||||
|
||||
* Official website: https://www.phoenixframework.org/
|
||||
|
||||
-36
@@ -1,36 +0,0 @@
|
||||
# Project Roadmap
|
||||
|
||||
High-level implementation milestones and strategic direction
|
||||
|
||||
---
|
||||
|
||||
## Phase 1: MVP & Core Functionality (Current Focus)
|
||||
Target: Q1 2027
|
||||
|
||||
- [ ] **Initial UI / Interface**
|
||||
- [ ] Create front page and settle on colour scheme
|
||||
- [ ] Apply colour scheme across the site
|
||||
- [ ] Allow colour theme to be changed on chessboard
|
||||
- [ ] **Core Features**
|
||||
- [x] Log in
|
||||
- [x] Rating of user and puzzles
|
||||
- [x] Implement core API endpoints with input validation.
|
||||
- [ ] Traverse puzzles in easy/medium/hard mode with session timer/rating+/-
|
||||
|
||||
---
|
||||
|
||||
## Phase 2: Polish & Reliability
|
||||
Target: Q2 2027
|
||||
|
||||
- [ ] **Security & Compliance**
|
||||
- [ ] Complete security hardening and dependency vulnerability auditing.
|
||||
- [ ] **Testing & Quality Control**
|
||||
- [ ] Expand integration test suite for critical API paths.
|
||||
- [ ] Set up automated WCAG accessibility audits in CI.
|
||||
- [ ] **Performance & Caching**
|
||||
- [ ] Optimize database indexes and payload response sizes.
|
||||
- [x] Implement local caching strategy for high-frequency queries.
|
||||
- [ ] **Logged in user features**
|
||||
- [ ] Allow logged in users to see their progrees on a profile page
|
||||
|
||||
---
|
||||
@@ -1,33 +0,0 @@
|
||||
# Immediate TODOs
|
||||
|
||||
Granular tasks and operational scratchpad for active development.
|
||||
|
||||
---
|
||||
|
||||
## In Progress 🟡
|
||||
- [x] Basic design and colour scheme
|
||||
- [x] Apply design to the rest of the site
|
||||
- [x] Create reusable components such as button
|
||||
- [x] Organise nav bar
|
||||
- [ ] Display puzzles and move to next
|
||||
- [x] Create footer
|
||||
|
||||
---
|
||||
|
||||
## Next Up (Sprint Backlog) 🟢
|
||||
- [ ] Forgot password
|
||||
- [ ] Anonymous trial of 10 puzzles without logging in
|
||||
- [x] Light / Dark mode
|
||||
- [ ] WCAG compliance
|
||||
- [x] Self host font - google fonts not gdpr compliant
|
||||
---
|
||||
|
||||
## Tech Debt & Refactoring 🧹
|
||||
- [ ] Split CSS into modules (ongoing)
|
||||
|
||||
---
|
||||
|
||||
## Deferred / Parking Lot 🧊
|
||||
- [ ] Profile page
|
||||
- [ ] Visual guide to user progress / attemps
|
||||
- [ ] Export user data
|
||||
@@ -20,8 +20,11 @@
|
||||
@import "./components/_icon.css";
|
||||
@import "./components/_button.css";
|
||||
@import "./components/_learning-strip.css";
|
||||
@import "./components/_mailing-list.css";
|
||||
@import "./components/_board.css";
|
||||
@import "./components/_promotion.css";
|
||||
@import "./pages/_legal.css";
|
||||
@import "./pages/_error.css";
|
||||
|
||||
@source "../css";
|
||||
@source "../js";
|
||||
@@ -40,6 +43,10 @@
|
||||
.avatar-stack i:last-child { background: var(--color-deep); color: var(--color-on-deep); }
|
||||
.puzzle-section { width: min(1180px, calc(100% - 48px)); margin: 0 auto; padding: 110px 0 125px; }
|
||||
.puzzle-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 16px; }
|
||||
.puzzle-coming-soon { min-height: 285px; display: grid; place-content: center; justify-items: center; gap: 10px; padding: 46px 28px; text-align: center; border: 1px dashed var(--color-hairline); border-radius: 12px; background: var(--color-canvas-raised); }
|
||||
.puzzle-coming-soon .eyebrow { margin-bottom: 6px; }
|
||||
.puzzle-coming-soon strong { font-family: 'DM Serif Display', serif; font-size: 30px; font-weight: 400; }
|
||||
.puzzle-coming-soon p { max-width: 420px; margin: 0; color: var(--color-muted); font-size: 14px; line-height: 1.7; }
|
||||
.puzzle-card { display: block; position: relative; min-height: 285px; padding: 25px; text-align: left; text-decoration: none; color: inherit; cursor: pointer; border: 1px solid var(--color-hairline); border-radius: 12px; background: rgba(255,255,255,.28); overflow: hidden; transition: transform .25s, background .25s, box-shadow .25s; }
|
||||
.puzzle-card:hover, .puzzle-card.active { transform: translateY(-5px); background: var(--color-canvas-raised); box-shadow: 0 18px 36px rgba(23,53,45,.08); }
|
||||
.puzzle-card.active { border-color: var(--color-success-text); }
|
||||
@@ -66,6 +73,7 @@ html[data-theme="dark"] .learning-strip { box-shadow: inset 0 1px 0 var(--color-
|
||||
@media (max-width: 650px) {
|
||||
.puzzle-section { width: calc(100% - 36px); padding: 80px 0; }
|
||||
.puzzle-grid { grid-template-columns: 1fr; }
|
||||
.puzzle-coming-soon { min-height: 255px; padding: 38px 22px; }
|
||||
.puzzle-card { min-height: 255px; }
|
||||
.progress-banner { width: calc(100% - 36px); padding: 48px 28px; flex-direction: column; align-items: flex-start; gap: 34px; }
|
||||
}
|
||||
|
||||
@@ -6,15 +6,23 @@
|
||||
html { scroll-behavior: smooth; }
|
||||
body {
|
||||
min-width: 320px;
|
||||
min-height: 100vh;
|
||||
min-height: 100dvh;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
background: var(--color-canvas);
|
||||
color: var(--color-body);
|
||||
font-family: 'DM Sans', sans-serif;
|
||||
}
|
||||
button, a { -webkit-tap-highlight-color: transparent; }
|
||||
button { cursor: pointer; }
|
||||
|
||||
/* A consistent focus ring for links, buttons and native controls. Components
|
||||
that provide their own ring (form inputs) override this through utilities. */
|
||||
:focus-visible { outline: 2px solid var(--color-coral-text); outline-offset: 2px; }
|
||||
}
|
||||
|
||||
main { overflow: hidden; }
|
||||
main { overflow: hidden; flex: 1 0 auto; }
|
||||
|
||||
/* LiveView */
|
||||
@custom-variant phx-click-loading (.phx-click-loading&, .phx-click-loading &);
|
||||
|
||||
+19
-10
@@ -10,8 +10,11 @@
|
||||
--color-coral: var(--coral);
|
||||
--color-coral-control: var(--coral);
|
||||
--color-coral-control-hover: var(--coral-dark);
|
||||
--color-coral-text: var(--coral-dark);
|
||||
--color-success-text: var(--mint-deep);
|
||||
--color-coral-text: #b8432c;
|
||||
--color-success-text: #3f6d5a;
|
||||
--color-warning-text: #8a5a00;
|
||||
--color-primary-text: #b8432c;
|
||||
--color-error-text: #b8432c;
|
||||
--color-mint-chip: var(--mint);
|
||||
--color-on-accent-muted: #5f2c23;
|
||||
|
||||
@@ -43,14 +46,17 @@
|
||||
--color-accent-content: #ffffff;
|
||||
--color-neutral: #587068;
|
||||
--color-neutral-content: #f4f0e6;
|
||||
--color-info: oklch(62% 0.214 259.815);
|
||||
--color-info-content: oklch(97% 0.014 254.604);
|
||||
/* Toasts use the brand palette rather than the stock blue/red: info is the
|
||||
deep ink green, error is the coral used by primary actions. Both pass AA
|
||||
against their content colour. */
|
||||
--color-info: #17352d;
|
||||
--color-info-content: #fffcf4;
|
||||
--color-success: oklch(70% 0.14 182.503);
|
||||
--color-success-content: oklch(98% 0.014 180.72);
|
||||
--color-warning: oklch(66% 0.179 58.318);
|
||||
--color-warning-content: oklch(98% 0.022 95.277);
|
||||
--color-error: oklch(58% 0.253 17.585);
|
||||
--color-error-content: oklch(96% 0.015 12.422);
|
||||
--color-error: #c74c33;
|
||||
--color-error-content: #ffffff;
|
||||
}
|
||||
|
||||
html[data-theme="dark"] {
|
||||
@@ -68,6 +74,9 @@ html[data-theme="dark"] {
|
||||
--color-coral-control-hover: #b8432c;
|
||||
--color-coral-text: #ff9c85;
|
||||
--color-success-text: #8fd3b5;
|
||||
--color-warning-text: #f0b35a;
|
||||
--color-primary-text: #f2816b;
|
||||
--color-error-text: #f2816b;
|
||||
--color-mint-chip: #24403a;
|
||||
--color-on-accent-muted: rgba(255, 255, 255, 0.97);
|
||||
--color-promotion-surface: #1b2822;
|
||||
@@ -87,12 +96,12 @@ html[data-theme="dark"] {
|
||||
--color-accent-content: #0f1714;
|
||||
--color-neutral: #2b3a33;
|
||||
--color-neutral-content: #e9efe9;
|
||||
--color-info: oklch(70% 0.14 240);
|
||||
--color-info-content: oklch(15% 0.02 240);
|
||||
--color-info: #24403a;
|
||||
--color-info-content: #e9efe9;
|
||||
--color-success: oklch(72% 0.13 165);
|
||||
--color-success-content: oklch(15% 0.02 165);
|
||||
--color-warning: oklch(78% 0.15 75);
|
||||
--color-warning-content: oklch(20% 0.03 75);
|
||||
--color-error: oklch(66% 0.19 22);
|
||||
--color-error-content: oklch(15% 0.02 22);
|
||||
--color-error: #c74c33;
|
||||
--color-error-content: #ffffff;
|
||||
}
|
||||
@@ -34,6 +34,16 @@ h1, h2 { font-family: 'DM Serif Display', serif; font-weight: 400; letter-spacin
|
||||
h1 { max-width: 590px; font-size: clamp(56px, 6vw, 87px); line-height: .93; }
|
||||
h1 em { color: var(--color-coral); font-weight: 400; }
|
||||
|
||||
.settings-header {
|
||||
font-size: 3rem;
|
||||
}
|
||||
|
||||
.settings-subtitle {
|
||||
font-size: 1rem;;
|
||||
color: var(--color-muted);
|
||||
margin-top: 0.5rem;
|
||||
}
|
||||
|
||||
@media (max-width: 650px) {
|
||||
h1 { font-size: clamp(51px, 15vw, 68px); }
|
||||
}
|
||||
@@ -39,3 +39,17 @@
|
||||
/* Admin Chessboard */
|
||||
.bg-boardwhite { background-color: #f2f5f3; /* light square */ }
|
||||
.bg-boardblack { background-color: #71828f; /* dark square */ }
|
||||
|
||||
/* Play board */
|
||||
#endgame-board { position: relative; }
|
||||
|
||||
/* Chessground's stock stylesheet shifts the file labels 24px right of the
|
||||
board, assuming a gutter we don't have, so they land on square boundaries
|
||||
instead of under each file. Place the row on the board and right-justify
|
||||
each label within its square; the row's width already matches the board
|
||||
because the container is sized to whole squares. */
|
||||
#endgame-board coords.files { left: 0; text-align: right; }
|
||||
|
||||
/* Chessground's wrapper has no intrinsic height; let it fill the sized
|
||||
aspect-ratio container so the board scales with the viewport. */
|
||||
#endgame-board .cg-wrap { width: 100%; height: 100%; }
|
||||
@@ -1,2 +1,9 @@
|
||||
.eyebrow { display: flex; align-items: center; gap: 9px; margin-bottom: 27px; color: var(--color-coral-text); text-transform: uppercase; letter-spacing: .13em; font-size: 12px; font-weight: 700; }
|
||||
.eyebrow svg { width: 20px; height: 20px; }
|
||||
|
||||
/* Icon-only external links, e.g. the Discord invite in the navbar and footer.
|
||||
Colour is inherited so the glyph matches the surrounding link row. */
|
||||
.discord-link { display: inline-flex; align-items: center; color: inherit; transition: opacity .2s; }
|
||||
.discord-link:hover { opacity: .55; }
|
||||
.discord-link:focus-visible { outline: 2px solid var(--color-coral-control); outline-offset: 3px; border-radius: 4px; }
|
||||
.discord-link svg { width: 20px; height: 20px; }
|
||||
|
||||
@@ -3,7 +3,9 @@
|
||||
display: grid; grid-template-columns: 1.5fr repeat(3, 1fr); align-items: center; background: var(--color-deep); color: var(--color-on-deep);
|
||||
}
|
||||
|
||||
.learning-strip > p { max-width: 260px; color: var(--color-on-deep-muted); font-family: 'DM Serif Display', serif; font-size: 19px; line-height: 1.25; }
|
||||
.learning-quote { margin: 0; max-width: 300px; }
|
||||
.learning-quote blockquote { margin: 0; color: var(--color-on-deep); font-family: 'DM Serif Display', serif; font-size: 19px; line-height: 1.25; }
|
||||
.learning-quote figcaption { margin-top: 10px; color: var(--color-on-deep-faint); font-size: 10px; text-transform: uppercase; letter-spacing: .09em; }
|
||||
|
||||
.stat { padding-left: 34px; border-left: 1px solid rgba(255,255,255,.17); }
|
||||
.stat strong { display: block; font-family: 'DM Serif Display', serif; font-size: 28px; font-weight: 400; }
|
||||
@@ -15,7 +17,7 @@
|
||||
|
||||
@media (max-width: 650px) {
|
||||
.learning-strip { padding: 38px 24px; grid-template-columns: 1fr 1fr; gap: 30px 10px; }
|
||||
.learning-strip > p { grid-column: 1 / -1; }
|
||||
.learning-quote { grid-column: 1 / -1; }
|
||||
.stat { padding-left: 18px; }
|
||||
.stat:last-child { grid-column: 1 / -1; }
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
.mailing-list {
|
||||
width: min(1180px, calc(100% - 48px));
|
||||
margin: 0 auto 110px;
|
||||
padding: 56px 60px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 48px;
|
||||
border-radius: 16px;
|
||||
background: var(--color-deep);
|
||||
color: var(--color-on-deep);
|
||||
}
|
||||
|
||||
.mailing-list-copy { max-width: 480px; }
|
||||
.mailing-list-copy .section-kicker { color: var(--color-on-deep-muted); }
|
||||
.mailing-list-copy h2 { font-size: clamp(32px, 3.4vw, 46px); line-height: 1; }
|
||||
.mailing-list-copy p { margin-top: 16px; color: var(--color-on-deep-muted); font-size: 14px; line-height: 1.65; }
|
||||
|
||||
.mailing-list-form { width: min(420px, 100%); flex-shrink: 0; }
|
||||
.mailing-list-honeypot { position: absolute; left: -10000px; width: 1px; height: 1px; overflow: hidden; }
|
||||
.mailing-list-form label { display: block; margin-bottom: 8px; color: var(--color-on-deep-faint); font-size: 11px; font-weight: 700; text-transform: uppercase; letter-spacing: .11em; }
|
||||
.mailing-list-row { display: flex; gap: 10px; }
|
||||
.mailing-list-row input { flex: 1; min-width: 0; padding: 15px 17px; border: 1px solid rgba(255, 255, 255, .22); border-radius: 8px; background: rgba(255, 255, 255, .1); color: var(--color-on-deep); font-size: 14px; }
|
||||
.mailing-list-row input::placeholder { color: var(--color-on-deep-faint); }
|
||||
.mailing-list-row input:focus { border-color: transparent; outline: 2px solid var(--color-coral); outline-offset: 2px; }
|
||||
.mailing-list-row .primary-button { white-space: nowrap; }
|
||||
|
||||
@media (max-width: 900px) {
|
||||
.mailing-list { flex-direction: column; align-items: flex-start; gap: 30px; }
|
||||
.mailing-list-form { width: 100%; }
|
||||
}
|
||||
|
||||
@media (max-width: 650px) {
|
||||
.mailing-list { width: calc(100% - 36px); margin-bottom: 80px; padding: 40px 24px; }
|
||||
.mailing-list-row { flex-direction: column; }
|
||||
.mailing-list-row .primary-button { justify-content: center; }
|
||||
}
|
||||
@@ -14,7 +14,15 @@
|
||||
.nav-links a { transition: opacity .2s; }
|
||||
.nav-links a:hover { opacity: .55; }
|
||||
.nav-links a.nav-cta:hover { opacity: 1; }
|
||||
.nav-user { color: var(--color-muted); font-weight: 500; }
|
||||
/* Utilities (colour mode, Discord) sit in the bar on desktop and in the
|
||||
collapsible menu on small screens. */
|
||||
.nav-menu-tools { display: none; }
|
||||
.nav-user-menu { position: relative; }
|
||||
.nav-user-menu summary { display: flex; align-items: center; gap: 6px; list-style: none; cursor: pointer; color: var(--color-muted); font-weight: 500; }
|
||||
.nav-user-menu summary::-webkit-details-marker { display: none; }
|
||||
.nav-user-menu summary::after { content: "▾"; font-size: 10px; }
|
||||
.nav-user-menu-panel { position: absolute; right: 0; top: calc(100% + 14px); z-index: 20; display: grid; gap: 12px; min-width: 170px; padding: 16px; border-radius: 10px; background: var(--color-canvas-raised); box-shadow: 0 18px 40px rgba(23,53,45,.15); }
|
||||
html[data-theme="dark"] .nav-user-menu-panel { box-shadow: 0 18px 40px rgba(0, 0, 0, .45); }
|
||||
.nav-cta, .primary-button, .light-button {
|
||||
display: inline-flex; align-items: center; justify-content: center; gap: 13px;
|
||||
border-radius: 999px; font-weight: 600; transition: transform .2s, background .2s;
|
||||
@@ -37,5 +45,11 @@
|
||||
.nav-links.open { display: flex; }
|
||||
.nav-cta { width: 100%; }
|
||||
.nav-links { display: none; position: absolute; top: 65px; left: 0; right: 0; padding: 24px; flex-direction: column; align-items: stretch; gap: 22px; border-radius: 10px; background: var(--color-canvas-raised); box-shadow: 0 18px 40px rgba(23,53,45,.15); }
|
||||
.nav-menu-tools { display: flex; align-items: center; justify-content: space-between; gap: 18px; width: 100%; }
|
||||
/* The menu owns these on small screens; keep them in the bar only when no
|
||||
menu is rendered (prelaunch with no links). */
|
||||
.nav-wrap:has(#nav-links) .nav-right > [role="radiogroup"],
|
||||
.nav-wrap:has(#nav-links) .nav-right > .discord-link { display: none; }
|
||||
.nav-user-menu-panel { position: static; min-width: 0; padding: 12px 0 0; background: transparent; box-shadow: none; }
|
||||
html[data-theme="dark"] .nav-links { box-shadow: 0 18px 40px rgba(0, 0, 0, .45); }
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
.error-page {
|
||||
width: min(760px, calc(100% - 48px));
|
||||
margin: 0 auto;
|
||||
padding: 100px 0 130px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.error-code {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
min-width: 68px;
|
||||
padding: 7px 16px;
|
||||
border: 1px solid var(--color-hairline);
|
||||
border-radius: 999px;
|
||||
color: var(--color-coral-text);
|
||||
font-size: 12px;
|
||||
font-weight: 700;
|
||||
letter-spacing: .16em;
|
||||
}
|
||||
|
||||
.error-page h1 {
|
||||
max-width: 640px;
|
||||
margin: 28px auto 0;
|
||||
font-size: clamp(40px, 5.5vw, 60px);
|
||||
line-height: 1.02;
|
||||
}
|
||||
|
||||
.error-page p {
|
||||
max-width: 48ch;
|
||||
margin: 18px auto 0;
|
||||
color: var(--color-muted);
|
||||
font-size: 16px;
|
||||
line-height: 1.7;
|
||||
}
|
||||
|
||||
.error-page .error-hint {
|
||||
margin-top: 10px;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.error-actions {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
margin-top: 34px;
|
||||
}
|
||||
|
||||
@media (max-width: 650px) {
|
||||
.error-page {
|
||||
width: calc(100% - 36px);
|
||||
padding: 64px 0 90px;
|
||||
}
|
||||
|
||||
.error-page h1 {
|
||||
font-size: clamp(34px, 10vw, 44px);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
.legal {
|
||||
width: min(760px, calc(100% - 48px));
|
||||
margin: 0 auto;
|
||||
padding: 84px 0 120px;
|
||||
}
|
||||
|
||||
.legal h1 {
|
||||
max-width: none;
|
||||
font-size: clamp(42px, 5vw, 62px);
|
||||
line-height: 1.02;
|
||||
}
|
||||
|
||||
.legal-meta {
|
||||
margin-top: 14px;
|
||||
color: var(--color-muted);
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.legal h2 {
|
||||
margin: 42px 0 12px;
|
||||
font-size: 26px;
|
||||
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;
|
||||
}
|
||||
|
||||
@media (max-width: 650px) {
|
||||
.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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
// Cookieless Matomo for anonymous public pages. The server only renders the
|
||||
// #matomo-config element for anonymous visitors, so account and admin pages
|
||||
// never load a tracker.
|
||||
|
||||
const OPT_OUT_KEY = "matomo_optout";
|
||||
|
||||
export function isOptedOut() {
|
||||
try {
|
||||
return localStorage.getItem(OPT_OUT_KEY) === "1";
|
||||
} catch (_error) {
|
||||
// If storage is unavailable we cannot remember an opt-out. Fail closed.
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
function setOptedOut(optedOut) {
|
||||
try {
|
||||
if (optedOut) {
|
||||
localStorage.setItem(OPT_OUT_KEY, "1");
|
||||
} else {
|
||||
localStorage.removeItem(OPT_OUT_KEY);
|
||||
}
|
||||
} catch (_error) {
|
||||
// Nothing else to do; the current page remains untracked.
|
||||
}
|
||||
}
|
||||
|
||||
function updateUI() {
|
||||
const optOutButton = document.getElementById("analytics-opt-out");
|
||||
const optInButton = document.getElementById("analytics-opt-in");
|
||||
const status = document.getElementById("analytics-status");
|
||||
|
||||
if (!optOutButton && !optInButton && !status) return;
|
||||
|
||||
const optedOut = isOptedOut();
|
||||
|
||||
if (optOutButton) optOutButton.hidden = optedOut;
|
||||
if (optInButton) optInButton.hidden = !optedOut;
|
||||
if (status) {
|
||||
status.textContent = optedOut
|
||||
? "Analytics is currently off in this browser."
|
||||
: "Analytics is currently on in this browser.";
|
||||
}
|
||||
}
|
||||
|
||||
function isPrivatePath() {
|
||||
return window.location.pathname.startsWith("/admin");
|
||||
}
|
||||
|
||||
function trackPageView() {
|
||||
if (isPrivatePath() || isOptedOut() || !window._paq) return;
|
||||
|
||||
window._paq.push(["setCustomUrl", window.location.href]);
|
||||
window._paq.push(["trackPageView"]);
|
||||
}
|
||||
|
||||
function loadTracker() {
|
||||
const config = document.getElementById("matomo-config");
|
||||
if (!config || isPrivatePath() || isOptedOut()) return;
|
||||
|
||||
const url = config.dataset.url;
|
||||
const siteId = config.dataset.siteId;
|
||||
if (!url || !siteId) return;
|
||||
|
||||
const _paq = (window._paq = window._paq || []);
|
||||
_paq.push(["disableCookies"]);
|
||||
_paq.push(["setDoNotTrack", true]);
|
||||
_paq.push(["trackPageView"]);
|
||||
_paq.push(["setTrackerUrl", `${url}matomo.php`]);
|
||||
_paq.push(["setSiteId", siteId]);
|
||||
|
||||
const script = document.createElement("script");
|
||||
script.async = true;
|
||||
script.src = `${url}matomo.js`;
|
||||
document.head.appendChild(script);
|
||||
}
|
||||
|
||||
function handleClick(event) {
|
||||
const target = event.target instanceof Element ? event.target : null;
|
||||
if (!target) return;
|
||||
|
||||
if (target.closest("#analytics-opt-out")) {
|
||||
event.preventDefault();
|
||||
setOptedOut(true);
|
||||
updateUI();
|
||||
return;
|
||||
}
|
||||
|
||||
if (target.closest("#analytics-opt-in")) {
|
||||
event.preventDefault();
|
||||
setOptedOut(false);
|
||||
// The tracker was not loaded while opted out. Reload to start it.
|
||||
window.location.reload();
|
||||
}
|
||||
}
|
||||
|
||||
export function initAnalytics() {
|
||||
if (window.__matomoInitialised) return;
|
||||
window.__matomoInitialised = true;
|
||||
|
||||
loadTracker();
|
||||
window.addEventListener("phx:navigate", trackPageView);
|
||||
document.addEventListener("click", handleClick);
|
||||
updateUI();
|
||||
}
|
||||
@@ -21,6 +21,8 @@
|
||||
import "phoenix_html";
|
||||
// Plain-DOM mobile navigation (works on controller and LiveView pages).
|
||||
import "./nav";
|
||||
// Cookieless Matomo for anonymous public pages.
|
||||
import { initAnalytics } from "./analytics";
|
||||
// Establish Phoenix Socket and LiveView configuration.
|
||||
import { Socket } from "phoenix";
|
||||
import { LiveSocket } from "phoenix_live_view";
|
||||
@@ -28,11 +30,13 @@ import { hooks as colocatedHooks } from "phoenix-colocated/chesstrainer";
|
||||
import topbar from "../vendor/topbar";
|
||||
import { ChessBoard } from "./hooks/chessBoard";
|
||||
import { CopyFen } from "./hooks/copyFen";
|
||||
import { SessionClock } from "./hooks/sessionClock";
|
||||
|
||||
let Hooks = {
|
||||
...colocatedHooks,
|
||||
ChessBoard,
|
||||
CopyFen,
|
||||
SessionClock,
|
||||
};
|
||||
|
||||
const csrfToken = document.querySelector("meta[name='csrf-token']").getAttribute("content");
|
||||
@@ -56,6 +60,8 @@ liveSocket.connect();
|
||||
// >> liveSocket.disableLatencySim()
|
||||
window.liveSocket = liveSocket;
|
||||
|
||||
initAnalytics();
|
||||
|
||||
// The lines below enable quality of life phoenix_live_reload
|
||||
// development features:
|
||||
//
|
||||
|
||||
@@ -22,7 +22,20 @@ export const ChessBoard = {
|
||||
this.applyBestLineMove({ from, to, promotion, san });
|
||||
});
|
||||
|
||||
this.handleEvent("apply_move", ({ from, to, promotion }) => {
|
||||
if (this.reviewing) return;
|
||||
this.executeMove(from, to, promotion);
|
||||
});
|
||||
|
||||
this.handleKeyDown = (event) => {
|
||||
if (this.pendingPromotion) {
|
||||
if (event.key === "Escape") {
|
||||
event.preventDefault();
|
||||
this.cancelPromotion();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (!this.reviewing) return;
|
||||
|
||||
if (event.key === "ArrowLeft") {
|
||||
@@ -31,6 +44,12 @@ export const ChessBoard = {
|
||||
} else if (event.key === "ArrowRight") {
|
||||
event.preventDefault();
|
||||
this.pushEvent("review_next", {});
|
||||
} else if (event.key === "Home") {
|
||||
event.preventDefault();
|
||||
this.pushEvent("review_start", {});
|
||||
} else if (event.key === "End") {
|
||||
event.preventDefault();
|
||||
this.pushEvent("review_end", {});
|
||||
}
|
||||
};
|
||||
|
||||
@@ -185,9 +204,13 @@ export const ChessBoard = {
|
||||
|
||||
showPromotionDialog(orig, dest) {
|
||||
this.pendingPromotion = { orig, dest };
|
||||
this.previousFocus = document.activeElement;
|
||||
const color = this.chess.turn() === "w" ? "white" : "black";
|
||||
const overlay = document.createElement("div");
|
||||
overlay.className = "promotion-overlay";
|
||||
overlay.setAttribute("role", "dialog");
|
||||
overlay.setAttribute("aria-modal", "true");
|
||||
overlay.setAttribute("aria-label", "Choose a promotion piece");
|
||||
const picker = document.createElement("div");
|
||||
picker.className = "promotion-picker";
|
||||
const pieces = [
|
||||
@@ -198,22 +221,64 @@ export const ChessBoard = {
|
||||
];
|
||||
pieces.forEach(({ type, code }) => {
|
||||
const btn = document.createElement("button");
|
||||
btn.type = "button";
|
||||
btn.className = `promotion-piece ${type} ${color}`;
|
||||
btn.setAttribute("aria-label", `Promote to ${type}`);
|
||||
btn.addEventListener("click", () => this.completePromotion(code));
|
||||
picker.appendChild(btn);
|
||||
});
|
||||
overlay.addEventListener("keydown", (event) => {
|
||||
if (event.key === "Escape") {
|
||||
event.preventDefault();
|
||||
this.cancelPromotion();
|
||||
return;
|
||||
}
|
||||
|
||||
if (event.key !== "Tab") return;
|
||||
|
||||
const buttons = Array.from(picker.querySelectorAll("button"));
|
||||
const first = buttons[0];
|
||||
const last = buttons[buttons.length - 1];
|
||||
|
||||
if (event.shiftKey && document.activeElement === first) {
|
||||
event.preventDefault();
|
||||
last.focus();
|
||||
} else if (!event.shiftKey && document.activeElement === last) {
|
||||
event.preventDefault();
|
||||
first.focus();
|
||||
}
|
||||
});
|
||||
overlay.appendChild(picker);
|
||||
const boardContainer = this.el.closest(".shadow-inner");
|
||||
boardContainer.style.position = "relative";
|
||||
boardContainer.appendChild(overlay);
|
||||
const container = this.el.parentElement;
|
||||
container.style.position = "relative";
|
||||
container.appendChild(overlay);
|
||||
picker.querySelector("button")?.focus();
|
||||
},
|
||||
|
||||
cancelPromotion() {
|
||||
this.pendingPromotion = null;
|
||||
const overlay = this.el.parentElement?.querySelector(".promotion-overlay");
|
||||
if (overlay) overlay.remove();
|
||||
this.restoreFocus();
|
||||
},
|
||||
|
||||
restoreFocus() {
|
||||
if (this.previousFocus instanceof HTMLElement) {
|
||||
this.previousFocus.focus();
|
||||
} else {
|
||||
document.getElementById("move-input")?.focus();
|
||||
}
|
||||
|
||||
this.previousFocus = null;
|
||||
},
|
||||
|
||||
completePromotion(pieceType) {
|
||||
const { orig, dest } = this.pendingPromotion;
|
||||
this.pendingPromotion = null;
|
||||
const picker = this.el.closest(".shadow-inner")?.querySelector(".promotion-overlay");
|
||||
const picker = this.el.parentElement?.querySelector(".promotion-overlay");
|
||||
if (picker) picker.remove();
|
||||
this.executeMove(orig, dest, pieceType);
|
||||
document.getElementById("move-input")?.focus();
|
||||
},
|
||||
|
||||
executeMove(orig, dest, promotion) {
|
||||
@@ -234,6 +299,7 @@ export const ChessBoard = {
|
||||
san: move.san,
|
||||
promotion: promotion || null,
|
||||
draw: this.chess.isDraw(),
|
||||
check: this.chess.isCheck(),
|
||||
checkmate: this.chess.isCheckmate(),
|
||||
};
|
||||
|
||||
@@ -252,8 +318,14 @@ export const ChessBoard = {
|
||||
? { color: null, dests: new Map() }
|
||||
: { color: nextTurnColor, dests: this.getValidDests() },
|
||||
});
|
||||
|
||||
return true;
|
||||
} else {
|
||||
this.ground.set({ fen: this.chess.fen() });
|
||||
this.pushEvent("move_input_error", {
|
||||
message: "That move is not legal in this position.",
|
||||
});
|
||||
return false;
|
||||
}
|
||||
},
|
||||
|
||||
@@ -279,6 +351,7 @@ export const ChessBoard = {
|
||||
fen: this.chess.fen(),
|
||||
san: move.san,
|
||||
draw: this.chess.isDraw(),
|
||||
check: this.chess.isCheck(),
|
||||
checkmate: this.chess.isCheckmate(),
|
||||
});
|
||||
},
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
// Ticks a session clock in mm:ss from its `data-started-at` (unix ms) so the
|
||||
// timer advances without a server round-trip. The server renders the initial
|
||||
// value, so a re-render stays in sync with the client.
|
||||
export const SessionClock = {
|
||||
mounted() {
|
||||
this.tick();
|
||||
this.timer = setInterval(() => this.tick(), 1000);
|
||||
},
|
||||
|
||||
updated() {
|
||||
this.tick();
|
||||
},
|
||||
|
||||
destroyed() {
|
||||
clearInterval(this.timer);
|
||||
},
|
||||
|
||||
tick() {
|
||||
const startedAt = parseInt(this.el.dataset.startedAt, 10);
|
||||
if (!startedAt) return;
|
||||
|
||||
const total = Math.max(0, Math.floor((Date.now() - startedAt) / 1000));
|
||||
const minutes = String(Math.floor(total / 60)).padStart(2, "0");
|
||||
const seconds = String(total % 60).padStart(2, "0");
|
||||
this.el.textContent = `${minutes}:${seconds}`;
|
||||
},
|
||||
};
|
||||
@@ -2,3 +2,6 @@
|
||||
// page. Keep this small: no Phoenix Socket, LiveView, hooks, or topbar.
|
||||
import "phoenix_html";
|
||||
import "./nav";
|
||||
import { initAnalytics } from "./analytics";
|
||||
|
||||
initAnalytics();
|
||||
|
||||
@@ -4,6 +4,11 @@
|
||||
const WRAP = ".nav-wrap";
|
||||
const TOGGLE = ".menu-button";
|
||||
const LINKS = ".nav-links";
|
||||
const USER_MENU = ".nav-user-menu";
|
||||
|
||||
const closeUserMenus = () => {
|
||||
document.querySelectorAll(`${USER_MENU}[open]`).forEach((menu) => menu.removeAttribute("open"));
|
||||
};
|
||||
|
||||
const setOpen = (open) => {
|
||||
const wrap = document.querySelector(WRAP);
|
||||
@@ -26,6 +31,16 @@ document.addEventListener("click", (event) => {
|
||||
return;
|
||||
}
|
||||
|
||||
if (target.closest(`${USER_MENU} a`)) {
|
||||
closeUserMenus();
|
||||
setOpen(false);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!target.closest(USER_MENU)) {
|
||||
closeUserMenus();
|
||||
}
|
||||
|
||||
if (target.closest(`${LINKS} a`)) {
|
||||
setOpen(false);
|
||||
return;
|
||||
@@ -39,5 +54,50 @@ document.addEventListener("click", (event) => {
|
||||
document.addEventListener("keydown", (event) => {
|
||||
if (event.key === "Escape") {
|
||||
setOpen(false);
|
||||
closeUserMenus();
|
||||
}
|
||||
});
|
||||
|
||||
// Flash toasts also render on controller pages (the landing page, after logging
|
||||
// out, for example), where there is no LiveView to handle the component's
|
||||
// phx-click. Dismiss them with plain DOM there; LiveView pages keep clearing
|
||||
// the server-side flash through `lv:clear-flash`.
|
||||
document.addEventListener("click", (event) => {
|
||||
const target = event.target instanceof Element ? event.target : null;
|
||||
const flash = target?.closest("[data-flash-dismiss]");
|
||||
if (!flash) return;
|
||||
if (window.liveSocket?.isConnected?.()) return;
|
||||
|
||||
flash.remove();
|
||||
});
|
||||
|
||||
// Auto-dismiss real flash messages after a few seconds. Synthetic clicks reuse
|
||||
// the manual dismiss path, so LiveView pages also clear the server-side flash.
|
||||
// The connectivity notices (`client-error`/`server-error`) start hidden and are
|
||||
// left alone: they should stay until the connection recovers.
|
||||
const FLASH_TIMEOUT_MS = 5000;
|
||||
const scheduledFlashes = new WeakSet();
|
||||
|
||||
const scheduleFlashDismiss = (flash) => {
|
||||
if (scheduledFlashes.has(flash) || flash.hasAttribute("hidden")) return;
|
||||
|
||||
scheduledFlashes.add(flash);
|
||||
setTimeout(() => flash.click(), FLASH_TIMEOUT_MS);
|
||||
};
|
||||
|
||||
const scheduleFlashes = (root) => {
|
||||
if (root.matches?.("[data-flash-dismiss]")) scheduleFlashDismiss(root);
|
||||
root.querySelectorAll?.("[data-flash-dismiss]").forEach(scheduleFlashDismiss);
|
||||
};
|
||||
|
||||
document.querySelectorAll("[data-flash-dismiss]").forEach(scheduleFlashDismiss);
|
||||
|
||||
// Flashes rendered later (LiveView updates, live navigation) arrive after the
|
||||
// initial pass, so watch for them.
|
||||
new MutationObserver((mutations) => {
|
||||
for (const mutation of mutations) {
|
||||
for (const node of mutation.addedNodes) {
|
||||
if (node instanceof Element) scheduleFlashes(node);
|
||||
}
|
||||
}
|
||||
}).observe(document.body, { childList: true, subtree: true });
|
||||
|
||||
@@ -7,6 +7,22 @@
|
||||
# General application configuration
|
||||
import Config
|
||||
|
||||
# Public-facing branding. Change these values to rename the site without
|
||||
# touching templates. The OTP app (`:chesstrainer`) and module namespaces are
|
||||
# identity, not branding, and stay as they are.
|
||||
config :chesstrainer, :branding,
|
||||
name: "Inner Square Chess",
|
||||
wordmark: "INNERSQUARE",
|
||||
tagline: "Endgame Trainer",
|
||||
support_email: "support@innersquare.app",
|
||||
mail_from: "no-reply@mail.innersquare.app",
|
||||
discord_invite: "https://discord.gg/Z2NfkG7thV"
|
||||
|
||||
# Prelaunch gating. Production sets these from PRELAUNCH and
|
||||
# MAILING_LIST_ENABLED; dev and test use these defaults.
|
||||
config :chesstrainer, :prelaunch, false
|
||||
config :chesstrainer, :mailing_list_enabled, true
|
||||
|
||||
config :chesstrainer, :scopes,
|
||||
user: [
|
||||
default: true,
|
||||
@@ -24,6 +40,16 @@ config :chesstrainer,
|
||||
ecto_repos: [Chesstrainer.Repo],
|
||||
generators: [timestamp_type: :utc_datetime]
|
||||
|
||||
# Password-login throttle. Failures are counted in fixed windows for each
|
||||
# client address and each normalised login. The address bucket is deliberately
|
||||
# wider so one account stays protected from distributed guessing while one
|
||||
# address cannot spray many accounts.
|
||||
config :chesstrainer, ChesstrainerWeb.LoginThrottle,
|
||||
window_ms: :timer.minutes(15),
|
||||
max_per_login: 5,
|
||||
max_per_ip: 10,
|
||||
confirmation_cooldown_ms: :timer.minutes(15)
|
||||
|
||||
# Glicko rating system.
|
||||
#
|
||||
# `system_constant` is the volatility constraint passed through to the Glicko
|
||||
@@ -36,6 +62,17 @@ config :chesstrainer, :ratings,
|
||||
window_days: 7,
|
||||
rd_inflation_c: 10.0
|
||||
|
||||
# Puzzle selection. Difficulty is a weighted bias towards a target rating —
|
||||
# `medium` targets the user's rating, `easy` 200 below it and `hard` 200 above
|
||||
# it — and `spread` is how many rating points it takes for a puzzle's chance to
|
||||
# fall off by a factor of e. `repeat_window_days` is how long an attempted
|
||||
# puzzle stays out of the pool. Tweak `spread` to widen or narrow the served
|
||||
# difficulty (e.g. 100 or 250).
|
||||
config :chesstrainer, :puzzles,
|
||||
spread: 150,
|
||||
repeat_window_days: 30,
|
||||
targets: [easy: -200, medium: 0, hard: 200]
|
||||
|
||||
# Public codes of the endgames pinned to the landing-page puzzle grid, in
|
||||
# display order. When empty (or short) the grid is topped up with a date-seeded
|
||||
# selection from the database, so it stays stable for a given day.
|
||||
|
||||
+10
-1
@@ -15,11 +15,15 @@ config :chesstrainer, ChesstrainerWeb.Endpoint,
|
||||
force_ssl: [
|
||||
rewrite_on: [:x_forwarded_proto],
|
||||
exclude: [
|
||||
# paths: ["/health"],
|
||||
paths: ["/health"],
|
||||
hosts: ["localhost", "127.0.0.1"]
|
||||
]
|
||||
]
|
||||
|
||||
# Fail closed in production: the mailing list stays off until SES production
|
||||
# access is granted and MAILING_LIST_ENABLED is set explicitly.
|
||||
config :chesstrainer, :mailing_list_enabled, false
|
||||
|
||||
# Configure Swoosh API Client
|
||||
config :swoosh, api_client: Swoosh.ApiClient.Req
|
||||
|
||||
@@ -29,5 +33,10 @@ config :swoosh, local: false
|
||||
# Do not print debug messages in production
|
||||
config :logger, level: :info
|
||||
|
||||
# Emit one JSON object per line in production so journald output can be
|
||||
# filtered and shipped without parsing prose. Dev and test keep the readable
|
||||
# default formatter configured in config.exs.
|
||||
config :logger, :default_handler, formatter: {Chesstrainer.JSONLogFormatter, %{}}
|
||||
|
||||
# Runtime production configuration, including reading
|
||||
# of environment variables, is done on config/runtime.exs.
|
||||
|
||||
+57
-6
@@ -20,12 +20,42 @@ if System.get_env("PHX_SERVER") do
|
||||
config :chesstrainer, ChesstrainerWeb.Endpoint, server: true
|
||||
end
|
||||
|
||||
if prelaunch = System.get_env("PRELAUNCH") do
|
||||
config :chesstrainer, :prelaunch, prelaunch in ~w(true 1)
|
||||
end
|
||||
|
||||
if mailing_list_enabled = System.get_env("MAILING_LIST_ENABLED") do
|
||||
config :chesstrainer, :mailing_list_enabled, mailing_list_enabled in ~w(true 1)
|
||||
end
|
||||
|
||||
# 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
|
||||
# .rtbw/.rtbz files. When unset, the local backend stays disabled and lookups
|
||||
# fall back to Lichess.
|
||||
# fall back to Lichess. Tests are always pinned to the committed 3-piece
|
||||
# fixtures by config/test.exs, so an exported TABLEBASE_PATH cannot make them
|
||||
# depend on whatever tables the developer happens to have downloaded.
|
||||
if config_env() != :test do
|
||||
if tablebase_path = System.get_env("TABLEBASE_PATH") do
|
||||
config :chesstrainer, :tablebase_path, tablebase_path
|
||||
end
|
||||
end
|
||||
|
||||
# Tablebase cache: size and the UTC time of the daily backup. Environment
|
||||
# variables win over the defaults in config/config.exs so deployments can tune
|
||||
@@ -81,6 +111,13 @@ config :chesstrainer, Chesstrainer.Cache,
|
||||
max_size: cache_max_size,
|
||||
backup_time: cache_backup_time
|
||||
|
||||
# Guest puzzle limit: free puzzles per UTC day for anonymous visitors. The
|
||||
# visitor is identified by a keyed hash of their address held in memory only.
|
||||
# Enable TRUST_FORWARDED_FOR only behind a proxy that sets the header.
|
||||
config :chesstrainer, Chesstrainer.GuestLimits,
|
||||
limit: String.to_integer(System.get_env("GUEST_PUZZLE_LIMIT", "5")),
|
||||
trust_forwarded_for: System.get_env("TRUST_FORWARDED_FOR") in ~w(true 1)
|
||||
|
||||
config :chesstrainer, ChesstrainerWeb.Endpoint,
|
||||
http: [port: String.to_integer(System.get_env("PORT", "4000"))]
|
||||
|
||||
@@ -94,6 +131,22 @@ if config_env() == :prod do
|
||||
|
||||
maybe_ipv6 = if System.get_env("ECTO_IPV6") in ~w(true 1), do: [:inet6], else: []
|
||||
|
||||
config :chesstrainer, Chesstrainer.Mailer,
|
||||
adapter: Swoosh.Adapters.AmazonSES,
|
||||
region:
|
||||
System.get_env("SES_REGION") ||
|
||||
raise("environment variable SES_REGION is missing"),
|
||||
access_key:
|
||||
System.get_env("SES_ACCESS_KEY_ID") ||
|
||||
raise("environment variable SES_ACCESS_KEY_ID is missing"),
|
||||
secret:
|
||||
System.get_env("SES_SECRET_ACCESS_KEY") ||
|
||||
raise("environment variable SES_SECRET_ACCESS_KEY is missing")
|
||||
|
||||
config :chesstrainer, :matomo,
|
||||
url: System.get_env("MATOMO_URL"),
|
||||
site_id: System.get_env("MATOMO_SITE_ID")
|
||||
|
||||
config :chesstrainer, Chesstrainer.Repo,
|
||||
# ssl: true,
|
||||
url: database_url,
|
||||
@@ -121,11 +174,9 @@ if config_env() == :prod do
|
||||
config :chesstrainer, ChesstrainerWeb.Endpoint,
|
||||
url: [host: host, port: 443, scheme: "https"],
|
||||
http: [
|
||||
# Enable IPv6 and bind on all interfaces.
|
||||
# Set it to {0, 0, 0, 0, 0, 0, 0, 1} for local network only access.
|
||||
# See the documentation on https://bandit.hexdocs.pm/Bandit.html#t:options/0
|
||||
# for details about using IPv6 vs IPv4 and loopback vs public addresses.
|
||||
ip: {0, 0, 0, 0, 0, 0, 0, 0}
|
||||
# The release runs behind Caddy, so bind to loopback and let the proxy
|
||||
# handle public traffic.
|
||||
ip: {127, 0, 0, 1}
|
||||
],
|
||||
secret_key_base: secret_key_base
|
||||
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
# 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.
|
||||
#
|
||||
# Cloudflare sits in front of Caddy. Two things matter here:
|
||||
#
|
||||
# 1. Only accept requests from Cloudflare's published edge ranges.
|
||||
# 2. Replace X-Forwarded-For with Cloudflare's single-value CF-Connecting-IP
|
||||
# header, so the app's TRUST_FORWARDED_FOR=true path sees the visitor, not a
|
||||
# Cloudflare edge address.
|
||||
#
|
||||
# The ranges live in cloudflare-ranges.caddy next to this file. A systemd
|
||||
# timer refreshes them from https://www.cloudflare.com/ips-v4 and /ips-v6;
|
||||
# see deploy/update-cloudflare-ranges.sh and deploy/README.md.
|
||||
|
||||
innersquare.app {
|
||||
encode zstd gzip
|
||||
|
||||
@cloudflare {
|
||||
import cloudflare-ranges.caddy
|
||||
}
|
||||
|
||||
handle @cloudflare {
|
||||
reverse_proxy 127.0.0.1:4100 {
|
||||
header_up X-Forwarded-For {http.request.header.CF-Connecting-IP}
|
||||
}
|
||||
}
|
||||
|
||||
# Direct-to-origin requests cannot spoof Cloudflare's client-IP header.
|
||||
handle {
|
||||
respond "Access Denied" 403
|
||||
}
|
||||
}
|
||||
|
||||
www.innersquare.app {
|
||||
redir https://innersquare.app{uri} permanent
|
||||
}
|
||||
+1492
File diff suppressed because it is too large
Load Diff
Executable
+113
@@ -0,0 +1,113 @@
|
||||
#!/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,
|
||||
# BACKUP_BIN, SKIP_PRE_DEPLOY_BACKUP=1
|
||||
|
||||
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)}"
|
||||
BACKUP_BIN="${BACKUP_BIN:-/usr/local/sbin/chesstrainer-backup}"
|
||||
SKIP_PRE_DEPLOY_BACKUP="${SKIP_PRE_DEPLOY_BACKUP:-0}"
|
||||
|
||||
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"
|
||||
|
||||
if [[ "$SKIP_PRE_DEPLOY_BACKUP" == "1" ]]; then
|
||||
echo "activate: SKIP_PRE_DEPLOY_BACKUP=1, not taking a pre-deploy dump"
|
||||
else
|
||||
backup_script="$BACKUP_BIN"
|
||||
if [[ ! -x "$backup_script" ]]; then
|
||||
backup_script="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/backup"
|
||||
fi
|
||||
|
||||
if [[ ! -x "$backup_script" ]]; then
|
||||
echo "activate: no backup script at $BACKUP_BIN or next to activate" >&2
|
||||
echo "activate: install deploy/backup or set SKIP_PRE_DEPLOY_BACKUP=1" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Migrations run in ExecStartPre after this, so the dump must exist first.
|
||||
echo "activate: taking a pre-deploy dump"
|
||||
if ! BACKUP_TAG=predeploy LOCK_WAIT=120 "$backup_script"; then
|
||||
echo "activate: pre-deploy dump failed, aborting" >&2
|
||||
echo "activate: fix the backup or re-run with SKIP_PRE_DEPLOY_BACKUP=1" >&2
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
|
||||
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
|
||||
Executable
+266
@@ -0,0 +1,266 @@
|
||||
#!/usr/bin/env bash
|
||||
#
|
||||
# Dump, verify, encrypt, prune and report on the production database.
|
||||
#
|
||||
# Installed as /usr/local/sbin/chesstrainer-backup (root-owned 0755) and run by
|
||||
# chesstrainer-backup.timer. deploy/activate also calls it before migrations.
|
||||
# Do not run the copy under /opt/chesstrainer/src as root: that tree belongs to
|
||||
# the application user.
|
||||
#
|
||||
# sudo systemctl start chesstrainer-backup # daily run, as the timer does
|
||||
# sudo BACKUP_TAG=manual chesstrainer-backup # ad-hoc, pruned by age
|
||||
#
|
||||
# Configuration lives in /etc/chesstrainer/backup.env (root:root 0600). See
|
||||
# deploy/README.md §Backups. Every setting can also be passed as an environment
|
||||
# variable.
|
||||
#
|
||||
# Each run prints exactly one JSON line (backup.completed or backup.failed) so
|
||||
# journald, and #140's log shipping, can pick it up.
|
||||
|
||||
set -euo pipefail
|
||||
umask 077
|
||||
|
||||
ENV_FILE="${ENV_FILE:-/etc/chesstrainer/backup.env}"
|
||||
if [[ -r "$ENV_FILE" ]]; then
|
||||
# shellcheck disable=SC1090
|
||||
source "$ENV_FILE"
|
||||
fi
|
||||
|
||||
DB_CONTAINER="${DB_CONTAINER:-chesstrainer-db}"
|
||||
PG_USER="${PG_USER:-chesstrainer}"
|
||||
PG_DB="${PG_DB:-chesstrainer_prod}"
|
||||
BACKUP_DIR="${BACKUP_DIR:-/var/backups/chesstrainer}"
|
||||
EXPECTED_ROLES="${EXPECTED_ROLES:-chesstrainer chesstrainer_ro}"
|
||||
AGE_RECIPIENT="${AGE_RECIPIENT:-}"
|
||||
HEALTHCHECK_URL="${HEALTHCHECK_URL:-}"
|
||||
SKIP_HEARTBEAT="${SKIP_HEARTBEAT:-0}"
|
||||
MIN_FREE_MB="${MIN_FREE_MB:-2048}"
|
||||
LOCAL_PLAINTEXT_DAYS="${LOCAL_PLAINTEXT_DAYS:-3}"
|
||||
LOCAL_ENCRYPTED_DAYS="${LOCAL_ENCRYPTED_DAYS:-14}"
|
||||
PREDEPLOY_KEEP="${PREDEPLOY_KEEP:-5}"
|
||||
BACKUP_TAG="${BACKUP_TAG:-daily}"
|
||||
LOCK_WAIT="${LOCK_WAIT:-0}"
|
||||
|
||||
START_SECONDS=$SECONDS
|
||||
FAILURE=""
|
||||
|
||||
log_event() {
|
||||
local event="$1"
|
||||
local extra="${2:-}"
|
||||
|
||||
printf '{"timestamp":"%s","event":"%s","tag":"%s"%s}\n' \
|
||||
"$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$event" "$BACKUP_TAG" "$extra"
|
||||
}
|
||||
|
||||
heartbeat() {
|
||||
local outcome="$1"
|
||||
|
||||
[[ "$SKIP_HEARTBEAT" == "1" ]] && return 0
|
||||
[[ -n "$HEALTHCHECK_URL" ]] || return 0
|
||||
|
||||
local url="${HEALTHCHECK_URL%/}"
|
||||
[[ "$outcome" == "fail" ]] && url="$url/fail"
|
||||
|
||||
if ! curl --fail --silent --show-error \
|
||||
--max-time 10 --retry 2 --retry-delay 2 \
|
||||
--output /dev/null "$url"; then
|
||||
echo "backup: heartbeat ping failed (run result is unaffected)" >&2
|
||||
fi
|
||||
}
|
||||
|
||||
fail() {
|
||||
FAILURE="$*"
|
||||
exit 1
|
||||
}
|
||||
|
||||
on_exit() {
|
||||
local status=$?
|
||||
|
||||
if ((status != 0)); then
|
||||
find "$BACKUP_DIR" -maxdepth 1 -name '*.partial' -delete 2>/dev/null || true
|
||||
log_event backup.failed ",\"reason\":\"${FAILURE:-exit $status}\""
|
||||
heartbeat fail
|
||||
fi
|
||||
|
||||
exit "$status"
|
||||
}
|
||||
|
||||
trap on_exit EXIT
|
||||
trap 'exit 143' TERM INT
|
||||
|
||||
if [[ "${EUID:-$(id -u)}" -ne 0 ]]; then
|
||||
fail "run as root"
|
||||
fi
|
||||
|
||||
[[ "$BACKUP_TAG" =~ ^[a-z0-9]+$ ]] || fail "BACKUP_TAG may contain only lowercase letters and digits"
|
||||
[[ "$MIN_FREE_MB" =~ ^[0-9]+$ ]] || fail "MIN_FREE_MB must be an integer"
|
||||
[[ "$LOCAL_PLAINTEXT_DAYS" =~ ^[0-9]+$ ]] || fail "LOCAL_PLAINTEXT_DAYS must be an integer"
|
||||
[[ "$LOCAL_ENCRYPTED_DAYS" =~ ^[0-9]+$ ]] || fail "LOCAL_ENCRYPTED_DAYS must be an integer"
|
||||
[[ "$PREDEPLOY_KEEP" =~ ^[0-9]+$ ]] || fail "PREDEPLOY_KEEP must be an integer"
|
||||
[[ "$LOCK_WAIT" =~ ^[0-9]+$ ]] || fail "LOCK_WAIT must be an integer"
|
||||
|
||||
[[ "$AGE_RECIPIENT" == age1* ]] || fail "AGE_RECIPIENT is not set to an age public key"
|
||||
|
||||
if [[ "$SKIP_HEARTBEAT" != "1" && -z "$HEALTHCHECK_URL" ]]; then
|
||||
fail "HEALTHCHECK_URL is not set (set SKIP_HEARTBEAT=1 to skip the ping)"
|
||||
fi
|
||||
|
||||
for cmd in docker flock curl age tar sha256sum; do
|
||||
command -v "$cmd" >/dev/null 2>&1 || fail "missing command: $cmd"
|
||||
done
|
||||
|
||||
install -d -m 0711 -o root -g root "$BACKUP_DIR"
|
||||
install -d -m 0755 -o root -g root "$BACKUP_DIR/offsite"
|
||||
# 0711 on the vault lets the workstation user traverse to offsite/ without
|
||||
# being able to list the plaintext dumps.
|
||||
chmod 0711 "$BACKUP_DIR"
|
||||
chmod 0755 "$BACKUP_DIR/offsite"
|
||||
|
||||
exec 9>/run/lock/chesstrainer-backup.lock
|
||||
if ! flock -w "$LOCK_WAIT" 9; then
|
||||
if [[ "$LOCK_WAIT" == "0" ]]; then
|
||||
# Overlapping timer/manual runs are not failures; the other run reports.
|
||||
log_event backup.skipped ',"reason":"another backup is running"'
|
||||
exit 0
|
||||
fi
|
||||
|
||||
fail "another backup is still running"
|
||||
fi
|
||||
|
||||
free_mb="$(df -Pm "$BACKUP_DIR" | awk 'NR == 2 { print $4 }')"
|
||||
[[ "$free_mb" =~ ^[0-9]+$ ]] || fail "cannot read free space for $BACKUP_DIR"
|
||||
if ((free_mb < MIN_FREE_MB)); then
|
||||
fail "only ${free_mb}MB free on $BACKUP_DIR, need ${MIN_FREE_MB}MB"
|
||||
fi
|
||||
|
||||
timestamp="$(date -u +%Y%m%dT%H%M%SZ)"
|
||||
if [[ "$BACKUP_TAG" == "daily" ]]; then
|
||||
prefix="$timestamp"
|
||||
else
|
||||
prefix="$timestamp-$BACKUP_TAG"
|
||||
fi
|
||||
|
||||
dump="$BACKUP_DIR/$prefix.dump"
|
||||
globals="$BACKUP_DIR/$prefix.globals.sql"
|
||||
counts="$BACKUP_DIR/$prefix.counts"
|
||||
checksums="$BACKUP_DIR/$prefix.sha256"
|
||||
archive="$BACKUP_DIR/offsite/$prefix.tar.age"
|
||||
|
||||
# Row counts first: writes between this query and the dump can only push the
|
||||
# restored counts up, so the drill treats this file as a lower bound.
|
||||
read -r -d '' counts_sql <<'SQL' || true
|
||||
select 'users=' || count(*) from users
|
||||
union all select 'endgames=' || count(*) from endgames
|
||||
union all select 'attempts=' || count(*) from attempts;
|
||||
SQL
|
||||
|
||||
docker exec "$DB_CONTAINER" psql -U "$PG_USER" -d "$PG_DB" \
|
||||
-At -v ON_ERROR_STOP=1 -c "$counts_sql" >"$counts.partial" ||
|
||||
fail "row count query failed"
|
||||
[[ -s "$counts.partial" ]] || fail "row count query returned nothing"
|
||||
|
||||
docker exec "$DB_CONTAINER" pg_dump -U "$PG_USER" -d "$PG_DB" -Fc \
|
||||
>"$dump.partial" || fail "pg_dump failed"
|
||||
[[ -s "$dump.partial" ]] || fail "pg_dump produced an empty file"
|
||||
|
||||
# pg_restore -l reads the archive header and table of contents. It needs the
|
||||
# Postgres client matching the server, so run it inside the container.
|
||||
docker exec -i "$DB_CONTAINER" pg_restore -l \
|
||||
<"$dump.partial" >/dev/null || fail "pg_restore -l rejected the dump"
|
||||
|
||||
docker exec "$DB_CONTAINER" pg_dumpall -U "$PG_USER" --globals-only \
|
||||
>"$globals.partial" || fail "pg_dumpall --globals-only failed"
|
||||
[[ -s "$globals.partial" ]] || fail "globals dump is empty"
|
||||
|
||||
# shellcheck disable=SC2086 # EXPECTED_ROLES is a space-separated list
|
||||
for role in $EXPECTED_ROLES; do
|
||||
grep -Eq "^CREATE ROLE \"?${role}\"?( |;)" "$globals.partial" ||
|
||||
fail "globals dump is missing role $role"
|
||||
done
|
||||
|
||||
# Promote only after every check passes, so a broken dump never looks finished.
|
||||
mv "$counts.partial" "$counts"
|
||||
mv "$dump.partial" "$dump"
|
||||
mv "$globals.partial" "$globals"
|
||||
|
||||
(
|
||||
cd "$BACKUP_DIR"
|
||||
sha256sum "${dump##*/}" "${globals##*/}" "${counts##*/}" >"${checksums##*/}"
|
||||
)
|
||||
|
||||
tar -C "$BACKUP_DIR" -cf - \
|
||||
"${dump##*/}" "${globals##*/}" "${counts##*/}" "${checksums##*/}" |
|
||||
age --recipient "$AGE_RECIPIENT" --output "$archive.partial" ||
|
||||
fail "encrypting the dump failed"
|
||||
|
||||
chmod 0644 "$archive.partial"
|
||||
mv "$archive.partial" "$archive"
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Retention
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
aged() {
|
||||
[[ -n "$(find "$1" -maxdepth 0 -mtime +"$2" -print -quit 2>/dev/null)" ]]
|
||||
}
|
||||
|
||||
remove_plaintext_set() {
|
||||
local prefix="$1"
|
||||
|
||||
rm -f -- \
|
||||
"$BACKUP_DIR/$prefix.dump" \
|
||||
"$BACKUP_DIR/$prefix.globals.sql" \
|
||||
"$BACKUP_DIR/$prefix.counts" \
|
||||
"$BACKUP_DIR/$prefix.sha256"
|
||||
}
|
||||
|
||||
prune_plaintext_by_age() {
|
||||
local dump base prefix
|
||||
|
||||
while IFS= read -r dump; do
|
||||
base="${dump##*/}"
|
||||
prefix="${base%%.*}"
|
||||
[[ "$base" == *-predeploy.dump ]] && continue
|
||||
|
||||
if aged "$dump" "$LOCAL_PLAINTEXT_DAYS"; then
|
||||
echo "backup: pruning $prefix (plaintext older than ${LOCAL_PLAINTEXT_DAYS}d)" >&2
|
||||
remove_plaintext_set "$prefix"
|
||||
fi
|
||||
done < <(find "$BACKUP_DIR" -maxdepth 1 -type f -name '*.dump')
|
||||
}
|
||||
|
||||
prune_predeploy_plaintext() {
|
||||
local -a dumps
|
||||
local i prefix
|
||||
|
||||
mapfile -t dumps < <(
|
||||
find "$BACKUP_DIR" -maxdepth 1 -type f -name '*-predeploy.dump' -printf '%f\n' | sort -r
|
||||
)
|
||||
|
||||
for ((i = PREDEPLOY_KEEP; i < ${#dumps[@]}; i++)); do
|
||||
prefix="${dumps[i]%%.*}"
|
||||
echo "backup: pruning $prefix (keeping last ${PREDEPLOY_KEEP} pre-deploy dumps)" >&2
|
||||
remove_plaintext_set "$prefix"
|
||||
done
|
||||
}
|
||||
|
||||
prune_encrypted() {
|
||||
local archive
|
||||
|
||||
while IFS= read -r archive; do
|
||||
echo "backup: pruning ${archive##*/} (encrypted older than ${LOCAL_ENCRYPTED_DAYS}d)" >&2
|
||||
rm -f -- "$archive"
|
||||
done < <(
|
||||
find "$BACKUP_DIR/offsite" -maxdepth 1 -type f -name '*.tar.age' -mtime +"$LOCAL_ENCRYPTED_DAYS"
|
||||
)
|
||||
}
|
||||
|
||||
prune_plaintext_by_age
|
||||
prune_predeploy_plaintext
|
||||
prune_encrypted
|
||||
|
||||
dump_bytes="$(stat -c %s "$dump")"
|
||||
archive_bytes="$(stat -c %s "$archive")"
|
||||
|
||||
log_event backup.completed ",\"dump\":\"$prefix\",\"dump_bytes\":$dump_bytes,\"offsite_bytes\":$archive_bytes,\"duration_s\":$((SECONDS - START_SECONDS))"
|
||||
heartbeat ok
|
||||
@@ -0,0 +1,33 @@
|
||||
# /etc/chesstrainer/backup.env -- root:root, mode 0600.
|
||||
#
|
||||
# Sourced by /usr/local/sbin/chesstrainer-backup. Every value below shows the
|
||||
# default; only AGE_RECIPIENT and HEALTHCHECK_URL must be set. Keep secrets out
|
||||
# of the repo and out of world-readable files.
|
||||
|
||||
# age public key, generated on the workstation with `age-keygen`.
|
||||
# The private key never leaves the workstation.
|
||||
AGE_RECIPIENT=age1...
|
||||
|
||||
# healthchecks.io (or compatible) ping URL. The script pings it after a good
|
||||
# run and pings <url>/fail after a bad one. Set SKIP_HEARTBEAT=1 to run without
|
||||
# monitoring (testing only).
|
||||
HEALTHCHECK_URL=https://hc-ping.com/00000000-0000-0000-0000-000000000000
|
||||
|
||||
# Refuse to dump when the filesystem has less than this much free space.
|
||||
MIN_FREE_MB=2048
|
||||
|
||||
# Retention. Dumps and their globals/counts/checksum siblings disappear as a
|
||||
# set; only the encrypted archives in offsite/ live for the longer window.
|
||||
LOCAL_PLAINTEXT_DAYS=3
|
||||
LOCAL_ENCRYPTED_DAYS=14
|
||||
PREDEPLOY_KEEP=5
|
||||
|
||||
# Postgres coordinates. The container trusts local Unix-socket connections, so
|
||||
# no password belongs here.
|
||||
DB_CONTAINER=chesstrainer-db
|
||||
PG_USER=chesstrainer
|
||||
PG_DB=chesstrainer_prod
|
||||
BACKUP_DIR=/var/backups/chesstrainer
|
||||
|
||||
# Roles the globals dump must be able to recreate.
|
||||
EXPECTED_ROLES="chesstrainer chesstrainer_ro"
|
||||
@@ -0,0 +1,7 @@
|
||||
[Unit]
|
||||
Description=Report a failed Inner Square Chess database backup
|
||||
Documentation=https://github.com/TheRealOwenRees/chess-endgame-trainer/blob/main/deploy/README.md
|
||||
|
||||
[Service]
|
||||
Type=oneshot
|
||||
ExecStart=/usr/bin/logger --tag chesstrainer-backup --priority daemon.err --stderr backup.unit-failed: chesstrainer-backup.service failed, see journalctl -u chesstrainer-backup
|
||||
@@ -0,0 +1,16 @@
|
||||
[Unit]
|
||||
Description=Inner Square Chess database backup
|
||||
Documentation=https://github.com/TheRealOwenRees/chess-endgame-trainer/blob/main/deploy/README.md
|
||||
After=network-online.target docker.service
|
||||
Wants=network-online.target
|
||||
OnFailure=chesstrainer-backup-failure.service
|
||||
|
||||
[Service]
|
||||
Type=oneshot
|
||||
User=root
|
||||
Group=root
|
||||
ExecStart=/usr/local/sbin/chesstrainer-backup
|
||||
Nice=10
|
||||
IOSchedulingClass=idle
|
||||
TimeoutStartSec=10min
|
||||
SyslogIdentifier=chesstrainer-backup
|
||||
@@ -0,0 +1,13 @@
|
||||
[Unit]
|
||||
Description=Daily Inner Square Chess database backup
|
||||
Documentation=https://github.com/TheRealOwenRees/chess-endgame-trainer/blob/main/deploy/README.md
|
||||
|
||||
[Timer]
|
||||
OnCalendar=*-*-* 03:15:00 UTC
|
||||
RandomizedDelaySec=5m
|
||||
AccuracySec=1m
|
||||
Persistent=true
|
||||
Unit=chesstrainer-backup.service
|
||||
|
||||
[Install]
|
||||
WantedBy=timers.target
|
||||
@@ -0,0 +1,11 @@
|
||||
[Unit]
|
||||
Description=Refresh Cloudflare CIDRs for Caddy
|
||||
Documentation=https://github.com/TheRealOwenRees/chess-endgame-trainer/blob/main/docs/security.md
|
||||
After=network-online.target
|
||||
Wants=network-online.target
|
||||
|
||||
[Service]
|
||||
Type=oneshot
|
||||
ExecStart=/usr/local/sbin/chesstrainer-update-cloudflare-ranges
|
||||
TimeoutStartSec=2min
|
||||
Nice=10
|
||||
@@ -0,0 +1,11 @@
|
||||
[Unit]
|
||||
Description=Hourly refresh of Cloudflare CIDRs for Caddy
|
||||
|
||||
[Timer]
|
||||
OnCalendar=hourly
|
||||
RandomizedDelaySec=10m
|
||||
Persistent=true
|
||||
Unit=chesstrainer-cloudflare-ranges.service
|
||||
|
||||
[Install]
|
||||
WantedBy=timers.target
|
||||
@@ -0,0 +1,13 @@
|
||||
[Unit]
|
||||
Description=Probe the public Inner Square Chess app and report to healthchecks.io
|
||||
Documentation=https://github.com/TheRealOwenRees/chess-endgame-trainer/blob/main/deploy/README.md
|
||||
After=network-online.target
|
||||
Wants=network-online.target
|
||||
|
||||
[Service]
|
||||
Type=oneshot
|
||||
User=root
|
||||
Group=root
|
||||
ExecStart=/usr/local/sbin/chesstrainer-probe
|
||||
TimeoutStartSec=90s
|
||||
SyslogIdentifier=chesstrainer-probe
|
||||
@@ -0,0 +1,12 @@
|
||||
[Unit]
|
||||
Description=Probe the public Inner Square Chess app every two minutes
|
||||
Documentation=https://github.com/TheRealOwenRees/chess-endgame-trainer/blob/main/deploy/README.md
|
||||
|
||||
[Timer]
|
||||
OnBootSec=30s
|
||||
OnUnitActiveSec=2min
|
||||
AccuracySec=5s
|
||||
Unit=chesstrainer-probe.service
|
||||
|
||||
[Install]
|
||||
WantedBy=timers.target
|
||||
@@ -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
|
||||
@@ -0,0 +1,3 @@
|
||||
# Generated by deploy/update-cloudflare-ranges.sh.
|
||||
# Source: https://www.cloudflare.com/ips-v4 and /ips-v6
|
||||
remote_ip 173.245.48.0/20 103.21.244.0/22 103.22.200.0/22 103.31.4.0/22 141.101.64.0/18 108.162.192.0/18 190.93.240.0/20 188.114.96.0/20 197.234.240.0/22 198.41.128.0/17 162.158.0.0/15 104.16.0.0/13 104.24.0.0/14 172.64.0.0/13 131.0.72.0/22 2400:cb00::/32 2606:4700::/32 2803:f800::/32 2405:b500::/32 2405:8100::/32 2a06:98c0::/29 2c0f:f248::/32
|
||||
@@ -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.6@sha256:...
|
||||
|
||||
services:
|
||||
chesstrainer-db:
|
||||
container_name: chesstrainer-db
|
||||
image: postgres:18.6
|
||||
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
|
||||
Executable
+359
@@ -0,0 +1,359 @@
|
||||
#!/usr/bin/env bash
|
||||
#
|
||||
# Probe the public Inner Square Chess app and report the verdict to
|
||||
# healthchecks.io.
|
||||
#
|
||||
# Installed as /usr/local/sbin/chesstrainer-probe (root-owned 0755) and run by
|
||||
# chesstrainer-probe.timer every two minutes. The probe deliberately goes
|
||||
# through the public hostname, not loopback: DNS, Cloudflare, Caddy and the
|
||||
# origin allowlist are part of what a visitor depends on. A loopback health
|
||||
# URL is still consulted on failure, as evidence only.
|
||||
#
|
||||
# sudo /usr/local/sbin/chesstrainer-probe
|
||||
# sudo /usr/local/sbin/chesstrainer-probe --dry-run # no network, no config
|
||||
#
|
||||
# Configuration lives in /etc/chesstrainer/probe.env (root:root 0600). See
|
||||
# deploy/README.md §Monitoring and alerting. Individual settings can be passed
|
||||
# as environment variables to a manual run, which is how the drills vary the
|
||||
# URL and the expected tablebase.
|
||||
#
|
||||
# Each run prints exactly one JSON line (probe.ok, probe.degraded or
|
||||
# probe.failed) so journald, and #140's log shipping, can pick it up.
|
||||
|
||||
set -euo pipefail
|
||||
umask 077
|
||||
|
||||
ENV_FILE="${ENV_FILE:-/etc/chesstrainer/probe.env}"
|
||||
|
||||
START_SECONDS=$SECONDS
|
||||
DRY_RUN=0
|
||||
TMPDIR_PROBE=""
|
||||
HTTP_BODY_FILE=""
|
||||
HTTP_HEADER_FILE=""
|
||||
HTTP_ERROR_FILE=""
|
||||
|
||||
usage() {
|
||||
cat <<'EOF'
|
||||
Usage: chesstrainer-probe [--dry-run]
|
||||
|
||||
--dry-run print the verdict for the success, degraded, fail, non-JSON and
|
||||
unreachable fixtures without reading the env file or making a
|
||||
network request
|
||||
EOF
|
||||
}
|
||||
|
||||
while (($# > 0)); do
|
||||
case "$1" in
|
||||
--dry-run) DRY_RUN=1 ;;
|
||||
-h | --help)
|
||||
usage
|
||||
exit 0
|
||||
;;
|
||||
*)
|
||||
usage >&2
|
||||
echo "probe: unknown argument: $1" >&2
|
||||
exit 2
|
||||
;;
|
||||
esac
|
||||
shift
|
||||
done
|
||||
|
||||
log_event() {
|
||||
local event="$1"
|
||||
local extra="${2:-}"
|
||||
|
||||
printf '{"timestamp":"%s","event":"%s"%s}\n' \
|
||||
"$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$event" "$extra"
|
||||
}
|
||||
|
||||
fail() {
|
||||
echo "probe: $*" >&2
|
||||
exit 1
|
||||
}
|
||||
|
||||
json_escape() {
|
||||
local text="$1"
|
||||
|
||||
text="${text//\\/\\\\}"
|
||||
text="${text//\"/\\\"}"
|
||||
text="${text//$'\n'/\\n}"
|
||||
text="${text//$'\r'/\\r}"
|
||||
text="${text//$'\t'/\\t}"
|
||||
text="$(printf '%s' "$text" | LC_ALL=C tr -d '[:cntrl:]')"
|
||||
|
||||
printf '%s' "$text"
|
||||
}
|
||||
|
||||
body_snippet() {
|
||||
local file="$1"
|
||||
|
||||
if [[ -s "$file" ]]; then
|
||||
head -c "$MAX_BODY_BYTES" "$file"
|
||||
fi
|
||||
}
|
||||
|
||||
json_field() {
|
||||
local key="$1"
|
||||
local json="$2"
|
||||
|
||||
if [[ "$json" =~ \"$key\"[[:space:]]*:[[:space:]]*\"([^\"]*)\" ]]; then
|
||||
printf '%s' "${BASH_REMATCH[1]}"
|
||||
fi
|
||||
}
|
||||
|
||||
http_get() {
|
||||
local url="$1"
|
||||
local prefix="$2"
|
||||
local proto="$3"
|
||||
local status=""
|
||||
local exit_code=0
|
||||
|
||||
HTTP_BODY_FILE="$prefix.body"
|
||||
HTTP_HEADER_FILE="$prefix.headers"
|
||||
HTTP_ERROR_FILE="$prefix.error"
|
||||
: >"$HTTP_BODY_FILE"
|
||||
: >"$HTTP_HEADER_FILE"
|
||||
: >"$HTTP_ERROR_FILE"
|
||||
|
||||
if status="$(curl --silent --show-error --location \
|
||||
--proto "$proto" \
|
||||
--connect-timeout 5 \
|
||||
--max-time "$PROBE_TIMEOUT_SECONDS" \
|
||||
--output "$HTTP_BODY_FILE" \
|
||||
--dump-header "$HTTP_HEADER_FILE" \
|
||||
--write-out '%{http_code}' \
|
||||
"$url")"; then
|
||||
exit_code=0
|
||||
else
|
||||
exit_code=$?
|
||||
fi
|
||||
|
||||
HTTP_STATUS="${status:-000}"
|
||||
CURL_EXIT="$exit_code"
|
||||
}
|
||||
|
||||
# Sets VERDICT (ok, degraded, failed), REASON, DB and TABLEBASE. The database is
|
||||
# the only hard dependency; a missing local tablebase still serves users from
|
||||
# Lichess, so it is reported as a green but degraded check-in.
|
||||
evaluate() {
|
||||
local status="$1"
|
||||
local exit_code="$2"
|
||||
local body="$3"
|
||||
local trimmed=""
|
||||
|
||||
VERDICT="failed"
|
||||
REASON=""
|
||||
DB=""
|
||||
TABLEBASE=""
|
||||
|
||||
if ((exit_code != 0)); then
|
||||
REASON="unreachable: curl exit $exit_code"
|
||||
return
|
||||
fi
|
||||
|
||||
if [[ "$status" != "200" ]]; then
|
||||
REASON="http $status"
|
||||
return
|
||||
fi
|
||||
|
||||
trimmed="${body#"${body%%[![:space:]]*}"}"
|
||||
trimmed="${trimmed%"${trimmed##*[![:space:]]}"}"
|
||||
if [[ "${trimmed:0:1}" != "{" || "${trimmed: -1}" != "}" ]]; then
|
||||
REASON="non-JSON response"
|
||||
return
|
||||
fi
|
||||
|
||||
DB="$(json_field db "$body")"
|
||||
TABLEBASE="$(json_field tablebase "$body")"
|
||||
|
||||
if [[ -z "$DB" ]]; then
|
||||
REASON="response has no db field"
|
||||
return
|
||||
fi
|
||||
|
||||
if [[ "$DB" != "ok" ]]; then
|
||||
REASON="db is $DB"
|
||||
return
|
||||
fi
|
||||
|
||||
if [[ "$EXPECT_TABLEBASE" != "any" && "$TABLEBASE" != "$EXPECT_TABLEBASE" ]]; then
|
||||
VERDICT="degraded"
|
||||
REASON="tablebase is ${TABLEBASE:-unknown}, expected $EXPECT_TABLEBASE"
|
||||
return
|
||||
fi
|
||||
|
||||
VERDICT="ok"
|
||||
}
|
||||
|
||||
# Exactly one call site per run, and one call site per outcome, so a forced
|
||||
# failure can only ever produce one fail ping.
|
||||
ping_check() {
|
||||
local outcome="$1"
|
||||
local body="$2"
|
||||
local url=""
|
||||
local body_file=""
|
||||
|
||||
if [[ -z "$HEALTHCHECK_URL" ]]; then
|
||||
echo "probe: HEALTHCHECK_URL is not set, not reporting" >&2
|
||||
return 0
|
||||
fi
|
||||
|
||||
url="${HEALTHCHECK_URL%/}"
|
||||
if [[ "$outcome" == "fail" ]]; then
|
||||
url="$url/fail"
|
||||
fi
|
||||
|
||||
body_file="$(mktemp)"
|
||||
printf '%s' "$body" >"$body_file"
|
||||
|
||||
if ! curl --silent --show-error --fail \
|
||||
--max-time 10 --retry 2 --retry-delay 2 \
|
||||
--header 'Content-Type: application/json' \
|
||||
--data-binary "@$body_file" \
|
||||
--output /dev/null "$url"; then
|
||||
echo "probe: check-in ping failed (run result is unaffected)" >&2
|
||||
fi
|
||||
|
||||
rm -f "$body_file"
|
||||
}
|
||||
|
||||
origin_evidence() {
|
||||
local prefix="$1"
|
||||
|
||||
http_get "$ORIGIN_URL" "$prefix" '=https,http'
|
||||
ORIGIN_STATUS="$HTTP_STATUS"
|
||||
ORIGIN_EXIT="$CURL_EXIT"
|
||||
ORIGIN_BODY="$(body_snippet "$HTTP_BODY_FILE")"
|
||||
ORIGIN_ERROR="$(body_snippet "$HTTP_ERROR_FILE")"
|
||||
}
|
||||
|
||||
fail_evidence() {
|
||||
local evidence=""
|
||||
|
||||
evidence="$(printf '{"probe":"failed","reason":"%s","url":"%s","http_status":"%s","curl_exit":%s' \
|
||||
"$(json_escape "$REASON")" "$(json_escape "$PROBE_URL")" "$PUBLIC_STATUS" "$PUBLIC_EXIT")"
|
||||
|
||||
if [[ -n "$ERROR_TEXT" ]]; then
|
||||
evidence+="$(printf ',"error":"%s"' "$(json_escape "$ERROR_TEXT")")"
|
||||
fi
|
||||
|
||||
if [[ -n "$BODY" ]]; then
|
||||
evidence+="$(printf ',"body":"%s"' "$(json_escape "$BODY")")"
|
||||
fi
|
||||
|
||||
evidence+="$(printf ',"origin_url":"%s","origin_status":"%s","origin_curl_exit":%s' \
|
||||
"$(json_escape "$ORIGIN_URL")" "$ORIGIN_STATUS" "$ORIGIN_EXIT")"
|
||||
|
||||
if [[ -n "$ORIGIN_BODY" ]]; then
|
||||
evidence+="$(printf ',"origin_body":"%s"' "$(json_escape "$ORIGIN_BODY")")"
|
||||
fi
|
||||
|
||||
if [[ -n "$ORIGIN_ERROR" ]]; then
|
||||
evidence+="$(printf ',"origin_error":"%s"' "$(json_escape "$ORIGIN_ERROR")")"
|
||||
fi
|
||||
|
||||
printf '%s}' "$evidence"
|
||||
}
|
||||
|
||||
dry_run() {
|
||||
local -a scenarios=(
|
||||
'HTTP 200, healthy|200|0|{"process":"ok","status":"ok","db":"ok","tablebase":"local"}'
|
||||
'HTTP 200, tablebase fallback|200|0|{"process":"ok","status":"degraded","db":"ok","tablebase":"fallback"}'
|
||||
'HTTP 503, db down|503|0|{"process":"ok","status":"down","db":"down","tablebase":"local"}'
|
||||
'HTTP 200, non-JSON|200|0|<html><body>502 Bad Gateway</body></html>'
|
||||
'timeout, no response|000|28|'
|
||||
)
|
||||
local row name status exit_code body action
|
||||
|
||||
printf 'probe: dry run, no network calls and no configuration read\n'
|
||||
printf 'probe: every fixture is evaluated with EXPECT_TABLEBASE=local\n\n'
|
||||
printf '%-28s %-9s %-46s %s\n' "scenario" "verdict" "reason" "would ping"
|
||||
|
||||
for row in "${scenarios[@]}"; do
|
||||
IFS='|' read -r name status exit_code body <<<"$row"
|
||||
EXPECT_TABLEBASE="local"
|
||||
evaluate "$status" "$exit_code" "$body"
|
||||
|
||||
case "$VERDICT" in
|
||||
ok) action="success, raw /health JSON" ;;
|
||||
degraded) action="success, mismatch evidence" ;;
|
||||
*) action="fail, evidence JSON" ;;
|
||||
esac
|
||||
|
||||
printf '%-28s %-9s %-46s %s\n' "$name" "$VERDICT" "${REASON:--}" "$action"
|
||||
done
|
||||
|
||||
printf '\nprobe: dry run complete, no check-ins sent\n'
|
||||
}
|
||||
|
||||
if ((DRY_RUN)); then
|
||||
dry_run
|
||||
exit 0
|
||||
fi
|
||||
|
||||
# Overrides passed on the command line survive the env file, so the drills can
|
||||
# vary the URL or the expected tablebase without editing a root-only file.
|
||||
_OVERRIDE_PROBE_URL="${PROBE_URL:-}"
|
||||
_OVERRIDE_EXPECT_TABLEBASE="${EXPECT_TABLEBASE:-}"
|
||||
_OVERRIDE_PROBE_TIMEOUT_SECONDS="${PROBE_TIMEOUT_SECONDS:-}"
|
||||
|
||||
if [[ -r "$ENV_FILE" ]]; then
|
||||
# shellcheck disable=SC1090
|
||||
source "$ENV_FILE"
|
||||
else
|
||||
fail "cannot read $ENV_FILE (set ENV_FILE to override)"
|
||||
fi
|
||||
|
||||
PROBE_URL="${_OVERRIDE_PROBE_URL:-${PROBE_URL:-}}"
|
||||
EXPECT_TABLEBASE="${_OVERRIDE_EXPECT_TABLEBASE:-${EXPECT_TABLEBASE:-local}}"
|
||||
PROBE_TIMEOUT_SECONDS="${_OVERRIDE_PROBE_TIMEOUT_SECONDS:-${PROBE_TIMEOUT_SECONDS:-10}}"
|
||||
|
||||
HEALTHCHECK_URL="${HEALTHCHECK_URL:-}"
|
||||
ORIGIN_URL="${ORIGIN_URL:-http://127.0.0.1:4100/health}"
|
||||
MAX_BODY_BYTES="${MAX_BODY_BYTES:-2000}"
|
||||
|
||||
[[ "$PROBE_URL" == https://* ]] || fail "PROBE_URL must be an https URL"
|
||||
[[ -n "$HEALTHCHECK_URL" ]] || fail "HEALTHCHECK_URL is not set"
|
||||
[[ "$EXPECT_TABLEBASE" =~ ^(local|fallback|not_configured|any)$ ]] ||
|
||||
fail "EXPECT_TABLEBASE must be local, fallback, not_configured or any"
|
||||
[[ "$PROBE_TIMEOUT_SECONDS" =~ ^[0-9]+$ ]] || fail "PROBE_TIMEOUT_SECONDS must be an integer"
|
||||
command -v curl >/dev/null 2>&1 || fail "missing command: curl"
|
||||
|
||||
TMPDIR_PROBE="$(mktemp -d)"
|
||||
|
||||
cleanup() {
|
||||
if [[ -n "$TMPDIR_PROBE" && -d "$TMPDIR_PROBE" ]]; then
|
||||
rm -rf "$TMPDIR_PROBE"
|
||||
fi
|
||||
}
|
||||
|
||||
trap cleanup EXIT
|
||||
trap 'exit 143' TERM INT
|
||||
|
||||
http_get "$PROBE_URL" "$TMPDIR_PROBE/public" '=https'
|
||||
PUBLIC_STATUS="$HTTP_STATUS"
|
||||
PUBLIC_EXIT="$CURL_EXIT"
|
||||
BODY="$(body_snippet "$HTTP_BODY_FILE")"
|
||||
ERROR_TEXT="$(body_snippet "$HTTP_ERROR_FILE")"
|
||||
|
||||
evaluate "$PUBLIC_STATUS" "$PUBLIC_EXIT" "$BODY"
|
||||
|
||||
case "$VERDICT" in
|
||||
ok)
|
||||
log_event probe.ok ",\"status\":\"$PUBLIC_STATUS\",\"tablebase\":\"$(json_escape "$TABLEBASE")\",\"duration_s\":$((SECONDS - START_SECONDS))"
|
||||
ping_check ok "$BODY"
|
||||
;;
|
||||
degraded)
|
||||
evidence="$(printf '{"expected_tablebase":"%s","health":%s}' \
|
||||
"$(json_escape "$EXPECT_TABLEBASE")" "$BODY")"
|
||||
log_event probe.degraded ",\"reason\":\"$(json_escape "$REASON")\",\"tablebase\":\"$(json_escape "$TABLEBASE")\",\"duration_s\":$((SECONDS - START_SECONDS))"
|
||||
ping_check ok "$evidence"
|
||||
;;
|
||||
*)
|
||||
origin_evidence "$TMPDIR_PROBE/origin"
|
||||
evidence="$(fail_evidence)"
|
||||
log_event probe.failed ",\"reason\":\"$(json_escape "$REASON")\",\"http_status\":\"$PUBLIC_STATUS\",\"curl_exit\":$PUBLIC_EXIT,\"duration_s\":$((SECONDS - START_SECONDS))"
|
||||
ping_check fail "$evidence"
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
@@ -0,0 +1,28 @@
|
||||
# /etc/chesstrainer/probe.env -- root:root, mode 0600.
|
||||
#
|
||||
# Sourced by /usr/local/sbin/chesstrainer-probe. The check-in URL is a secret:
|
||||
# anyone who has it can mark the check green, so keep it out of the repo and
|
||||
# out of world-readable files.
|
||||
|
||||
# The public URL a visitor actually requests. Probing the edge rather than
|
||||
# loopback is deliberate: DNS, TLS, Cloudflare, Caddy and the origin allowlist
|
||||
# are part of the contract. Must be https.
|
||||
PROBE_URL=https://innersquare.app/health
|
||||
|
||||
# healthchecks.io ping URL for the two-minute probe check. A healthy run posts
|
||||
# to it; a failed run posts to <url>/fail.
|
||||
HEALTHCHECK_URL=https://hc-ping.com/00000000-0000-0000-0000-000000000000
|
||||
|
||||
# The tablebase value /health should report. "local" means Syzygy files are
|
||||
# loaded, "fallback" means Lichess is used, "not_configured" means
|
||||
# TABLEBASE_PATH is unset. A mismatch is reported as degraded, never as down.
|
||||
# Set to "any" to accept whatever the app reports.
|
||||
EXPECT_TABLEBASE=local
|
||||
|
||||
# Whole-request timeout. The timer runs every two minutes, so keep this well
|
||||
# under that.
|
||||
PROBE_TIMEOUT_SECONDS=10
|
||||
|
||||
# Loopback health URL. It is consulted only when the public probe fails, and
|
||||
# only as evidence: it does not change the verdict. Defaults to the value shown.
|
||||
# ORIGIN_URL=http://127.0.0.1:4100/health
|
||||
Executable
+58
@@ -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"
|
||||
@@ -0,0 +1,20 @@
|
||||
__SITE_ADDRESS__ {
|
||||
root * /var/www/innersquare
|
||||
encode zstd gzip
|
||||
try_files {path}.html {path}
|
||||
file_server
|
||||
|
||||
header {
|
||||
X-Content-Type-Options nosniff
|
||||
X-Frame-Options DENY
|
||||
Referrer-Policy strict-origin-when-cross-origin
|
||||
Permissions-Policy "geolocation=(), microphone=(), camera=()"
|
||||
X-Robots-Tag "noindex, nofollow"
|
||||
}
|
||||
|
||||
@immutable path /fonts/* /favicon.ico
|
||||
header @immutable Cache-Control "public, max-age=31536000, immutable"
|
||||
|
||||
@html path / /index.html /privacy /terms-conditions
|
||||
header @html Cache-Control "no-cache"
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
# Static coming-soon page
|
||||
|
||||
A self-contained branding page for the domain while the gated app (#116) and
|
||||
mail delivery (#84) are still outstanding. It needs no BEAM, no database, no
|
||||
newsletter form, and no JavaScript — just static files and Caddy.
|
||||
|
||||
```
|
||||
deploy/static/
|
||||
├── 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
|
||||
├── mentions-legales.html # French legal notice, served at /mentions-legales
|
||||
├── legal.css # shared styles for the legal pages
|
||||
├── fonts/ # DM Sans + DM Serif Display woff2 files
|
||||
├── favicon.ico # copied from priv/static
|
||||
├── Caddyfile # site block template; rendered by deploy.sh --caddy
|
||||
├── deploy.sh # upload files; optional marked Caddy block
|
||||
└── README.md
|
||||
```
|
||||
|
||||
The Caddyfile uses `try_files {path}.html {path}` so `/privacy`,
|
||||
`/terms-conditions`, and `/mentions-legales` serve the matching `.html` files
|
||||
without a redirect.
|
||||
|
||||
## Preview locally
|
||||
|
||||
```sh
|
||||
python3 -m http.server 8080 --directory deploy/static
|
||||
# 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
|
||||
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
|
||||
by opening `index.html` directly.
|
||||
|
||||
## One-time VPS setup
|
||||
|
||||
1. **DNS** — point an `A` record (and `AAAA` if you have IPv6) for the domain
|
||||
and `www` at the VPS.
|
||||
2. **SSH user** — the deploy user needs passwordless `sudo` for the commands in
|
||||
`deploy.sh`, or use your normal sudo-capable user (`VPS_USER=ubuntu`).
|
||||
3. **Firewall** — allow SSH, 80 and 443. With UFW:
|
||||
|
||||
```sh
|
||||
sudo ufw allow OpenSSH
|
||||
sudo ufw allow 80/tcp
|
||||
sudo ufw allow 443/tcp
|
||||
sudo ufw enable
|
||||
```
|
||||
|
||||
Also open 80/443 in your provider's security group if you have one.
|
||||
4. **Caddy** — install from the official apt repository:
|
||||
|
||||
```sh
|
||||
sudo apt install -y debian-keyring debian-archive-keyring apt-transport-https curl
|
||||
curl -1sLf 'https://dl.cloudsmith.io/public/caddy/stable/gpg.key' \
|
||||
| sudo gpg --dearmor -o /usr/share/keyrings/caddy-stable-archive-keyring.gpg
|
||||
curl -1sLf 'https://dl.cloudsmith.io/public/caddy/stable/debian.deb.txt' \
|
||||
| sudo tee /etc/apt/sources.list.d/caddy-stable.list
|
||||
sudo apt update
|
||||
sudo apt install -y caddy
|
||||
sudo systemctl enable --now caddy
|
||||
```
|
||||
|
||||
Caddy obtains and renews the TLS certificate automatically once DNS points
|
||||
at the VPS and ports 80/443 are reachable.
|
||||
|
||||
## Deploy
|
||||
|
||||
### Files only (default)
|
||||
|
||||
Use this when the site block is already in your Caddy config. The script
|
||||
uploads the files and **never touches Caddy**.
|
||||
|
||||
```sh
|
||||
VPS_HOST=203.0.113.10 VPS_USER=ubuntu ./deploy/static/deploy.sh
|
||||
```
|
||||
|
||||
Re-run this to update the page.
|
||||
|
||||
### Let the script manage the Caddy block (`--caddy`)
|
||||
|
||||
Pass `--caddy` and a `SITE_ADDRESS` to have the script add or update the site
|
||||
block:
|
||||
|
||||
```sh
|
||||
SITE_ADDRESS="innersquare.app, www.innersquare.app" \
|
||||
VPS_HOST=203.0.113.10 \
|
||||
VPS_USER=ubuntu \
|
||||
./deploy/static/deploy.sh --caddy
|
||||
```
|
||||
|
||||
The script edits only the region between these markers in `REMOTE_CADDYFILE`
|
||||
(default `/etc/caddy/Caddyfile`):
|
||||
|
||||
```caddyfile
|
||||
# BEGIN innersquare-coming-soon (managed by deploy/static/deploy.sh)
|
||||
...
|
||||
# END innersquare-coming-soon
|
||||
```
|
||||
|
||||
It backs up the file, validates the whole config, restores the backup if
|
||||
validation fails, and reloads Caddy. If the domain already appears in the file
|
||||
**without** the markers — for example, a block added by hand — it refuses to
|
||||
touch the file rather than risk duplicating the site.
|
||||
|
||||
### Single shared Caddyfile
|
||||
|
||||
If all your server blocks live in `/etc/caddy/Caddyfile` and the innersquare
|
||||
block is already there, use the default files-only mode. Don't run `--caddy`
|
||||
unless you remove the manual block first and want the script to own it.
|
||||
|
||||
### Dedicated file / import
|
||||
|
||||
You can point `REMOTE_CADDYFILE` at a dedicated file and add one import line to
|
||||
the main Caddyfile:
|
||||
|
||||
```sh
|
||||
REMOTE_CADDYFILE=/etc/caddy/conf.d/innersquare.caddy \
|
||||
SITE_ADDRESS=innersquare.app \
|
||||
VPS_HOST=203.0.113.10 \
|
||||
VPS_USER=ubuntu \
|
||||
./deploy/static/deploy.sh --caddy
|
||||
```
|
||||
|
||||
```caddyfile
|
||||
import /etc/caddy/conf.d/*.caddy
|
||||
```
|
||||
|
||||
Optional overrides: `SSH_PORT`, `WEB_ROOT` (default `/var/www/innersquare`),
|
||||
`REMOTE_CADDYFILE` (default `/etc/caddy/Caddyfile`).
|
||||
|
||||
## What this page deliberately does not do
|
||||
|
||||
- **No newsletter signup** — that waits on real mail delivery (#84) and the
|
||||
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 indexing** — `robots.txt` is absent and Caddy sends
|
||||
`X-Robots-Tag: noindex, nofollow` plus the page has a robots meta tag.
|
||||
|
||||
## Replacing it later
|
||||
|
||||
When the Phoenix release lands (#117), either point Caddy's reverse proxy at
|
||||
the app or remove this Caddy site block. Keep the static page around as an
|
||||
instant fallback if a deploy goes wrong.
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 15 KiB |
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,707 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<title>Inner Square Chess — Endgame Trainer</title>
|
||||
<meta
|
||||
name="description"
|
||||
content="Short, focused endgame puzzles against tablebase-perfect defence. Learn to see the winning move and make the endgame your strongest phase."
|
||||
/>
|
||||
<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="Inner Square Chess — Endgame Trainer" />
|
||||
<meta
|
||||
property="og:description"
|
||||
content="Short, focused endgame puzzles against tablebase-perfect defence. Launching soon."
|
||||
/>
|
||||
<meta name="twitter:card" content="summary" />
|
||||
<link rel="icon" href="/favicon.ico" />
|
||||
|
||||
<style>
|
||||
@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-mint-chip: var(--mint);
|
||||
|
||||
--color-board-light: #e9e1cc;
|
||||
--color-board-dark: #81a996;
|
||||
--color-piece-light: #fffdf5;
|
||||
--color-piece-outline: #17352d;
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
/* Navigation */
|
||||
.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);
|
||||
}
|
||||
|
||||
/* Hero */
|
||||
.hero {
|
||||
width: min(1180px, calc(100% - 48px));
|
||||
min-height: 650px;
|
||||
margin: 0 auto;
|
||||
display: grid;
|
||||
grid-template-columns: 0.91fr 1.09fr;
|
||||
align-items: center;
|
||||
gap: 60px;
|
||||
}
|
||||
|
||||
.hero-copy {
|
||||
position: relative;
|
||||
z-index: 2;
|
||||
padding: 74px 0 92px;
|
||||
}
|
||||
|
||||
.eyebrow {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
color: var(--color-coral-text);
|
||||
font-size: 11px;
|
||||
font-weight: 700;
|
||||
letter-spacing: 0.14em;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
.eyebrow::before {
|
||||
content: "";
|
||||
width: 7px;
|
||||
height: 7px;
|
||||
border-radius: 50%;
|
||||
background: var(--color-coral);
|
||||
}
|
||||
|
||||
h1 {
|
||||
max-width: 590px;
|
||||
margin: 18px 0 0;
|
||||
font-family: "DM Serif Display", Georgia, serif;
|
||||
font-size: clamp(56px, 6vw, 87px);
|
||||
font-weight: 400;
|
||||
letter-spacing: -0.035em;
|
||||
line-height: 0.93;
|
||||
}
|
||||
|
||||
h1 em {
|
||||
color: var(--color-coral);
|
||||
font-weight: 400;
|
||||
}
|
||||
|
||||
.hero-copy > p {
|
||||
max-width: 480px;
|
||||
margin: 29px 0 0;
|
||||
color: var(--color-muted);
|
||||
font-size: 17px;
|
||||
line-height: 1.65;
|
||||
}
|
||||
|
||||
.hero-copy > .note {
|
||||
margin-top: 20px;
|
||||
color: var(--color-muted);
|
||||
font-size: 13px;
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
/* Board */
|
||||
.board-stage {
|
||||
position: relative;
|
||||
min-height: 580px;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
}
|
||||
|
||||
.coral-orbit,
|
||||
.mint-orbit {
|
||||
position: absolute;
|
||||
border-radius: 50%;
|
||||
}
|
||||
|
||||
.coral-orbit {
|
||||
width: 460px;
|
||||
height: 460px;
|
||||
right: -34px;
|
||||
top: 46px;
|
||||
background: var(--color-coral);
|
||||
}
|
||||
|
||||
.mint-orbit {
|
||||
width: 230px;
|
||||
height: 230px;
|
||||
left: 14px;
|
||||
bottom: 28px;
|
||||
background: var(--color-mint-chip);
|
||||
}
|
||||
|
||||
.board-shell {
|
||||
position: relative;
|
||||
z-index: 2;
|
||||
width: min(458px, 85vw);
|
||||
padding: 18px;
|
||||
border-radius: 12px;
|
||||
background: var(--color-canvas-raised);
|
||||
box-shadow: 0 26px 65px rgba(23, 53, 45, 0.25);
|
||||
transform: rotate(1.5deg);
|
||||
}
|
||||
|
||||
.board-topline,
|
||||
.board-caption {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
}
|
||||
|
||||
.board-topline {
|
||||
padding: 1px 1px 13px;
|
||||
}
|
||||
|
||||
.player {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 9px;
|
||||
}
|
||||
|
||||
.player-piece {
|
||||
display: grid;
|
||||
place-items: center;
|
||||
width: 31px;
|
||||
height: 31px;
|
||||
border-radius: 50%;
|
||||
background: var(--color-deep);
|
||||
color: var(--color-on-deep);
|
||||
font-size: 20px;
|
||||
}
|
||||
|
||||
.player span:last-child {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
line-height: 1.05;
|
||||
}
|
||||
|
||||
.player small {
|
||||
color: var(--color-muted);
|
||||
font-size: 8px;
|
||||
letter-spacing: 0.1em;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
.player strong {
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.piece-count {
|
||||
color: var(--color-muted);
|
||||
font-size: 10px;
|
||||
font-weight: 600;
|
||||
letter-spacing: 0.08em;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
.chessboard {
|
||||
aspect-ratio: 1;
|
||||
display: grid;
|
||||
grid-template-columns: repeat(8, 1fr);
|
||||
overflow: hidden;
|
||||
border-radius: 4px;
|
||||
box-shadow: inset 0 0 0 1px rgba(0, 0, 0, 0.05);
|
||||
}
|
||||
|
||||
.square {
|
||||
position: relative;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
aspect-ratio: 1;
|
||||
}
|
||||
|
||||
.square.light {
|
||||
background: var(--color-board-light);
|
||||
}
|
||||
|
||||
.square.dark {
|
||||
background: var(--color-board-dark);
|
||||
}
|
||||
|
||||
.piece {
|
||||
position: relative;
|
||||
z-index: 2;
|
||||
font-family: Georgia, serif;
|
||||
font-size: clamp(25px, 4vw, 42px);
|
||||
line-height: 1;
|
||||
transform: translateY(-1px);
|
||||
}
|
||||
|
||||
.white-piece {
|
||||
color: var(--color-piece-light);
|
||||
text-shadow:
|
||||
0 2px 0 var(--color-piece-outline),
|
||||
1px 0 0 var(--color-piece-outline),
|
||||
-1px 0 0 var(--color-piece-outline),
|
||||
0 -1px 0 var(--color-piece-outline);
|
||||
}
|
||||
|
||||
.black-piece {
|
||||
color: var(--color-piece-outline);
|
||||
text-shadow: 0 1px 0 rgba(255, 255, 255, 0.25);
|
||||
}
|
||||
|
||||
.rank,
|
||||
.file {
|
||||
position: absolute;
|
||||
z-index: 3;
|
||||
color: rgba(23, 53, 45, 0.65);
|
||||
font-size: 7px;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.rank {
|
||||
top: 3px;
|
||||
left: 4px;
|
||||
}
|
||||
|
||||
.file {
|
||||
right: 4px;
|
||||
bottom: 2px;
|
||||
}
|
||||
|
||||
.square.dark .rank,
|
||||
.square.dark .file {
|
||||
color: rgba(255, 255, 255, 0.65);
|
||||
}
|
||||
|
||||
.board-caption {
|
||||
padding: 14px 2px 0;
|
||||
}
|
||||
|
||||
.board-caption div {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.board-caption span {
|
||||
color: var(--color-muted);
|
||||
font-size: 9px;
|
||||
letter-spacing: 0.1em;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
.board-caption strong {
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.board-themes {
|
||||
color: var(--color-coral-text) !important;
|
||||
font-size: 8px !important;
|
||||
font-weight: 700;
|
||||
letter-spacing: 0.08em;
|
||||
}
|
||||
|
||||
/* Footer */
|
||||
.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: 900px) {
|
||||
.hero {
|
||||
grid-template-columns: 1fr;
|
||||
gap: 0;
|
||||
}
|
||||
|
||||
.hero-copy {
|
||||
padding-bottom: 30px;
|
||||
}
|
||||
|
||||
.hero-copy > p {
|
||||
max-width: 560px;
|
||||
}
|
||||
|
||||
.coral-orbit {
|
||||
right: 6%;
|
||||
}
|
||||
|
||||
.mint-orbit {
|
||||
left: 10%;
|
||||
}
|
||||
|
||||
.board-stage {
|
||||
min-height: 620px;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 650px) {
|
||||
.nav-wrap,
|
||||
.hero,
|
||||
.site-footer {
|
||||
width: calc(100% - 36px);
|
||||
}
|
||||
|
||||
.nav-wrap {
|
||||
height: 74px;
|
||||
}
|
||||
|
||||
.status {
|
||||
padding: 7px 10px;
|
||||
font-size: 9px;
|
||||
}
|
||||
|
||||
.hero-copy {
|
||||
padding: 65px 0 24px;
|
||||
}
|
||||
|
||||
.hero-copy > p {
|
||||
font-size: 15px;
|
||||
}
|
||||
|
||||
h1 {
|
||||
font-size: clamp(51px, 15vw, 68px);
|
||||
}
|
||||
|
||||
.board-stage {
|
||||
min-height: 500px;
|
||||
}
|
||||
|
||||
.coral-orbit {
|
||||
width: 340px;
|
||||
height: 340px;
|
||||
right: -28%;
|
||||
top: 65px;
|
||||
}
|
||||
|
||||
.mint-orbit {
|
||||
width: 170px;
|
||||
height: 170px;
|
||||
left: -8%;
|
||||
}
|
||||
|
||||
.board-shell {
|
||||
width: min(390px, 92vw);
|
||||
padding: 12px;
|
||||
}
|
||||
|
||||
.piece {
|
||||
font-size: clamp(24px, 9vw, 38px);
|
||||
}
|
||||
|
||||
.site-footer {
|
||||
flex-direction: column;
|
||||
align-items: flex-start;
|
||||
gap: 24px;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
</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">
|
||||
<section class="hero">
|
||||
<div class="hero-copy">
|
||||
<span class="eyebrow">Endgame training, coming soon</span>
|
||||
<h1>Master the <em>endgame.</em></h1>
|
||||
<p>
|
||||
Short, focused endgame puzzles against tablebase-perfect defence.
|
||||
Learn to see the winning move and make the endgame your strongest
|
||||
phase.
|
||||
</p>
|
||||
<p class="note">
|
||||
We’re putting the finishing touches on the trainer.
|
||||
Check back soon.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div class="board-stage">
|
||||
<div class="coral-orbit" aria-hidden="true"></div>
|
||||
<div class="mint-orbit" aria-hidden="true"></div>
|
||||
|
||||
<div class="board-shell">
|
||||
<div class="board-topline">
|
||||
<div class="player">
|
||||
<span class="player-piece" aria-hidden="true">♚</span>
|
||||
<span>
|
||||
<small>To move</small>
|
||||
<strong>White</strong>
|
||||
</span>
|
||||
</div>
|
||||
<span class="piece-count">3 pieces</span>
|
||||
</div>
|
||||
|
||||
<div
|
||||
class="chessboard"
|
||||
role="img"
|
||||
aria-label="Chess position: white king on d5, white rook on g3, black king on f7. White to move."
|
||||
>
|
||||
<div class="square light"><span class="rank">8</span></div>
|
||||
<div class="square dark"></div>
|
||||
<div class="square light"></div>
|
||||
<div class="square dark"></div>
|
||||
<div class="square light"></div>
|
||||
<div class="square dark"></div>
|
||||
<div class="square light"></div>
|
||||
<div class="square dark"></div>
|
||||
|
||||
<div class="square dark"><span class="rank">7</span></div>
|
||||
<div class="square light"></div>
|
||||
<div class="square dark"></div>
|
||||
<div class="square light"></div>
|
||||
<div class="square dark"></div>
|
||||
<div class="square light"><span class="piece black-piece" aria-hidden="true">♚</span></div>
|
||||
<div class="square dark"></div>
|
||||
<div class="square light"></div>
|
||||
|
||||
<div class="square light"><span class="rank">6</span></div>
|
||||
<div class="square dark"></div>
|
||||
<div class="square light"></div>
|
||||
<div class="square dark"></div>
|
||||
<div class="square light"></div>
|
||||
<div class="square dark"></div>
|
||||
<div class="square light"></div>
|
||||
<div class="square dark"></div>
|
||||
|
||||
<div class="square dark"><span class="rank">5</span></div>
|
||||
<div class="square light"></div>
|
||||
<div class="square dark"></div>
|
||||
<div class="square light"><span class="piece white-piece" aria-hidden="true">♔</span></div>
|
||||
<div class="square dark"></div>
|
||||
<div class="square light"></div>
|
||||
<div class="square dark"></div>
|
||||
<div class="square light"></div>
|
||||
|
||||
<div class="square light"><span class="rank">4</span></div>
|
||||
<div class="square dark"></div>
|
||||
<div class="square light"></div>
|
||||
<div class="square dark"></div>
|
||||
<div class="square light"></div>
|
||||
<div class="square dark"></div>
|
||||
<div class="square light"></div>
|
||||
<div class="square dark"></div>
|
||||
|
||||
<div class="square dark"><span class="rank">3</span></div>
|
||||
<div class="square light"></div>
|
||||
<div class="square dark"></div>
|
||||
<div class="square light"></div>
|
||||
<div class="square dark"></div>
|
||||
<div class="square light"></div>
|
||||
<div class="square dark"><span class="piece white-piece" aria-hidden="true">♖</span></div>
|
||||
<div class="square light"></div>
|
||||
|
||||
<div class="square light"><span class="rank">2</span></div>
|
||||
<div class="square dark"></div>
|
||||
<div class="square light"></div>
|
||||
<div class="square dark"></div>
|
||||
<div class="square light"></div>
|
||||
<div class="square dark"></div>
|
||||
<div class="square light"></div>
|
||||
<div class="square dark"></div>
|
||||
|
||||
<div class="square dark"><span class="rank">1</span><span class="file">a</span></div>
|
||||
<div class="square light"><span class="file">b</span></div>
|
||||
<div class="square dark"><span class="file">c</span></div>
|
||||
<div class="square light"><span class="file">d</span></div>
|
||||
<div class="square dark"><span class="file">e</span></div>
|
||||
<div class="square light"><span class="file">f</span></div>
|
||||
<div class="square dark"><span class="file">g</span></div>
|
||||
<div class="square light"><span class="file">h</span></div>
|
||||
</div>
|
||||
|
||||
<div class="board-caption">
|
||||
<div>
|
||||
<span>Sample position</span>
|
||||
<strong>King and rook vs king</strong>
|
||||
<small class="board-themes">Rook endgame</small>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</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>
|
||||
<a href="/mentions-legales">Mentions légales</a>
|
||||
</nav>
|
||||
<small>© 2026 Inner Square Chess</small>
|
||||
</footer>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,299 @@
|
||||
@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;
|
||||
}
|
||||
|
||||
.analytics-buttons {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 12px;
|
||||
margin-top: 16px;
|
||||
}
|
||||
|
||||
.analytics-buttons button {
|
||||
padding: 10px 16px;
|
||||
border: 1px solid var(--color-hairline);
|
||||
border-radius: 8px;
|
||||
background: var(--color-canvas-raised);
|
||||
color: var(--color-body);
|
||||
font: inherit;
|
||||
font-weight: 600;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.analytics-buttons button:hover {
|
||||
background: var(--color-canvas);
|
||||
}
|
||||
|
||||
.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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
<!doctype html>
|
||||
<html lang="fr">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<title>Mentions légales — Inner Square Chess</title>
|
||||
<meta
|
||||
name="description"
|
||||
content="Éditeur, hébergeur et informations légales du site 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="Mentions légales — Inner Square Chess" />
|
||||
<meta
|
||||
property="og:description"
|
||||
content="Éditeur, hébergeur et informations légales du site 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" lang="fr">
|
||||
<h1>Mentions légales</h1>
|
||||
<p class="legal-meta">Dernière mise à jour : 10 novembre 2026</p>
|
||||
|
||||
<p>
|
||||
Ces mentions sont publiées en application de l'article 6-III de la loi
|
||||
n° 2004-575 du 21 juin 2004 pour la confiance dans l'économie numérique.
|
||||
</p>
|
||||
|
||||
<h2>Éditeur du site</h2>
|
||||
<p>
|
||||
Le site <a href="/">innersquare.app</a>, édité sous le nom commercial
|
||||
« Inner Square Chess », est édité par :
|
||||
</p>
|
||||
<ul>
|
||||
<li><strong>Owen REES</strong>, entrepreneur individuel (EI)</li>
|
||||
<li>Adresse : [adresse à compléter]</li>
|
||||
<li>SIRET : 929 553 774 00019</li>
|
||||
<li>Téléphone : <a href="tel:+33683019513">+33 6 83 01 95 13</a></li>
|
||||
<li>
|
||||
Courriel :
|
||||
<a href="mailto:support@innersquare.app">support@innersquare.app</a>
|
||||
</li>
|
||||
<li>TVA non applicable, article 293 B du Code général des impôts.</li>
|
||||
</ul>
|
||||
|
||||
<h2>Directeur de la publication</h2>
|
||||
<p>Owen REES.</p>
|
||||
|
||||
<h2>Hébergeur</h2>
|
||||
<p>
|
||||
Hetzner Online GmbH<br />
|
||||
Industriestraße 25<br />
|
||||
91710 Gunzenhausen<br />
|
||||
Allemagne<br />
|
||||
Téléphone : <a href="tel:+4998315050">+49 9831 505-0</a>
|
||||
</p>
|
||||
|
||||
<h2>Propriété intellectuelle</h2>
|
||||
<p>
|
||||
Les contenus du site — textes, interface, code, éléments graphiques, ainsi
|
||||
que les positions et solutions d'échecs — sont protégés par le droit
|
||||
d'auteur et restent la propriété de l'éditeur ou de ses concédants. Toute
|
||||
reproduction ou réutilisation non autorisée est interdite.
|
||||
</p>
|
||||
|
||||
<h2>Données personnelles</h2>
|
||||
<p>
|
||||
Les données traitées, les finalités, les durées de conservation et vos
|
||||
droits sont décrits dans la
|
||||
<a href="/privacy">politique de confidentialité</a>, disponible en anglais.
|
||||
</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>
|
||||
<a href="/mentions-legales">Mentions légales</a>
|
||||
</nav>
|
||||
<small>© 2026 Inner Square Chess</small>
|
||||
</footer>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,334 @@
|
||||
<!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: 10 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>Data controller</h2>
|
||||
<p>
|
||||
The controller responsible for your personal information is Owen REES,
|
||||
an entrepreneur individuel (EI) established in France, trading as
|
||||
Inner Square Chess. Our business register number (SIRET) is
|
||||
929 553 774 00019. You can contact us about anything in
|
||||
this policy, or about your data, at
|
||||
<a href="mailto:support@innersquare.app">support@innersquare.app</a>
|
||||
or <a href="tel:+33683019513">+33 6 83 01 95 13</a>.
|
||||
</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>
|
||||
We do not keep our own access logs. The companies that host the site
|
||||
and run our content delivery network keep short-lived request logs
|
||||
(IP address, browser, timestamps) for security, abuse prevention, and
|
||||
troubleshooting, under their own retention policies.
|
||||
</li>
|
||||
<li>
|
||||
<strong>Usage data.</strong>
|
||||
On public pages and the guest trainer, we use a self-hosted Matomo
|
||||
instance to understand aggregate usage. Matomo is configured without
|
||||
cookies, with IP addresses shortened before storage, and to respect
|
||||
Do Not Track. We do not use user IDs, track signed-in account pages,
|
||||
or share this data with third parties.
|
||||
</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 security cookie that our content delivery network, Cloudflare, may
|
||||
set when it checks that a request is not automated abuse;
|
||||
</li>
|
||||
<li>a colour-mode preference stored in your browser.</li>
|
||||
<li>
|
||||
an analytics opt-out preference stored in your browser's local
|
||||
storage, if you choose to opt out.
|
||||
</li>
|
||||
</ul>
|
||||
<p>
|
||||
We do not use advertising cookies, analytics cookies, or cross-site
|
||||
tracking. The only cookie not set by this site is Cloudflare's security
|
||||
check described above; our analytics is self-hosted Matomo and is
|
||||
configured without cookies. You can clear these entries at any time in
|
||||
your browser settings; doing so will sign you out, reset your colour
|
||||
mode, and reset your analytics preference.
|
||||
</p>
|
||||
|
||||
<h2>Analytics</h2>
|
||||
<p>
|
||||
We use a self-hosted Matomo instance at
|
||||
<a href="https://analytics.owenrees.eu/">analytics.owenrees.eu</a>
|
||||
to understand aggregate use of the public site and guest trainer. It is
|
||||
configured without cookies, with IP addresses shortened before storage,
|
||||
and to respect Do Not Track. We do not use user IDs, track signed-in
|
||||
account pages, or share this data with third parties.
|
||||
</p>
|
||||
<p>
|
||||
Raw analytics data is retained for up to 180 days. We process it on the
|
||||
basis of our legitimate interests in improving the service. You can
|
||||
object at any time using the control below or by emailing
|
||||
<a href="mailto:support@innersquare.app">support@innersquare.app</a>.
|
||||
</p>
|
||||
<p id="analytics-status">Analytics is currently on in this browser.</p>
|
||||
<div class="analytics-buttons">
|
||||
<button id="analytics-opt-out" type="button">Opt out of analytics</button>
|
||||
<button id="analytics-opt-in" type="button" hidden>Opt back in</button>
|
||||
</div>
|
||||
|
||||
<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 understand aggregate use of the public site and guest trainer, and
|
||||
improve the service.
|
||||
</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 id="hosting-and-infrastructure">Hosting and infrastructure</h2>
|
||||
<p>
|
||||
The site runs on a virtual private server operated for us by Hetzner
|
||||
inside the European Union. Our database runs on the same server, our
|
||||
transactional email is sent through Amazon SES in the EU, and our
|
||||
self-hosted Matomo analytics runs on infrastructure we control in the
|
||||
EU.
|
||||
</p>
|
||||
<p>
|
||||
We also use Cloudflare as our content delivery network and security
|
||||
proxy. Because Cloudflare sits between your browser and our server, it
|
||||
processes your IP address, the requested URL, and request headers.
|
||||
Cloudflare is a US company, so that request data may be transferred
|
||||
outside the UK and EEA. The transfer relies on the EU–US Data Privacy
|
||||
Framework and standard contractual clauses. Cloudflare and Hetzner each
|
||||
keep their own logs under their own retention policies; we do not
|
||||
receive or keep them.
|
||||
</p>
|
||||
<p>
|
||||
These providers act as our processors under data protection law. We
|
||||
share with them only what they need to run the service, and we remain
|
||||
responsible for how your information is handled.
|
||||
</p>
|
||||
|
||||
<h2>Sharing</h2>
|
||||
<p>
|
||||
We do not sell your personal information. We share it only with the
|
||||
providers described under
|
||||
<a href="#hosting-and-infrastructure">hosting and infrastructure</a>
|
||||
— our hosting, content delivery, database, and email delivery providers
|
||||
— and only as far as they need it to perform that work. Self-hosted
|
||||
Matomo analytics is operated by us on infrastructure we control; we do
|
||||
not share that data with third parties. 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. We retain raw analytics data for up to 180 days.
|
||||
</p>
|
||||
<p>
|
||||
Two exceptions are worth naming. If you unsubscribe from the mailing
|
||||
list, or ask us not to email you, we keep your address on a suppression
|
||||
list so that we do not contact you again; we hold only what is needed to
|
||||
recognise the address. We also keep database backups for disaster
|
||||
recovery, stored off the primary server, so a deleted account may remain
|
||||
in a backup for some time after deletion. We do not use backups to
|
||||
restore individual accounts, and we delete them once they are no longer
|
||||
needed.
|
||||
</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. You can object to analytics processing at any time using
|
||||
the control on this page or by contacting us. 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>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>
|
||||
<a href="/mentions-legales">Mentions légales</a>
|
||||
</nav>
|
||||
<small>© 2026 Inner Square Chess</small>
|
||||
</footer>
|
||||
|
||||
<script>
|
||||
(function () {
|
||||
var key = "matomo_optout";
|
||||
var optOut = document.getElementById("analytics-opt-out");
|
||||
var optIn = document.getElementById("analytics-opt-in");
|
||||
var status = document.getElementById("analytics-status");
|
||||
|
||||
function optedOut() {
|
||||
try {
|
||||
return localStorage.getItem(key) === "1";
|
||||
} catch (error) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
function update() {
|
||||
var off = optedOut();
|
||||
if (optOut) optOut.hidden = off;
|
||||
if (optIn) optIn.hidden = !off;
|
||||
if (status) {
|
||||
status.textContent = off
|
||||
? "Analytics is currently off in this browser."
|
||||
: "Analytics is currently on in this browser.";
|
||||
}
|
||||
}
|
||||
|
||||
if (optOut) {
|
||||
optOut.addEventListener("click", function () {
|
||||
try {
|
||||
localStorage.setItem(key, "1");
|
||||
} catch (error) {}
|
||||
update();
|
||||
});
|
||||
}
|
||||
|
||||
if (optIn) {
|
||||
optIn.addEventListener("click", function () {
|
||||
try {
|
||||
localStorage.removeItem(key);
|
||||
} catch (error) {}
|
||||
update();
|
||||
});
|
||||
}
|
||||
|
||||
update();
|
||||
})();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,181 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<title>Terms & 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 & 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 & Conditions</h1>
|
||||
<p class="legal-meta">Last updated: 10 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>
|
||||
<p>
|
||||
Inner Square Chess is operated by Owen REES, entrepreneur individuel (EI),
|
||||
established in France, business register number (SIRET)
|
||||
929 553 774 00019. Full publisher details are on the
|
||||
<a href="/mentions-legales">mentions légales</a> page.
|
||||
</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>
|
||||
If you are under 16 and in the UK or EU, you may only use an account
|
||||
with the consent of a parent or guardian.
|
||||
</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>
|
||||
<a href="/mentions-legales">Mentions légales</a>
|
||||
</nav>
|
||||
<small>© 2026 Inner Square Chess</small>
|
||||
</footer>
|
||||
</body>
|
||||
</html>
|
||||
Executable
+115
@@ -0,0 +1,115 @@
|
||||
#!/usr/bin/env bash
|
||||
#
|
||||
# Refresh Caddy's Cloudflare origin allowlist from Cloudflare's published
|
||||
# ranges. Called by chesstrainer-cloudflare-ranges.timer.
|
||||
#
|
||||
# The generated file is imported by /etc/caddy/Caddyfile:
|
||||
#
|
||||
# @cloudflare {
|
||||
# import cloudflare-ranges.caddy
|
||||
# }
|
||||
#
|
||||
# The script validates the candidate Caddyfile before reloading Caddy. If the
|
||||
# download or validation fails, the previous ranges stay in place.
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
CADDYFILE="${CADDYFILE:-/etc/caddy/Caddyfile}"
|
||||
RANGES_FILE="${RANGES_FILE:-/etc/caddy/cloudflare-ranges.caddy}"
|
||||
CADDY_BIN="${CADDY_BIN:-caddy}"
|
||||
RELOAD_CMD="${RELOAD_CMD:-systemctl reload caddy}"
|
||||
LOCK_FILE="${LOCK_FILE:-/run/lock/chesstrainer-cloudflare-ranges.lock}"
|
||||
|
||||
tmpdir="$(mktemp -d)"
|
||||
trap 'rm -rf "$tmpdir"' EXIT
|
||||
|
||||
exec 9>"$LOCK_FILE"
|
||||
if ! flock -n 9; then
|
||||
echo "another Cloudflare range update is already running" >&2
|
||||
exit 0
|
||||
fi
|
||||
|
||||
fetch() {
|
||||
local url="$1"
|
||||
local output="$2"
|
||||
|
||||
curl --fail --silent --show-error --location \
|
||||
--proto '=https' \
|
||||
--retry 3 --retry-delay 2 --connect-timeout 10 \
|
||||
"$url" --output "$output"
|
||||
}
|
||||
|
||||
validate_download() {
|
||||
local file="$1"
|
||||
|
||||
[[ -s "$file" ]] || return 1
|
||||
|
||||
# One CIDR per line. Caddy performs the real validation; this prevents
|
||||
# obviously malformed or injected content from being written.
|
||||
if grep -Evq '^[0-9A-Fa-f:.]+/[0-9]{1,3}$' "$file"; then
|
||||
return 1
|
||||
fi
|
||||
}
|
||||
|
||||
fetch "https://www.cloudflare.com/ips-v4" "$tmpdir/ips-v4"
|
||||
fetch "https://www.cloudflare.com/ips-v6" "$tmpdir/ips-v6"
|
||||
|
||||
validate_download "$tmpdir/ips-v4"
|
||||
validate_download "$tmpdir/ips-v6"
|
||||
|
||||
ranges="$(awk 'NF { printf "%s ", $0 }' "$tmpdir/ips-v4" "$tmpdir/ips-v6" | sed -e 's/[[:space:]]*$//')"
|
||||
|
||||
if [[ -z "$ranges" ]]; then
|
||||
echo "Cloudflare returned an empty CIDR list" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
candidate="$tmpdir/cloudflare-ranges.caddy"
|
||||
|
||||
{
|
||||
echo "# Generated by deploy/update-cloudflare-ranges.sh."
|
||||
echo "# Source: https://www.cloudflare.com/ips-v4 and /ips-v6"
|
||||
echo "remote_ip $ranges"
|
||||
} >"$candidate"
|
||||
|
||||
if cmp -s "$candidate" "$RANGES_FILE"; then
|
||||
echo "Cloudflare ranges are unchanged"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
install -d -m 0755 "$(dirname "$RANGES_FILE")"
|
||||
|
||||
backup="$tmpdir/previous-ranges.caddy"
|
||||
if [[ -e "$RANGES_FILE" ]]; then
|
||||
cp -a "$RANGES_FILE" "$backup"
|
||||
fi
|
||||
|
||||
install -m 0644 "$candidate" "$RANGES_FILE"
|
||||
|
||||
if ! "$CADDY_BIN" validate --config "$CADDYFILE" --adapter caddyfile; then
|
||||
echo "Caddy rejected the new Cloudflare ranges; restoring the previous file" >&2
|
||||
|
||||
if [[ -e "$backup" ]]; then
|
||||
install -m 0644 "$backup" "$RANGES_FILE"
|
||||
else
|
||||
rm -f "$RANGES_FILE"
|
||||
fi
|
||||
|
||||
exit 1
|
||||
fi
|
||||
|
||||
read -r -a reload_command <<<"$RELOAD_CMD"
|
||||
|
||||
if ! "${reload_command[@]}"; then
|
||||
echo "Caddy reload failed; restoring the previous ranges" >&2
|
||||
|
||||
if [[ -e "$backup" ]]; then
|
||||
install -m 0644 "$backup" "$RANGES_FILE"
|
||||
else
|
||||
rm -f "$RANGES_FILE"
|
||||
fi
|
||||
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "Cloudflare ranges updated and Caddy reloaded"
|
||||
Executable
+190
@@ -0,0 +1,190 @@
|
||||
#!/usr/bin/env bash
|
||||
#
|
||||
# Restore the newest (or a named) archive into a throwaway Postgres container
|
||||
# and prove that the dump, the roles and the row counts all came back.
|
||||
#
|
||||
# backup-drill # newest archive in DEST
|
||||
# backup-drill 20261111T031500Z.tar.age
|
||||
#
|
||||
# Runs on the workstation. The production database is never contacted: the
|
||||
# container is created and destroyed by this script. Results are appended to
|
||||
# $DRILL_LOG (default $DEST/drills.log).
|
||||
#
|
||||
# Configuration: same file as backup-pull,
|
||||
# ~/.config/chesstrainer/backup-pull.env.
|
||||
|
||||
set -euo pipefail
|
||||
umask 077
|
||||
|
||||
CONFIG="${PULL_ENV_FILE:-${XDG_CONFIG_HOME:-$HOME/.config}/chesstrainer/backup-pull.env}"
|
||||
if [[ -r "$CONFIG" ]]; then
|
||||
# shellcheck disable=SC1090
|
||||
source "$CONFIG"
|
||||
fi
|
||||
|
||||
DEST="${DEST:-$HOME/chesstrainer-backups}"
|
||||
AGE_KEY="${AGE_KEY:-${XDG_CONFIG_HOME:-$HOME/.config}/chesstrainer/age.key}"
|
||||
EXPECTED_ROLES="${EXPECTED_ROLES:-chesstrainer chesstrainer_ro}"
|
||||
DRILL_IMAGE="${DRILL_IMAGE:-postgres:18.6}"
|
||||
DRILL_DB="${DRILL_DB:-chesstrainer_restore}"
|
||||
DRILL_LOG="${DRILL_LOG:-$DEST/drills.log}"
|
||||
DRILL_CONTAINER="${DRILL_CONTAINER:-chesstrainer-drill-$$}"
|
||||
|
||||
START_SECONDS=$SECONDS
|
||||
FAILURE=""
|
||||
TMPDIR_DRILL=""
|
||||
|
||||
log_event() {
|
||||
local event="$1"
|
||||
local extra="${2:-}"
|
||||
|
||||
printf '{"timestamp":"%s","event":"%s"%s}\n' \
|
||||
"$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$event" "$extra"
|
||||
}
|
||||
|
||||
record() {
|
||||
local line="$1"
|
||||
|
||||
printf '%s\n' "$line"
|
||||
printf '%s\n' "$line" >>"$DRILL_LOG"
|
||||
}
|
||||
|
||||
fail() {
|
||||
FAILURE="$*"
|
||||
exit 1
|
||||
}
|
||||
|
||||
cleanup() {
|
||||
local status=$?
|
||||
|
||||
docker rm -f "$DRILL_CONTAINER" >/dev/null 2>&1 || true
|
||||
|
||||
if [[ -n "$TMPDIR_DRILL" ]]; then
|
||||
rm -rf "$TMPDIR_DRILL"
|
||||
fi
|
||||
|
||||
if ((status != 0)); then
|
||||
if [[ -d "$DEST" ]]; then
|
||||
record "$(log_event drill.failed ",\"reason\":\"${FAILURE:-exit $status}\"")"
|
||||
else
|
||||
log_event drill.failed ",\"reason\":\"${FAILURE:-exit $status}\""
|
||||
fi
|
||||
fi
|
||||
|
||||
exit "$status"
|
||||
}
|
||||
|
||||
trap cleanup EXIT
|
||||
trap 'exit 143' TERM INT
|
||||
|
||||
[[ -d "$DEST" ]] || fail "archive directory does not exist: $DEST"
|
||||
[[ -r "$AGE_KEY" ]] || fail "age identity not readable: $AGE_KEY"
|
||||
|
||||
for cmd in docker age tar sha256sum; do
|
||||
command -v "$cmd" >/dev/null 2>&1 || fail "missing command: $cmd"
|
||||
done
|
||||
|
||||
if [[ $# -gt 0 ]]; then
|
||||
case "$1" in
|
||||
/*) archive="$1" ;;
|
||||
*) archive="$DEST/$1" ;;
|
||||
esac
|
||||
else
|
||||
archive="$(find "$DEST" -maxdepth 1 -type f -name '*.tar.age' -printf '%p\n' | sort | tail -n 1)"
|
||||
[[ -n "$archive" ]] || fail "no archives in $DEST"
|
||||
fi
|
||||
|
||||
[[ -f "$archive" ]] || fail "archive not found: $archive"
|
||||
|
||||
name="${archive##*/}"
|
||||
[[ "$name" =~ ^[0-9]{8}T[0-9]{6}Z(-[a-z0-9]+)?\.tar\.age$ ]] ||
|
||||
fail "unexpected archive name: $name"
|
||||
|
||||
prefix="${name%%.*}"
|
||||
TMPDIR_DRILL="$(mktemp -d "${TMPDIR:-/tmp}/chesstrainer-drill.XXXXXX")"
|
||||
|
||||
echo "backup-drill: decrypting $name" >&2
|
||||
age --decrypt --identity "$AGE_KEY" --output "$TMPDIR_DRILL/$prefix.tar" "$archive" ||
|
||||
fail "could not decrypt $name"
|
||||
|
||||
tar -xf "$TMPDIR_DRILL/$prefix.tar" -C "$TMPDIR_DRILL" ||
|
||||
fail "archive does not contain a readable tar file"
|
||||
|
||||
(
|
||||
cd "$TMPDIR_DRILL"
|
||||
sha256sum --check --strict --quiet "$prefix.sha256"
|
||||
) || fail "checksum verification failed for $name"
|
||||
|
||||
echo "backup-drill: starting $DRILL_IMAGE" >&2
|
||||
docker image inspect "$DRILL_IMAGE" >/dev/null 2>&1 ||
|
||||
docker pull "$DRILL_IMAGE" >/dev/null ||
|
||||
fail "could not pull $DRILL_IMAGE"
|
||||
|
||||
docker run --rm --detach \
|
||||
--name "$DRILL_CONTAINER" \
|
||||
--env POSTGRES_USER=chesstrainer \
|
||||
--env POSTGRES_PASSWORD=drill \
|
||||
--env POSTGRES_HOST_AUTH_METHOD=trust \
|
||||
"$DRILL_IMAGE" >/dev/null || fail "could not start the drill container"
|
||||
|
||||
ready=0
|
||||
for _ in $(seq 1 60); do
|
||||
if docker exec "$DRILL_CONTAINER" pg_isready -U chesstrainer -d postgres >/dev/null 2>&1; then
|
||||
ready=1
|
||||
break
|
||||
fi
|
||||
sleep 1
|
||||
done
|
||||
((ready == 1)) || fail "postgres did not become ready"
|
||||
|
||||
# Recreating the cluster roles is half of disaster recovery. The scratch
|
||||
# cluster uses the same superuser name as production (`chesstrainer`), because
|
||||
# the globals dump ends with grants issued "GRANTED BY chesstrainer". The dump
|
||||
# always repeats the cluster's own superuser role, so "already exists" is
|
||||
# expected; anything else is a real failure.
|
||||
echo "backup-drill: applying globals" >&2
|
||||
docker exec -i "$DRILL_CONTAINER" psql -U chesstrainer -d postgres \
|
||||
-q -v ON_ERROR_STOP=0 -f - \
|
||||
<"$TMPDIR_DRILL/$prefix.globals.sql" >/dev/null 2>"$TMPDIR_DRILL/globals.err" ||
|
||||
fail "applying the globals dump failed"
|
||||
|
||||
globals_errors="$(grep -v 'already exists' "$TMPDIR_DRILL/globals.err" | sed '/^$/d' || true)"
|
||||
if [[ -n "$globals_errors" ]]; then
|
||||
fail "globals restore reported errors: $(printf '%s' "$globals_errors" | head -n 1)"
|
||||
fi
|
||||
|
||||
for role in $EXPECTED_ROLES; do
|
||||
found="$(docker exec "$DRILL_CONTAINER" psql -U chesstrainer -d postgres -Atc \
|
||||
"select 1 from pg_roles where rolname = '$role'")"
|
||||
[[ "$found" == "1" ]] || fail "globals did not recreate role $role"
|
||||
done
|
||||
|
||||
owner="${EXPECTED_ROLES%% *}"
|
||||
|
||||
docker exec "$DRILL_CONTAINER" psql -U chesstrainer -d postgres \
|
||||
-q -v ON_ERROR_STOP=1 -c "create database $DRILL_DB owner $owner" ||
|
||||
fail "could not create $DRILL_DB"
|
||||
|
||||
echo "backup-drill: restoring into $DRILL_DB" >&2
|
||||
docker exec -i "$DRILL_CONTAINER" pg_restore -U chesstrainer -d "$DRILL_DB" \
|
||||
--single-transaction --exit-on-error <"$TMPDIR_DRILL/$prefix.dump" ||
|
||||
fail "pg_restore failed"
|
||||
|
||||
restored_counts=""
|
||||
for table in users endgames attempts; do
|
||||
expected="$(awk -F= -v key="$table" '$1 == key { print $2 }' "$TMPDIR_DRILL/$prefix.counts")"
|
||||
[[ "$expected" =~ ^[0-9]+$ ]] || fail "counts file has no value for $table"
|
||||
|
||||
actual="$(docker exec "$DRILL_CONTAINER" psql -U chesstrainer -d "$DRILL_DB" -Atc \
|
||||
"select count(*) from $table")"
|
||||
[[ "$actual" =~ ^[0-9]+$ ]] || fail "could not count $table"
|
||||
|
||||
if ((actual < expected)); then
|
||||
fail "restored $table=$actual is below the recorded $expected"
|
||||
fi
|
||||
|
||||
echo "backup-drill: $table restored=$actual recorded=$expected drift=$((actual - expected))" >&2
|
||||
restored_counts+="${restored_counts:+,}$table=$actual"
|
||||
done
|
||||
|
||||
record "$(log_event drill.completed ",\"archive\":\"$name\",\"result\":\"pass\",\"counts\":\"$restored_counts\",\"duration_s\":$((SECONDS - START_SECONDS))")"
|
||||
Executable
+248
@@ -0,0 +1,248 @@
|
||||
#!/usr/bin/env bash
|
||||
#
|
||||
# Pull the encrypted database archives from the VPS, verify them end to end,
|
||||
# and apply the 7 daily / 4 weekly / 6 monthly retention policy.
|
||||
#
|
||||
# Runs on the workstation, never on the server. Install as
|
||||
# ~/.local/bin/chesstrainer-backup-pull and enable
|
||||
# chesstrainer-backup-pull.timer as a user unit.
|
||||
#
|
||||
# Configuration: ~/.config/chesstrainer/backup-pull.env (0600). See
|
||||
# deploy/README.md §Backups.
|
||||
|
||||
set -euo pipefail
|
||||
umask 077
|
||||
|
||||
CONFIG="${PULL_ENV_FILE:-${XDG_CONFIG_HOME:-$HOME/.config}/chesstrainer/backup-pull.env}"
|
||||
if [[ -r "$CONFIG" ]]; then
|
||||
# shellcheck disable=SC1090
|
||||
source "$CONFIG"
|
||||
fi
|
||||
|
||||
VPS_HOST="${VPS_HOST:-}"
|
||||
REMOTE_DIR="${REMOTE_DIR:-/var/backups/chesstrainer/offsite}"
|
||||
DEST="${DEST:-$HOME/chesstrainer-backups}"
|
||||
AGE_KEY="${AGE_KEY:-${XDG_CONFIG_HOME:-$HOME/.config}/chesstrainer/age.key}"
|
||||
MAX_STALENESS_HOURS="${MAX_STALENESS_HOURS:-48}"
|
||||
KEEP_DAILY_DAYS="${KEEP_DAILY_DAYS:-7}"
|
||||
KEEP_WEEKLY_WEEKS="${KEEP_WEEKLY_WEEKS:-4}"
|
||||
KEEP_MONTHLY_MONTHS="${KEEP_MONTHLY_MONTHS:-6}"
|
||||
PULL_HEALTHCHECK_URL="${PULL_HEALTHCHECK_URL:-}"
|
||||
SSH_OPTIONS="${SSH_OPTIONS:--o BatchMode=yes -o ConnectTimeout=10 -o ServerAliveInterval=15}"
|
||||
RSYNC_ATTEMPTS="${RSYNC_ATTEMPTS:-3}"
|
||||
|
||||
START_SECONDS=$SECONDS
|
||||
FAILURE=""
|
||||
VERIFIED=0
|
||||
|
||||
log_event() {
|
||||
local event="$1"
|
||||
local extra="${2:-}"
|
||||
|
||||
printf '{"timestamp":"%s","event":"%s"%s}\n' \
|
||||
"$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$event" "$extra"
|
||||
}
|
||||
|
||||
heartbeat() {
|
||||
local outcome="$1"
|
||||
|
||||
[[ -n "$PULL_HEALTHCHECK_URL" ]] || return 0
|
||||
|
||||
local url="${PULL_HEALTHCHECK_URL%/}"
|
||||
[[ "$outcome" == "fail" ]] && url="$url/fail"
|
||||
|
||||
if ! curl --fail --silent --show-error \
|
||||
--max-time 10 --retry 2 --retry-delay 2 \
|
||||
--output /dev/null "$url"; then
|
||||
echo "backup-pull: heartbeat ping failed (run result is unaffected)" >&2
|
||||
fi
|
||||
}
|
||||
|
||||
fail() {
|
||||
FAILURE="$*"
|
||||
exit 1
|
||||
}
|
||||
|
||||
cleanup() {
|
||||
local status=$?
|
||||
|
||||
if [[ -d "$DEST" ]]; then
|
||||
find "$DEST" -maxdepth 1 -name '.verify.*' -type d -exec rm -rf {} + 2>/dev/null || true
|
||||
fi
|
||||
|
||||
if ((status != 0)); then
|
||||
log_event pull.failed ",\"reason\":\"${FAILURE:-exit $status}\""
|
||||
heartbeat fail
|
||||
fi
|
||||
|
||||
exit "$status"
|
||||
}
|
||||
|
||||
trap cleanup EXIT
|
||||
trap 'exit 143' TERM INT
|
||||
|
||||
[[ -n "$VPS_HOST" ]] || fail "VPS_HOST is not set"
|
||||
[[ -r "$AGE_KEY" ]] || fail "age identity not readable: $AGE_KEY"
|
||||
[[ "$MAX_STALENESS_HOURS" =~ ^[0-9]+$ ]] || fail "MAX_STALENESS_HOURS must be an integer"
|
||||
[[ "$KEEP_DAILY_DAYS" =~ ^[0-9]+$ ]] || fail "KEEP_DAILY_DAYS must be an integer"
|
||||
[[ "$KEEP_WEEKLY_WEEKS" =~ ^[0-9]+$ ]] || fail "KEEP_WEEKLY_WEEKS must be an integer"
|
||||
[[ "$KEEP_MONTHLY_MONTHS" =~ ^[0-9]+$ ]] || fail "KEEP_MONTHLY_MONTHS must be an integer"
|
||||
[[ "$RSYNC_ATTEMPTS" =~ ^[0-9]+$ ]] || fail "RSYNC_ATTEMPTS must be an integer"
|
||||
|
||||
for cmd in rsync ssh age tar sha256sum curl flock; do
|
||||
command -v "$cmd" >/dev/null 2>&1 || fail "missing command: $cmd"
|
||||
done
|
||||
|
||||
# Never create DEST on the root filesystem when the backup disk is unmounted.
|
||||
[[ -d "$(dirname "$DEST")" ]] ||
|
||||
fail "parent directory of $DEST does not exist (is the backup disk mounted?)"
|
||||
|
||||
install -d -m 0700 "$DEST"
|
||||
install -d -m 0700 "$DEST/.verified"
|
||||
|
||||
exec 9>"$DEST/.pull.lock"
|
||||
if ! flock -n 9; then
|
||||
# A manual run overlapping the timer is not an error; the other run reports.
|
||||
log_event pull.skipped ',"reason":"another pull is running"'
|
||||
exit 0
|
||||
fi
|
||||
|
||||
archive_epoch() {
|
||||
local name="$1"
|
||||
local ts="${name:0:16}"
|
||||
|
||||
[[ "$ts" =~ ^[0-9]{8}T[0-9]{6}Z$ ]] || return 1
|
||||
|
||||
date -u -d "${ts:0:4}-${ts:4:2}-${ts:6:2} ${ts:9:2}:${ts:11:2}:${ts:13:2}Z" +%s
|
||||
}
|
||||
|
||||
verify_archive() {
|
||||
local archive="$1"
|
||||
local name="${archive##*/}"
|
||||
local marker="$DEST/.verified/$name"
|
||||
local sum tmp
|
||||
|
||||
sum="$(sha256sum "$archive" | awk '{ print $1 }')"
|
||||
|
||||
if [[ -f "$marker" && "$(cat "$marker")" == "$sum" ]]; then
|
||||
return 0
|
||||
fi
|
||||
|
||||
tmp="$(mktemp -d "$DEST/.verify.XXXXXX")"
|
||||
|
||||
if ! age --decrypt --identity "$AGE_KEY" --output "$tmp/$name.tar" "$archive"; then
|
||||
rm -rf "$tmp"
|
||||
echo "backup-pull: $name failed to decrypt" >&2
|
||||
return 1
|
||||
fi
|
||||
|
||||
if ! tar -xf "$tmp/$name.tar" -C "$tmp"; then
|
||||
rm -rf "$tmp"
|
||||
echo "backup-pull: $name did not contain a readable tar archive" >&2
|
||||
return 1
|
||||
fi
|
||||
|
||||
if ! (cd "$tmp" && sha256sum --check --strict --quiet ./*.sha256); then
|
||||
rm -rf "$tmp"
|
||||
echo "backup-pull: $name failed its checksum verification" >&2
|
||||
return 1
|
||||
fi
|
||||
|
||||
rm -rf "$tmp"
|
||||
|
||||
printf '%s\n' "$sum" >"$marker.tmp"
|
||||
mv "$marker.tmp" "$marker"
|
||||
|
||||
VERIFIED=$((VERIFIED + 1))
|
||||
}
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Copy
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
attempt=1
|
||||
while true; do
|
||||
if rsync --archive --partial --compress --timeout=120 \
|
||||
--include='*.tar.age' --exclude='*' \
|
||||
--rsh "ssh $SSH_OPTIONS" \
|
||||
"$VPS_HOST:$REMOTE_DIR/" "$DEST/"; then
|
||||
break
|
||||
fi
|
||||
|
||||
if ((attempt >= RSYNC_ATTEMPTS)); then
|
||||
fail "rsync from $VPS_HOST failed after $attempt attempts"
|
||||
fi
|
||||
|
||||
echo "backup-pull: rsync attempt $attempt failed, retrying" >&2
|
||||
attempt=$((attempt + 1))
|
||||
sleep 20
|
||||
done
|
||||
|
||||
mapfile -t archives < <(
|
||||
find "$DEST" -maxdepth 1 -type f -name '*.tar.age' -printf '%f\n' | sort
|
||||
)
|
||||
|
||||
((${#archives[@]} > 0)) || fail "no archives in $DEST after the pull"
|
||||
|
||||
for name in "${archives[@]}"; do
|
||||
[[ "$name" =~ ^[0-9]{8}T[0-9]{6}Z(-[a-z0-9]+)?\.tar\.age$ ]] ||
|
||||
fail "unexpected file in $DEST: $name"
|
||||
done
|
||||
|
||||
newest="${archives[${#archives[@]} - 1]}"
|
||||
newest_epoch="$(archive_epoch "$newest")" || fail "cannot parse a timestamp from $newest"
|
||||
age_seconds=$(($(date -u +%s) - newest_epoch))
|
||||
|
||||
if ((age_seconds > MAX_STALENESS_HOURS * 3600)); then
|
||||
fail "newest archive $newest is $((age_seconds / 3600))h old (limit ${MAX_STALENESS_HOURS}h): VPS backups may have stopped"
|
||||
fi
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Verify every archive once; unchanged ciphertext is only re-hashed.
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
for name in "${archives[@]}"; do
|
||||
verify_archive "$DEST/$name" || fail "$name failed verification"
|
||||
done
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Retention: 7 daily, then one per ISO week for 4 weeks, then one per calendar
|
||||
# month for 6 months. Archives outside all three windows are deleted.
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
now="$(date -u +%s)"
|
||||
pruned=0
|
||||
declare -A kept_week=()
|
||||
declare -A kept_month=()
|
||||
|
||||
mapfile -t newest_first < <(
|
||||
find "$DEST" -maxdepth 1 -type f -name '*.tar.age' -printf '%f\n' | sort -r
|
||||
)
|
||||
|
||||
for name in "${newest_first[@]}"; do
|
||||
epoch="$(archive_epoch "$name")" || continue
|
||||
age_days=$(((now - epoch) / 86400))
|
||||
|
||||
if ((age_days < KEEP_DAILY_DAYS)); then
|
||||
continue
|
||||
fi
|
||||
|
||||
week="$(date -u -d "@$epoch" +%G-W%V)"
|
||||
if ((age_days < KEEP_WEEKLY_WEEKS * 7)) && [[ -z "${kept_week[$week]:-}" ]]; then
|
||||
kept_week[$week]=1
|
||||
continue
|
||||
fi
|
||||
|
||||
month="$(date -u -d "@$epoch" +%Y-%m)"
|
||||
if ((age_days < KEEP_MONTHLY_MONTHS * 31)) && [[ -z "${kept_month[$month]:-}" ]]; then
|
||||
kept_month[$month]=1
|
||||
continue
|
||||
fi
|
||||
|
||||
echo "backup-pull: pruning $name" >&2
|
||||
rm -f -- "$DEST/$name" "$DEST/.verified/$name"
|
||||
pruned=$((pruned + 1))
|
||||
done
|
||||
|
||||
log_event pull.completed ",\"newest\":\"$newest\",\"archives\":$(( ${#archives[@]} - pruned )),\"verified\":$VERIFIED,\"pruned\":$pruned,\"duration_s\":$((SECONDS - START_SECONDS))"
|
||||
heartbeat ok
|
||||
@@ -0,0 +1,37 @@
|
||||
# ~/.config/chesstrainer/backup-pull.env -- mode 0600.
|
||||
#
|
||||
# Sourced by ~/.local/bin/chesstrainer-backup-pull. Values below are the
|
||||
# defaults; VPS_HOST and AGE_KEY must be right. Quote anything containing
|
||||
# spaces.
|
||||
|
||||
VPS_HOST=owen@159.69.21.225
|
||||
REMOTE_DIR=/var/backups/chesstrainer/offsite
|
||||
DEST="/mnt/Mint Data/chesstrainer-backups"
|
||||
|
||||
# Private half of the age key. Back this file up somewhere safe: without it
|
||||
# every archive is unreadable.
|
||||
AGE_KEY="$HOME/.config/chesstrainer/age.key"
|
||||
|
||||
# Fail the pull when the newest archive from the VPS is older than this, which
|
||||
# means the VPS backup timer has stopped.
|
||||
MAX_STALENESS_HOURS=48
|
||||
|
||||
# Keep every archive from the last 7 days, then one per ISO week for 4 weeks,
|
||||
# then one per calendar month for 6 months.
|
||||
KEEP_DAILY_DAYS=7
|
||||
KEEP_WEEKLY_WEEKS=4
|
||||
KEEP_MONTHLY_MONTHS=6
|
||||
|
||||
# Restore drill. It runs in a throwaway container matching the production
|
||||
# Postgres major and appends results to DRILL_LOG.
|
||||
# DRILL_IMAGE=postgres:18.6
|
||||
# DRILL_DB=chesstrainer_restore
|
||||
# DRILL_LOG="$DEST/drills.log"
|
||||
EXPECTED_ROLES="chesstrainer chesstrainer_ro"
|
||||
|
||||
# Optional second heartbeat check with a long period (for example 72h), so you
|
||||
# hear about it when the workstation stops pulling. Leave empty to disable.
|
||||
# PULL_HEALTHCHECK_URL=https://hc-ping.com/00000000-0000-0000-0000-000000000000
|
||||
|
||||
# Extra ssh options, space separated.
|
||||
# SSH_OPTIONS="-o BatchMode=yes -o ConnectTimeout=10 -o ServerAliveInterval=15"
|
||||
@@ -0,0 +1,7 @@
|
||||
[Unit]
|
||||
Description=Report a failed Inner Square Chess backup unit
|
||||
Documentation=https://github.com/TheRealOwenRees/chess-endgame-trainer/blob/main/deploy/README.md
|
||||
|
||||
[Service]
|
||||
Type=oneshot
|
||||
ExecStart=/usr/bin/logger --tag chesstrainer-backup --priority user.err --stderr backup.unit-failed: %i failed, see journalctl --user -u %i
|
||||
@@ -0,0 +1,13 @@
|
||||
[Unit]
|
||||
Description=Monthly restore drill for Inner Square Chess backups
|
||||
Documentation=https://github.com/TheRealOwenRees/chess-endgame-trainer/blob/main/deploy/README.md
|
||||
OnFailure=chesstrainer-backup-alert@%N.service
|
||||
|
||||
[Service]
|
||||
Type=oneshot
|
||||
ExecStart=%h/.local/bin/chesstrainer-backup-drill
|
||||
WorkingDirectory=%h
|
||||
Environment=PATH=%h/.local/bin:/usr/local/bin:/usr/bin:/bin
|
||||
Nice=10
|
||||
TimeoutStartSec=20min
|
||||
SyslogIdentifier=chesstrainer-backup-drill
|
||||
@@ -0,0 +1,13 @@
|
||||
[Unit]
|
||||
Description=Monthly restore drill for Inner Square Chess backups
|
||||
Documentation=https://github.com/TheRealOwenRees/chess-endgame-trainer/blob/main/deploy/README.md
|
||||
|
||||
[Timer]
|
||||
OnCalendar=*-*-01 09:00:00
|
||||
RandomizedDelaySec=30m
|
||||
AccuracySec=5m
|
||||
Persistent=true
|
||||
Unit=chesstrainer-backup-drill.service
|
||||
|
||||
[Install]
|
||||
WantedBy=timers.target
|
||||
@@ -0,0 +1,15 @@
|
||||
[Unit]
|
||||
Description=Pull encrypted Inner Square Chess backups from the VPS
|
||||
Documentation=https://github.com/TheRealOwenRees/chess-endgame-trainer/blob/main/deploy/README.md
|
||||
After=network-online.target
|
||||
Wants=network-online.target
|
||||
OnFailure=chesstrainer-backup-alert@%N.service
|
||||
|
||||
[Service]
|
||||
Type=oneshot
|
||||
ExecStart=%h/.local/bin/chesstrainer-backup-pull
|
||||
WorkingDirectory=%h
|
||||
Environment=PATH=%h/.local/bin:/usr/local/bin:/usr/bin:/bin
|
||||
Nice=10
|
||||
TimeoutStartSec=15min
|
||||
SyslogIdentifier=chesstrainer-backup-pull
|
||||
@@ -0,0 +1,14 @@
|
||||
[Unit]
|
||||
Description=Daily pull of encrypted Inner Square Chess backups
|
||||
Documentation=https://github.com/TheRealOwenRees/chess-endgame-trainer/blob/main/deploy/README.md
|
||||
|
||||
[Timer]
|
||||
OnCalendar=*-*-* 12:00:00
|
||||
OnBootSec=10m
|
||||
RandomizedDelaySec=10m
|
||||
AccuracySec=1m
|
||||
Persistent=true
|
||||
Unit=chesstrainer-backup-pull.service
|
||||
|
||||
[Install]
|
||||
WantedBy=timers.target
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
services:
|
||||
db:
|
||||
container_name: chesstrainer_dev-db
|
||||
image: postgres:18.0
|
||||
image: postgres:18.6
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
- POSTGRES_USER=postgres
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
# Puzzle sessions are ephemeral and share one play surface
|
||||
|
||||
A session — one continuous spell of puzzle play, started by choosing a
|
||||
difficulty — carries a start time and a rating baseline for the timer and
|
||||
rating-gain monitor, and lives only in the running `Train` LiveView. Nothing is
|
||||
persisted: attempts are still recorded per endgame, but the session itself has
|
||||
no table.
|
||||
|
||||
The alternative was to keep `EndgameLive.Play` as the play surface and navigate
|
||||
from puzzle to puzzle (e.g. `/endgames/:code/play?session=...`), carrying the
|
||||
session in the URL or a short-lived server token. Navigation kills the LiveView
|
||||
socket, so the timer, per-puzzle times, baseline and completed count would all
|
||||
have to be carried or re-derived; that fights the "ephemeral" decision and
|
||||
leaks session state into URLs. Instead the session owns one socket and swaps the
|
||||
current endgame in place, which keeps every session value in one place.
|
||||
|
||||
To avoid a second copy of the move grading and best-line review, the play
|
||||
surface (board, grading, opponent reply, review, retry) is extracted into a
|
||||
shared module used by both `EndgameLive.Play` (standalone, optional auth, used
|
||||
by daily/curated deep links) and the new `EndgameLive.Train` (session, login
|
||||
only). Both keep their own `handle_event` entry points, which delegate to the
|
||||
shared logic, so the existing play tests and event contract are unchanged.
|
||||
|
||||
## Consequences
|
||||
|
||||
- `/endgames/:public_code/play` stays a standalone play surface; `/train` is the
|
||||
session front door.
|
||||
- Session state (difficulty, start time, baseline, completed count, per-puzzle
|
||||
timing) never leaves the `Train` socket and disappears when the page closes.
|
||||
- Difficulty is relative to the current user's rating, not an absolute property
|
||||
of an endgame; its band width is a config constant.
|
||||
@@ -0,0 +1,38 @@
|
||||
# Guest puzzles are capped per UTC day by a hashed address
|
||||
|
||||
`/guest-train` gives anonymous visitors 5 puzzles per UTC day. The budget is per
|
||||
client address, but the address is never stored: the limiter keys an in-memory
|
||||
ETS table by `HMAC-SHA256(boot_secret, "<gregorian_day>|<address>")`. The secret
|
||||
is generated when the node boots, so digests are not stable across restarts and
|
||||
cannot be correlated with anything else. The table is swept when the day rolls
|
||||
over, and no entry is ever written to the database, a log, or a backup.
|
||||
|
||||
## Why a daily UTC reset
|
||||
|
||||
A fixed 00:00 UTC boundary makes the rule easy to state ("5 free puzzles a
|
||||
day"), gives every visitor the same reset instant, and removes the need for
|
||||
per-entry timestamps: the UTC date is part of the key, so yesterday's entries
|
||||
simply stop matching. That also means the stored data's lifetime is bounded by
|
||||
the calendar day.
|
||||
|
||||
## Why not an IP address
|
||||
|
||||
The raw address is never persisted; only the digest is, and only until the day
|
||||
rolls over or the node restarts. This is abuse prevention with data
|
||||
minimisation, not tracking, and needs no cookie or client-side storage. The
|
||||
processing is disclosed in the privacy policy (see #87).
|
||||
|
||||
## Consequences
|
||||
|
||||
- Visitors behind one NAT share a budget. Masking to a subnet would make that
|
||||
worse, so the full address is hashed.
|
||||
- The budget lives in one node's memory: a restart resets it, and a second node
|
||||
would keep its own. Move the counter to Postgres or Redis if that matters.
|
||||
- The unit being metered is a puzzle load, not a move. A LiveView reconnect
|
||||
re-runs the connected mount and therefore consumes one puzzle.
|
||||
- Retry and review never consume a puzzle because they reuse the loaded
|
||||
position.
|
||||
- Signed-in visitors are redirected to `/train` and are never metered.
|
||||
- Behind a proxy, set `TRUST_FORWARDED_FOR=1` and make sure the proxy overwrites
|
||||
or appends `X-Forwarded-For`; otherwise every visitor shares the proxy's
|
||||
budget. `GUEST_PUZZLE_LIMIT` changes the daily allowance.
|
||||
@@ -0,0 +1,55 @@
|
||||
# Eight-or-more-piece endgames are trained from engine-sourced corridors that hand off to the tablebase at seven
|
||||
|
||||
_Status: accepted. Extends ADR-0005: the ≤7-piece source split stands; this adds a source for 8+._
|
||||
|
||||
Syzygy stops at seven pieces and there is no tablebase for eight or more. To
|
||||
train such endgames without pretending to a completeness they lack, each 8+
|
||||
endgame is backed by a **corridor**: one or two winning lines, generated offline
|
||||
with a chess engine (Stockfish), that stay clearly winning at every step. The
|
||||
corridor is stored as solved positions keyed by position key and served by a new
|
||||
tablebase backend, so the play loop and grading are unchanged.
|
||||
|
||||
The corridor ends at the first capture that brings the board to seven pieces or
|
||||
fewer. From that position the existing router answers from Syzygy (≤5, local) or
|
||||
Lichess (6–7), so the tail of every puzzle is tablebase-optimal. Generation
|
||||
verifies the handoff: it probes the ≤7 position and asserts it is still a win for
|
||||
the winning side. A promotion does not end the corridor, because it does not
|
||||
reduce the piece count; only a capture does.
|
||||
|
||||
A second line is stored only when both lines are clearly winning — the engine's
|
||||
evaluation stays above the winning threshold throughout. A line that dips is
|
||||
discarded rather than shipped as a dubious alternative.
|
||||
|
||||
## Grading
|
||||
|
||||
Inside the corridor grading is binary: a move on a stored line passes, a move
|
||||
off the lines fails. The stored move list is deliberately incomplete, so it
|
||||
cannot support the "any winning move passes" rule the tablebase enables; the
|
||||
user must find the technique the corridor encodes. Once the position reaches
|
||||
seven pieces, grading returns to the existing optimal/winning/losing model.
|
||||
|
||||
## Why not the alternatives
|
||||
|
||||
- **Engine at runtime.** Removes the offline step but adds per-move latency, a
|
||||
rate limit if it is a remote service, and non-determinism in what counts as
|
||||
"winning". The corridor is deterministic and free at play time.
|
||||
- **Hand-authored book.** The same shape without an engine to generate it:
|
||||
fragile, narrow, and prone to grading a move as losing only because nobody
|
||||
wrote it down.
|
||||
- **Solving the whole 8+ region.** Infeasible. The corridor trades completeness
|
||||
for a short, verified path to a position the tablebase can finish.
|
||||
|
||||
## Consequences
|
||||
|
||||
- Endgames gain an `oracle` (`:tablebase` or `:corridor`). The changeset admits
|
||||
8+ FENs only for corridor endgames.
|
||||
- A corridor-position store (keyed by position key) and a tree backend join the
|
||||
existing Fathom/Lichess backends. Eight-plus positions without a corridor are
|
||||
still rejected.
|
||||
- Generation depends on a Stockfish binary at build/curation time, not at
|
||||
runtime.
|
||||
- The corridor is engine-best, not proven-optimal. Honest wording ("engine-best
|
||||
defence") is required in player-facing copy, and GLOSSARY's *optimal move* and
|
||||
*winning move* need a corridor-aware distinction.
|
||||
- An off-corridor legal move fails the attempt; this is a deliberate departure
|
||||
from tablebase grading and must be reflected in the play surface.
|
||||
@@ -0,0 +1,65 @@
|
||||
# Launch observability is the probe, honest error states, and the runbook
|
||||
|
||||
_Status: accepted._
|
||||
|
||||
At launch, observability means three things and no more: an external check that
|
||||
the public app answers, error states that are honest and recoverable, and a
|
||||
written runbook for when either fails. Everything else is deferred with a named
|
||||
trigger, so the gaps are explicit rather than ambient.
|
||||
|
||||
## The launch bar
|
||||
|
||||
- **Probe.** A healthchecks.io check with a two-minute period and grace, fed by
|
||||
an on-box prober with off-box alerting (#160, #161). It curls the public
|
||||
`/health` through Cloudflare, so DNS, TLS, Caddy, the origin allowlist,
|
||||
Phoenix and one Postgres query are covered. The loopback cross-check in a
|
||||
failure body is evidence only. The prober shares a host with the app, so host
|
||||
death is caught by silence, not by a ping.
|
||||
- **Error states.** The audit (#162) and its fixes (#163), verified by #164.
|
||||
Every failure mode has copy and a retry or a way home; exception details and
|
||||
raw error terms do not reach the page.
|
||||
- **Runbook.** `deploy/README.md` §Monitoring and alerting: the check, install,
|
||||
what `/health` proves and does not, Beszel's blind spot, the drills, and the
|
||||
dated drill log.
|
||||
|
||||
## Deferred, with triggers
|
||||
|
||||
- **Error tracking (#109, GlitchTip/Sentry).** Deferred because JSON logs
|
||||
already carry the crash reason and stacktrace per request, and there is no
|
||||
traffic to aggregate over. Revisit when the first production 500 cannot be
|
||||
diagnosed from its journal line (missing or truncated stacktrace), or a user
|
||||
reports an error without a request id, or unexplained errors exceed roughly
|
||||
50 a day and per-line grep stops being practical.
|
||||
- **Metrics and LiveDashboard (#111).** Deferred because Beszel covers host
|
||||
resources and the probe covers the HTTP contract. Revisit when a capacity
|
||||
question needs a number neither can answer (database pool saturation, p95
|
||||
latency, queue depth), or daily active users pass 100, or a performance
|
||||
incident takes more than an hour to localise.
|
||||
- **Off-box log shipping and error-rate alerts (#140).** Deferred because
|
||||
journald is persistent on the host and the probe alerts on downness. Revisit
|
||||
when an alert must fire on a log pattern (error rate, authentication
|
||||
failures), or the journal retention budget cannot cover a 30-day
|
||||
investigation, or the host is rebuilt and local logs would be lost in the same
|
||||
incident.
|
||||
|
||||
## Why journald and backups are enough at launch
|
||||
|
||||
Persistent journald (`Storage=persistent`, `SystemMaxUse`) holds one JSON object
|
||||
per line: crashes carry a reason and stacktrace, access lines carry status and
|
||||
duration, and token-shaped paths, emails and credentials are redacted. Off-box
|
||||
encrypted backups cover the data.
|
||||
|
||||
The accepted risk: losing the host loses the logs with it, and there is no
|
||||
aggregate error rate. At launch that is acceptable — one host, one operator,
|
||||
low traffic, and an incident is diagnosed from the journal on the box or from
|
||||
the probe's alert body. The triggers above are the point at which that risk
|
||||
stops being acceptable.
|
||||
|
||||
## Consequences
|
||||
|
||||
- Investigation starts with `journalctl -u chesstrainer -o cat | jq`, not a
|
||||
dashboard.
|
||||
- Error tracking, metrics and log shipping stay explicit backlog items with
|
||||
triggers rather than ambient gaps.
|
||||
- The probe is an on-box prober with off-box alerting; it is not external
|
||||
uptime monitoring and the runbook says so.
|
||||
@@ -0,0 +1,93 @@
|
||||
# Analytics
|
||||
|
||||
We use a self-hosted Matomo instance for privacy-conscious analytics on public
|
||||
pages and the guest trainer.
|
||||
|
||||
## What is collected
|
||||
|
||||
- Page views on anonymous public pages and the guest trainer.
|
||||
- Standard request data Matomo needs to count a visit, with IP anonymisation.
|
||||
|
||||
We do **not**:
|
||||
|
||||
- set Matomo cookies,
|
||||
- use user IDs,
|
||||
- track signed-in account, profile, or admin pages,
|
||||
- enable cross-site or advertising features,
|
||||
- share analytics data with third parties.
|
||||
|
||||
## Configuration
|
||||
|
||||
The app reads these environment variables at boot:
|
||||
|
||||
```sh
|
||||
MATOMO_URL=https://analytics.owenrees.eu/
|
||||
MATOMO_SITE_ID=6
|
||||
```
|
||||
|
||||
They are configured in `config/runtime.exs` for production only. If either is
|
||||
missing, no analytics config is rendered and no tracker is loaded.
|
||||
|
||||
The root layout renders a hidden `#matomo-config` element only when the visitor
|
||||
is anonymous. `assets/js/analytics.js` initialises Matomo cookieless from that
|
||||
element. Signed-in users never receive the element.
|
||||
|
||||
## Matomo settings
|
||||
|
||||
In the Matomo administration UI:
|
||||
|
||||
1. **Administration → Websites → Manage**
|
||||
- URL: `https://innersquare.app`
|
||||
- Site ID: `6`
|
||||
- Timezone: match the site
|
||||
2. **Administration → Privacy → Anonymize data**
|
||||
- Enable IP anonymisation (at least the last byte; 2 bytes is safer)
|
||||
- Disable tracking cookies
|
||||
- Respect Do Not Track
|
||||
- Do not use user IDs
|
||||
- Set raw data retention to **180 days**
|
||||
3. **Administration → System check / trusted hosts**
|
||||
- Add `innersquare.app` and `www.innersquare.app` if host validation is on.
|
||||
4. Do not enable ecommerce, advertising, or cross-domain tracking.
|
||||
|
||||
The JavaScript also calls:
|
||||
|
||||
```js
|
||||
_paq.push(["disableCookies"]);
|
||||
_paq.push(["setDoNotTrack", true]);
|
||||
```
|
||||
|
||||
## Opt-out
|
||||
|
||||
The privacy page has an **Analytics** section with an opt-out control. The
|
||||
preference is stored in `localStorage["matomo_optout"]`, not a cookie. When set,
|
||||
the tracker is never loaded and LiveView page views are skipped.
|
||||
|
||||
The preference is local to the browser. Clearing site data resets it. Users can
|
||||
also object by emailing `support@innersquare.app`.
|
||||
|
||||
## Verification
|
||||
|
||||
On an anonymous public page:
|
||||
|
||||
```sh
|
||||
curl -s https://innersquare.app/ | grep -c matomo-config
|
||||
```
|
||||
|
||||
should return `1`.
|
||||
|
||||
In the browser:
|
||||
|
||||
- `matomo.js` and `matomo.php` load once.
|
||||
- Matomo Real-time shows the page view.
|
||||
- No `_pk_*` cookies are created.
|
||||
- Opting out sets `matomo_optout=1` in localStorage and stops further requests.
|
||||
- Signed-in pages produce no Matomo config or requests.
|
||||
- A DNT browser setting suppresses tracking.
|
||||
|
||||
## Legal basis
|
||||
|
||||
Analytics runs on the basis of legitimate interests in improving the service.
|
||||
The privacy policy discloses it, explains the data, and provides the opt-out.
|
||||
This document is an engineering configuration guide, not legal advice; keep a
|
||||
short legitimate-interest assessment on 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.
|
||||
@@ -0,0 +1,61 @@
|
||||
# Error-state verification
|
||||
|
||||
The #162 checklist, walked on 2026-11-13 against a local production-like build.
|
||||
Failures were filed as #171 and fixed in the follow-up for that issue; this page
|
||||
records the verification run, not the current state. It is linked from the
|
||||
audit.
|
||||
|
||||
## Method
|
||||
|
||||
- **Build:** `MIX_ENV=prod` `mix phx.server` on `127.0.0.1:4010`, commit
|
||||
`021e412` plus this branch's documentation.
|
||||
- **Database:** a scratch `postgres:18.6` on port 55432. Empty at first, then
|
||||
one confirmed user and one 8+ piece endgame (inserted directly, because the
|
||||
admin changeset rejects positions beyond seven pieces).
|
||||
- **Configuration:** `PRELAUNCH=false`, `MAILING_LIST_ENABLED=true`,
|
||||
`TABLEBASE_PATH` pointing at a missing directory, dummy SES credentials.
|
||||
- **Forced failures:** Postgres stopped, missing tablebase directory, empty
|
||||
puzzle pool, expired reset and confirmation tokens (backdated
|
||||
`users_tokens.inserted_at`), stale and invalid mailing-list forms, guest
|
||||
budget exhausted, unknown public play code.
|
||||
- **Observation:** `curl` for controller-rendered pages, headless Chrome over
|
||||
the DevTools Protocol for LiveView-connected pages, and `mix test` for the
|
||||
interactive states that need a click. Each row names its evidence.
|
||||
- **Not forced:** a real Lichess 429 (the cooldown and classifier paths were
|
||||
exercised by the tests), a crash after connect, and the two admin-only import
|
||||
leaks (code inspection and tests). The first run rejected the socket origin
|
||||
because `PHX_HOST` defaulted to `example.com`; setting `PHX_HOST=127.0.0.1`
|
||||
fixed it. That was local configuration, not a product finding.
|
||||
|
||||
## Results
|
||||
|
||||
| Checklist row | Result | Evidence |
|
||||
|---|---|---|
|
||||
| T1 cooldown | **pass** | LiveView test: mount with a cooldown shows "Tablebase cooling down"; Retry re-fetches and returns to play. |
|
||||
| T2 429 | **pass** | LiveView test: classifier maps 429 to "Tablebase rate-limited"; HTML carries no `429`, `too_many_requests` or upstream body. |
|
||||
| T3 not covered | **pass** | Prod run: guest page with a 12-piece endgame shows "Position not covered… can't be graded", no `not_covered` in the DOM, Next puzzle or back available. |
|
||||
| T4 generic | **pass** | LiveView test: classifier returns "Tablebase unavailable"; the reason is logged and never rendered. |
|
||||
| T5/T6 load and reply failure | **pass** | T5 covered by the cooldown-at-mount test and Retry. T6 shares the blocked panel and `reset/1` path; not separately forced. |
|
||||
| T8 invalid FEN | **fail** | Existing test: the flash still contains the client message and the raw FEN. #171. |
|
||||
| S1/S2/S3/S5 empty pools | **pass** | S1 prod: Medium picker shows the in-page empty state and Retry. S5 prod: guest shows "No endgames are available yet" and Retry. S2/S3 tests: exhausted state, Retry and Change difficulty. |
|
||||
| S4 guest limit | **pass** | Prod run: five visits exhaust the budget; the wall shows the reset time, Sign up free and Log in. |
|
||||
| A1 reset token | **pass** | Prod run: an expired token flashes "Reset password link is invalid or it has expired." on the log-in page, with Forgot your password available. |
|
||||
| A2 confirmation token | **fail** | Prod run: an expired token flashes "User not found or token is invalid." and lands on registration, not log in. #171. |
|
||||
| A3/A4 login | **pass** | Tests: invalid credentials use one message; the throttle reports the remaining minutes. |
|
||||
| M1–M5 mailing list | **pass** | Prod run: invalid confirmation link, removed address, stale form, invalid email and an SES send failure each show their specific copy with the form reachable. |
|
||||
| W1/W2 404 and 500 | **pass** | Prod run: styled 404 for an unknown path; with Postgres stopped, `/` returns the styled 500 with no exception or stacktrace. |
|
||||
| W3 crash | **fail** | The server-error banner has no reload action; a repeating crash has no manual escape. Not separately forced; same banner as W4. #171. |
|
||||
| W4 disconnect | **pass** | Observed "Something went wrong! Attempting to reconnect" while the socket was rejected, with automatic retries; the banner hides on reconnect. |
|
||||
| W5 database down | **pass** | Prod run: `/health` returns 503 `db:down`; `/` returns the 500 page. Note the loop: the home link also needs the database, so it 500s too. |
|
||||
| D1/D2 export | **fail** | Prod run: an export with the database stopped returns the 500 page (no export-specific copy); `/users/profile/export/xml` returns plain text "Unknown export format". #171. |
|
||||
| H1 empty-database home | **fail** | Prod run: the fallback board renders, but "Try today's puzzle" points at the auth-gated `/endgames`. #171. |
|
||||
| X1 unknown play code | **pass** | Prod run: `/endgames/nope/play` returns the styled 404 page. This corrects the audit's earlier claim that it 500ed. |
|
||||
| X2/X3 admin leaks | **fail** | Code inspection and tests: both importer messages still interpolate `inspect(reason)`. Not forced. #171. |
|
||||
|
||||
## Tally
|
||||
|
||||
- 14 checklist rows pass, 6 fail (8 individual regressions, because D1/D2 and
|
||||
X2/X3 share a row).
|
||||
- Every failure row is a state that was already listed as "improve" in the
|
||||
audit and was outside #163; no new regression came from the #163 changes.
|
||||
- The regressions are filed together in #171 rather than fixed silently.
|
||||
@@ -0,0 +1,152 @@
|
||||
# User-facing error states
|
||||
|
||||
What a player sees when something fails, with a verdict for every state and the
|
||||
concrete change each one needs. This is the audit required by #162; #163
|
||||
implements the tablebase and empty-pool items, and #164 walks the sign-off
|
||||
checklist on a production-like build.
|
||||
|
||||
Verdicts:
|
||||
|
||||
- **keep** — the state is honest, recoverable and leak-free as it stands
|
||||
- **improve** — a state exists but needs different copy, a recovery action, or
|
||||
both
|
||||
- **add** — there is no user-facing state today
|
||||
|
||||
"Internal detail" means an exception term, an `inspect/1` result, a raw HTTP
|
||||
status body, a stacktrace, or a raw FEN appearing in rendered HTML.
|
||||
|
||||
**Status:** #163 implements T1–T6, S1–S3 and S5. The rows below describe the
|
||||
state before that change. #164 walked this checklist on a local prod build:
|
||||
see [error-states-verification.md](error-states-verification.md).
|
||||
|
||||
## Play and tablebase
|
||||
|
||||
| ID | State | Trigger | What the user sees today | Verdict | Action |
|
||||
|---|---|---|---|---|---|
|
||||
| T1 | Cooldown | A previous 429 put Lichess in cooldown; `Tablebase.new/1` returns `{:cooldown, ms}` (`play_core.ex:386`) | Panel headed **Tablebase unavailable**, body "The tablebase is rate-limited. Try again in about Ns."; move hint "The tablebase is unavailable, so moves cannot be entered."; **Reset** | improve | Heading per failure class ("Tablebase cooling down"), keep the countdown, and relabel Reset to **Retry** while blocked. Fold into #163. |
|
||||
| T2 | Lichess 429 | Lichess returns 429; the parser records a cooldown (`tablebase/parser.ex:69`) | Same panel; "The tablebase is rate-limited. Try again in a minute." | improve | Same class as T1, with the real countdown once known. Never show `429` or the response body. Fold into #163. |
|
||||
| T3 | Position not covered | More than seven pieces, Lichess 404, or `:not_covered` (`play_core.ex:394-401`) | Panel headed **Tablebase unavailable**, body "This position is not covered by the tablebase."; **Reset** | improve | Say the puzzle cannot be graded, and offer **Try another puzzle** (session) or **Browse endgames** (single). Retry is futile here, so do not present it as the primary action. Fold into #163. |
|
||||
| T4 | Generic tablebase failure | 5xx, transport error, malformed response (`play_core.ex:403`) | **"The tablebase is unavailable (#{inspect(reason)})."** | improve | Replace with "The tablebase is unavailable right now. Try again in a moment." and log the reason. This is the leak #163 calls out. Also applies to the review panel's `review_blocked` copy. |
|
||||
| T5 | Load failure at session start | `Tablebase.new/1` fails in `PlayCore.init/2` → `load_attempt/1` | Board non-interactive; blocked panel and reason; **Reset** | improve | Class-correct copy plus **Retry**; `reset/1` already re-fetches, so this is a label and copy change. Fold into #163. |
|
||||
| T6 | Fetch failure for the opponent's reply | `start_opponent_reply/2` cannot fetch the new position (`play_core.ex:457`) | Play stops; blocked panel; the move already played is still on the board; **Reset** | improve | Explain that the puzzle is paused and **Retry** resumes from the current position. Fold into #163. |
|
||||
| T7 | Move while blocked | A move event arrives while `status == :blocked` (`play_core.ex:76`) | Flash "The tablebase is unavailable, so this move cannot be graded." | keep | Defensive guard; the board should already be non-interactive. #164 asserts that. |
|
||||
| T8 | Invalid FEN from the board hook | `chess_fen_invalid` (`play_core.ex:184`) | Flash **"Endgame FEN is invalid and the board cannot be loaded: #{message} (#{fen})"** | improve | Generic copy ("The board couldn't load this position. Reset to try again."), log the details, and keep **Reset** visible. Leak: client message and raw FEN. |
|
||||
|
||||
## Sessions and puzzle pools
|
||||
|
||||
| ID | State | Trigger | What the user sees today | Verdict | Action |
|
||||
|---|---|---|---|---|---|
|
||||
| S1 | No puzzles available | `Puzzles.next_endgame/3` returns `nil` on start (`train.ex:201`) | Flash error "No puzzles are available right now."; the difficulty picker stays behind it | improve | Replace the flash with an in-page state inside the picker: what happened, **Retry**, and a way to pick another difficulty. Fold into #163. |
|
||||
| S2 | No more puzzles at this difficulty | `next_endgame` returns `nil` with `exclude_ids` (`train.ex:232`) | Flash info "No more puzzles at this difficulty."; the finished puzzle and **Next puzzle** remain | improve | In-page end-of-run panel: "You've finished every puzzle at this difficulty" with **Retry**, **Change difficulty** (stop session) and the existing Stop session. Hide or disable Next. Fold into #163. |
|
||||
| S3 | Guest: no more puzzles | Guest `next_puzzle` finds nothing (`guest_train.ex:137`) | Flash info "No more puzzles are available right now." | improve | In-page state with **Retry** and the sign-up/log-in actions, matching the guest-limit panel's tone. Fold into #163. |
|
||||
| S4 | Guest limit reached | `GuestLimits.take/1` returns `{:limit_reached, ms}` (`guest_train.ex:45-70`) | In-page panel: used N free puzzles, reset time, **Sign up free**, **Log in** | keep | This is the reference state for tone and recovery. |
|
||||
| S5 | Guest pool empty on load | Random endgame is `nil` (`guest_train.ex:98`) | In-page "No endgames are available yet. Please check back soon." | improve | Add a **Retry** action so the state is not a dead end. Fold into #163. |
|
||||
|
||||
## Accounts and email
|
||||
|
||||
| ID | State | Trigger | What the user sees today | Verdict | Action |
|
||||
|---|---|---|---|---|---|
|
||||
| A1 | Reset token invalid or expired | `get_user_by_reset_password_token/1` returns `nil` (`reset_password.ex:66`) | Flash "Reset password link is invalid or it has expired." then the log-in page, where **Forgot your password?** is available | keep | Honest and recoverable in two clicks. |
|
||||
| A2 | Confirmation token invalid or expired | `Accounts.confirm_user/1` returns `:error` (`user_confirmation_controller.ex:17`) | Flash **"User not found or token is invalid."** then the registration page | improve | Say "That confirmation link is invalid or has expired." and send the user to log in, where an unconfirmed account triggers a fresh confirmation email. No "user not found" phrasing. |
|
||||
| A3 | Invalid credentials | `get_user_by_login_and_password/2` returns `nil` | Flash "Invalid email, username or password"; email is prefilled | keep | Deliberately identical for unknown and wrong-password logins, so it does not enumerate accounts. |
|
||||
| A4 | Login throttle | 5 failures per login or 10 per address in 15 minutes (`LoginThrottle`) | Flash "Too many attempts. Try again in N minutes." | keep | Accurate countdown, no account information. |
|
||||
|
||||
## Mailing list
|
||||
|
||||
| ID | State | Trigger | What the user sees today | Verdict | Action |
|
||||
|---|---|---|---|---|---|
|
||||
| M1 | Confirmation link invalid or expired | Token fails verification (`mailing_list_controller.ex:36`) | Flash "That confirmation link is invalid or has expired." → `/#mailing-list` | keep | The signup form is on the destination page. |
|
||||
| M2 | Confirmed address no longer subscribed | `MailingList.confirm/1` returns `:not_found` (`:52`) | Flash "That address is no longer on the mailing list. Please sign up again." → `/#mailing-list` | keep | Actionable and specific. |
|
||||
| M3 | Stale signup form | `MailingListFormToken.verify/1` fails (`:126`) | Flash "Please refresh the page and try again." → `/#mailing-list` | keep | The form is on the page; refresh is the fix. |
|
||||
| M4 | Invalid email | Missing or invalid address (`:132`) | Flash "Enter a valid email address." | keep | Specific and actionable. |
|
||||
| M5 | Confirmation email send failure | `Notifier.deliver_confirmation_instructions/2` returns an error (`:111`) | Flash "We couldn't send the confirmation email. Please try again." | improve | Keep the copy, add "If it keeps happening, email …" from `Branding.support_email/0`, and log the reason — the controller currently discards it. |
|
||||
| M6 | List closed / honeypot / already subscribed | Feature flag, honeypot, or existing address | "The mailing list isn't open yet." / success copy / "You're already on the mailing list." | keep | Closed and honeypot are deliberate; the existing-address message is honest. |
|
||||
|
||||
## Site-level
|
||||
|
||||
| ID | State | Trigger | What the user sees today | Verdict | Action |
|
||||
|---|---|---|---|---|---|
|
||||
| W1 | 404 | Unknown route (`ErrorHTML`, catch-all route) | Styled page: "This page isn't on the board", **Back to home**, plus **Browse puzzles** for premium users | keep | Uses the shared `error_page/1`. |
|
||||
| W2 | 500 | Controller or render crash | Styled page: "Something went wrong", **Back to home**, **Browse puzzles**, support email | keep | Honest, no exception detail. |
|
||||
| W3 | LiveView crash | Raise in `mount` or `handle_event` | Mount crash → the 500 page. A crash after connect → the **"Something went wrong!"** banner, automatic reconnect, no manual action | improve | Add a **Reload** action (and keep home) to the server-error banner so a crash that repeats on reconnect has an escape. The banner lives in `layouts.ex:274`. |
|
||||
| W4 | Disconnect | Socket or network loss | **"We can't find the internet"** banner with a spinner; hides on reconnect | keep | Automatic recovery, no action needed. |
|
||||
| W5 | Database unavailable | Postgres stopped or pool exhausted | DB-backed pages and LiveView mounts raise → the 500 page; `/health` returns 503 | keep | The 500 page is the right state, but note the loop: the home page also needs the database, so "Back to home" fails too. The probe is the operational signal. No app change proposed here. |
|
||||
|
||||
## Data and landing
|
||||
|
||||
| ID | State | Trigger | What the user sees today | Verdict | Action |
|
||||
|---|---|---|---|---|---|
|
||||
| D1 | Export failure | `Attempts.list_attempts_for_user/1` raises in `UserDataController.export/2` | The 500 page, with no export-specific explanation | improve | Rescue, log, and redirect to `/users/profile/data` with "We couldn't build your export. Try again; if it keeps failing, email …". |
|
||||
| D2 | Unknown export format | `/users/profile/export/<anything else>` | Plain text `404 "Unknown export format"` with no chrome, links, or home | improve | Return the styled 404 page instead. |
|
||||
| D3 | Export of an empty account | No attempts | CSV with the header and an empty row; JSON with an empty list | keep | Deliberate and documented by the shape. |
|
||||
| H1 | Home page with an empty database | No endgames (`PageController.home/2`) | Fallback KRK board, "Featured position", "0 players training", and a **Try today's puzzle** button pointing at `/endgames` | improve | When `active_endgame` is `nil`, do not send the visitor to an auth-gated page with no puzzles: point the call to action at `/guest-train` (which has its own empty state) or disable it with "New puzzles are coming". |
|
||||
|
||||
## Admin surfaces (extra)
|
||||
|
||||
| ID | State | Trigger | What the user sees today | Verdict | Action |
|
||||
|---|---|---|---|---|---|
|
||||
| X1 | Unknown public play code | `/endgames/:code/play` with a code that does not exist (`play.ex:79`) | The styled 404 page: `Ecto.NoResultsError` maps to 404 through `Plug.Exception` | keep | Verified by #164; no change. |
|
||||
| X2 | Bulk import lookup crash | `handle_async` exits (`import.ex:271`) | Flash **"Could not look up the FENs: #{inspect(reason)}"** | improve | Generic copy plus a logged reason. Admin-only, but still an internal leak. |
|
||||
| X3 | Bulk import tablebase load failure | `Local.check/0` returns an unexpected error (`import.ex:287`) | **"Local tablebase failed to load: #{inspect(reason)}"** | improve | Generic copy plus a logged reason. Admin-only, but still an internal leak. |
|
||||
|
||||
## Internal-detail leaks
|
||||
|
||||
These are the only places where an exception term, a raw HTTP status or a raw
|
||||
FEN can reach rendered HTML. T4 is the one #162 calls out; the rest are smaller
|
||||
but real.
|
||||
|
||||
| Where | Leak | Fix |
|
||||
|---|---|---|
|
||||
| `play_core.ex:404` | `inspect(reason)` in the blocked panel | T4 |
|
||||
| `play_core.ex:189` | client message and raw FEN in a flash | T8 |
|
||||
| `import.ex:271` | `inspect(reason)` in a flash | X2 |
|
||||
| `import.ex:287` | `inspect(reason)` in the tablebase status | X3 |
|
||||
| `user_data_controller.ex:21` | plain-text "Unknown export format" | D2 |
|
||||
|
||||
Server logs already carry the real reasons, so none of these fixes lose
|
||||
diagnostic information.
|
||||
|
||||
## Sign-off checklist
|
||||
|
||||
For #164 to walk against a production-like build. Every row passes only if the
|
||||
state offers **retry or a way home** and rendered HTML contains no exception,
|
||||
stacktrace, raw error term, or raw FEN.
|
||||
|
||||
- [ ] **T1 cooldown** — force a cooldown: class-correct heading, countdown, Retry re-fetches.
|
||||
- [ ] **T2 429** — make Lichess return 429: rate-limit copy, no `429` or response body.
|
||||
- [ ] **T3 not covered** — play a position with more than seven pieces: explanation, another puzzle or home, no futile Retry.
|
||||
- [ ] **T4 generic** — make Lichess fail (network off or 5xx): generic copy, Retry works when it recovers, no `inspect`.
|
||||
- [ ] **T5/T6 load and reply failure** — start a puzzle and lose the tablebase mid-game: paused explanation, Retry resumes.
|
||||
- [ ] **T8 invalid FEN** — force `chess_fen_invalid`: no client message or raw FEN, Reset visible.
|
||||
- [ ] **S1/S2/S3/S5 empty pools** — empty the pool: in-page states on train and guest, Retry and change-difficulty reachable.
|
||||
- [ ] **S4 guest limit** — exhaust the guest allowance: panel, reset time, sign-up and log-in reachable.
|
||||
- [ ] **A1 reset token** — use an expired link: message, log-in page, forgot-password reachable.
|
||||
- [ ] **A2 confirmation token** — use an expired link: message, log-in page, fresh confirmation email on next login.
|
||||
- [ ] **A3/A4 login** — wrong password and throttled login: no account enumeration, countdown.
|
||||
- [ ] **M1-M5 mailing list** — expired confirmation, stale form, invalid address, send failure: specific copy and the form reachable.
|
||||
- [ ] **W1/W2 404 and 500** — unknown path and forced crash: styled page, home and browse reachable, no exception.
|
||||
- [ ] **W3 crash** — raise in a `handle_event`: reload action reachable.
|
||||
- [ ] **W4 disconnect** — drop the socket: reconnect banner and automatic recovery.
|
||||
- [ ] **W5 database down** — stop Postgres: 500 pages, `/health` 503, no stacktrace; note that home is also down.
|
||||
- [ ] **D1/D2 export** — force an export error and an unknown format: flash or 404 page, home reachable.
|
||||
- [ ] **H1 empty database** — empty the pool: home renders, call to action is not an auth-gated dead end.
|
||||
- [ ] **X1 unknown play code** — open a stale link: 404 page, not a 500.
|
||||
- [ ] **X2/X3 admin leaks** — force an import crash and a tablebase error: no `inspect` output.
|
||||
|
||||
## Fix list
|
||||
|
||||
Fold into **#163** (tablebase and empty-pool recoverability): T1, T2, T3, T4,
|
||||
T5, T6, S1, S2, S3, S5.
|
||||
|
||||
Separate changes, each independently testable:
|
||||
|
||||
- **T8** — generic invalid-FEN flash; log the details.
|
||||
- **A2** — confirmation-token copy and destination.
|
||||
- **M5** — support fallback on send failure; log the reason.
|
||||
- **W3** — reload action in the server-error banner.
|
||||
- **D1** — rescue export errors into a flash on the data tab.
|
||||
- **D2** — styled 404 for unknown export formats.
|
||||
- **H1** — empty-database call to action.
|
||||
- **X2/X3** — generic admin import copy; log the details.
|
||||
|
||||
No code changes are part of this audit.
|
||||
+223
@@ -0,0 +1,223 @@
|
||||
# Logging
|
||||
|
||||
Production writes one JSON object per line to standard output, which systemd
|
||||
captures in journald. Development and test keep the readable
|
||||
`[level] message` formatter.
|
||||
|
||||
## Configuration
|
||||
|
||||
`config/prod.exs` swaps the default handler's formatter for
|
||||
`Chesstrainer.JSONLogFormatter`; nothing else changes per environment. The
|
||||
formatter adds no runtime dependency beyond `Jason`, which the app already uses
|
||||
for Phoenix JSON.
|
||||
|
||||
## Line shape
|
||||
|
||||
```json
|
||||
{
|
||||
"timestamp": "2026-11-10T21:36:28.489000Z",
|
||||
"level": "error",
|
||||
"message": "GET /endgames 500 in 12.5ms",
|
||||
"request_id": "F7x...",
|
||||
"method": "GET",
|
||||
"path": "/endgames",
|
||||
"status": 500,
|
||||
"duration_ms": 12.5,
|
||||
"error": {
|
||||
"kind": "RuntimeError",
|
||||
"reason": "bad thing",
|
||||
"stacktrace": ["lib/foo.ex:10: Foo.bar/1"]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
`timestamp`, `level` and `message` are always present. Metadata keys are
|
||||
flattened into the object; reserved internal keys (`time`, `gl`, `report_cb`,
|
||||
`error_logger`, `exception`, `stacktrace`, `crash_reason`, `reason`, `kind`)
|
||||
are either unpacked into the line or omitted. Fixed fields win over metadata
|
||||
with the same name.
|
||||
|
||||
| Field | When | Meaning |
|
||||
|---|---|---|
|
||||
| `timestamp` | always | ISO-8601 UTC, microsecond precision |
|
||||
| `level` | always | `debug`, `info`, `notice`, `warning`, `error`, … |
|
||||
| `message` | always | Rendered log message, truncated to 8 KiB |
|
||||
| `request_id` | request-scoped logs | `Plug.RequestId` value, including LiveView processes |
|
||||
| `method`, `path`, `status`, `duration_ms` | access lines | One HTTP request; no query string or body |
|
||||
| `error.kind` | exceptions/crashes | Exception module, or the crash reason's kind |
|
||||
| `error.reason` | exceptions/crashes | `Exception.message/1` or an inspected reason |
|
||||
| `error.stacktrace` | exceptions/crashes | Array of formatted frames, capped at 50 |
|
||||
| everything else | as supplied | Flattened atom metadata, sanitised and redacted |
|
||||
|
||||
Exceptions (`Logger.error(..., exception: ..., stacktrace: ...)`) and OTP crash
|
||||
reports (`meta.crash_reason`, including Bandit request crashes and GenServer
|
||||
terminations) become the `error` object. Stacktrace frames are an array of
|
||||
strings so `jq -r '.error.stacktrace[]'` prints them readably.
|
||||
|
||||
## Redaction
|
||||
|
||||
The formatter redacts:
|
||||
|
||||
- metadata keys named `email`, `*_email`, `email_address`, `contact_email` or
|
||||
`recipient`;
|
||||
- any email-shaped string anywhere in metadata, nested `params`, or the rendered
|
||||
message;
|
||||
- credentials in `password`, `secret`, `token`, `authorization`, `cookie`,
|
||||
`api_key`, `private_key` and `credential` keys;
|
||||
- `token=...`/`password=...` assignments in messages.
|
||||
|
||||
Path segments of 20 or more URL-safe characters (reset/confirmation tokens,
|
||||
UUIDs) are replaced with `[REDACTED]` in access lines. Query parameters and
|
||||
request bodies are never logged.
|
||||
|
||||
## Access lines
|
||||
|
||||
`ChesstrainerWeb.RequestLogger` listens to `[:phoenix, :endpoint, :stop]` and
|
||||
emits one `:info` line per HTTP request that reaches the endpoint, including a
|
||||
LiveView's initial request. Phoenix's own endpoint start/stop pair is disabled
|
||||
with `log: false` in `ChesstrainerWeb.Endpoint` so there is exactly one line.
|
||||
|
||||
`ChesstrainerWeb.Plugs.PutRequestId` copies `Plug.RequestId`'s id into the
|
||||
session, and `UserAuth.mount_current_scope/2` puts it into `Logger.metadata/1`,
|
||||
so logs from the LiveView process keep the id after the HTTP request ends.
|
||||
|
||||
## Writing logs
|
||||
|
||||
Normal `Logger` calls need no changes. Atom metadata keys are flattened into the
|
||||
JSON object:
|
||||
|
||||
```elixir
|
||||
require Logger
|
||||
|
||||
Logger.info("tablebase cache miss", table: :tablebase, key: key)
|
||||
Logger.warning("tablebase fetch failed", status: 503, reason: reason)
|
||||
```
|
||||
|
||||
For a caught exception, pass the exception and stacktrace so the formatter can
|
||||
build the `error` object:
|
||||
|
||||
```elixir
|
||||
Logger.error("cache backup failed", exception: exception, stacktrace: __STACKTRACE__)
|
||||
```
|
||||
|
||||
For background work, wrap the body so `{:error, reason}` returns, throws, exits
|
||||
and crashes all produce a log line:
|
||||
|
||||
```elixir
|
||||
Task.Supervisor.start_child(Chesstrainer.Cache.BackupSupervisor, fn ->
|
||||
Chesstrainer.Background.run("send digest", [user_id: user.id], fn ->
|
||||
send_digest(user)
|
||||
end)
|
||||
end)
|
||||
```
|
||||
|
||||
Prefer identifiers such as `user_id` or `table` over emails, and never log
|
||||
params or request bodies. The formatter is a safety net, not a licence to log
|
||||
PII.
|
||||
|
||||
## Authentication events
|
||||
|
||||
`ChesstrainerWeb.UserSessionController` emits warning lines consumed by
|
||||
host-level tooling such as fail2ban:
|
||||
|
||||
| Message | Metadata | Meaning |
|
||||
|---|---|---|
|
||||
| `auth.login.failed` | `reason` (`invalid_credentials` / `unconfirmed`), `ip` | A password login failed. |
|
||||
| `auth.login.throttled` | `reason` (`ip` / `login`), `ip` | The address or login bucket blocked the attempt before bcrypt. |
|
||||
|
||||
`ip` is a boot-scoped HMAC of the client address, not the address itself. The
|
||||
raw login identifier and password are never included. The login throttle is
|
||||
configured in `config/config.exs` and defaults to five failures per login and
|
||||
ten per address in a fifteen-minute window.
|
||||
|
||||
## Querying logs
|
||||
|
||||
`journalctl` prints the raw line only with `-o cat`; the default output wraps it
|
||||
in journald fields. Install `jq` once on the VPS with
|
||||
`sudo apt-get install -y jq`, then:
|
||||
|
||||
```sh
|
||||
# Pretty-print recent lines
|
||||
sudo journalctl -u chesstrainer -o cat -n 50 --no-pager | jq .
|
||||
|
||||
# Errors only
|
||||
sudo journalctl -u chesstrainer -o cat --since "1 hour ago" \
|
||||
| jq 'select(.level == "error")'
|
||||
|
||||
# Everything from one request id
|
||||
sudo journalctl -u chesstrainer -o cat \
|
||||
| jq 'select(.request_id == "REQUEST_ID")'
|
||||
|
||||
# Crash reason and stacktrace
|
||||
sudo journalctl -u chesstrainer -o cat \
|
||||
| jq -r 'select(.error) | "\(.timestamp) \(.error.kind): \(.error.reason)\n\((.error.stacktrace // []) | join("\n"))"'
|
||||
|
||||
# Slow requests
|
||||
sudo journalctl -u chesstrainer -o cat \
|
||||
| jq 'select(.duration_ms > 1000) | {timestamp, method, path, status, duration_ms}'
|
||||
|
||||
# Most common error kinds in the current boot
|
||||
sudo journalctl -u chesstrainer -o cat -b \
|
||||
| jq -r 'select(.error.kind) | .error.kind' | sort | uniq -c | sort -rn
|
||||
```
|
||||
|
||||
`Plug.RequestId` also returns the id in the `x-request-id` response header, so a
|
||||
user can report the id from a failed request and you can filter straight to it.
|
||||
|
||||
## Local checks
|
||||
|
||||
The formatter tests run without a production release:
|
||||
|
||||
```sh
|
||||
mix test test/chesstrainer/json_log_formatter_test.exs \
|
||||
test/chesstrainer/background_test.exs \
|
||||
test/chesstrainer_web/request_logger_test.exs
|
||||
```
|
||||
|
||||
To render one event without touching the Logger configuration:
|
||||
|
||||
```sh
|
||||
mix run --no-start -e '
|
||||
event = %{
|
||||
level: :error,
|
||||
msg: {:string, "boom"},
|
||||
meta: %{
|
||||
time: System.system_time(:microsecond),
|
||||
request_id: "req-1",
|
||||
email: "user@example.com",
|
||||
exception: %RuntimeError{message: "bad"},
|
||||
stacktrace: [{Foo, :bar, 1, [file: ~c"lib/foo.ex", line: 10]}]
|
||||
}
|
||||
}
|
||||
IO.puts(Chesstrainer.JSONLogFormatter.format(event, %{}))
|
||||
'
|
||||
```
|
||||
|
||||
That prints one JSON line with the email redacted and the exception unpacked
|
||||
into `error`.
|
||||
|
||||
## Background work audit (#107)
|
||||
|
||||
Checked:
|
||||
|
||||
- `Chesstrainer.Cache` scheduled backup: `Task.Supervisor.start_child` ignored
|
||||
the task's return value and `Persist.backup/1` returns `{:error, reason}`
|
||||
without logging. Now wrapped in `Chesstrainer.Background.run/3`, which logs
|
||||
`{:error, reason}` returns and crashes (with exception, reason and
|
||||
stacktrace). A failure to start the task is logged too.
|
||||
- `Chesstrainer.Cache.Persist.restore/1`: an unreadable backup was silently
|
||||
skipped. It now logs a warning with the reason and starts with an empty cache.
|
||||
- `Chesstrainer.Endgames.Tablebase.Parser`: Lichess 5xx and network failures
|
||||
were returned to the caller (which shows a flash) but never logged. They now
|
||||
log a warning with the status or reason. 429 cooldowns stay quiet because they
|
||||
are expected.
|
||||
- `Mix.Tasks.Tablebase.Fetch`: already aborts loudly with `Mix.raise` on HTTP or
|
||||
network failure; no change.
|
||||
- Email delivery: sends are synchronous and their error is returned to the
|
||||
controller, so nothing is silent today. Future background sends should use
|
||||
`Chesstrainer.Background.run/3`.
|
||||
|
||||
## Reading logs on the VPS
|
||||
|
||||
See the "Reading production logs" and "Keep the journal" sections in
|
||||
[`deploy/README.md`](../deploy/README.md).
|
||||
@@ -0,0 +1,191 @@
|
||||
# Login and edge security
|
||||
|
||||
The login surface is protected in layers. The application throttle is the
|
||||
primary control; Cloudflare is the edge backstop for volume. There is no
|
||||
origin-level fail2ban for HTTP logins, because it would require storing raw IP
|
||||
addresses and would ban Cloudflare edge addresses on this deployment.
|
||||
|
||||
## Current production configuration
|
||||
|
||||
- Caddy accepts only Cloudflare's published ranges and forwards
|
||||
`CF-Connecting-IP` as `X-Forwarded-For`. The ranges are refreshed hourly by
|
||||
`chesstrainer-cloudflare-ranges.timer`.
|
||||
- `TRUST_FORWARDED_FOR=true`, so the app throttles by the real visitor address.
|
||||
- Cloudflare Bot Fight Mode is off. The Caddy origin allowlist above stays in
|
||||
force; re-enabling is tracked in #153.
|
||||
- The free-plan login flood rule allows 10 login POSTs per 10 seconds per IP and
|
||||
blocks for 10 seconds.
|
||||
|
||||
The short Cloudflare block is rate smoothing, not a credential lockout. The
|
||||
application's 5-per-login and 10-per-address failures in a 15-minute window are
|
||||
the real control.
|
||||
|
||||
## 1. Application login throttle
|
||||
|
||||
`ChesstrainerWeb.LoginThrottle` counts failures in two buckets:
|
||||
|
||||
| Bucket | Limit | Window |
|
||||
|---|---|---|
|
||||
| Normalised login (email or username) | 5 failures | 15 minutes |
|
||||
| Client address | 10 failures | 15 minutes |
|
||||
|
||||
Blocked attempts are rejected before the database lookup and bcrypt, so they do
|
||||
not consume password-hashing CPU. A successful login clears the login bucket
|
||||
only, keeping the address bucket in place so one address cannot spray many
|
||||
accounts.
|
||||
|
||||
The bucket keys are boot-scoped HMACs. Raw addresses and raw login identifiers
|
||||
are never stored in ETS or written to the application logs. The login form
|
||||
returns the same generic error for unknown accounts, bad passwords and
|
||||
unconfirmed accounts.
|
||||
|
||||
Configured in `config/config.exs`:
|
||||
|
||||
```elixir
|
||||
config :chesstrainer, ChesstrainerWeb.LoginThrottle,
|
||||
window_ms: :timer.minutes(15),
|
||||
max_per_login: 5,
|
||||
max_per_ip: 10,
|
||||
confirmation_cooldown_ms: :timer.minutes(15)
|
||||
```
|
||||
|
||||
`auth.login.failed` and `auth.login.throttled` are documented in
|
||||
`docs/logging.md`.
|
||||
|
||||
## 2. Real client IPs behind Cloudflare and Caddy
|
||||
|
||||
The production chain is:
|
||||
|
||||
```text
|
||||
Internet
|
||||
└─ Cloudflare
|
||||
└─ Caddy :443
|
||||
└─ Phoenix 127.0.0.1:4100
|
||||
```
|
||||
|
||||
Caddy ignores incoming `X-Forwarded-*` values by default and replaces them with
|
||||
the immediate peer address. Behind Cloudflare that peer is a Cloudflare edge
|
||||
node, so without configuration the app would throttle whole Cloudflare POPs
|
||||
rather than individual visitors.
|
||||
|
||||
`deploy/Caddyfile` fixes this by:
|
||||
|
||||
1. accepting only Cloudflare's published ranges, and
|
||||
2. setting `X-Forwarded-For` from Cloudflare's single-value `CF-Connecting-IP`
|
||||
header.
|
||||
|
||||
That keeps `TRUST_FORWARDED_FOR=true` safe: direct clients cannot reach the app
|
||||
through Caddy, so they cannot forge the header.
|
||||
|
||||
`deploy/Caddyfile` imports `cloudflare-ranges.caddy`. The file is generated by
|
||||
`deploy/update-cloudflare-ranges.sh`; do not edit it by hand.
|
||||
|
||||
The script is run hourly by `chesstrainer-cloudflare-ranges.timer`. It:
|
||||
|
||||
- downloads <https://www.cloudflare.com/ips-v4> and
|
||||
<https://www.cloudflare.com/ips-v6>,
|
||||
- rejects empty or malformed responses,
|
||||
- validates the candidate Caddyfile,
|
||||
- reloads Caddy only when the ranges changed.
|
||||
|
||||
If the download, validation or Caddy reload fails, the previous ranges stay in
|
||||
place.
|
||||
|
||||
Install and run it:
|
||||
|
||||
```sh
|
||||
sudo install -m 0755 /opt/chesstrainer/src/deploy/update-cloudflare-ranges.sh \
|
||||
/usr/local/sbin/chesstrainer-update-cloudflare-ranges
|
||||
sudo install -m 0644 /opt/chesstrainer/src/deploy/cloudflare-ranges.caddy \
|
||||
/etc/caddy/cloudflare-ranges.caddy
|
||||
sudo install -m 0644 /opt/chesstrainer/src/deploy/chesstrainer-cloudflare-ranges.service \
|
||||
/etc/systemd/system/chesstrainer-cloudflare-ranges.service
|
||||
sudo install -m 0644 /opt/chesstrainer/src/deploy/chesstrainer-cloudflare-ranges.timer \
|
||||
/etc/systemd/system/chesstrainer-cloudflare-ranges.timer
|
||||
sudo systemctl daemon-reload
|
||||
sudo systemctl enable --now chesstrainer-cloudflare-ranges.timer
|
||||
sudo systemctl start chesstrainer-cloudflare-ranges.service
|
||||
```
|
||||
|
||||
If `/opt/chesstrainer/src/deploy` is not present on the VPS, create the same
|
||||
four files directly with `sudo tee` from the canonical contents in `deploy/`.
|
||||
The timer only uses the installed copies.
|
||||
|
||||
Check the timer and last run:
|
||||
|
||||
```sh
|
||||
systemctl list-timers chesstrainer-cloudflare-ranges.timer
|
||||
systemctl status chesstrainer-cloudflare-ranges.service
|
||||
journalctl -u chesstrainer-cloudflare-ranges.service --since "24 hours ago"
|
||||
```
|
||||
|
||||
Apply the site block by hand on the shared Caddy host, then validate and
|
||||
reload:
|
||||
|
||||
```sh
|
||||
sudo caddy validate --config /etc/caddy/Caddyfile
|
||||
sudo systemctl reload caddy
|
||||
```
|
||||
|
||||
Direct requests to the origin with a spoofed `CF-Connecting-IP` must receive
|
||||
`403 Access Denied`; only Cloudflare's ranges should reach the Phoenix app. A
|
||||
host firewall allowlist for Cloudflare on ports 80 and 443 is a useful
|
||||
defence-in-depth addition.
|
||||
|
||||
## 3. Cloudflare edge rate limiting
|
||||
|
||||
This is for connection and request floods, not credential guessing. The
|
||||
application already stops password attempts cheaply.
|
||||
|
||||
The production rule is the free-plan version:
|
||||
|
||||
| Setting | Value |
|
||||
|---|---|
|
||||
| Name | Login POST flood |
|
||||
| Expression | `(http.request.method eq "POST" and http.request.uri.path in {"/admin/log-in" "/users/log-in"})` |
|
||||
| Characteristic | IP |
|
||||
| Period | 10 seconds |
|
||||
| Requests | 10 |
|
||||
| Action | Block |
|
||||
| Duration | 10 seconds |
|
||||
|
||||
Because the free plan only offers a 10-second period and a 10-second block, this
|
||||
is a burst limiter rather than a lasting ban. An attacker can retry after ten
|
||||
seconds, but the application still stops that login after five failures and that
|
||||
address after ten failures within fifteen minutes. A slow attacker staying under
|
||||
10 requests per 10 seconds never gets to make useful guesses because of the app
|
||||
throttle.
|
||||
|
||||
Bot Fight Mode is off. On the free plan it cannot be skipped for CI or for the
|
||||
on-box health probe, so a datacenter `curl` gets a 403 while the site itself is
|
||||
healthy; #153 covers the gate and probe changes needed before it goes back on.
|
||||
If the plan later gains longer rate-limit windows or managed WAF rules, raise
|
||||
the block duration and consider a broader site-wide rule, such as 100 requests
|
||||
per 10 seconds per IP with a managed challenge. Use Under Attack Mode during an
|
||||
active incident.
|
||||
|
||||
### Registration cannot be limited this way
|
||||
|
||||
`/users/register` is a LiveView. The form submit is a LiveView event sent over
|
||||
the shared `/live/websocket` connection, not a `POST /users/register` request.
|
||||
Cloudflare therefore cannot count account creations with a rule on the
|
||||
registration path.
|
||||
|
||||
A Cloudflare rule on `GET /users/register` only limits page opens; a bot can
|
||||
open one page and submit many registrations over the socket. If registration
|
||||
spam becomes a problem, add an application-level registration throttle keyed by
|
||||
`ChesstrainerWeb.ClientAddress.from_socket/1`, and/or add Cloudflare Turnstile
|
||||
to the form.
|
||||
|
||||
While `PRELAUNCH=true`, registration is blocked entirely by the prelaunch plug
|
||||
and LiveView mount redirect.
|
||||
|
||||
## 4. Why not fail2ban for HTTP?
|
||||
|
||||
fail2ban needs the raw client address to build a firewall rule. The application
|
||||
deliberately logs only a boot-scoped HMAC, and this deployment sits behind
|
||||
Cloudflare. Banning the address that reaches the origin would ban Cloudflare
|
||||
edges, not attackers.
|
||||
|
||||
fail2ban remains useful for services that terminate connections directly on the
|
||||
VPS, such as SSH. It is not part of the HTTP login defence.
|
||||
+19
-2
@@ -23,10 +23,27 @@ machine and a VPS will point at different copies.
|
||||
export TABLEBASE_PATH=/home/you/Downloads/tablebase
|
||||
mix phx.server
|
||||
|
||||
# Production (release)
|
||||
TABLEBASE_PATH=/data/syzygy/3-4-5 bin/chesstrainer start
|
||||
# Production (release), behind systemd
|
||||
TABLEBASE_PATH=/opt/chesstrainer/tablebases bin/chesstrainer start
|
||||
```
|
||||
|
||||
On the production VPS the directory is `/opt/chesstrainer/tablebases`, owned by
|
||||
the `chesstrainer` user. Set `TABLEBASE_PATH` in `/etc/chesstrainer/env` rather
|
||||
than an interactive shell, then restart `chesstrainer.service` — the value is
|
||||
read at boot.
|
||||
|
||||
```sh
|
||||
sudo chown -R chesstrainer:chesstrainer /opt/chesstrainer/tablebases
|
||||
sudo chmod -R u=rwX,g=rX,o= /opt/chesstrainer/tablebases
|
||||
sudo systemctl restart chesstrainer
|
||||
curl -s http://127.0.0.1:4100/health
|
||||
```
|
||||
|
||||
Healthy local tablebases report `tablebase: "local"` and `status: "ok"`. A
|
||||
missing, empty, or unreadable directory reports `tablebase: "fallback"` or
|
||||
`"not_configured"` and `status: "degraded"`, still with HTTP 200 because the
|
||||
Lichess fallback is available.
|
||||
|
||||
The value must reach the process. A bare `TABLEBASE_PATH=...` line in bash
|
||||
only sets a shell variable and is **not** exported to `mix` or the release —
|
||||
use `export`, or prefix the command. For a release, systemd unit or container,
|
||||
|
||||
@@ -4,9 +4,13 @@ defmodule Chesstrainer.Accounts do
|
||||
"""
|
||||
|
||||
import Ecto.Query, warn: false
|
||||
require Logger
|
||||
alias Chesstrainer.Repo
|
||||
|
||||
alias Chesstrainer.Accounts.{User, UserToken, UserNotifier}
|
||||
alias Chesstrainer.Accounts.{Policy, Role, Scope, User, UserToken, UserNotifier}
|
||||
alias Chesstrainer.MailingList
|
||||
|
||||
@admin_users_per_page 25
|
||||
|
||||
## Database getters
|
||||
|
||||
@@ -164,6 +168,320 @@ defmodule Chesstrainer.Accounts do
|
||||
|> Repo.update()
|
||||
end
|
||||
|
||||
@doc """
|
||||
Updates a user's subscription plan.
|
||||
|
||||
Plans are programmatic values; registration never casts `plan`, so a user
|
||||
cannot upgrade themselves.
|
||||
"""
|
||||
def update_user_plan(%User{} = user, plan) do
|
||||
user
|
||||
|> User.plan_changeset(%{plan: plan})
|
||||
|> Repo.update()
|
||||
end
|
||||
|
||||
## Admin user management
|
||||
|
||||
@doc """
|
||||
Returns a page of users the scope may administer, newest first.
|
||||
|
||||
Options:
|
||||
|
||||
* `:search` - case-insensitive match on email or username
|
||||
* `:page` - 1-based page number (defaults to 1)
|
||||
* `:per_page` - page size (defaults to 25, capped at 100)
|
||||
|
||||
Admins only see members and moderators; super admins see every role.
|
||||
Returns `{:error, :unauthorized}` when the scope lacks user management.
|
||||
"""
|
||||
def list_users_for_admin(scope, opts \\ []) do
|
||||
with :ok <- ensure_manage_users(scope) do
|
||||
page = normalize_page(Keyword.get(opts, :page, 1))
|
||||
per_page = normalize_per_page(Keyword.get(opts, :per_page, @admin_users_per_page))
|
||||
offset = (page - 1) * per_page
|
||||
|
||||
users =
|
||||
scope
|
||||
|> admin_users_query(opts)
|
||||
|> order_by([u], desc: u.inserted_at, desc: u.id)
|
||||
|> limit(^per_page)
|
||||
|> offset(^offset)
|
||||
|> Repo.all()
|
||||
|
||||
{:ok, users}
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Counts the users visible to the scope, using the same filters as
|
||||
`list_users_for_admin/2`.
|
||||
"""
|
||||
def count_users_for_admin(scope, opts \\ []) do
|
||||
with :ok <- ensure_manage_users(scope) do
|
||||
count =
|
||||
scope
|
||||
|> admin_users_query(opts)
|
||||
|> select([u], count(u.id))
|
||||
|> Repo.one()
|
||||
|
||||
{:ok, count}
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Fetches a user for the admin detail page.
|
||||
|
||||
Returns `{:error, :unauthorized}` when the scope may not view the target and
|
||||
`{:error, :not_found}` for an unknown id.
|
||||
"""
|
||||
def get_user_for_admin(scope, id) do
|
||||
with :ok <- ensure_manage_users(scope) do
|
||||
case fetch_user(id) do
|
||||
nil ->
|
||||
{:error, :not_found}
|
||||
|
||||
%User{} = user ->
|
||||
if Policy.can_view_user?(scope, user) do
|
||||
{:ok, user}
|
||||
else
|
||||
{:error, :unauthorized}
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Returns an `%Ecto.Changeset{}` for the admin-editable fields (role and plan).
|
||||
"""
|
||||
def change_user_as_admin(%User{} = user, attrs \\ %{}) do
|
||||
User.admin_changeset(user, attrs)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Updates a user's role and plan after enforcing the admin capability matrix.
|
||||
|
||||
The last-super-admin check runs inside the update transaction with a row lock,
|
||||
so concurrent demotions cannot remove the final super admin.
|
||||
|
||||
Returns `{:error, :unauthorized}`, `{:error, :own_role}`,
|
||||
`{:error, :last_super_admin}` or `{:error, %Ecto.Changeset{}}` instead of
|
||||
raising.
|
||||
"""
|
||||
def update_user_as_admin(scope, %User{} = user, attrs) do
|
||||
changeset = User.admin_changeset(user, attrs)
|
||||
role_change = Ecto.Changeset.get_change(changeset, :role)
|
||||
|
||||
with :ok <- ensure_manage_users(scope),
|
||||
:ok <- ensure_not_own_role_change(scope, user, role_change),
|
||||
:ok <- ensure_can_manage_user(scope, user),
|
||||
:ok <- ensure_can_assign_role(scope, role_change),
|
||||
{:ok, updated} <- persist_user_changes(user, changeset) do
|
||||
log_user_update(scope, user, changeset)
|
||||
{:ok, updated}
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Creates an invitation and emails the recipient a link to choose a password.
|
||||
|
||||
The account is confirmed but has no password until the invitee follows the
|
||||
link. `invite_url_fun` receives the encoded token and must return a URL.
|
||||
"""
|
||||
def invite_user_as_admin(scope, attrs, invite_url_fun)
|
||||
when is_function(invite_url_fun, 1) do
|
||||
role = normalize_role(role_param(attrs) || :member)
|
||||
|
||||
with :ok <- ensure_manage_users(scope),
|
||||
:ok <- ensure_can_assign_role(scope, role) do
|
||||
changeset =
|
||||
%User{}
|
||||
|> User.invite_changeset(attrs)
|
||||
|> User.admin_changeset(attrs)
|
||||
|
||||
case Repo.insert(changeset) do
|
||||
{:ok, user} ->
|
||||
Logger.info("admin.user.invited",
|
||||
actor_id: scope.user.id,
|
||||
target_id: user.id,
|
||||
fields: [:invite]
|
||||
)
|
||||
|
||||
case deliver_invite_instructions(user, invite_url_fun) do
|
||||
{:ok, _email} -> {:ok, user}
|
||||
{:error, reason} -> {:error, reason}
|
||||
end
|
||||
|
||||
{:error, changeset} ->
|
||||
{:error, changeset}
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Sends a password-reset email on behalf of an administrator.
|
||||
|
||||
Uses the same policy as the editable user screen: an admin cannot trigger a
|
||||
reset for another admin or a super admin.
|
||||
"""
|
||||
def send_user_reset_password_instructions_as_admin(scope, %User{} = user, reset_url_fun)
|
||||
when is_function(reset_url_fun, 1) do
|
||||
with :ok <- ensure_manage_users(scope),
|
||||
:ok <- ensure_can_manage_user(scope, user) do
|
||||
case deliver_user_reset_password_instructions(user, reset_url_fun) do
|
||||
{:ok, email} ->
|
||||
Logger.info("admin.user.password_reset_sent",
|
||||
actor_id: scope.user.id,
|
||||
target_id: user.id
|
||||
)
|
||||
|
||||
{:ok, email}
|
||||
|
||||
error ->
|
||||
error
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Resends the account-confirmation email on behalf of an administrator.
|
||||
"""
|
||||
def resend_user_confirmation_instructions_as_admin(scope, %User{} = user, confirmation_url_fun)
|
||||
when is_function(confirmation_url_fun, 1) do
|
||||
with :ok <- ensure_manage_users(scope),
|
||||
:ok <- ensure_can_manage_user(scope, user) do
|
||||
case deliver_user_confirmation_instructions(user, confirmation_url_fun) do
|
||||
{:ok, email} ->
|
||||
Logger.info("admin.user.confirmation_resent",
|
||||
actor_id: scope.user.id,
|
||||
target_id: user.id
|
||||
)
|
||||
|
||||
{:ok, email}
|
||||
|
||||
error ->
|
||||
error
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
defp admin_users_query(scope, opts) do
|
||||
roles = Policy.visible_roles(scope)
|
||||
search = opts |> Keyword.get(:search, "") |> to_string() |> String.trim()
|
||||
|
||||
query = from(u in User, where: u.role in ^roles)
|
||||
|
||||
if search == "" do
|
||||
query
|
||||
else
|
||||
pattern = "%#{search}%"
|
||||
|
||||
where(
|
||||
query,
|
||||
[u],
|
||||
ilike(u.email, ^pattern) or ilike(u.username, ^pattern)
|
||||
)
|
||||
end
|
||||
end
|
||||
|
||||
defp persist_user_changes(user, changeset) do
|
||||
Repo.transact(fn ->
|
||||
with :ok <- ensure_not_last_super_admin(user, changeset),
|
||||
{:ok, updated} <- Repo.update(changeset) do
|
||||
{:ok, updated}
|
||||
end
|
||||
end)
|
||||
end
|
||||
|
||||
defp ensure_not_last_super_admin(%User{role: :super_admin}, changeset) do
|
||||
case Ecto.Changeset.get_change(changeset, :role) do
|
||||
role when role in [nil, :super_admin] ->
|
||||
:ok
|
||||
|
||||
_role ->
|
||||
super_admins =
|
||||
Repo.all(from(u in User, where: u.role == :super_admin, lock: "FOR UPDATE"))
|
||||
|
||||
if length(super_admins) <= 1 do
|
||||
{:error, :last_super_admin}
|
||||
else
|
||||
:ok
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
defp ensure_not_last_super_admin(_user, _changeset), do: :ok
|
||||
|
||||
defp log_user_update(scope, user, changeset) do
|
||||
fields = changeset.changes |> Map.keys() |> Enum.sort()
|
||||
|
||||
if fields != [] do
|
||||
Logger.info("admin.user.updated",
|
||||
actor_id: scope.user.id,
|
||||
target_id: user.id,
|
||||
fields: fields
|
||||
)
|
||||
end
|
||||
end
|
||||
|
||||
defp deliver_invite_instructions(user, invite_url_fun) do
|
||||
{encoded_token, user_token} = UserToken.build_email_token(user, "reset_password")
|
||||
Repo.insert!(user_token)
|
||||
UserNotifier.deliver_invite_instructions(user, invite_url_fun.(encoded_token))
|
||||
end
|
||||
|
||||
defp ensure_manage_users(scope) do
|
||||
if Policy.can?(scope, :manage_users), do: :ok, else: {:error, :unauthorized}
|
||||
end
|
||||
|
||||
defp ensure_can_manage_user(scope, user) do
|
||||
if Policy.can_manage_user?(scope, user), do: :ok, else: {:error, :unauthorized}
|
||||
end
|
||||
|
||||
defp ensure_can_assign_role(_scope, nil), do: :ok
|
||||
|
||||
defp ensure_can_assign_role(scope, role) do
|
||||
if Policy.can_assign_role?(scope, role), do: :ok, else: {:error, :unauthorized}
|
||||
end
|
||||
|
||||
defp ensure_not_own_role_change(%Scope{user: %User{id: id}}, %User{id: id}, role)
|
||||
when not is_nil(role),
|
||||
do: {:error, :own_role}
|
||||
|
||||
defp ensure_not_own_role_change(_scope, _user, _role), do: :ok
|
||||
|
||||
defp fetch_user(id) do
|
||||
Repo.get(User, id)
|
||||
rescue
|
||||
Ecto.Query.CastError -> nil
|
||||
end
|
||||
|
||||
defp role_param(attrs), do: Map.get(attrs, "role") || Map.get(attrs, :role)
|
||||
|
||||
defp normalize_role(role) do
|
||||
cond do
|
||||
role in Role.values() -> role
|
||||
is_binary(role) -> Enum.find(Role.values(), &(Atom.to_string(&1) == role))
|
||||
true -> nil
|
||||
end
|
||||
end
|
||||
|
||||
defp normalize_page(page) when is_integer(page) and page > 0, do: page
|
||||
|
||||
defp normalize_page(page) when is_binary(page) do
|
||||
case Integer.parse(page) do
|
||||
{number, ""} when number > 0 -> number
|
||||
_ -> 1
|
||||
end
|
||||
end
|
||||
|
||||
defp normalize_page(_page), do: 1
|
||||
|
||||
defp normalize_per_page(per_page) when is_integer(per_page) and per_page > 0 do
|
||||
min(per_page, 100)
|
||||
end
|
||||
|
||||
defp normalize_per_page(_per_page), do: @admin_users_per_page
|
||||
|
||||
## Settings
|
||||
|
||||
@doc """
|
||||
@@ -207,6 +525,7 @@ defmodule Chesstrainer.Accounts do
|
||||
with {:ok, query} <- UserToken.verify_change_email_token_query(token, context),
|
||||
%UserToken{sent_to: email} <- Repo.one(query),
|
||||
{:ok, user} <- Repo.update(User.email_changeset(user, %{email: email})),
|
||||
{:ok, _subscription} <- MailingList.update_subscriber_email(user, email),
|
||||
{_count, _result} <-
|
||||
Repo.delete_all(from(UserToken, where: [user_id: ^user.id, context: ^context])) do
|
||||
{:ok, user}
|
||||
@@ -332,6 +651,22 @@ defmodule Chesstrainer.Accounts do
|
||||
Repo.one(query)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Returns the number of users with at least one valid session token.
|
||||
|
||||
Session tokens stay valid for `UserToken.session_validity_in_days/0` days, so
|
||||
this counts users who logged in during that window, not necessarily users who
|
||||
are connected right now. A user with multiple sessions counts once.
|
||||
"""
|
||||
def count_logged_in_users do
|
||||
days = UserToken.session_validity_in_days()
|
||||
|
||||
UserToken
|
||||
|> where([t], t.context == "session" and t.inserted_at > ago(^days, "day"))
|
||||
|> select([t], count(t.user_id, :distinct))
|
||||
|> Repo.one()
|
||||
end
|
||||
|
||||
@doc ~S"""
|
||||
Delivers the update email instructions to the given user.
|
||||
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
defmodule Chesstrainer.Accounts.Policy do
|
||||
@moduledoc """
|
||||
The single source of truth for administrator capabilities.
|
||||
|
||||
Roles are ordered by `Chesstrainer.Accounts.Role`. An administrator may only
|
||||
manage users below their own rank; a `super_admin` may also manage admins and
|
||||
other super admins, but never changes their own role.
|
||||
|
||||
The router uses `can?/2` to gate the admin area, and every mutating admin
|
||||
LiveView calls back into this module or into the scoped `Accounts` functions
|
||||
so hidden buttons are never the only protection.
|
||||
"""
|
||||
|
||||
alias Chesstrainer.Accounts.{Role, Scope, User}
|
||||
|
||||
@capabilities %{
|
||||
manage_endgames: [:admin, :super_admin],
|
||||
manage_themes: [:admin, :super_admin],
|
||||
manage_users: [:admin, :super_admin]
|
||||
}
|
||||
|
||||
@doc "All admin capabilities."
|
||||
@spec capabilities() :: [atom()]
|
||||
def capabilities, do: Map.keys(@capabilities)
|
||||
|
||||
@doc """
|
||||
Returns true when the scope may perform the given admin capability.
|
||||
|
||||
A nil scope or a member/moderator never satisfies an admin capability.
|
||||
"""
|
||||
@spec can?(Scope.t() | nil, atom()) :: boolean()
|
||||
def can?(%Scope{user: %User{role: role}}, capability) when is_atom(capability) do
|
||||
role in Map.get(@capabilities, capability, [])
|
||||
end
|
||||
|
||||
def can?(_scope, _capability), do: false
|
||||
|
||||
@doc """
|
||||
Returns true when the scope may edit the target user's role and plan.
|
||||
|
||||
An actor may only modify a user whose role rank is strictly lower, except a
|
||||
`super_admin`, who may also modify admins and other super admins. Nobody may
|
||||
modify themselves through the admin area.
|
||||
"""
|
||||
@spec can_manage_user?(Scope.t() | nil, User.t()) :: boolean()
|
||||
def can_manage_user?(%Scope{user: %User{} = actor} = scope, %User{} = target) do
|
||||
cond do
|
||||
not can?(scope, :manage_users) -> false
|
||||
actor.id == target.id -> false
|
||||
actor.role == :super_admin -> true
|
||||
Role.rank(actor.role) > Role.rank(target.role) -> true
|
||||
true -> false
|
||||
end
|
||||
end
|
||||
|
||||
def can_manage_user?(_scope, _target), do: false
|
||||
|
||||
@doc """
|
||||
Returns true when the scope may view the target user in the admin area.
|
||||
|
||||
Admins can see themselves and lower-ranked users read-only; super admins can
|
||||
see everyone. This is deliberately wider than `can_manage_user?/2`, which
|
||||
controls the editable form.
|
||||
"""
|
||||
@spec can_view_user?(Scope.t() | nil, User.t()) :: boolean()
|
||||
def can_view_user?(%Scope{user: %User{} = actor} = scope, %User{} = target) do
|
||||
can?(scope, :manage_users) and
|
||||
(actor.id == target.id or actor.role == :super_admin or
|
||||
Role.rank(actor.role) > Role.rank(target.role))
|
||||
end
|
||||
|
||||
def can_view_user?(_scope, _target), do: false
|
||||
|
||||
@doc """
|
||||
Returns true when the scope may assign the given role.
|
||||
|
||||
Admins can only assign member or moderator. Super admins can assign any role.
|
||||
"""
|
||||
@spec can_assign_role?(Scope.t() | nil, Role.value()) :: boolean()
|
||||
def can_assign_role?(%Scope{user: %User{role: :super_admin}}, role) do
|
||||
role in Role.values()
|
||||
end
|
||||
|
||||
def can_assign_role?(%Scope{user: %User{role: actor_role}}, role) do
|
||||
role in Role.values() and Role.rank(actor_role) > Role.rank(role)
|
||||
end
|
||||
|
||||
def can_assign_role?(_scope, _role), do: false
|
||||
|
||||
@doc """
|
||||
Returns the roles whose users the scope may see in the admin user list.
|
||||
|
||||
Admins only see members and moderators; super admins see every role.
|
||||
"""
|
||||
@spec visible_roles(Scope.t() | nil) :: [Role.value()]
|
||||
def visible_roles(%Scope{user: %User{role: :super_admin}}), do: Role.values()
|
||||
|
||||
def visible_roles(%Scope{user: %User{role: :admin}}), do: [:member, :moderator]
|
||||
def visible_roles(_scope), do: []
|
||||
end
|
||||
@@ -6,6 +6,8 @@ defmodule Chesstrainer.Accounts.Role do
|
||||
should ask for the minimum tier they need via `at_least?/2`.
|
||||
"""
|
||||
|
||||
@type value :: :member | :moderator | :admin | :super_admin
|
||||
|
||||
@values [:member, :moderator, :admin, :super_admin]
|
||||
|
||||
@ranks %{
|
||||
|
||||
@@ -20,6 +20,8 @@ defmodule Chesstrainer.Accounts.Scope do
|
||||
|
||||
defstruct user: nil
|
||||
|
||||
@type t :: %__MODULE__{user: User.t() | nil}
|
||||
|
||||
@doc """
|
||||
Creates a scope for the given user.
|
||||
|
||||
@@ -30,4 +32,13 @@ defmodule Chesstrainer.Accounts.Scope do
|
||||
end
|
||||
|
||||
def for_user(nil), do: nil
|
||||
|
||||
@doc """
|
||||
True when the scope belongs to a premium user.
|
||||
|
||||
`for_user/1` returns `nil` for anonymous visitors, so the catch-all covers
|
||||
both nil scopes and free plans.
|
||||
"""
|
||||
def premium?(%__MODULE__{user: %User{plan: :premium}}), do: true
|
||||
def premium?(_scope), do: false
|
||||
end
|
||||
|
||||
@@ -15,10 +15,13 @@ defmodule Chesstrainer.Accounts.User do
|
||||
field :rating_deviation, :float, default: 350.0
|
||||
field :confirmed_at, :utc_datetime
|
||||
field :authenticated_at, :utc_datetime, virtual: true
|
||||
field :mailing_list, :boolean, virtual: true, default: false
|
||||
|
||||
timestamps(type: :utc_datetime)
|
||||
end
|
||||
|
||||
@type t :: %__MODULE__{}
|
||||
|
||||
@doc """
|
||||
A user changeset for registration.
|
||||
|
||||
@@ -34,7 +37,7 @@ defmodule Chesstrainer.Accounts.User do
|
||||
"""
|
||||
def registration_changeset(user, attrs, opts \\ []) do
|
||||
user
|
||||
|> cast(attrs, [:email, :username, :password])
|
||||
|> cast(attrs, [:email, :username, :password, :mailing_list])
|
||||
|> validate_email(opts)
|
||||
|> validate_username(opts)
|
||||
|> validate_confirmation(:password, message: "does not match password")
|
||||
@@ -52,6 +55,43 @@ defmodule Chesstrainer.Accounts.User do
|
||||
|> validate_required([:role])
|
||||
end
|
||||
|
||||
@doc """
|
||||
A user changeset for changing the plan.
|
||||
|
||||
The plan is programmatic and must never be cast from user-supplied params.
|
||||
"""
|
||||
def plan_changeset(user, attrs) do
|
||||
user
|
||||
|> cast(attrs, [:plan])
|
||||
|> validate_required([:plan])
|
||||
end
|
||||
|
||||
@doc """
|
||||
A user changeset for an admin-created invitation.
|
||||
|
||||
The account is created without a password and marked confirmed, so the
|
||||
recipient can choose a password from the emailed invitation link and log in
|
||||
immediately afterwards. Role and plan are applied separately by
|
||||
`admin_changeset/2` after the caller has checked the policy.
|
||||
"""
|
||||
def invite_changeset(user, attrs) do
|
||||
user
|
||||
|> cast(attrs, [:email, :username])
|
||||
|> validate_email([])
|
||||
|> validate_username([])
|
||||
|> put_change(:confirmed_at, DateTime.utc_now(:second))
|
||||
end
|
||||
|
||||
@doc """
|
||||
A user changeset for the fields an administrator may edit.
|
||||
|
||||
These values are programmatic, so this changeset is only used by the scoped
|
||||
admin functions in `Chesstrainer.Accounts`.
|
||||
"""
|
||||
def admin_changeset(user, attrs) do
|
||||
cast(user, attrs, [:role, :plan])
|
||||
end
|
||||
|
||||
@doc """
|
||||
A user changeset for registering or changing the email.
|
||||
|
||||
|
||||
@@ -1,20 +1,16 @@
|
||||
defmodule Chesstrainer.Accounts.UserNotifier do
|
||||
import Swoosh.Email
|
||||
|
||||
alias Chesstrainer.Mailer
|
||||
alias Chesstrainer.Branding
|
||||
alias Chesstrainer.Mail
|
||||
|
||||
# Delivers the email using the application mailer.
|
||||
defp deliver(recipient, subject, body) do
|
||||
email =
|
||||
new()
|
||||
|> to(recipient)
|
||||
|> from({"Chesstrainer", "contact@example.com"})
|
||||
|> subject(subject)
|
||||
|> text_body(body)
|
||||
|
||||
with {:ok, _metadata} <- Mailer.deliver(email) do
|
||||
{:ok, email}
|
||||
end
|
||||
|> Mail.deliver()
|
||||
end
|
||||
|
||||
@doc """
|
||||
@@ -37,6 +33,31 @@ defmodule Chesstrainer.Accounts.UserNotifier do
|
||||
""")
|
||||
end
|
||||
|
||||
@doc """
|
||||
Deliver an invitation to choose a password.
|
||||
|
||||
Admins create the account without a password; the invitation link uses the
|
||||
same reset-password token flow so the recipient can set one.
|
||||
"""
|
||||
def deliver_invite_instructions(user, url) do
|
||||
deliver(user.email, "You're invited to #{Branding.name()}", """
|
||||
|
||||
==============================
|
||||
|
||||
Hi #{user.username},
|
||||
|
||||
An administrator has created an account for you on #{Branding.name()}.
|
||||
|
||||
Choose your password by visiting the URL below:
|
||||
|
||||
#{url}
|
||||
|
||||
If you weren't expecting this invitation, please ignore this email.
|
||||
|
||||
==============================
|
||||
""")
|
||||
end
|
||||
|
||||
@doc """
|
||||
Deliver instructions to reset a user password.
|
||||
"""
|
||||
|
||||
@@ -48,6 +48,9 @@ defmodule Chesstrainer.Accounts.UserToken do
|
||||
{token, %UserToken{token: token, context: "session", user_id: user.id, authenticated_at: dt}}
|
||||
end
|
||||
|
||||
@doc "How long a session token stays valid, in days."
|
||||
def session_validity_in_days, do: @session_validity_in_days
|
||||
|
||||
@doc """
|
||||
Checks if the token is valid and returns its underlying lookup query.
|
||||
|
||||
|
||||
@@ -16,6 +16,8 @@ defmodule Chesstrainer.Application do
|
||||
{Phoenix.PubSub, name: Chesstrainer.PubSub},
|
||||
# Start a worker by calling: Chesstrainer.Worker.start_link(arg)
|
||||
# {Chesstrainer.Worker, arg},
|
||||
Chesstrainer.GuestLimits,
|
||||
ChesstrainerWeb.LoginThrottle,
|
||||
# Start to serve requests, typically the last entry
|
||||
ChesstrainerWeb.Endpoint,
|
||||
{Registry, keys: :unique, name: Chesstrainer.CacheRegistry},
|
||||
|
||||
@@ -59,5 +59,68 @@ defmodule Chesstrainer.Attempts do
|
||||
|> Repo.one()
|
||||
end
|
||||
|
||||
@doc """
|
||||
Returns the number of users who have recorded at least one attempt.
|
||||
|
||||
A retry does not count twice: the count is over distinct users.
|
||||
"""
|
||||
def count_users_with_attempts do
|
||||
Attempt
|
||||
|> select([a], count(a.user_id, :distinct))
|
||||
|> Repo.one()
|
||||
end
|
||||
|
||||
@doc """
|
||||
Aggregated attempt totals for `user_id`.
|
||||
|
||||
Returns a map with `:attempts`, `:solved`, `:failed` and `:endgames` (the
|
||||
number of distinct puzzles tried).
|
||||
"""
|
||||
def stats_for_user(user_id) do
|
||||
Attempt
|
||||
|> where([a], a.user_id == ^user_id)
|
||||
|> select([a], %{
|
||||
attempts: count(a.id),
|
||||
solved: filter(count(a.id), a.outcome == :solved),
|
||||
failed: filter(count(a.id), a.outcome == :failed),
|
||||
endgames: count(a.endgame_id, :distinct)
|
||||
})
|
||||
|> Repo.one()
|
||||
end
|
||||
|
||||
@doc """
|
||||
The attempts of `user_id`, newest first, with each endgame preloaded.
|
||||
|
||||
Pass `limit: n` to cap the history (the profile page shows a recent window;
|
||||
exports pass no limit).
|
||||
"""
|
||||
def list_attempts_for_user(user_id, opts \\ []) do
|
||||
Attempt
|
||||
|> where([a], a.user_id == ^user_id)
|
||||
|> order_by([a], desc: a.inserted_at)
|
||||
|> maybe_limit(Keyword.get(opts, :limit))
|
||||
|> preload(:endgame)
|
||||
|> Repo.all()
|
||||
end
|
||||
|
||||
@doc """
|
||||
The distinct endgame ids `user_id` has attempted in the last `days` days.
|
||||
|
||||
Used by puzzle selection to skip puzzles inside the repeat window; a retry
|
||||
still counts as an attempt, even though the rating window leaves it unrated.
|
||||
"""
|
||||
def recent_endgame_ids(user_id, days \\ 30) do
|
||||
cutoff = DateTime.add(DateTime.utc_now(), -days, :day)
|
||||
|
||||
Attempt
|
||||
|> where([a], a.user_id == ^user_id and a.inserted_at >= ^cutoff)
|
||||
|> distinct(true)
|
||||
|> select([a], a.endgame_id)
|
||||
|> Repo.all()
|
||||
end
|
||||
|
||||
defp rated(query), do: where(query, [a], not is_nil(a.rated_at))
|
||||
|
||||
defp maybe_limit(query, nil), do: query
|
||||
defp maybe_limit(query, limit) when is_integer(limit), do: limit(query, ^limit)
|
||||
end
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
defmodule Chesstrainer.Background do
|
||||
@moduledoc """
|
||||
Runs background work and logs any failure.
|
||||
|
||||
Background failures otherwise disappear: a task exits, the supervisor keeps
|
||||
the rest of the system running, and nobody sees why the work did not happen.
|
||||
This wrapper turns crashes, throws, exits and `{:error, reason}` returns into
|
||||
one structured error line with the reason and stacktrace.
|
||||
|
||||
The label is a short description of the work; metadata is added to the log
|
||||
line unchanged (minus the formatter's own redaction).
|
||||
"""
|
||||
|
||||
require Logger
|
||||
|
||||
@type result :: term()
|
||||
|
||||
@doc """
|
||||
Runs `fun` and logs a failure. Returns the function's value, or `:error` when
|
||||
it crashed or returned an error tuple.
|
||||
"""
|
||||
@spec run(String.t(), (-> result)) :: result() | :error
|
||||
def run(label, fun), do: run(label, [], fun)
|
||||
|
||||
@doc """
|
||||
Like `run/2`, with extra metadata for the error line.
|
||||
"""
|
||||
@spec run(String.t(), keyword(), (-> result)) :: result() | :error
|
||||
def run(label, metadata, fun)
|
||||
when is_binary(label) and is_list(metadata) and is_function(fun, 0) do
|
||||
case fun.() do
|
||||
{:error, reason} ->
|
||||
Logger.error(
|
||||
"#{label} failed: #{format_term(reason)}",
|
||||
Keyword.merge(metadata, reason: reason)
|
||||
)
|
||||
|
||||
:error
|
||||
|
||||
result ->
|
||||
result
|
||||
end
|
||||
rescue
|
||||
exception ->
|
||||
Logger.error(
|
||||
"#{label} crashed: #{Exception.message(exception)}",
|
||||
Keyword.merge(metadata, exception: exception, stacktrace: __STACKTRACE__)
|
||||
)
|
||||
|
||||
:error
|
||||
catch
|
||||
kind, reason ->
|
||||
Logger.error(
|
||||
"#{label} crashed: #{format_term(reason)}",
|
||||
Keyword.merge(metadata, kind: kind, reason: reason, stacktrace: __STACKTRACE__)
|
||||
)
|
||||
|
||||
:error
|
||||
end
|
||||
|
||||
defp format_term(term) when is_binary(term), do: term
|
||||
defp format_term(term), do: inspect(term, limit: 10, printable_limit: 500)
|
||||
end
|
||||
@@ -0,0 +1,64 @@
|
||||
defmodule Chesstrainer.Branding do
|
||||
@moduledoc """
|
||||
Public-facing branding, read from `config :chesstrainer, :branding`.
|
||||
|
||||
Keeps display names out of templates and controllers so the site can be
|
||||
renamed in one place. Values are read at runtime, so a deploy can override
|
||||
them without recompiling.
|
||||
"""
|
||||
|
||||
@defaults [
|
||||
name: "Inner Square Chess",
|
||||
wordmark: "INNERSQUARE",
|
||||
tagline: "Endgame Trainer",
|
||||
support_email: "support@innersquare.app",
|
||||
mail_from: "no-reply@mail.innersquare.app",
|
||||
discord_invite: "https://discord.gg/Z2NfkG7thV"
|
||||
]
|
||||
|
||||
@doc "The display name, e.g. `\"Lucid Chess\"`."
|
||||
def name, do: get(:name)
|
||||
|
||||
@doc "The short wordmark used in the navbar and footer."
|
||||
def wordmark, do: get(:wordmark)
|
||||
|
||||
@doc "The tagline appended to the home title, e.g. `\"Endgame Trainer\"`."
|
||||
def tagline, do: get(:tagline)
|
||||
|
||||
@doc "The support address shown in legal pages and used as the mailer reply-to."
|
||||
def support_email, do: get(:support_email)
|
||||
|
||||
@doc "The From address used for outgoing mail."
|
||||
def mail_from, do: get(:mail_from)
|
||||
|
||||
@doc """
|
||||
The Discord invite URL, or `nil` when no invite is configured.
|
||||
|
||||
Accepts either a bare invite code (`"abc123"`) or a full URL; a bare code is
|
||||
expanded to `https://discord.gg/<code>`.
|
||||
"""
|
||||
def discord_invite_url do
|
||||
case get(:discord_invite) do
|
||||
value when is_binary(value) ->
|
||||
case String.trim(value) do
|
||||
"" -> nil
|
||||
"http" <> _ = url -> url
|
||||
code -> "https://discord.gg/#{code}"
|
||||
end
|
||||
|
||||
_ ->
|
||||
nil
|
||||
end
|
||||
end
|
||||
|
||||
@doc "The home-page title, e.g. `\"Lucid Chess — Endgame Trainer\"`."
|
||||
def home_title, do: "#{name()} — #{tagline()}"
|
||||
|
||||
@doc "Builds a page title, e.g. `title(\"Privacy Policy\")`."
|
||||
def title(page), do: "#{page} — #{name()}"
|
||||
|
||||
defp get(key) do
|
||||
config = Application.get_env(:chesstrainer, :branding) || []
|
||||
Keyword.get(config, key, Keyword.fetch!(@defaults, key))
|
||||
end
|
||||
end
|
||||
@@ -11,7 +11,8 @@ defmodule Chesstrainer.Cache do
|
||||
that were used heavily once but have not been used since eventually age out.
|
||||
|
||||
A daily backup runs off the cache process at a configurable UTC time, so reads
|
||||
and writes stay responsive while the snapshot is written.
|
||||
and writes stay responsive while the snapshot is written. Failures are logged
|
||||
rather than lost.
|
||||
|
||||
## Examples
|
||||
|
||||
@@ -19,7 +20,9 @@ defmodule Chesstrainer.Cache do
|
||||
"""
|
||||
|
||||
use GenServer
|
||||
require Logger
|
||||
|
||||
alias Chesstrainer.Background
|
||||
alias Chesstrainer.Cache.BackupSchedule
|
||||
alias Chesstrainer.Cache.Persist
|
||||
|
||||
@@ -121,7 +124,18 @@ defmodule Chesstrainer.Cache do
|
||||
table = state.table
|
||||
backup_fun = state.backup_fun
|
||||
|
||||
Task.Supervisor.start_child(Chesstrainer.Cache.BackupSupervisor, fn -> backup_fun.(table) end)
|
||||
task = fn ->
|
||||
Background.run("cache backup", [table: table], fn -> backup_fun.(table) end)
|
||||
end
|
||||
|
||||
case Task.Supervisor.start_child(Chesstrainer.Cache.BackupSupervisor, task) do
|
||||
{:ok, _pid} ->
|
||||
:ok
|
||||
|
||||
{:error, reason} ->
|
||||
Logger.error("cache backup could not start", table: table, reason: reason)
|
||||
:ok
|
||||
end
|
||||
end
|
||||
|
||||
defp schedule_backup(state) do
|
||||
|
||||
Vendored
+7
-1
@@ -5,8 +5,13 @@ defmodule Chesstrainer.Cache.Persist do
|
||||
A backup is written to a temporary DETS file in the same directory and then
|
||||
atomically renamed into place. A crash during the write therefore leaves the
|
||||
previous backup untouched instead of a truncated file that fails to restore.
|
||||
|
||||
A backup that cannot be opened at boot is logged and skipped, so a damaged
|
||||
file does not stop the application from starting with an empty cache.
|
||||
"""
|
||||
|
||||
require Logger
|
||||
|
||||
@backup_path "priv/static/backups"
|
||||
@format_version "v2"
|
||||
|
||||
@@ -54,7 +59,8 @@ defmodule Chesstrainer.Cache.Persist do
|
||||
|
||||
:dets.close(table)
|
||||
|
||||
{:error, _} ->
|
||||
{:error, reason} ->
|
||||
Logger.warning("cache backup restore failed", table: table, reason: reason)
|
||||
:ok
|
||||
end
|
||||
end
|
||||
|
||||
@@ -23,11 +23,23 @@ defmodule Chesstrainer.Endgames do
|
||||
|
||||
@doc """
|
||||
Returns a random endgame, or `nil` when none exist.
|
||||
|
||||
`:exclude_ids` (default `[]`) skips endgames by id — used to avoid repeating
|
||||
the puzzle just played.
|
||||
"""
|
||||
def random_endgame do
|
||||
Repo.one(from e in Endgame, order_by: fragment("RANDOM()"), limit: 1)
|
||||
def random_endgame(opts \\ []) do
|
||||
exclude_ids = Keyword.get(opts, :exclude_ids, [])
|
||||
|
||||
Endgame
|
||||
|> skip_ids(exclude_ids)
|
||||
|> order_by([e], fragment("RANDOM()"))
|
||||
|> limit(1)
|
||||
|> Repo.one()
|
||||
end
|
||||
|
||||
defp skip_ids(query, []), do: query
|
||||
defp skip_ids(query, ids), do: where(query, [e], e.id not in ^ids)
|
||||
|
||||
@doc """
|
||||
Returns the number of stored endgames, each of which is played as a puzzle.
|
||||
"""
|
||||
@@ -99,8 +111,13 @@ defmodule Chesstrainer.Endgames do
|
||||
@doc """
|
||||
Returns `{key, count}` groups for endgames matching the filters, sorted by key.
|
||||
|
||||
Filters is a map with optional `:themes` (a list of theme ids; an endgame must
|
||||
carry any one of them) and `:key` (an exact Key).
|
||||
Filters is a map with optional:
|
||||
|
||||
* `:themes` - a list of theme ids; an endgame must carry any one of them
|
||||
* `:key` - an exact Key
|
||||
* `:with_theme` - `{theme_id, source}`; only endgames linked to the theme
|
||||
with that source
|
||||
* `:without_theme` - a theme id; only endgames not linked to the theme at all
|
||||
"""
|
||||
def list_key_groups(filters \\ %{}) do
|
||||
Endgame
|
||||
@@ -113,20 +130,31 @@ defmodule Chesstrainer.Endgames do
|
||||
|
||||
@doc """
|
||||
Returns the endgames for one Key, matching the filters, with themes preloaded.
|
||||
|
||||
Accepts `:limit` and `:offset` options for paginating large Key groups.
|
||||
"""
|
||||
def list_endgames_for_key(key, filters \\ %{}) do
|
||||
def list_endgames_for_key(key, filters \\ %{}, opts \\ []) do
|
||||
skip = Keyword.get(opts, :offset, 0)
|
||||
|
||||
Endgame
|
||||
|> apply_filters(filters)
|
||||
|> where([e], e.key == ^key)
|
||||
|> preload(:themes)
|
||||
|> order_by([e], asc: e.fen)
|
||||
|> order_by([e], asc: e.fen, asc: e.id)
|
||||
|> limit_query(Keyword.get(opts, :limit))
|
||||
|> offset(^skip)
|
||||
|> Repo.all()
|
||||
end
|
||||
|
||||
defp limit_query(query, nil), do: query
|
||||
defp limit_query(query, limit), do: limit(query, ^limit)
|
||||
|
||||
defp apply_filters(query, filters) do
|
||||
query
|
||||
|> filter_themes(Map.get(filters, :themes, []))
|
||||
|> filter_key(Map.get(filters, :key))
|
||||
|> filter_with_theme(Map.get(filters, :with_theme))
|
||||
|> filter_without_theme(Map.get(filters, :without_theme))
|
||||
end
|
||||
|
||||
defp filter_themes(query, []), do: query
|
||||
@@ -144,6 +172,30 @@ defmodule Chesstrainer.Endgames do
|
||||
defp filter_key(query, key) when key in [nil, ""], do: query
|
||||
defp filter_key(query, key), do: where(query, [e], e.key == ^key)
|
||||
|
||||
defp filter_with_theme(query, nil), do: query
|
||||
|
||||
defp filter_with_theme(query, {theme_id, source}) do
|
||||
endgame_ids =
|
||||
from(t in "endgames_themes",
|
||||
where: t.theme_id == ^theme_id and t.source == ^to_string(source),
|
||||
select: t.endgame_id
|
||||
)
|
||||
|
||||
where(query, [e], e.id in subquery(endgame_ids))
|
||||
end
|
||||
|
||||
defp filter_without_theme(query, nil), do: query
|
||||
|
||||
defp filter_without_theme(query, theme_id) do
|
||||
endgame_ids =
|
||||
from(t in "endgames_themes",
|
||||
where: t.theme_id == ^theme_id,
|
||||
select: t.endgame_id
|
||||
)
|
||||
|
||||
where(query, [e], e.id not in subquery(endgame_ids))
|
||||
end
|
||||
|
||||
@doc """
|
||||
Gets a single endgame.
|
||||
|
||||
|
||||
@@ -0,0 +1,218 @@
|
||||
defmodule Chesstrainer.Endgames.BulkImport do
|
||||
@moduledoc """
|
||||
Classifies pasted FENs for the admin bulk importer and inserts the positions
|
||||
the local Syzygy tablebase can answer.
|
||||
|
||||
Results always come from `Chesstrainer.Endgames.Tablebase.probe_local_result/1`,
|
||||
so a bulk import never consults the remote (Lichess) backend.
|
||||
"""
|
||||
|
||||
import Ecto.Query, warn: false
|
||||
|
||||
alias Chesstrainer.Endgames.Endgame
|
||||
alias Chesstrainer.Endgames.Tablebase
|
||||
alias Chesstrainer.{FEN, Key, Repo}
|
||||
|
||||
@max_fens 1000
|
||||
@max_pieces 5
|
||||
@default_rating 1500.0
|
||||
|
||||
@type status ::
|
||||
:ready
|
||||
| :duplicate
|
||||
| :invalid_fen
|
||||
| :too_many_pieces
|
||||
| :illegal
|
||||
| :terminal
|
||||
| :unsupported
|
||||
|
||||
@type entry :: %{
|
||||
line: pos_integer(),
|
||||
fen: String.t(),
|
||||
key: String.t() | nil,
|
||||
color: :white | :black | nil,
|
||||
result: Tablebase.result() | nil,
|
||||
status: status(),
|
||||
reason: String.t() | nil
|
||||
}
|
||||
|
||||
@doc """
|
||||
The most FENs a single import will consider.
|
||||
"""
|
||||
@spec max_fens() :: pos_integer()
|
||||
def max_fens, do: @max_fens
|
||||
|
||||
@doc """
|
||||
Parses one FEN per line, skipping blank lines and lines beginning with `#`.
|
||||
|
||||
Returns entries with a status explaining whether the line can be imported,
|
||||
and `too_many?` when the input exceeded `max_fens/0` (only the first
|
||||
`max_fens/0` lines are considered).
|
||||
|
||||
FENs already in the database and duplicates within the batch are reported as
|
||||
duplicates without probing the tablebase.
|
||||
"""
|
||||
@spec preview(String.t()) :: %{entries: [entry()], too_many?: boolean()}
|
||||
def preview(text) when is_binary(text) do
|
||||
lines = parse_lines(text)
|
||||
{lines, rest} = Enum.split(lines, @max_fens)
|
||||
|
||||
fens = Enum.map(lines, fn {_line, fen} -> FEN.normalize(fen) end)
|
||||
existing = existing_fens(fens)
|
||||
|
||||
{entries, _seen} =
|
||||
Enum.map_reduce(lines, %{}, fn {line, raw_fen}, seen ->
|
||||
classify(line, FEN.normalize(raw_fen), seen, existing)
|
||||
end)
|
||||
|
||||
%{entries: entries, too_many?: rest != []}
|
||||
end
|
||||
|
||||
@doc """
|
||||
Inserts every `:ready` entry, attaching `themes` and `rating` to each.
|
||||
|
||||
Rows that collide with an existing FEN are skipped. Returns the number
|
||||
imported and the number of entries that were not ready or were skipped.
|
||||
"""
|
||||
@spec commit([entry()], [Chesstrainer.Themes.Theme.t()], number()) ::
|
||||
%{imported: non_neg_integer(), skipped: non_neg_integer()}
|
||||
def commit(entries, themes \\ [], rating \\ @default_rating) do
|
||||
ready = Enum.filter(entries, &(&1.status == :ready))
|
||||
now = DateTime.utc_now() |> DateTime.truncate(:second)
|
||||
|
||||
rows =
|
||||
Enum.map(ready, fn entry ->
|
||||
%{
|
||||
id: Ecto.UUID.generate(),
|
||||
public_code: Endgame.generate_public_code(),
|
||||
fen: entry.fen,
|
||||
color: entry.color,
|
||||
key: entry.key,
|
||||
result: entry.result,
|
||||
rating: (rating || @default_rating) * 1.0,
|
||||
rating_deviation: 350.0,
|
||||
times_attempted: 0,
|
||||
times_solved: 0,
|
||||
inserted_at: now,
|
||||
updated_at: now
|
||||
}
|
||||
end)
|
||||
|
||||
{imported, inserted_rows} =
|
||||
Repo.insert_all(Endgame, rows, on_conflict: :nothing, returning: [:id])
|
||||
|
||||
join_rows =
|
||||
for %Endgame{id: id} <- inserted_rows, theme <- themes do
|
||||
%{
|
||||
endgame_id: Ecto.UUID.dump!(id),
|
||||
theme_id: theme.id
|
||||
}
|
||||
end
|
||||
|
||||
if join_rows != [] do
|
||||
Repo.insert_all("endgames_themes", join_rows, on_conflict: :nothing)
|
||||
end
|
||||
|
||||
%{imported: imported, skipped: length(entries) - imported}
|
||||
end
|
||||
|
||||
defp parse_lines(text) do
|
||||
text
|
||||
|> String.split(~r/\r?\n/)
|
||||
|> Enum.with_index(1)
|
||||
|> Enum.reduce([], fn {raw, index}, acc ->
|
||||
trimmed = String.trim(raw)
|
||||
|
||||
if trimmed == "" or String.starts_with?(trimmed, "#") do
|
||||
acc
|
||||
else
|
||||
[{index, trimmed} | acc]
|
||||
end
|
||||
end)
|
||||
|> Enum.reverse()
|
||||
end
|
||||
|
||||
defp existing_fens(fens) do
|
||||
fens
|
||||
|> Enum.uniq()
|
||||
|> then(fn fens -> Repo.all(from e in Endgame, where: e.fen in ^fens, select: e.fen) end)
|
||||
|> Map.new(&{&1, true})
|
||||
end
|
||||
|
||||
defp classify(line, fen, seen, existing) do
|
||||
cond do
|
||||
Map.has_key?(seen, fen) ->
|
||||
{entry(line, fen, :duplicate, "Duplicate FEN in this batch"), seen}
|
||||
|
||||
Map.has_key?(existing, fen) ->
|
||||
{entry(line, fen, :duplicate, "FEN already exists"), seen}
|
||||
|
||||
true ->
|
||||
{classify_new(line, fen), Map.put(seen, fen, true)}
|
||||
end
|
||||
end
|
||||
|
||||
defp classify_new(line, fen) do
|
||||
issues = Endgame.fen_issues(fen)
|
||||
pieces = FEN.piece_count(fen)
|
||||
|
||||
cond do
|
||||
issues != [] ->
|
||||
entry(line, fen, :invalid_fen, Enum.join(issues, "; "))
|
||||
|
||||
is_integer(pieces) and pieces > @max_pieces ->
|
||||
entry(
|
||||
line,
|
||||
fen,
|
||||
:too_many_pieces,
|
||||
"Only positions with #{@max_pieces} or fewer pieces are supported"
|
||||
)
|
||||
|
||||
true ->
|
||||
classify_probe(line, fen)
|
||||
end
|
||||
end
|
||||
|
||||
defp classify_probe(line, fen) do
|
||||
case Tablebase.probe_local_result(fen) do
|
||||
{:ok, result} ->
|
||||
entry(line, fen, :ready, nil) |> Map.put(:result, result)
|
||||
|
||||
{:error, :terminal} ->
|
||||
entry(line, fen, :terminal, "Checkmate, stalemate, or no legal moves")
|
||||
|
||||
{:error, :illegal} ->
|
||||
entry(line, fen, :illegal, "The tablebase rejected this position")
|
||||
|
||||
{:error, :not_configured} ->
|
||||
entry(
|
||||
line,
|
||||
fen,
|
||||
:unsupported,
|
||||
"Local tablebase is not configured (set TABLEBASE_PATH)"
|
||||
)
|
||||
|
||||
{:error, :unsupported} ->
|
||||
entry(line, fen, :unsupported, "The local tablebase cannot answer this position")
|
||||
end
|
||||
end
|
||||
|
||||
defp entry(line, fen, status, reason) do
|
||||
%{
|
||||
line: line,
|
||||
fen: fen,
|
||||
key: key_for(fen),
|
||||
color: FEN.color_from_fen(fen),
|
||||
result: nil,
|
||||
status: status,
|
||||
reason: reason
|
||||
}
|
||||
end
|
||||
|
||||
defp key_for(fen) do
|
||||
case Key.from_fen(fen) do
|
||||
{:ok, key} -> key
|
||||
_ -> nil
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -90,10 +90,15 @@ defmodule Chesstrainer.Endgames.Endgame do
|
||||
|
||||
defp normalize_attrs(attrs), do: attrs
|
||||
|
||||
# Strict structural validation. Mirrors chess.js rules so the FEN survives
|
||||
# both the server-side parser (Chex, permissive) and the client-side parser
|
||||
# (chess.js, strict).
|
||||
defp fen_issues(fen) do
|
||||
@doc """
|
||||
Returns the structural problems with a FEN, or `[]` when it is well formed.
|
||||
|
||||
Strict structural validation. Mirrors chess.js rules so the FEN survives
|
||||
both the server-side parser (Chex, permissive) and the client-side parser
|
||||
(chess.js, strict). Used by the admin bulk importer to explain why a line
|
||||
was rejected.
|
||||
"""
|
||||
def fen_issues(fen) do
|
||||
case String.split(fen, " ") do
|
||||
[board, active, _castling, _en_passant, halfmove, fullmove] ->
|
||||
board_valid? = valid_board?(board)
|
||||
|
||||
@@ -0,0 +1,215 @@
|
||||
defmodule Chesstrainer.Endgames.MaterialThemes do
|
||||
@moduledoc """
|
||||
Derives each endgame's material family from its canonical Key.
|
||||
|
||||
Every endgame belongs to exactly one family, so the themes behave as a
|
||||
partition: selecting several in a filter produces their union, never an
|
||||
ambiguous intersection. A lone king against heavy or pawn material is split
|
||||
out because those positions teach a specific technique — basic mate or
|
||||
promotion — rather than a general material class.
|
||||
|
||||
Families are derived, never judged. They are stored with source `derived`, so
|
||||
a refresh replaces them without touching curated or community themes.
|
||||
Positions with no legal content (`K v K`) and rows without a Key are skipped.
|
||||
"""
|
||||
|
||||
import Ecto.Query, warn: false
|
||||
|
||||
alias Chesstrainer.Endgames.Endgame
|
||||
alias Chesstrainer.Repo
|
||||
alias Chesstrainer.Themes
|
||||
|
||||
@families [
|
||||
basic_mate: %{
|
||||
name: "basic mate",
|
||||
description:
|
||||
"A lone king against the queen or a rook, with no pawns: the puzzle is about delivering mate."
|
||||
},
|
||||
king_and_pawn: %{
|
||||
name: "king and pawn",
|
||||
description:
|
||||
"A lone king against king and pawns: the puzzle is about promotion, or holding the draw."
|
||||
},
|
||||
bare_king_other: %{
|
||||
name: "bare king other",
|
||||
description:
|
||||
"A lone king against minor pieces, or against pawns and pieces: usually a technique exercise with little counterplay."
|
||||
},
|
||||
queen_and_pawn: %{
|
||||
name: "queen and pawn",
|
||||
description: "Queens and pawns on the board."
|
||||
},
|
||||
queen_endgame: %{
|
||||
name: "queen endgame",
|
||||
description: "Queens on the board, with no pawns."
|
||||
},
|
||||
rook_and_pawn: %{
|
||||
name: "rook and pawn",
|
||||
description: "Rooks and pawns, with no queens."
|
||||
},
|
||||
rook_endgame: %{
|
||||
name: "rook endgame",
|
||||
description: "Rooks, with no queens and no pawns."
|
||||
},
|
||||
minor_piece_and_pawn: %{
|
||||
name: "minor piece and pawn",
|
||||
description: "Bishops and knights with pawns, with no queens or rooks."
|
||||
},
|
||||
minor_piece_endgame: %{
|
||||
name: "minor piece endgame",
|
||||
description: "Bishops and knights, with no queens, rooks or pawns."
|
||||
},
|
||||
pawn_endgame: %{
|
||||
name: "pawn endgame",
|
||||
description: "Kings and pawns only."
|
||||
}
|
||||
]
|
||||
|
||||
@type family ::
|
||||
:basic_mate
|
||||
| :king_and_pawn
|
||||
| :bare_king_other
|
||||
| :queen_and_pawn
|
||||
| :queen_endgame
|
||||
| :rook_and_pawn
|
||||
| :rook_endgame
|
||||
| :minor_piece_and_pawn
|
||||
| :minor_piece_endgame
|
||||
| :pawn_endgame
|
||||
|
||||
@doc "The material families, in a stable order."
|
||||
def families, do: @families
|
||||
|
||||
@doc """
|
||||
Returns the material family for a Key.
|
||||
|
||||
Returns `:kings_only` for `"K v K"` and `:unknown` when the Key is missing or
|
||||
not shaped like `"<side> v <side>"`.
|
||||
"""
|
||||
@spec family(String.t() | nil) :: family() | :kings_only | :unknown
|
||||
def family(key) when is_binary(key) do
|
||||
case String.split(key, " v ") do
|
||||
[a, b] ->
|
||||
cond do
|
||||
bare?(a) and bare?(b) -> :kings_only
|
||||
bare?(a) -> bare_king_family(counts(b))
|
||||
bare?(b) -> bare_king_family(counts(a))
|
||||
true -> material_family(merge(counts(a), counts(b)))
|
||||
end
|
||||
|
||||
_ ->
|
||||
:unknown
|
||||
end
|
||||
end
|
||||
|
||||
def family(_key), do: :unknown
|
||||
|
||||
@doc """
|
||||
Creates or corrects the material themes, keyed by family.
|
||||
|
||||
An existing theme with the same name is reused and its kind and description
|
||||
are corrected, so a theme seeded as a technique becomes a material theme
|
||||
without losing its existing links.
|
||||
"""
|
||||
@spec ensure_themes() :: %{family() => Chesstrainer.Themes.Theme.t()}
|
||||
def ensure_themes do
|
||||
Map.new(@families, fn {family, attrs} ->
|
||||
{:ok, theme} = Themes.get_or_create(attrs.name, "endgame", kind: :material)
|
||||
{family, ensure_material_theme(theme, attrs)}
|
||||
end)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Refreshes every endgame's derived material theme.
|
||||
|
||||
Returns the number of endgames tagged, the number skipped (kings only or no
|
||||
Key) and the number of material themes. Re-running is idempotent.
|
||||
"""
|
||||
@spec derive() :: %{
|
||||
tagged: non_neg_integer(),
|
||||
skipped: non_neg_integer(),
|
||||
themes: non_neg_integer()
|
||||
}
|
||||
def derive do
|
||||
themes = ensure_themes()
|
||||
material_ids = Enum.map(themes, fn {_family, theme} -> theme.id end)
|
||||
|
||||
{links, skipped} =
|
||||
Endgame
|
||||
|> select([e], {e.id, e.key})
|
||||
|> Repo.all()
|
||||
|> Enum.reduce({[], 0}, fn {id, key}, {links, skipped} ->
|
||||
case family(key) do
|
||||
family when family in [:kings_only, :unknown] ->
|
||||
{links, skipped + 1}
|
||||
|
||||
family ->
|
||||
{[{id, Map.fetch!(themes, family).id} | links], skipped}
|
||||
end
|
||||
end)
|
||||
|
||||
:ok = Themes.replace_theme_links(material_ids, links)
|
||||
|
||||
%{tagged: length(links), skipped: skipped, themes: map_size(themes)}
|
||||
end
|
||||
|
||||
defp ensure_material_theme(theme, attrs) do
|
||||
if theme.kind == :material and (theme.description || "") == attrs.description do
|
||||
theme
|
||||
else
|
||||
{:ok, updated} =
|
||||
Themes.update_theme(theme, %{kind: :material, description: attrs.description})
|
||||
|
||||
updated
|
||||
end
|
||||
end
|
||||
|
||||
defp bare?(side), do: side == "K"
|
||||
|
||||
defp bare_king_family(counts) do
|
||||
cond do
|
||||
count(counts, "P") == 0 and (count(counts, "Q") > 0 or count(counts, "R") > 0) ->
|
||||
:basic_mate
|
||||
|
||||
count(counts, "P") > 0 and count(counts, "Q") == 0 and count(counts, "R") == 0 ->
|
||||
:king_and_pawn
|
||||
|
||||
true ->
|
||||
:bare_king_other
|
||||
end
|
||||
end
|
||||
|
||||
defp material_family(counts) do
|
||||
cond do
|
||||
count(counts, "Q") > 0 and count(counts, "P") > 0 ->
|
||||
:queen_and_pawn
|
||||
|
||||
count(counts, "Q") > 0 ->
|
||||
:queen_endgame
|
||||
|
||||
count(counts, "R") > 0 and count(counts, "P") > 0 ->
|
||||
:rook_and_pawn
|
||||
|
||||
count(counts, "R") > 0 ->
|
||||
:rook_endgame
|
||||
|
||||
count(counts, "B") + count(counts, "N") > 0 and count(counts, "P") > 0 ->
|
||||
:minor_piece_and_pawn
|
||||
|
||||
count(counts, "B") + count(counts, "N") > 0 ->
|
||||
:minor_piece_endgame
|
||||
|
||||
count(counts, "P") > 0 ->
|
||||
:pawn_endgame
|
||||
|
||||
true ->
|
||||
:kings_only
|
||||
end
|
||||
end
|
||||
|
||||
defp counts(side), do: Enum.frequencies(String.graphemes(side))
|
||||
|
||||
defp merge(left, right), do: Map.merge(left, right, fn _piece, a, b -> a + b end)
|
||||
|
||||
defp count(counts, piece), do: Map.get(counts, piece, 0)
|
||||
end
|
||||
@@ -0,0 +1,198 @@
|
||||
defmodule Chesstrainer.Endgames.MotifThemes do
|
||||
@moduledoc """
|
||||
Derives objective motif themes by probing each endgame's position.
|
||||
|
||||
Motifs describe the kind of problem, independent of the material family: an
|
||||
endgame can be a rook endgame and an only-move puzzle at the same time. Every
|
||||
motif is proved from the local Syzygy tables — one probe returns the root WDL,
|
||||
the DTZ and every legal move with its own WDL — so nothing here is a guess and
|
||||
nothing calls the remote backend.
|
||||
|
||||
Motif links are recorded as `derived` and refreshed as a whole. Material
|
||||
families, curated links and community links are untouched because the refresh
|
||||
is scoped to the motif themes.
|
||||
|
||||
Loss endgames are skipped: only-move is undefined when every move loses, and
|
||||
the library no longer contains them.
|
||||
"""
|
||||
|
||||
import Ecto.Query, warn: false
|
||||
|
||||
alias Chesstrainer.Endgames.Endgame
|
||||
alias Chesstrainer.Endgames.Tablebase
|
||||
alias Chesstrainer.Endgames.Tablebase.Backend.Fathom, as: FathomBackend
|
||||
alias Chesstrainer.Repo
|
||||
alias Chesstrainer.Themes
|
||||
|
||||
@motifs [
|
||||
only_move: %{
|
||||
name: "only move",
|
||||
description:
|
||||
"Exactly one legal move keeps the result, so the puzzle is about finding the single accurate move."
|
||||
},
|
||||
underpromotion: %{
|
||||
name: "underpromotion",
|
||||
description:
|
||||
"The result can only be preserved by promoting to a rook, bishop or knight; promoting to a queen does not work."
|
||||
},
|
||||
fifty_move_draw: %{
|
||||
name: "50-move draw",
|
||||
description:
|
||||
"The result turns on the fifty-move rule: the win needs more moves than the halfmove clock allows, so the defender can claim a draw."
|
||||
}
|
||||
]
|
||||
|
||||
@type motif :: :only_move | :underpromotion | :fifty_move_draw
|
||||
|
||||
@doc "The motif themes, in a stable order."
|
||||
def motifs, do: @motifs
|
||||
|
||||
@doc """
|
||||
Returns the motifs for one probed position.
|
||||
|
||||
`moves` are Fathom move tuples `{wdl, from, to, promotes, ep, dtz}` and carry
|
||||
the mover's perspective, so they are compared with the root WDL directly.
|
||||
`halfmove_clock` comes from the FEN; the probe itself runs with `rule50 = 0`.
|
||||
"""
|
||||
@spec motifs_for(atom(), integer() | nil, [tuple()], non_neg_integer()) :: [motif()]
|
||||
def motifs_for(wdl, dtz, moves, halfmove_clock) do
|
||||
outcome = Tablebase.normalize_wdl(wdl)
|
||||
|
||||
preserving =
|
||||
Enum.filter(moves, fn {move_wdl, _from, _to, _promotes, _ep, _dtz} ->
|
||||
Tablebase.normalize_wdl(move_wdl) == outcome
|
||||
end)
|
||||
|
||||
[]
|
||||
|> maybe_only_move(outcome, moves, preserving)
|
||||
|> maybe_underpromotion(preserving)
|
||||
|> maybe_fifty_move(wdl, dtz, halfmove_clock)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Creates or corrects the motif themes, keyed by motif.
|
||||
|
||||
An existing theme with the same name is reused and its kind and description
|
||||
are corrected, so a theme seeded as a technique becomes a motif without
|
||||
losing its existing links.
|
||||
"""
|
||||
@spec ensure_themes() :: %{motif() => Chesstrainer.Themes.Theme.t()}
|
||||
def ensure_themes do
|
||||
Map.new(@motifs, fn {motif, attrs} ->
|
||||
{:ok, theme} = Themes.get_or_create(attrs.name, "endgame", kind: :motif)
|
||||
{motif, ensure_motif_theme(theme, attrs)}
|
||||
end)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Refreshes every endgame's derived motif links.
|
||||
|
||||
Returns the number of links written, the number of endgames skipped because
|
||||
the local tables could not answer them, and a count per motif. Re-running is
|
||||
idempotent.
|
||||
"""
|
||||
@spec derive() :: %{
|
||||
links: non_neg_integer(),
|
||||
skipped: non_neg_integer(),
|
||||
by_motif: %{motif() => non_neg_integer()},
|
||||
themes: non_neg_integer()
|
||||
}
|
||||
def derive do
|
||||
themes = ensure_themes()
|
||||
motif_ids = Enum.map(themes, fn {_motif, theme} -> theme.id end)
|
||||
|
||||
initial_counts = Map.new(@motifs, fn {motif, _attrs} -> {motif, 0} end)
|
||||
|
||||
{links, skipped, by_motif} =
|
||||
Endgame
|
||||
|> where([e], e.result in [:win, :draw])
|
||||
|> select([e], {e.id, e.fen})
|
||||
|> Repo.all()
|
||||
|> Enum.reduce({[], 0, initial_counts}, fn {id, fen}, {links, skipped, counts} ->
|
||||
case probe(fen) do
|
||||
{:ok, %{wdl: wdl, dtz: dtz, moves: moves}} ->
|
||||
motifs = motifs_for(wdl, dtz, moves, halfmove_clock(fen))
|
||||
|
||||
links =
|
||||
Enum.reduce(motifs, links, fn motif, acc ->
|
||||
[{id, Map.fetch!(themes, motif).id} | acc]
|
||||
end)
|
||||
|
||||
counts =
|
||||
Enum.reduce(motifs, counts, fn motif, acc ->
|
||||
Map.update!(acc, motif, &(&1 + 1))
|
||||
end)
|
||||
|
||||
{links, skipped, counts}
|
||||
|
||||
{:error, _reason} ->
|
||||
{links, skipped + 1, counts}
|
||||
end
|
||||
end)
|
||||
|
||||
:ok = Themes.replace_theme_links(motif_ids, links)
|
||||
|
||||
%{links: length(links), skipped: skipped, by_motif: by_motif, themes: map_size(themes)}
|
||||
end
|
||||
|
||||
defp ensure_motif_theme(theme, attrs) do
|
||||
if theme.kind == :motif and (theme.description || "") == attrs.description do
|
||||
theme
|
||||
else
|
||||
{:ok, updated} =
|
||||
Themes.update_theme(theme, %{kind: :motif, description: attrs.description})
|
||||
|
||||
updated
|
||||
end
|
||||
end
|
||||
|
||||
defp probe(fen), do: probe_module().probe_local_detail(fen)
|
||||
|
||||
defp probe_module do
|
||||
Application.get_env(:chesstrainer, :motif_probe, FathomBackend)
|
||||
end
|
||||
|
||||
defp maybe_only_move(acc, outcome, moves, preserving) do
|
||||
if outcome in [:win, :draw] and length(moves) > 1 and length(preserving) == 1 do
|
||||
[:only_move | acc]
|
||||
else
|
||||
acc
|
||||
end
|
||||
end
|
||||
|
||||
defp maybe_underpromotion(acc, preserving) do
|
||||
underpromotes? =
|
||||
Enum.any?(preserving, fn {_wdl, _from, _to, promotes, _ep, _dtz} ->
|
||||
promotes in [2, 3, 4]
|
||||
end)
|
||||
|
||||
queen_promotes? =
|
||||
Enum.any?(preserving, fn {_wdl, _from, _to, promotes, _ep, _dtz} ->
|
||||
promotes == 1
|
||||
end)
|
||||
|
||||
if underpromotes? and not queen_promotes?, do: [:underpromotion | acc], else: acc
|
||||
end
|
||||
|
||||
defp maybe_fifty_move(acc, wdl, dtz, halfmove_clock) do
|
||||
table_draw? = wdl in [:cursed_win, :blessed_loss]
|
||||
|
||||
clock_exhausted? =
|
||||
wdl == :win and is_integer(dtz) and dtz > 100 - halfmove_clock
|
||||
|
||||
if table_draw? or clock_exhausted?, do: [:fifty_move_draw | acc], else: acc
|
||||
end
|
||||
|
||||
defp halfmove_clock(fen) do
|
||||
case String.split(fen, " ") do
|
||||
[_board, _active, _castling, _ep, clock, _fullmove] ->
|
||||
case Integer.parse(clock) do
|
||||
{value, _rest} -> value
|
||||
:error -> 0
|
||||
end
|
||||
|
||||
_ ->
|
||||
0
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -12,6 +12,7 @@ defmodule Chesstrainer.Endgames.Tablebase do
|
||||
"""
|
||||
|
||||
alias Chesstrainer.Endgames.Tablebase
|
||||
alias Chesstrainer.Endgames.Tablebase.Backend.Fathom, as: FathomBackend
|
||||
alias Chesstrainer.FEN
|
||||
|
||||
@type result :: :win | :draw | :loss | :unknown
|
||||
@@ -67,6 +68,19 @@ defmodule Chesstrainer.Endgames.Tablebase do
|
||||
def flip(:draw), do: :draw
|
||||
def flip(_outcome), do: :unknown
|
||||
|
||||
@doc """
|
||||
Probes a FEN using only the local Syzygy tablebase and returns the result
|
||||
from the side-to-move's perspective.
|
||||
|
||||
Unlike `new/1` this never falls back to the remote backend and never reads or
|
||||
writes the cache. It is the primitive behind the admin bulk importer, so an
|
||||
imported result always comes from our own tablebases.
|
||||
"""
|
||||
@spec probe_local_result(String.t()) ::
|
||||
{:ok, result()}
|
||||
| {:error, :not_configured | :illegal | :terminal | :unsupported}
|
||||
def probe_local_result(fen), do: FathomBackend.probe_result_local(fen)
|
||||
|
||||
@spec new(String.t()) ::
|
||||
{:ok, t()}
|
||||
| {:cooldown, non_neg_integer()}
|
||||
|
||||
@@ -18,6 +18,7 @@ defmodule Chesstrainer.Endgames.Tablebase.Backend.Fathom do
|
||||
alias Chesstrainer.Endgames.Tablebase.Local
|
||||
alias Chesstrainer.Endgames.Tablebase.Move
|
||||
alias Chesstrainer.Endgames.Tablebase.San
|
||||
alias Chesstrainer.FEN
|
||||
|
||||
@impl true
|
||||
def probe(fen) do
|
||||
@@ -32,6 +33,85 @@ defmodule Chesstrainer.Endgames.Tablebase.Backend.Fathom do
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Probes the local tablebase without the remote fallback and returns only the
|
||||
position's result.
|
||||
|
||||
Used by the admin bulk importer, which must never import a result from
|
||||
Lichess. The result is from the side-to-move's perspective, matching the
|
||||
`category` on `Chesstrainer.Endgames.Tablebase`.
|
||||
|
||||
Returns `{:error, :terminal}` for checkmate, stalemate, and positions with no
|
||||
legal moves, because they cannot be played as puzzles.
|
||||
"""
|
||||
@spec probe_result_local(String.t()) ::
|
||||
{:ok, Tablebase.result()}
|
||||
| {:error, :not_configured | :illegal | :terminal | :unsupported}
|
||||
def probe_result_local(fen) do
|
||||
with {:ok, largest} <- Local.check(),
|
||||
pieces when is_integer(pieces) <- FEN.piece_count(fen),
|
||||
true <- pieces <= largest || {:error, :unsupported},
|
||||
{:ok, {root, moves}} <- Nif.probe(fen) do
|
||||
case root do
|
||||
:failed ->
|
||||
{:error, :illegal}
|
||||
|
||||
:checkmate ->
|
||||
{:error, :terminal}
|
||||
|
||||
:stalemate ->
|
||||
{:error, :terminal}
|
||||
|
||||
{wdl, _from, _to, _promotes, _ep, _dtz} ->
|
||||
if moves == [] do
|
||||
{:error, :terminal}
|
||||
else
|
||||
case Tablebase.normalize_wdl(wdl) do
|
||||
:unknown -> {:error, :unsupported}
|
||||
category -> {:ok, category}
|
||||
end
|
||||
end
|
||||
end
|
||||
else
|
||||
{:error, :not_configured} = error -> error
|
||||
{:error, :unsupported} = error -> error
|
||||
{:error, _reason} -> {:error, :unsupported}
|
||||
nil -> {:error, :unsupported}
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Probes the local tablebase and returns the raw root outcome and move list.
|
||||
|
||||
Unlike `probe_result_local/1`, this keeps the per-move tuples and the raw WDL
|
||||
atom, including `:cursed_win` and `:blessed_loss`, which the motif derivation
|
||||
needs. It never falls back to the remote backend or consults the cache.
|
||||
|
||||
Returns `{:error, :unsupported}` when the local files cannot answer the
|
||||
position, including a partial tablebase set where Fathom reports `:failed`.
|
||||
"""
|
||||
@spec probe_local_detail(String.t()) ::
|
||||
{:ok, %{wdl: atom(), dtz: integer(), moves: [tuple()]}}
|
||||
| {:error, :not_configured | :terminal | :unsupported}
|
||||
def probe_local_detail(fen) do
|
||||
with {:ok, largest} <- Local.check(),
|
||||
pieces when is_integer(pieces) <- FEN.piece_count(fen),
|
||||
true <- pieces <= largest || {:error, :unsupported},
|
||||
{:ok, {root, moves}} <- Nif.probe(fen) do
|
||||
case root do
|
||||
:failed -> {:error, :unsupported}
|
||||
:checkmate -> {:error, :terminal}
|
||||
:stalemate -> {:error, :terminal}
|
||||
{wdl, _from, _to, _promotes, _ep, dtz} -> {:ok, %{wdl: wdl, dtz: dtz, moves: moves}}
|
||||
end
|
||||
else
|
||||
{:error, :not_configured} = error -> error
|
||||
{:error, :unsupported} = error -> error
|
||||
{:error, _reason} -> {:error, :unsupported}
|
||||
nil -> {:error, :unsupported}
|
||||
end
|
||||
end
|
||||
|
||||
defp fallback(fen) do
|
||||
(Application.get_env(:chesstrainer, :tablebase_fallback) || Lichess).probe(fen)
|
||||
end
|
||||
|
||||
@@ -11,6 +11,8 @@ defmodule Chesstrainer.Endgames.Tablebase.Parser do
|
||||
import Chesstrainer.Ratelimiters
|
||||
alias Chesstrainer.Endgames.Tablebase
|
||||
|
||||
require Logger
|
||||
|
||||
@lichess_tablebase_url "https://tablebase.lichess.ovh/standard?fen="
|
||||
|
||||
@spec from_fen(String.t()) ::
|
||||
@@ -74,6 +76,7 @@ defmodule Chesstrainer.Endgames.Tablebase.Parser do
|
||||
|
||||
# Server errors
|
||||
{:ok, %Req.Response{status: status, body: body}} when status in 500..599 ->
|
||||
Logger.warning("tablebase fetch failed with HTTP #{status}", status: status)
|
||||
{:error, {:server_error, status, body}}
|
||||
|
||||
# Catch‑all for other status codes
|
||||
@@ -82,6 +85,7 @@ defmodule Chesstrainer.Endgames.Tablebase.Parser do
|
||||
|
||||
# Network / client‑side failure
|
||||
{:error, reason} ->
|
||||
Logger.warning("tablebase fetch failed: #{inspect(reason)}", reason: reason)
|
||||
{:error, reason}
|
||||
end
|
||||
end
|
||||
|
||||
@@ -0,0 +1,146 @@
|
||||
defmodule Chesstrainer.GuestLimits do
|
||||
@moduledoc """
|
||||
Daily puzzle budget for anonymous visitors.
|
||||
|
||||
Each visitor gets a fixed number of puzzles per UTC day. Visitors are
|
||||
identified by an HMAC of their client address — the address itself is never
|
||||
stored, logged, or persisted. The digest lives only in ETS, is scoped to the
|
||||
current UTC date, and is swept away when the day rolls over. The HMAC secret
|
||||
is generated at boot, so digests are not stable across restarts.
|
||||
|
||||
Budgets reset for everyone at 00:00 UTC: the date is part of the key, so a
|
||||
new day simply starts a new entry.
|
||||
"""
|
||||
|
||||
use GenServer
|
||||
|
||||
@table :guest_limits
|
||||
@default_limit 5
|
||||
@sweep_interval :timer.minutes(10)
|
||||
|
||||
@typedoc "An IPv4/IPv6 address, or `nil` when the socket has no peer data."
|
||||
@type address :: :inet.ip_address() | nil
|
||||
|
||||
@doc "Starts the limiter."
|
||||
def start_link(opts \\ []), do: GenServer.start_link(__MODULE__, opts, name: __MODULE__)
|
||||
|
||||
@doc """
|
||||
Consumes one puzzle from `address`'s budget for `today`.
|
||||
|
||||
Returns `{:ok, remaining}` with the puzzles left today, or
|
||||
`{:limit_reached, retry_in_ms}` when the budget is spent. A `nil` address is
|
||||
not limited and returns `{:ok, nil}`.
|
||||
"""
|
||||
@spec take(address, Date.t()) ::
|
||||
{:ok, non_neg_integer | nil} | {:limit_reached, non_neg_integer}
|
||||
def take(address, today \\ Date.utc_today()) do
|
||||
GenServer.call(__MODULE__, {:take, address, today})
|
||||
end
|
||||
|
||||
@doc "Clears every budget. Intended for tests."
|
||||
def reset, do: GenServer.call(__MODULE__, :reset)
|
||||
|
||||
@doc """
|
||||
Returns the puzzles left today without consuming one.
|
||||
|
||||
Mirrors `take/2`'s result shape so a caller can show the wall before doing
|
||||
work that would otherwise spend a puzzle.
|
||||
"""
|
||||
@spec remaining(address, Date.t()) ::
|
||||
{:ok, non_neg_integer | nil} | {:limit_reached, non_neg_integer}
|
||||
def remaining(address, today \\ Date.utc_today()) do
|
||||
GenServer.call(__MODULE__, {:remaining, address, today})
|
||||
end
|
||||
|
||||
@doc "The daily puzzle allowance for a guest."
|
||||
def limit, do: config() |> Keyword.get(:limit, @default_limit)
|
||||
|
||||
@doc """
|
||||
Whether to read the client address from `X-Forwarded-For`.
|
||||
|
||||
Enable only behind a proxy that overwrites or appends the header.
|
||||
"""
|
||||
def trust_forwarded_for?, do: config() |> Keyword.get(:trust_forwarded_for, false)
|
||||
|
||||
defp config, do: Application.get_env(:chesstrainer, __MODULE__, [])
|
||||
|
||||
@impl true
|
||||
def init(opts) do
|
||||
:ets.new(@table, [:named_table, :set])
|
||||
Process.send_after(self(), :sweep, @sweep_interval)
|
||||
|
||||
{:ok,
|
||||
%{
|
||||
limit: Keyword.get(opts, :limit, limit()),
|
||||
secret: :crypto.strong_rand_bytes(32)
|
||||
}}
|
||||
end
|
||||
|
||||
@impl true
|
||||
def handle_call({:take, nil, _today}, _from, state), do: {:reply, {:ok, nil}, state}
|
||||
|
||||
def handle_call({:remaining, nil, _today}, _from, state), do: {:reply, {:ok, nil}, state}
|
||||
|
||||
def handle_call({:remaining, address, today}, _from, state) do
|
||||
day = Date.to_gregorian_days(today)
|
||||
key = key(state.secret, day, address)
|
||||
|
||||
case count(key, day) do
|
||||
used when used >= state.limit ->
|
||||
{:reply, {:limit_reached, ms_until_utc_midnight()}, state}
|
||||
|
||||
used ->
|
||||
{:reply, {:ok, state.limit - used}, state}
|
||||
end
|
||||
end
|
||||
|
||||
def handle_call({:take, address, today}, _from, state) do
|
||||
day = Date.to_gregorian_days(today)
|
||||
key = key(state.secret, day, address)
|
||||
|
||||
case count(key, day) do
|
||||
used when used >= state.limit ->
|
||||
{:reply, {:limit_reached, ms_until_utc_midnight()}, state}
|
||||
|
||||
used ->
|
||||
:ets.insert(@table, {key, day, used + 1})
|
||||
{:reply, {:ok, state.limit - used - 1}, state}
|
||||
end
|
||||
end
|
||||
|
||||
def handle_call(:reset, _from, state) do
|
||||
:ets.delete_all_objects(@table)
|
||||
{:reply, :ok, state}
|
||||
end
|
||||
|
||||
@impl true
|
||||
def handle_info(:sweep, state) do
|
||||
sweep(Date.to_gregorian_days(Date.utc_today()))
|
||||
Process.send_after(self(), :sweep, @sweep_interval)
|
||||
{:noreply, state}
|
||||
end
|
||||
|
||||
defp count(key, day) do
|
||||
case :ets.lookup(@table, key) do
|
||||
[{^key, ^day, used}] -> used
|
||||
_ -> 0
|
||||
end
|
||||
end
|
||||
|
||||
defp key(secret, day, address) do
|
||||
:crypto.mac(:hmac, :sha256, secret, [Integer.to_string(day), "|", address_binary(address)])
|
||||
end
|
||||
|
||||
defp address_binary(address) when is_tuple(address), do: :erlang.term_to_binary(address)
|
||||
|
||||
defp sweep(day) do
|
||||
:ets.select_delete(@table, [{{:_, :"$1", :_}, [{:<, :"$1", day}], [true]}])
|
||||
end
|
||||
|
||||
defp ms_until_utc_midnight do
|
||||
now = DateTime.utc_now()
|
||||
midnight = now |> DateTime.to_date() |> Date.add(1) |> DateTime.new!(~T[00:00:00], "Etc/UTC")
|
||||
|
||||
max(DateTime.diff(midnight, now, :millisecond), 0)
|
||||
end
|
||||
end
|
||||
@@ -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
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user