BlueGit

projects-timfalken-com microchess

Files

microchess / web
README.md

Microchess

Self-contained PHP 8.2+ application. Set the document root to this web/ directory. No Composer, Node, build step or files outside this directory are required in production.

Run locally

From the repository root:

php -S 127.0.0.1:8080 -t web web/router.php

Open http://127.0.0.1:8080. You are automatically signed in as test_user_1. Account → Switch to test_user_2 switches accounts. Use a second browser profile or private window for two independent sessions. Test accounts are created on first use, with no fabricated friends or games.

Autologin works with PHP's development server, Apache and PHP-FPM. It requires both a loopback client IP and a localhost/loopback Host header; public domains do not enable test accounts. A previous OAuth session on localhost is replaced with test_user_1; a selected test account remains selected. Do not expose the local development site through a public proxy.

Production

Requirements: PHP 8.2+, PDO SQLite, cURL, mbstring, OpenSSL with elliptic-curve support, writable web/data/, and HTTPS. All application writes (database, SQLite WAL/SHM, sessions and application error log) remain under web/data/. Session contents, games, move histories, invitations, friendships and results are stored in SQLite. The app does not write to a system temporary or session directory.

On the first page request, the app creates web/data/config.php with empty base_url, client_id and client_secret fields if the file does not exist. Existing files are never overwritten. This file is ignored by Git and excluded from deployment with the rest of data/. Fill it in on each server, for example:

<?php
return [
    'base_url' => 'https://your-chess-domain.example',
    'client_id' => 'your-registered-domain.example',
    'client_secret' => 'your-client-secret',
];

Environment equivalents: MICROCHESS_BASE_URL, MICROCHESS_CLIENT_ID, MICROCHESS_CLIENT_SECRET. Empty or missing config fields fall back to these environment variables; populated fields in the file take precedence. The base URL may include a subdirectory and must not have a trailing slash.

Register your client domain and /callback.php (or /subdirectory/callback.php) in the auth service admin. Integration follows the service's integration guide: state validation, server-side code exchange, /api/me validation, session renewal and logout. Credentials and bearer tokens never enter client JavaScript. Provider validation occurs at most once per minute during active use; sessions expire after 24 hours of inactivity (sliding on activity). OAuth itself requires the real registered client credentials to test.

Apache: enable AllowOverride All for this directory so the included .htaccess files deny access to data/, lib/ and tests/, and disable directory listings. Nginx does not read .htaccess; add equivalent deny rules before your PHP location and adjust the prefix if mounted in a subdirectory:

location ~* ^/(data|lib|tests)(/|$) { deny all; }
location ~ /\. { deny all; }
location ~* ^/(README\.md|router\.php)$ { deny all; }

Use a normal PHP-FPM configuration that only executes existing PHP files. Verify that /data/microchess.sqlite, /data/config.php and /lib/bootstrap.php return 403 before putting real data in the app. Only the PHP user should have filesystem write access to data/.

Deploy this directory's contents. Preserve the entire production data/ directory: exclude data/ itself and all descendants from upload and deletion, including config.php, .htaccess, the database and WAL files. The included CI script creates data/ and installs its .htaccess separately before mirroring; do the same when deploying manually. Never upload your development database or tests/artifacts/. The root .gitlab-ci.yml runs PHP syntax, chess/API tests, JavaScript syntax checks and an isolated FTP deployment test before deploying master. Deployments are serialized with a production resource group. FTP credentials are passed to lftp through its password environment variable; FTP TLS certificate verification is disabled for this hosting account, as configured by the owner.

SQLite supports a single application instance with concurrent requests; writes use BEGIN IMMEDIATE, game versions reject stale actions, and invitation acceptance is atomic. Keep the database on local persistent storage. Use SQLite's backup API for live backups; copying just the .sqlite file while WAL is active can miss transactions.

Game behavior

Initial position, viewed from White:

5  k n b r
4  p . . .
3  . . . .
2  . . . P
1  R B N K
   a b c d

White moves first. Pawns move one square, never double-step; there is no castling or en passant. Promotion is mandatory to queen, rook, bishop or knight. The server generates legal moves and checks king safety. Checkmate and stalemate are evaluated after every move. Standard insufficient material positions (bare kings, lone bishop/knight, only bishops on one square color) draw automatically. Threefold repetition and the 50-move rule can be claimed from the game menu, including using an intended legal move; fivefold repetition and 75 moves are automatic, with checkmate taking precedence. A draw can also be offered or the game resigned from your turn's menu.

The top grid includes your moves, incoming challenges and finished games that still need Rematch or Exit. After you request a rematch, that tile moves to the lower grid while you wait. Opponent-turn games and sent challenges are noninteractive in the lower grid. Boards orient toward your color. Polling updates the other player every 2.5 seconds while the tab is visible. No clocks or timeouts are applied to games.

A friend invitation is valid for one month and can be accepted once. Accepting inserts one symmetric friendship; either player can remove it. Direct challenges require friendship. Match links likewise expire after one calendar month and are consumed only by acceptance; dismissing/rejecting the modal preserves the link. An expired link cannot be accepted. Both link types survive the login redirect.

Click an opponent's name above a game to open the same rivalry statistics shown from the friends list. Non-friends can send a friend request; incoming requests appear below the friends list with Accept/Reject controls. Requests persist across sessions, and only the recipient can accept or reject them. Acceptance adds both players to each other's friends lists. Duplicate requests do not create extra entries; accepting a friend invitation link also clears any pending request between those players. Pending requests are included in data exports.

Rematches need both players' agreement and swap colors, keeping the tile ID. Exit hides a completed tile only for that player and disables rematch for both. Historical results remain available for friend statistics, even after removal/re-adding. Account → Export my data (JSON) exports the user's profile, relationships, invitations, games and historical results.

Ratings and matchmaking

Existing and new accounts start at 1200 Elo. Results completed after this update use Elo with K=32 (win 1, draw 0.5, loss 0), rounded to whole points with equal and opposite changes. Past results are preserved without retroactive rating changes. All completed games count, including friend challenges, match links and rematches. Stopped unfinished games do not count. Ratings and a per-result ledger are written in the same transaction as the result; rematches reuse a tile but get their own result and rating change. Ratings appear in the account summary, friends list and opponent headers, and rating history is included in data exports.

New game → Challenge a random player adds one persistent search per account, with cancellation and retry after expiry. Searches last 24 hours, including while offline. Joining immediately checks the entire pool; authenticated state requests otherwise trigger a transactionally throttled check at most once per minute. There is no background worker. Each player's allowed difference starts at 100, grows by 50 per elapsed minute and stops at 500. Both players must allow the difference. The oldest search selects its closest eligible opponent (ties prefer older searches), then processing continues through the remaining pool. Pairing creates one active game with random colors and consumes both entries atomically. Expired entries cannot match and display a retry option. A match does not create a friendship.

The integration tests exercise rating updates, rematches, duplicate results, concurrent joins, cancellation, expiry, widening, the maximum difference and whole-pool matching. Browser tests cover joining from below the invite link, persistence after reload, cancellation, automatic game appearance and visible ratings.

Avatars

Click your avatar at the bottom of the friends sidebar to open the piece picker. The local collection contains 103 selected avatars: 67 fairy pieces and 36 colored standard pieces (including White and Black). Removed files are excluded from the catalog; PNG and SVG versions of the same piece appear as one choice. The picker has color/family filters and an option to choose randomly. Accounts without an avatar receive a random piece automatically. Selection is saved in SQLite and appears in friend lists, opponent tile headers and your data export. Click your name under the avatar to choose default or custom piece colours (White/Black/Red/Blue/Green/Yellow); resolved skins are stored per game for live play and replays. Account settings store a “Disable custom colours” preference on your account (default off, so custom colours show). The user_avatars table is created automatically, preserving existing accounts and game data.

Avatars use locally stored PNG previews from Wikimedia Commons; available original SVGs are included alongside them. Author, original file and license links are recorded in avatar credits and assets/avatars/catalog.json. There are no runtime requests to Wikimedia.

Checks

From the repository root:

find web -name '*.php' -not -path '*/artifacts/*' -print0 | xargs -0 -n1 php -l
php web/tests/chess.php
php web/tests/feedback.php
php web/tests/push.php
python3 web/tests/startup.py
python3 web/tests/integration.py
node --check web/assets/app.js
node --check web/assets/pwa.js
node --check web/sw.js
node web/tests/pwa.mjs

Engine tests cover movement, pins, king safety, promotions, endings, draw thresholds and deterministic random games. API tests start an isolated copy under web/tests/artifacts/, covering two sessions, CSRF, invitations, bilateral friendship, turn enforcement, stale actions, rematches, statistics, export and protected paths. They run four PHP workers, verify concurrent link acceptance, remove the isolated copy afterwards and never touch the real database.

Optional real-browser tests (requires Node.js):

npm install --prefix web/tests/artifacts --no-audit --no-fund playwright
PLAYWRIGHT_BROWSERS_PATH="$PWD/web/tests/artifacts/browsers" web/tests/artifacts/node_modules/.bin/playwright install chromium
PLAYWRIGHT_BROWSERS_PATH="$PWD/web/tests/artifacts/browsers" node web/tests/browser.mjs

These cover click, mouse drag, touch drag, promotion, rematch, friendships, desktop and mobile layouts. Screenshots are written under web/tests/artifacts/; the application copy and its database are discarded.

Piece credits

Unmodified Chess_{piece}{l|d}t45.svg images by Cburnett, downloaded from Wikimedia Commons, used under Creative Commons Attribution-ShareAlike 3.0. See asset credits for individual source links. The rules dialog includes visible attribution. The Microchess starting position follows Green Chess.

Inactive games and final positions

Ended games retain the final board and move highlights, with a transparent result bar that becomes readable on hover or keyboard focus. Touch devices show readable controls immediately. After seven days without game activity, either player can confirm removal of both tiles. Existing result history is retained; stopping an unfinished game awards no result. Activity tracking begins at deployment for existing games because earlier move timestamps were not stored.

Move feedback

Move feedback works immediately with the normal local server; no generator, position database, external engine, packages or build step is needed:

php -S 127.0.0.1:8080 -t web web/router.php

After your successfully submitted move, the game tile briefly pulses blue for a clear estimated gain or red for a likely material loss / mating threat. Quiet positions, small differences, drawn endings and inconclusive analysis get no pulse. There is no yellow “perfect move” verdict. The pulse lasts 1.8 seconds during the existing three-second tile pause, appears only to the player who made the move, and does not replay on polling, selection or reload. Reduced-motion users get a temporary static indication.

The bar under the opponent’s name compares remaining material, with White always on the left and Black on the right. Values are pawn 1, knight/bishop 3, rook 5 and queen 9; kings do not contribute. Each color occupies its share of the combined value (e.g. White 10 vs Black 5 gives White two thirds). Bare kings give a neutral 50/50 bar. Captures and promotions update the ratio with a 650 ms transition, including on opponent polling updates; reduced-motion users see the new value immediately. This calculation only counts the twenty board squares in the browser and performs no chess search. Hover or focus the bar for the material totals.

lib/MoveFeedback.php compares material before the move with a short tactical evaluation after it. It considers the opponent's best reply, your response, and up to two additional plies of captures/promotions; checks may extend the search by up to two further evasions. All moves use the same legal move generation, promotion and king-safety rules as the game. Checkmate, stalemate, insufficient material, automatic draws and available draw claims are handled. Claimable positions receive no move-only grade.

Values are pawn 100, knight/bishop 300, rook 500 and queen 900. A change of at least 100 triggers a pulse; visible mating lines also trigger a pulse. Captures are followed through likely recaptures so an equal exchange is not rewarded halfway through. This is a material/tactics estimate, not a best-move ranking, perfect-play verdict or distance-to-mate calculation. It can miss deeper sacrifices, positional improvements and distant threats, and may flag a loss that was already unavoidable.

Analysis runs after the game transaction and session writes finish, with a 200 ms / 8,000-node budget. It never rolls back a saved move. If the budget expires or a check remains unresolved at the search limit, it returns no grade. The compute limit is checked between nodes; operating-system scheduling and network latency are outside it. The API reports the grade, reason, node count and elapsed milliseconds in the move response for local inspection. Polling performs no analysis and transmits no position evaluations.

Previous offline solver code is removed. Any existing .tablebase/ work files and web/lib/tablebase/ data remain untouched and ignored by Git; the app no longer uses them.

Checks:

php web/tests/chess.php
php web/tests/feedback.php
python3 web/tests/integration.py
node web/tests/browser.mjs

The feedback tests cover free and poisoned captures, exchanges, mate, allowing mate, promotion, both colors, draws, budget exhaustion and a small reproducible timing sample. Browser tests exercise real feedback through the API, one-time animation and reduced motion in an isolated application copy.

Saved games

Games newly entering Your turn go to the end of the queue; the ordering survives reloads. The account summary’s hourglass opens finished games, newest first, showing opponent, outcome and end date. Both players retain access after exiting a tile or starting a rematch. Replay uses the same board orientation and tile styling, with jump-to-start, step back, play/pause, step forward and jump-to-end controls. Play/Pause advances every 500 ms. Closing the dialog stops playback. A saved result animates once per player/browser toward the hourglass; reduced-motion preferences suppress motion.

Replays store the initial position plus two binary bytes per ply, including promotions, separately from permanent result/rating statistics. Saved games have no retention limit and are not automatically deleted based on age. Existing finished tiles can be imported when their original color and complete history are still available. Older rematches whose color was overwritten cannot be reconstructed reliably and are not imported. Data exports include available replay positions. No scheduled worker is required.

The replay footer’s chain icon copies a permanent link with an unguessable token. Anyone with that link can view and play back that one game, signed in or not. Shared links open a standalone replay page containing only the tile and playback/share controls, with no modal, close button or surrounding application interface, plus a Microchess link back to the home page. Replay headers identify White and Black with their king icons; transport buttons use jump-to-start, rewind, play/pause, fast-forward and jump-to-end icons with accessible labels. Public replay responses include player names and game positions, not account IDs or private history. Invalid tokens return 404.

Notifications and home-screen installation

Account → Enable turn notifications opts this browser/device in. Notifications cover a new turn (including accepted challenges, match links, matchmaking and rematches), incoming challenges and rematch requests. The service worker skips showing an OS notification when any Microchess tab in that browser is already visible; background/hidden tabs and other devices still notify. Enabling on another device adds that device; disabling affects only the current one. Sign-out removes the current browser's server registration. An existing browser subscription is associated with the current account after signing in or switching accounts. There is a limit of ten subscriptions per account.

Game actions collect notification events inside the game transaction and dispatch only after commit. There is no cronjob, persistent notification queue, polling-based notification scan or background worker. Matchmaking triggered by a state request also dispatches its newly created games. PHP closes the session before sending; with PHP-FPM it finishes the HTTP response first. Other SAPIs may wait for push delivery (two-second connection timeout, five-second request timeout). Delivery failures are logged without endpoints/keys and cannot roll back a move. Expired subscriptions are removed. Failed deliveries are not retried; notifications are best effort. Superseded game versions are skipped before sending, messages expire after one hour, and each game's topic/tag replaces older pending/displayed notifications.

Web Push uses the bundled minishlink/web-push library under lib/push/vendor/, with its licenses and Composer lockfile. Production still needs no Composer or build step. To update the bundled dependencies during development, run composer update --working-dir=web/lib/push --no-dev and commit the lockfile and vendor changes together. The lockfile targets PHP 8.2. The host must allow outgoing HTTPS to browser push services. Subscription endpoints are restricted to supported Google, Mozilla, Apple and Windows push-service hosts; adding a new provider requires extending that allowlist.

The first notification setup automatically generates a VAPID keypair in data/push-keys.json, protected by a file lock and the existing data-directory access rules. Preserve it along with the database during backups and deployment; replacing it invalidates existing browser subscriptions. Private keys never reach JavaScript. Subscription APIs require authentication and CSRF protection.

Notification clicks navigate to ./?game=ID. The regular home screen loads; the game ID survives the sign-in page, OAuth round trip, and expired-session sign-in prompt. Once authenticated games load, the URL parameter is consumed and the corresponding card pulses white/gray three times. Reduced-motion users get a brief static outline. Missing/hidden games show a short message. The service worker reuses an existing app window where possible and never caches pages, API responses or credentials.

The manifest, 192/512-pixel maskable icons and Apple touch icon support installation within any deployment subdirectory. Add to home screen uses the browser's installation prompt when available, otherwise displays platform instructions. On iOS/iPadOS 16.4+, add to the home screen, open that installed app, sign in if needed, and enable notifications there. A closed tab can receive Web Push; delivery with the entire browser stopped depends on OS/browser background support and notification settings.

php web/tests/push.php verifies real VAPID authentication/encryption using an in-memory HTTP transport, expiration cleanup, recipient selection, stale-event suppression and subscription validation in an isolated database. API tests verify event triggers and authorization without contacting push services. Browser tests cover the notification link/highlight, reduced motion and service-worker activation. Actual background delivery and installation should also be checked on an Android device and an iPhone/iPad after deployment.

On first authenticated use, a one-time dialog explains where to enable turn notifications. Its atomic, CSRF-protected claim is stored per account in notification_intro, so simultaneous tabs and other devices do not repeat it. The dialog waits for other dialogs to close and never requests browser permission automatically. Existing accounts receive it once after this update as well.

Notification setup failures open a second dialog above Account. Push-service errors include the Brave settings address and setting name, framed as a possible cause, with alternative network advice. Other failures have permission/setup/save guidance. Closing the error leaves Account open and returns focus to its notification button.