From c250653961c589dc86154d8a705f01162cfdd121 Mon Sep 17 00:00:00 2001 From: wolf_reaper90 Date: Sun, 8 Nov 2026 16:24:06 -0600 Subject: [PATCH] Add comprehensive test suite for application functionality - Implement tests for HTTP API endpoints, ensuring correct responses and security headers. - Create configuration tests to validate loading of defaults and environment overrides. - Add tests for FEDL service to verify data handling and snapshot functionality. - Introduce GitHub service tests to check API data normalization and caching behavior. - Develop monitor service tests for network checks and uptime calculations. - Implement persistence tests to ensure database migrations are idempotent and data persists across restarts. - Add vault service tests for session management and brute-force protection mechanisms. - Include helper functions for test context creation and JSON response handling. --- .env.example | 134 ++++++ .gitignore | 12 +- README.md | 259 ++++++++++-- analytics.js | 53 +++ dashboard.css | 332 +++++++++++++++ dashboard.html | 233 +++++++++++ dashboard.js | 579 ++++++++++++++++++++++++++ docs/API.md | 656 ++++++++++++++++++++++++++++++ docs/DEPLOYMENT.md | 554 +++++++++++++++++++++++++ index.html | 2 + moon-vault.html | 309 +++++--------- package-lock.json | 164 ++++++++ package.json | 22 + projects/script.js | 14 +- robots.txt | 7 +- server/app.js | 447 ++++++++++++++++++++ server/config.js | 269 ++++++++++++ server/config/projects.json | 179 ++++++++ server/config/servers.json | 18 + server/config/services.json | 39 ++ server/db/index.js | 13 + server/db/migrate.js | 43 ++ server/db/migrations/001_init.sql | 117 ++++++ server/db/seed.js | 89 ++++ server/index.js | 136 +++++++ server/lib/cookies.js | 37 ++ server/lib/crypto.js | 48 +++ server/lib/env.js | 40 ++ server/lib/errors.js | 23 ++ server/lib/http.js | 141 +++++++ server/lib/logger.js | 38 ++ server/lib/rate-limit.js | 47 +++ server/lib/static.js | 191 +++++++++ server/lib/validate.js | 63 +++ server/scripts/hash-password.js | 34 ++ server/scripts/migrate.js | 20 + server/scripts/smoke.js | 54 +++ server/services/analytics.js | 152 +++++++ server/services/fedl.js | 296 ++++++++++++++ server/services/github.js | 505 +++++++++++++++++++++++ server/services/http-check.js | 50 +++ server/services/monitor.js | 152 +++++++ server/services/ping.js | 124 ++++++ server/services/status.js | 243 +++++++++++ server/services/vault.js | 167 ++++++++ server/views/vault.html | 154 +++++++ tests/analytics.test.js | 108 +++++ tests/app.test.js | 217 ++++++++++ tests/config.test.js | 78 ++++ tests/fedl.test.js | 122 ++++++ tests/github.test.js | 176 ++++++++ tests/helpers.js | 151 +++++++ tests/monitor.test.js | 163 ++++++++ tests/persistence.test.js | 38 ++ tests/vault.test.js | 88 ++++ 55 files changed, 8174 insertions(+), 226 deletions(-) create mode 100644 .env.example create mode 100644 analytics.js create mode 100644 dashboard.css create mode 100644 dashboard.html create mode 100644 dashboard.js create mode 100644 docs/API.md create mode 100644 docs/DEPLOYMENT.md create mode 100644 package-lock.json create mode 100644 package.json create mode 100644 server/app.js create mode 100644 server/config.js create mode 100644 server/config/projects.json create mode 100644 server/config/servers.json create mode 100644 server/config/services.json create mode 100644 server/db/index.js create mode 100644 server/db/migrate.js create mode 100644 server/db/migrations/001_init.sql create mode 100644 server/db/seed.js create mode 100644 server/index.js create mode 100644 server/lib/cookies.js create mode 100644 server/lib/crypto.js create mode 100644 server/lib/env.js create mode 100644 server/lib/errors.js create mode 100644 server/lib/http.js create mode 100644 server/lib/logger.js create mode 100644 server/lib/rate-limit.js create mode 100644 server/lib/static.js create mode 100644 server/lib/validate.js create mode 100644 server/scripts/hash-password.js create mode 100644 server/scripts/migrate.js create mode 100644 server/scripts/smoke.js create mode 100644 server/services/analytics.js create mode 100644 server/services/fedl.js create mode 100644 server/services/github.js create mode 100644 server/services/http-check.js create mode 100644 server/services/monitor.js create mode 100644 server/services/ping.js create mode 100644 server/services/status.js create mode 100644 server/services/vault.js create mode 100644 server/views/vault.html create mode 100644 tests/analytics.test.js create mode 100644 tests/app.test.js create mode 100644 tests/config.test.js create mode 100644 tests/fedl.test.js create mode 100644 tests/github.test.js create mode 100644 tests/helpers.js create mode 100644 tests/monitor.test.js create mode 100644 tests/persistence.test.js create mode 100644 tests/vault.test.js diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..9a87c63 --- /dev/null +++ b/.env.example @@ -0,0 +1,134 @@ +# milesallen.site dashboard — environment template +# +# Copy this file to .env for local development or deployment, then edit it. +# Never commit .env. .env is gitignored; this template is not. + +# --------------------------------------------------------------------------- +# Runtime +# --------------------------------------------------------------------------- +# Use "production" on a public server. Production requires SESSION_SECRET, +# enables Secure cookies by default, and adds HSTS. +NODE_ENV=production + +# Bind to loopback when Caddy/Cloudflare Tunnel is in front of the app. +# Use 0.0.0.0 only if you intentionally expose the Node server directly. +HOST=127.0.0.1 +PORT=8787 + +# The canonical browser origin. Also used as the default CORS origin. +PUBLIC_ORIGIN=https://milesallen.site + +# Extra cross-origin origins, comma-separated. https://milesallen.site and +# https://www.milesallen.site are always allowed. Same-origin requests from the +# browser's current host are also accepted. +# ALLOWED_ORIGINS=https://milesallen.site,https://www.milesallen.site + +# Set true only when a trusted reverse proxy (Caddy, Cloudflare Tunnel) sets +# CF-Connecting-IP or X-Forwarded-For. Never enable this on a direct public +# listener, because clients could spoof their IP and bypass rate limits. +TRUST_PROXY=true + +# Where the static site lives. Defaults to the process working directory. +# SITE_ROOT=/opt/miles-web + +# SQLite file. Keep it outside the web root if you serve files with another +# web server. The Node app already blocks /data and /server. +DB_PATH=/var/lib/miles-dashboard/dashboard.db + +# --------------------------------------------------------------------------- +# Sessions and Moon Vault +# --------------------------------------------------------------------------- +# Generate with: openssl rand -hex 32 +# Required in production, minimum 32 characters. +SESSION_SECRET= + +# Generate with: npm run hash-password -- "your long passphrase" +# Prefer this over VAULT_PASSWORD. The hash is Argon2id, never the passphrase. +VAULT_PASSWORD_HASH= + +# Optional local-only convenience. Prefer VAULT_PASSWORD_HASH in production. +# VAULT_PASSWORD= + +# Session lifetime in hours (1–720). +VAULT_SESSION_HOURS=12 + +# Failed attempts allowed per IP hash before temporary lockout. +VAULT_MAX_ATTEMPTS=5 +VAULT_ATTEMPT_WINDOW_MINUTES=15 + +VAULT_COOKIE_NAME=miles_vault + +# Defaults to true in production and false in development. Keep true on HTTPS. +# COOKIE_SECURE=true + +# --------------------------------------------------------------------------- +# GitHub (server-side official REST API only) +# --------------------------------------------------------------------------- +GITHUB_USERNAME=mileswolfallen2 + +# A classic token with no scopes is enough for public data and raises the rate +# limit. The token is only used server-side and is never sent to the browser. +GITHUB_TOKEN= +GITHUB_ENRICH=false +GITHUB_REFRESH_MS=1800000 +GITHUB_TIMEOUT_MS=10000 +GITHUB_API_BASE=https://api.github.com + +# --------------------------------------------------------------------------- +# FEDL (real public API only) +# --------------------------------------------------------------------------- +FEDL_API_BASE=https://server.fedl.site/fedl/api +FEDL_SITE_URL=https://fedl.site +FEDL_REFRESH_MS=900000 +FEDL_TIMEOUT_MS=15000 + +# --------------------------------------------------------------------------- +# Monitoring +# --------------------------------------------------------------------------- +# Used to decide whether this machine is on the home LAN. When it is not, +# failed home-server pings are reported as "unknown" instead of "offline". +HOME_SUBNET=10.0.0.0/24 + +SERVER_CHECK_INTERVAL_MS=60000 +SERVICE_CHECK_INTERVAL_MS=120000 +PING_TIMEOUT_MS=2000 +HTTP_CHECK_TIMEOUT_MS=5000 +MONITOR_RETENTION_DAYS=90 + +# The server list lives in server/config/servers.json. Environment overrides: +# SERVER_1_NAME=Home Server 1 +# SERVER_1_IP=10.0.0.87 +# SERVER_1_ENABLED=true +# SERVER_2_NAME=Home Server 2 +# SERVER_2_IP=10.0.0.119 +# SERVER_2_ENABLED=true + +# The website list lives in server/config/services.json. Override a check URL +# by id (uppercase, non-alphanumerics become underscores): +# SERVICE_FEDL_URL=https://fedl.site/ +# SERVICE_FEDL_ENABLED=true + +# --------------------------------------------------------------------------- +# Analytics (privacy-friendly) +# --------------------------------------------------------------------------- +ANALYTICS_RETENTION_DAYS=30 +ANALYTICS_DEDUPE_SECONDS=10 + +# --------------------------------------------------------------------------- +# Limits and logging +# --------------------------------------------------------------------------- +API_RATE_LIMIT=300 +ANALYTICS_RATE_LIMIT=120 +LOGIN_RATE_LIMIT=15 +REQUEST_TIMEOUT_MS=30000 +BODY_LIMIT_BYTES=16384 + +# debug | info | warn | error +LOG_LEVEL=info + +# --------------------------------------------------------------------------- +# Optional registry path overrides +# --------------------------------------------------------------------------- +# PROJECTS_CONFIG_PATH=/opt/miles-web/server/config/projects.json +# SERVICES_CONFIG_PATH=/opt/miles-web/server/config/services.json +# SERVERS_CONFIG_PATH=/opt/miles-web/server/config/servers.json diff --git a/.gitignore b/.gitignore index 0ae008c..5c3cba9 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,11 @@ -share-server/node_modules \ No newline at end of file +node_modules/ +share-server/node_modules/ +.env +.env.* +!.env.example +data/ +*.db +*.db-wal +*.db-shm +.DS_Store +npm-debug.log* diff --git a/README.md b/README.md index bfc4fdd..24a79b1 100644 --- a/README.md +++ b/README.md @@ -1,41 +1,248 @@ # miles-web -A developer portfolio website for Miles Wolf Allen, showcasing projects, skills, and contact details. +The personal site for Miles Wolf Allen: a hand-written static portfolio plus a +small Node.js + SQLite backend that serves it locally, monitors infrastructure, +tracks development activity, records privacy-friendly analytics, and protects +the Moon Vault behind server-side authentication. -## Overview +The static HTML/CSS site is unchanged in spirit and still has no build step. +The backend is plain JavaScript on Node.js with two native dependencies +(`better-sqlite3` and `argon2`); there is no Docker, Go, Rust, Python, or +frontend framework involved. -- Static personal homepage built with HTML and CSS. -- Includes sections for About, Skills, Projects, Highlights, and Contact. -- Designed with a retro cyberpunk aesthetic and smooth scrolling navigation. +## What is included -## Featured Projects +| Area | What it does | +| --- | --- | +| Infrastructure | ICMP ping checks for `10.0.0.87` and `10.0.0.119`, HTTP health checks for five sites, uptime history, and honest network context | +| GitHub | Official REST API data for `mileswolfallen2` with server-side caching, ETags, rate-limit handling, and no token exposure | +| FEDL | Real data from `https://server.fedl.site/fedl/api/list` and `/runs`, with snapshot diffs for additions, removals, and rank changes | +| Analytics | Cookieless, IP-hash-only pageviews with bot filtering, deduplication, path normalization, and 30-day retention | +| Moon Vault | Argon2id passphrase verification, signed HttpOnly sessions, login rate limiting, logout, and server-gated content | +| Dashboard | `/dashboard.html` renders every panel from the local API and labels unavailable data instead of inventing values | -- **OmniEmu 2.0** — Emulator launcher for managing 20+ systems in one app. -- **FEDL** — Geometry Dash demon list tracker with ranked levels and community features. -- **Noto** — AI-enhanced note-taking app built with Flutter. -- **Nova AI** — Local AI assistant with desktop, web, and CLI interfaces. -- **Music App** — Ad-free music player inspired by YouTube Music. -- **Rhythm Game** — Browser-based rhythm game with keyboard controls. -- **FEDL Geode Mod** — In-game Geometry Dash mod for demon list integration. -- **Decompilations** — Native PC ports and reverse-engineered game projects. -- **Issue Tracker** — Custom issue tracking app built with Node.js. -- **Moon Gaming** — Browser game hub with a large commit history. +## Requirements -## Usage +- Node.js **20 or newer** (tested locally on Node 26) +- npm +- A C toolchain for the native modules (`better-sqlite3`, `argon2`), which is + normally present on macOS and can be installed on Debian with + `build-essential` and `python3` +- `ping` available on the host for server monitoring (`iputils-ping` on Debian) -1. Open `index.html` in a browser. -2. Navigate with the scattered menu links or scroll through the sections. -3. Click on any project card to explore the project pages in `projects/`. +## Local quick start + +```bash +npm install +cp .env.example .env +``` + +Edit `.env` for local use. At minimum set a session secret: + +```bash +# macOS/Linux +openssl rand -hex 32 +# put the output in SESSION_SECRET +``` + +Enable the Moon Vault by generating a hash for a local passphrase: + +```bash +npm run hash-password -- "a long local passphrase" +# copy the printed VAULT_PASSWORD_HASH=... line into .env +``` + +Then initialize the database and start the server: + +```bash +npm run db:migrate +npm run dev +``` + +Open . The dashboard is at + and the vault lock page is at +. + +For local development, use these overrides in `.env` so cookies work over +plain HTTP: + +```dotenv +NODE_ENV=development +HOST=127.0.0.1 +PORT=8787 +PUBLIC_ORIGIN=http://localhost:8787 +COOKIE_SECURE=false +TRUST_PROXY=false +DB_PATH=./data/dashboard.db +``` + +Do not reuse a development passphrase in production, and never commit `.env`. + +## Commands + +| Command | Purpose | +| --- | --- | +| `npm run dev` | Start the server with Node's watch mode | +| `npm start` | Start the server without watch mode | +| `npm test` | Run the full automated test suite with `node:test` | +| `npm run db:migrate` | Apply migrations and seed the project/service/server registries | +| `npm run hash-password -- "passphrase"` | Print an Argon2id hash to put in `.env` | +| `npm run smoke` | Check a running local server's APIs and vault gates | + +`npm run smoke` uses `SMOKE_BASE_URL` if set, otherwise +`http://127.0.0.1:${PORT:-8787}`. + +## Configuration + +Environment variables are documented in [`.env.example`](.env.example). The +project registry, monitored services, and home servers are JSON files: + +- `server/config/projects.json` — id, name, description, GitHub repo, website, + API integration, order, visibility, and featured flag +- `server/config/services.json` — website health-check targets +- `server/config/servers.json` — home-network ping targets + +The JSON files are the defaults. Environment variables can override service +URLs/enabled flags and server name/IP/enabled flags without editing code. The +registries are seeded into SQLite on startup and can be re-seeded by running +`npm run db:migrate`. + +### Adding a project + +Add an object to `server/config/projects.json`: + +```json +{ + "id": "my-project", + "name": "My Project", + "description": "What it does.", + "github": { "owner": "mileswolfallen2", "repo": "my-project" }, + "website": "https://example.milesallen.site", + "api": null, + "order": 21, + "visible": true, + "featured": false +} +``` + +Use `"visible": false` to hide an entry without deleting it. Reorder with +`order`. Restart the server (or run `npm run db:migrate`) after editing. + +### Adding a monitored website + +Add an entry to `server/config/services.json`: + +```json +{ + "id": "my-site", + "name": "My Site", + "url": "https://my-site.milesallen.site/", + "order": 6, + "enabled": true +} +``` + +Only server-side configured URLs are checked. The API never accepts a URL from +a visitor, which avoids SSRF. + +## Moon Vault + +The public `moon-vault.html` page is now only a lock screen. The authenticated +content lives in `server/views/vault.html` and is served at `/vault` only with a +valid server-side session. Files under `/games/*` are also gated by the same +session. + +The old plaintext passphrase has been removed from the public HTML. The server +stores only an Argon2id hash in `.env`, sessions are signed and stored in +SQLite, and cookies are HttpOnly, SameSite=Strict, path `/`, and Secure when +`COOKIE_SECURE=true` (the production default). Failed login attempts are rate +limited per hashed IP and persisted in the database. + +If `VAULT_PASSWORD_HASH` is not set, the vault reports itself as unconfigured +and refuses logins; it does not fall back to a default password. + +## Privacy and security notes + +- Analytics does not set cookies and never stores a raw IP address. The backend + hashes the request IP with a daily rotating secret scoped to analytics, then + stores only the hash, normalized path, referrer domain, and timestamp. +- Query strings and fragments are stripped from recorded paths. Bot user agents + are ignored. Repeat hits on the same path within the dedupe window are + dropped. Rows older than the retention period are deleted. +- GitHub and FEDL calls happen on the server. The GitHub token is never included + in API responses or frontend code. +- CORS is an explicit allowlist: `https://milesallen.site`, + `https://www.milesallen.site`, local development origins, and same-origin + requests. Unknown cross-origin API requests are rejected. +- Request bodies have a hard size limit, API and login routes are rate limited, + request timeouts are enforced, and errors returned to clients do not expose + stack traces or secrets. +- Static file serving blocks path traversal and private paths such as `.env`, + `server/`, `data/`, and `node_modules/`. +- Security headers include `X-Content-Type-Options`, `X-Frame-Options`, + `Referrer-Policy`, `Permissions-Policy`, COOP/CORP, and HSTS in production. + +## Testing + +```bash +npm test +``` + +The suite uses Node's built-in test runner. Each test gets an isolated temporary +SQLite database; network calls are mocked. There are tests for configuration, +ping/network context, HTTP checks, monitor persistence and uptime, GitHub +caching and fallbacks, FEDL snapshot diffs and fallbacks, analytics privacy and +retention, vault auth and brute-force protection, CORS/security headers, static +traversal protection, and database persistence across restarts. + +Live smoke test against a running local server: + +```bash +npm run dev # terminal 1 +npm run smoke # terminal 2 +``` + +The smoke script checks every public API, the static pages, the unauthenticated +vault/game redirects, and that an analytics hit is accepted. + +## Project layout + +```text +analytics.js Privacy-friendly pageview beacon +dashboard.html/.css/.js API-driven developer dashboard +moon-vault.html Public vault lock screen +server/ + app.js HTTP router, CORS, security headers, gates + index.js Startup, background refresh, cleanup, shutdown + config.js Environment and registry loading + config/*.json Projects, services, servers + db/ SQLite connection, migrations, seed + lib/ Env, cookies, crypto, errors, HTTP, logging, limits + services/ Ping, HTTP checks, status, monitor, GitHub, FEDL, + analytics, vault + scripts/ migrate, hash-password, smoke + views/vault.html Authenticated vault content + migrations/001_init.sql Schema and indexes +tests/ node:test suite and isolated fixtures +docs/API.md API reference +docs/DEPLOYMENT.md Debian deployment and operations guide +``` + +## Documentation + +- [API reference](docs/API.md) +- [Deployment guide for Debian 13](docs/DEPLOYMENT.md) ## Contacts - Email: mileswa1q2@gmail.com -- GitHub: https://github.com/mileswolfallen2 -- Replit: https://replit.com/@MilesAllen1 -- CodePen: https://codepen.io/mileswolfallen2-the-typescripter -- Personal site: https://milesallen.site +- GitHub: +- Personal site: ## Notes -- The project is currently a static site and does not require a build step. -- The design uses custom CSS and Google Fonts for typography. +- The backend is designed to run locally without any production SSH, DNS, + Cloudflare Tunnel, Caddy, or remote access. Those are deployment choices, not + local requirements. +- Production deployment is documented but not performed by this repository. + Follow `docs/DEPLOYMENT.md` and verify each step on the target host. diff --git a/analytics.js b/analytics.js new file mode 100644 index 0000000..da0fe84 --- /dev/null +++ b/analytics.js @@ -0,0 +1,53 @@ +/* + * Privacy-friendly pageview beacon. + * - no cookies + * - no localStorage identifier + * - no query strings or fragments + * - never runs on private or operator pages + * The backend hashes the request IP with a daily rotating secret and discards it. + */ +(function () { + 'use strict'; + + if (window.__milesAnalyticsLoaded) return; + window.__milesAnalyticsLoaded = true; + + var path = window.location.pathname || '/'; + var skip = [ + /^\/dashboard(?:\.html)?\/?$/, + /^\/vault\/?$/, + /^\/moon-vault(?:\.html)?$/, + /^\/games(?:\/|$)/, + /^\/api(?:\/|$)/, + /^\/404(?:\.html)?$/ + ]; + if (skip.some(function (pattern) { return pattern.test(path); })) return; + + var meta = document.querySelector('meta[name="miles-analytics-endpoint"]'); + var endpoint = (meta && meta.getAttribute('content')) || '/api/analytics/hit'; + + var payload = { + path: path, + referrer: document.referrer || null + }; + + function send() { + try { + var body = JSON.stringify(payload); + fetch(endpoint, { + method: 'POST', + mode: 'cors', + credentials: 'same-origin', + cache: 'no-store', + keepalive: true, + headers: { 'Content-Type': 'application/json' }, + body: body + }).catch(function () {}); + } catch (err) { + // Analytics must never break the page. + } + } + + if (document.readyState === 'complete') send(); + else window.addEventListener('load', send, { once: true }); +})(); diff --git a/dashboard.css b/dashboard.css new file mode 100644 index 0000000..8a1095f --- /dev/null +++ b/dashboard.css @@ -0,0 +1,332 @@ +:root { + --bg: #050507; + --bg-2: #08080d; + --panel: rgba(12, 12, 19, 0.88); + --panel-solid: #0c0c13; + --line: rgba(255, 255, 255, 0.09); + --line-strong: rgba(255, 255, 255, 0.16); + --text: #f1eff5; + --muted: #8b8994; + --dim: #5c5a66; + --accent: #ff3d9a; + --accent-soft: rgba(255, 61, 154, 0.14); + --green: #39ff14; + --green-soft: rgba(57, 255, 20, 0.12); + --amber: #ffc93c; + --amber-soft: rgba(255, 201, 60, 0.12); + --red: #ff4d6d; + --red-soft: rgba(255, 77, 109, 0.12); + --cyan: #55d7ff; + --font-pixel: 'Press Start 2P', monospace; + --font-mono: 'Space Mono', monospace; + --font-body: 'Inter', sans-serif; + --radius: 3px; +} + +* { margin: 0; padding: 0; box-sizing: border-box; } +html { scroll-behavior: smooth; } +body { + background: var(--bg); + color: var(--text); + font-family: var(--font-body); + line-height: 1.6; + min-height: 100vh; + -webkit-font-smoothing: antialiased; + overflow-x: hidden; +} +body::before { + content: ''; + position: fixed; + inset: 0; + z-index: -2; + background: + radial-gradient(900px 500px at 12% 0%, rgba(255, 61, 154, 0.11), transparent 60%), + radial-gradient(900px 600px at 92% 8%, rgba(85, 215, 255, 0.07), transparent 60%), + linear-gradient(rgba(255,255,255,0.025) 1px, transparent 1px), + linear-gradient(90deg, rgba(255,255,255,0.025) 1px, transparent 1px); + background-size: auto, auto, 44px 44px, 44px 44px; +} +.scanlines { + position: fixed; + inset: 0; + z-index: 50; + pointer-events: none; + opacity: 0.22; + background: repeating-linear-gradient(0deg, transparent, transparent 3px, rgba(0,0,0,0.22) 3px, rgba(0,0,0,0.22) 4px); + mix-blend-mode: multiply; +} +::selection { background: var(--accent); color: #000; } +a { color: inherit; } +button { font: inherit; } + +.topbar { + position: sticky; + top: 0; + z-index: 40; + display: flex; + align-items: center; + justify-content: space-between; + gap: 18px; + padding: 14px max(20px, 4vw); + background: rgba(5, 5, 7, 0.86); + border-bottom: 1px solid var(--line); + backdrop-filter: blur(16px); +} +.brand { display: flex; align-items: center; gap: 9px; text-decoration: none; } +.brand-mark { + width: 10px; height: 10px; background: var(--accent); + box-shadow: 0 0 16px rgba(255,61,154,.9); +} +.brand-text { font-family: var(--font-pixel); font-size: 10px; letter-spacing: .02em; } +.brand-dim { color: var(--muted); } +.topnav { display: flex; align-items: center; gap: 20px; } +.topnav a, .refresh-btn { + font-family: var(--font-mono); font-size: 11px; text-transform: uppercase; + letter-spacing: .07em; color: var(--muted); text-decoration: none; + background: none; border: 0; cursor: pointer; +} +.topnav a:hover, .refresh-btn:hover { color: var(--accent); } +.refresh-btn { + border: 1px solid var(--line-strong); + padding: 8px 12px; +} +.refresh-btn:hover { border-color: var(--accent); } +.refresh-btn[disabled] { opacity: .45; cursor: wait; } + +.wrap { width: min(1440px, 100%); margin: 0 auto; padding: 0 max(20px, 4vw) 40px; } +.hero { + display: flex; align-items: flex-end; justify-content: space-between; + gap: 40px; padding: 58px 0 34px; +} +.eyebrow { + font-family: var(--font-mono); color: var(--accent); font-size: 11px; + letter-spacing: .16em; text-transform: uppercase; margin-bottom: 12px; +} +.hero h1 { + font-family: var(--font-pixel); + font-size: clamp(24px, 4.2vw, 52px); + line-height: 1.16; + letter-spacing: -0.02em; + text-shadow: 4px 4px 0 rgba(255, 61, 154, 0.5); +} +.hero-sub { max-width: 680px; color: var(--muted); font-size: 14px; margin-top: 16px; } +.hero-status { text-align: right; flex: 0 0 auto; padding-bottom: 3px; } +.overall-pill { + display: inline-flex; align-items: center; gap: 10px; + border: 1px solid var(--line-strong); padding: 10px 15px; + font-family: var(--font-mono); font-size: 11px; text-transform: uppercase; + letter-spacing: .12em; background: rgba(255,255,255,.02); color: var(--muted); +} +.overall-pill .pulse { width: 8px; height: 8px; border-radius: 50%; background: var(--dim); } +.overall-pill.ok { color: var(--green); border-color: rgba(57,255,20,.4); background: var(--green-soft); } +.overall-pill.ok .pulse { background: var(--green); animation: pulse 2s infinite; } +.overall-pill.warn { color: var(--amber); border-color: rgba(255,201,60,.4); background: var(--amber-soft); } +.overall-pill.warn .pulse { background: var(--amber); } +.overall-pill.bad { color: var(--red); border-color: rgba(255,77,109,.4); background: var(--red-soft); } +.overall-pill.bad .pulse { background: var(--red); animation: pulse 1.1s infinite; } +.overall-pill.unknown .pulse { background: var(--dim); } +@keyframes pulse { 0%,100% { opacity: 1; transform: scale(1); } 50% { opacity: .45; transform: scale(.72); } } +.hero-meta { font-family: var(--font-mono); font-size: 10px; color: var(--dim); margin-top: 12px; } +.meta-sep { margin: 0 7px; color: var(--dim); } + +.stat-strip { + display: grid; grid-template-columns: repeat(6, minmax(0, 1fr)); + border: 1px solid var(--line); background: var(--panel); +} +.stat-cell { padding: 18px 20px 16px; border-right: 1px solid var(--line); } +.stat-cell:last-child { border-right: 0; } +.stat-label, .gh-label { + display: block; font-family: var(--font-mono); font-size: 9px; + text-transform: uppercase; letter-spacing: .11em; color: var(--dim); +} +.stat-value { + display: block; font-family: var(--font-pixel); font-size: clamp(16px, 2vw, 24px); + margin-top: 9px; color: var(--text); +} +.stat-note { display: block; font-family: var(--font-mono); font-size: 9px; color: var(--muted); margin-top: 6px; } + +.notice { + border: 1px solid rgba(255,201,60,.35); + background: var(--amber-soft); color: #ffe7a3; + padding: 12px 16px; margin-top: 16px; + font-family: var(--font-mono); font-size: 11px; +} + +.grid { + display: grid; grid-template-columns: repeat(12, minmax(0, 1fr)); + gap: 18px; margin-top: 18px; +} +.panel { + grid-column: span 12; + border: 1px solid var(--line); + background: var(--panel); + padding: 22px; + min-width: 0; + position: relative; + overflow: hidden; +} +.panel::before { + content: ''; position: absolute; inset: 0 auto auto 0; width: 34px; height: 2px; + background: var(--accent); opacity: .8; +} +.span-7 { grid-column: span 7; } +.span-5 { grid-column: span 5; } +.featured { border-color: rgba(255,61,154,.25); background: linear-gradient(145deg, rgba(255,61,154,.065), rgba(12,12,19,.9) 55%); } +.panel-head { display: flex; align-items: flex-start; justify-content: space-between; gap: 18px; margin-bottom: 20px; } +.panel-kicker { font-family: var(--font-mono); font-size: 9px; color: var(--accent); letter-spacing: .15em; text-transform: uppercase; } +.panel h2 { font-family: var(--font-body); font-size: clamp(19px, 2vw, 24px); font-weight: 700; letter-spacing: -.02em; margin-top: 4px; } +.panel-tag, .panel-link { + font-family: var(--font-mono); font-size: 9px; text-transform: uppercase; + letter-spacing: .09em; color: var(--dim); text-decoration: none; + border: 1px solid var(--line); padding: 5px 8px; white-space: nowrap; +} +.panel-link:hover { color: var(--accent); border-color: var(--accent); } +.panel-foot { font-family: var(--font-mono); font-size: 9px; color: var(--dim); margin-top: 18px; line-height: 1.7; } +.panel-foot code { color: var(--muted); } + +.rows { display: flex; flex-direction: column; } +.row { + display: grid; grid-template-columns: minmax(0, 1.4fr) 72px 92px 108px; + gap: 16px; align-items: center; padding: 14px 0; border-top: 1px solid var(--line); +} +.rows .row:first-child { border-top: 0; } +.row-main { display: flex; align-items: center; gap: 12px; min-width: 0; } +.status-dot { width: 8px; height: 8px; border-radius: 50%; flex: 0 0 auto; background: var(--dim); box-shadow: 0 0 0 3px rgba(255,255,255,.03); } +.status-dot.ok { background: var(--green); box-shadow: 0 0 12px rgba(57,255,20,.55); } +.status-dot.warn { background: var(--amber); box-shadow: 0 0 12px rgba(255,201,60,.45); } +.status-dot.bad { background: var(--red); box-shadow: 0 0 12px rgba(255,77,109,.5); } +.row-name { font-weight: 600; font-size: 13px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } +.row-sub { font-family: var(--font-mono); font-size: 9px; color: var(--dim); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } +.row-status { font-family: var(--font-mono); font-size: 9px; text-transform: uppercase; letter-spacing: .08em; color: var(--muted); text-align: left; } +.row-status.ok { color: var(--green); } +.row-status.warn { color: var(--amber); } +.row-status.bad { color: var(--red); } +.row-metric { font-family: var(--font-mono); font-size: 10px; color: var(--muted); text-align: right; } +.row-uptime { text-align: right; } +.uptime-bar { height: 4px; background: rgba(255,255,255,.08); overflow: hidden; } +.uptime-fill { height: 100%; background: var(--green); } +.uptime-fill.warn { background: var(--amber); } +.uptime-fill.bad { background: var(--red); } +.uptime-text { display: block; font-family: var(--font-mono); font-size: 9px; color: var(--dim); margin-top: 4px; } +.row-empty { padding: 18px 0; color: var(--dim); font-family: var(--font-mono); font-size: 11px; } +@media (max-width: 1100px) { + .span-7, .span-5 { grid-column: span 12; } + .stat-strip { grid-template-columns: repeat(3, 1fr); } + .stat-cell:nth-child(3n) { border-right: 0; } + .stat-cell:nth-child(-n+3) { border-bottom: 1px solid var(--line); } +} +@media (max-width: 720px) { + .hero { flex-direction: column; align-items: flex-start; gap: 24px; padding-top: 38px; } + .hero-status { text-align: left; } + .stat-strip { grid-template-columns: repeat(2, 1fr); } + .stat-cell { border-bottom: 1px solid var(--line); } + .stat-cell:nth-child(3n) { border-right: 1px solid var(--line); } + .stat-cell:nth-child(2n) { border-right: 0; } + .row { grid-template-columns: minmax(0, 1fr) 60px 82px; } + .row-uptime { display: none; } + .topnav a:nth-child(1), .topnav a:nth-child(2) { display: none; } + .panel { padding: 18px; } +} + +.github-meta { display: grid; grid-template-columns: repeat(4, 1fr); border: 1px solid var(--line); } +.gh-stat { padding: 13px 14px; border-right: 1px solid var(--line); } +.gh-stat:last-child { border-right: 0; } +.gh-num { display: block; font-family: var(--font-pixel); font-size: 15px; } +.gh-label { margin-top: 5px; } +.chart-wrap { margin-top: 20px; } +.chart-head { + display: flex; justify-content: space-between; gap: 12px; + font-family: var(--font-mono); font-size: 9px; color: var(--dim); + text-transform: uppercase; letter-spacing: .08em; margin-bottom: 8px; +} +.bar-chart { + display: flex; align-items: flex-end; gap: 3px; height: 92px; + border-bottom: 1px solid var(--line); padding-bottom: 1px; +} +.bar-col { flex: 1; height: 100%; display: flex; align-items: flex-end; min-width: 2px; } +.bar { + width: 100%; min-height: 2px; background: rgba(255,61,154,.42); + transition: height .5s ease, background .2s; +} +.bar:hover { background: var(--accent); } +.bar.zero { background: rgba(255,255,255,.055); } +.split { display: grid; grid-template-columns: 1fr 1fr; gap: 26px; margin-top: 20px; } +@media (max-width: 760px) { .split { grid-template-columns: 1fr; } } +.mini-title { + font-family: var(--font-mono); font-size: 9px; text-transform: uppercase; + letter-spacing: .12em; color: var(--dim); margin-bottom: 9px; +} +.mini-title.spaced { margin-top: 20px; } +.feed { list-style: none; display: flex; flex-direction: column; } +.feed li { + display: flex; flex-direction: column; gap: 2px; + padding: 9px 0; border-top: 1px solid var(--line); + font-size: 11px; min-width: 0; +} +.feed li:first-child { border-top: 0; } +.feed .feed-top { display: flex; align-items: baseline; justify-content: space-between; gap: 10px; } +.feed .feed-name { font-weight: 600; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } +.feed .feed-meta { font-family: var(--font-mono); font-size: 9px; color: var(--dim); white-space: nowrap; } +.feed .feed-sub { font-family: var(--font-mono); font-size: 9px; color: var(--muted); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } +.feed .empty, .empty { color: var(--dim); font-family: var(--font-mono); font-size: 10px; line-height: 1.7; } +.feed .error { color: var(--red); } +.chips { display: flex; flex-wrap: wrap; gap: 6px; } +.chip { + font-family: var(--font-mono); font-size: 9px; color: var(--muted); + border: 1px solid var(--line); padding: 4px 7px; +} +.chip.muted { color: var(--dim); } + +.fedl-hero { display: flex; align-items: stretch; border: 1px solid var(--line); margin-bottom: 20px; } +.fedl-big { padding: 16px 18px; border-right: 1px solid var(--line); min-width: 130px; display: flex; flex-direction: column; justify-content: center; } +.fedl-big > span:first-child { font-family: var(--font-pixel); font-size: 27px; color: var(--accent); line-height: 1; } +.fedl-unit { font-family: var(--font-mono); font-size: 9px; color: var(--dim); margin-top: 7px; } +.fedl-side { display: grid; grid-template-columns: 1fr; flex: 1; padding: 8px 16px; gap: 4px; } +.fedl-side div { display: flex; align-items: baseline; justify-content: space-between; gap: 10px; } +.fedl-side strong { font-family: var(--font-mono); font-size: 11px; font-weight: 400; color: var(--text); } +.fedl-side span { font-family: var(--font-mono); font-size: 9px; color: var(--dim); } +.rank-list { list-style: none; display: flex; flex-direction: column; counter-reset: rank; } +.rank-list li { display: flex; align-items: center; gap: 10px; padding: 6px 0; border-top: 1px solid var(--line); font-size: 11px; } +.rank-list li:first-child { border-top: 0; } +.rank-list .rank { font-family: var(--font-mono); font-size: 9px; color: var(--accent); width: 22px; flex: 0 0 auto; } +.rank-list .rank-name { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } + +.analytics-meta { display: grid; grid-template-columns: repeat(4, 1fr); border: 1px solid var(--line); } +.analytics-meta div { padding: 12px 14px; border-right: 1px solid var(--line); } +.analytics-meta div:last-child { border-right: 0; } +.analytics-meta strong { display: block; font-family: var(--font-pixel); font-size: 15px; font-weight: 400; } +.analytics-meta span { display: block; font-family: var(--font-mono); font-size: 9px; color: var(--dim); margin-top: 4px; } +@media (max-width: 760px) { .analytics-meta, .github-meta { grid-template-columns: repeat(2, 1fr); } .analytics-meta div:nth-child(2), .gh-stat:nth-child(2) { border-right: 0; } .analytics-meta div:nth-child(-n+2), .gh-stat:nth-child(-n+2) { border-bottom: 1px solid var(--line); } } + +.project-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 10px; } +@media (max-width: 620px) { .project-grid { grid-template-columns: 1fr; } } +.project-card { + border: 1px solid var(--line); padding: 12px 13px; + display: flex; flex-direction: column; gap: 4px; text-decoration: none; + transition: border-color .2s, background .2s; +} +.project-card:hover { border-color: var(--accent); background: var(--accent-soft); } +.project-card .pc-top { display: flex; align-items: center; justify-content: space-between; gap: 8px; } +.project-card .pc-name { font-size: 12px; font-weight: 600; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } +.project-card .pc-desc { font-family: var(--font-mono); font-size: 9px; color: var(--dim); line-height: 1.55; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; } +.project-card .pc-meta { font-family: var(--font-mono); font-size: 8px; color: var(--muted); text-transform: uppercase; letter-spacing: .06em; margin-top: 3px; } + +.skeleton-row { + height: 52px; margin: 8px 0; + background: linear-gradient(90deg, rgba(255,255,255,.03), rgba(255,255,255,.07), rgba(255,255,255,.03)); + background-size: 200% 100%; animation: shimmer 1.5s infinite; border: 1px solid var(--line); +} +@keyframes shimmer { to { background-position: -200% 0; } } + +.footer { + display: flex; flex-wrap: wrap; align-items: center; gap: 4px; + border-top: 1px solid var(--line); margin-top: 28px; padding: 24px 0; + font-family: var(--font-mono); font-size: 10px; color: var(--dim); +} +.footer a { color: var(--muted); text-decoration: none; } +.footer a:hover { color: var(--accent); } + +@media (prefers-reduced-motion: reduce) { + * { animation: none !important; transition: none !important; } + html { scroll-behavior: auto; } +} diff --git a/dashboard.html b/dashboard.html new file mode 100644 index 0000000..ad75a20 --- /dev/null +++ b/dashboard.html @@ -0,0 +1,233 @@ + + + + + + System Console | Miles Allen + + + + + + + + + + + +
+ + + milesallen.site + + +
+ +
+
+
+
// live telemetry
+

System Console

+

Infrastructure, development activity, FEDL, and traffic for milesallen.site. Everything on this page comes from the local backend API.

+
+
+
+ + Connecting +
+
+ Waiting for first check + · + auto-refresh 60s +
+
+
+ +
+
+
Services up
+
--
+
website checks
+
+
+
Servers up
+
--
+
home network
+
+
+
GitHub stars
+
--
+
tracked repos
+
+
+
FEDL levels
+
--
+
ranked
+
+
+
Pageviews today
+
--
+
privacy-friendly
+
+
+
Visitors 30d
+
--
+
daily hashes
+
+
+ + + +
+
+
+
+
01 / infrastructure
+

Home servers

+
+ network unknown +
+
+
+
+
+
+ +
+
+
+
02 / websites
+

Service health

+
+ traffic → +
+
+
+
+
+
+
+ +
+
+
+
03 / development
+

GitHub activity

+
+ profile → +
+
+
--public repos
+
--tracked
+
--stars
+
--forks
+
+
+
30-day event activity
+ +
+
+
+

Recent commits

+
  • Loading GitHub data…
+
+
+

Most active

+
  • Loading repositories…
+

Languages

+
—
+
+
+

Data is cached server-side; the GitHub token never reaches the browser.

+
+ + + +
+
+
+
05 / traffic
+

Analytics

+
+ 30-day retention +
+
+
--total pageviews
+
--today
+
--7 days
+
--unique 30d
+
+
+
Daily pageviews · 30 days
+ +
+
+
+

Most visited

+
  • Loading analytics…
+
+
+

Recent hits

+
  • Loading analytics…
+
+
+

No cookies, no raw IP addresses. Daily salted hashes only.

+
+ +
+
+
+
06 / registry
+

Project registry

+
+ — +
+
+
+
+
+
+

Add, remove, reorder, or hide projects in server/config/projects.json. The registry is seeded into SQLite on startup.

+
+
+ +
+ milesallen.site system console + · + back home + · + moon vault + · + API status is honest: unknown means unknown. +
+
+ + + + diff --git a/dashboard.js b/dashboard.js new file mode 100644 index 0000000..231911e --- /dev/null +++ b/dashboard.js @@ -0,0 +1,579 @@ +(function () { + 'use strict'; + + var API = document.documentElement.dataset.api || '/api'; + var REFRESH_SECONDS = 60; + var countdown = REFRESH_SECONDS; + var refreshing = false; + var hasLoaded = false; + + var $ = function (id) { return document.getElementById(id); }; + + function el(tag, className, text) { + var node = document.createElement(tag); + if (className) node.className = className; + if (text !== undefined && text !== null) node.textContent = String(text); + return node; + } + + function setText(id, value) { + var node = $(id); + if (node) node.textContent = value === null || value === undefined ? '--' : String(value); + } + + function fmtNumber(value) { + if (value === null || value === undefined || Number.isNaN(Number(value))) return '--'; + return Number(value).toLocaleString('en-US'); + } + + function fmtMs(value) { + if (value === null || value === undefined || Number.isNaN(Number(value))) return '--'; + var n = Number(value); + return n >= 1000 ? (n / 1000).toFixed(2) + ' s' : Math.round(n) + ' ms'; + } + + function fmtPct(value) { + if (value === null || value === undefined || Number.isNaN(Number(value))) return '--'; + return Number(value).toFixed(Number(value) % 1 === 0 ? 0 : 1) + '%'; + } + + function fmtRelative(iso) { + if (!iso) return 'never'; + var then = new Date(iso).getTime(); + if (!Number.isFinite(then)) return 'never'; + var diff = Math.round((Date.now() - then) / 1000); + if (diff < 0) diff = 0; + if (diff < 45) return 'just now'; + if (diff < 90) return '1m ago'; + if (diff < 3600) return Math.round(diff / 60) + 'm ago'; + if (diff < 86400) return Math.round(diff / 3600) + 'h ago'; + if (diff < 2592000) return Math.round(diff / 86400) + 'd ago'; + return new Date(iso).toLocaleDateString(); + } + + function fmtDateTime(iso) { + if (!iso) return '—'; + var d = new Date(iso); + if (!Number.isFinite(d.getTime())) return '—'; + return d.toLocaleString(undefined, { + month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' + }); + } + + function toneFor(status) { + if (status === 'operational' || status === 'online' || status === 'ok') return 'ok'; + if (status === 'degraded' || status === 'slow') return 'warn'; + if (status === 'offline' || status === 'down') return 'bad'; + return 'unknown'; + } + + function labelFor(status) { + if (status === 'operational') return 'operational'; + if (status === 'online') return 'online'; + if (status === 'degraded') return 'degraded'; + if (status === 'offline') return 'offline'; + return 'unknown'; + } + + async function get(path) { + var response = await fetch(API + path, { + cache: 'no-store', + credentials: 'same-origin', + headers: { Accept: 'application/json' } + }); + var body = null; + try { body = await response.json(); } catch (err) { body = null; } + if (!response.ok) { + throw new Error((body && body.error && body.error.message) || ('Request failed (' + response.status + ')')); + } + return body; + } + + function renderBarChart(container, rows, valueKey, secondaryKey, labelKey, label) { + container.replaceChildren(); + var max = 0; + rows.forEach(function (row) { + var value = Number(row[valueKey]) || 0; + if (value > max) max = value; + }); + rows.forEach(function (row) { + var value = Number(row[valueKey]) || 0; + var col = el('div', 'bar-col'); + var bar = el('div', 'bar' + (value === 0 ? ' zero' : '')); + var height = max ? Math.max(2, Math.round((value / max) * 100)) : 2; + bar.style.height = height + '%'; + var extra = secondaryKey && row[secondaryKey] !== undefined ? ' · ' + row[secondaryKey] : ''; + bar.title = row[labelKey] + ' · ' + value + ' ' + label + extra; + col.appendChild(bar); + container.appendChild(col); + }); + container.setAttribute('aria-label', label + ' over the last ' + rows.length + ' days'); + } + + function renderRowsError(container, message) { + container.replaceChildren(); + container.appendChild(el('div', 'row-empty', message)); + } + + function renderFeedError(container, message) { + container.replaceChildren(); + container.appendChild(el('li', 'empty error', message)); + } + + function feedItem(title, meta, sub, href) { + var li = el('li'); + var top = el('div', 'feed-top'); + var name = el('span', 'feed-name', title); + if (href) { + var link = el('a', null, title); + link.href = href; + link.target = '_blank'; + link.rel = 'noopener'; + name = link; + name.className = 'feed-name'; + } + top.appendChild(name); + top.appendChild(el('span', 'feed-meta', meta || '')); + li.appendChild(top); + if (sub) li.appendChild(el('span', 'feed-sub', sub)); + return li; + } + + function agoText(iso) { + if (!iso) return ''; + return fmtRelative(iso); + } + + function renderServerRows(status) { + var container = $('serverRows'); + var servers = status.servers || []; + if (!servers.length) { + renderRowsError(container, 'No home servers are configured.'); + return; + } + container.replaceChildren(); + servers.forEach(function (server) { + var tone = toneFor(server.status); + var row = el('div', 'row'); + var main = el('div', 'row-main'); + main.appendChild(el('span', 'status-dot ' + tone)); + var text = el('div'); + text.style.minWidth = '0'; + text.appendChild(el('div', 'row-name', server.name)); + var sub = server.ip + ' · checked ' + agoText(server.lastCheckAt); + if (server.status === 'unknown' && server.reason === 'not_on_home_network') { + sub = server.ip + ' · outside home network'; + } else if (server.status === 'unknown' && server.reason && server.reason !== 'no_data') { + sub = server.ip + ' · ' + String(server.reason).replace(/_/g, ' '); + } else if (server.lastSuccessAt) { + sub += ' · up ' + agoText(server.lastSuccessAt); + } + text.appendChild(el('div', 'row-sub', sub)); + main.appendChild(text); + + var state = el('div', 'row-status ' + tone, labelFor(server.status)); + var metric = el('div', 'row-metric', fmtMs(server.responseMs)); + var uptime = el('div', 'row-uptime'); + var pct = server.uptime ? server.uptime['24h'] : null; + var fillTone = pct === null ? '' : pct >= 99 ? '' : pct >= 90 ? 'warn' : 'bad'; + var bar = el('div', 'uptime-bar'); + var fill = el('div', 'uptime-fill ' + fillTone); + fill.style.width = pct === null ? '0%' : Math.max(1, Math.min(100, pct)) + '%'; + bar.appendChild(fill); + uptime.appendChild(bar); + uptime.appendChild(el('span', 'uptime-text', '24h ' + fmtPct(pct) + ' · 7d ' + fmtPct(server.uptime ? server.uptime['7d'] : null))); + + row.appendChild(main); + row.appendChild(state); + row.appendChild(metric); + row.appendChild(uptime); + container.appendChild(row); + }); + } + + function renderServiceRows(status) { + var container = $('serviceRows'); + var services = status.services || []; + if (!services.length) { + renderRowsError(container, 'No websites are configured.'); + return; + } + container.replaceChildren(); + services.slice().sort(function (a, b) { + var rank = { offline: 0, degraded: 1, unknown: 2, operational: 3 }; + return (rank[a.status] ?? 9) - (rank[b.status] ?? 9); + }).forEach(function (service) { + var tone = toneFor(service.status); + var row = el('div', 'row'); + var main = el('div', 'row-main'); + main.appendChild(el('span', 'status-dot ' + tone)); + var text = el('div'); + text.style.minWidth = '0'; + text.appendChild(el('div', 'row-name', service.name)); + var host = service.url; + try { host = new URL(service.url).hostname; } catch (err) {} + var sub = host + ' · checked ' + agoText(service.lastCheckAt); + if (service.lastSuccessAt) sub += ' · last ok ' + agoText(service.lastSuccessAt); + text.appendChild(el('div', 'row-sub', sub)); + main.appendChild(text); + + var state = el('div', 'row-status ' + tone, labelFor(service.status)); + var metric = el('div', 'row-metric', fmtMs(service.responseMs)); + var uptime = el('div', 'row-uptime'); + var pct = service.uptime ? service.uptime['24h'] : null; + var fillTone = pct === null ? '' : pct >= 99 ? '' : pct >= 90 ? 'warn' : 'bad'; + var bar = el('div', 'uptime-bar'); + var fill = el('div', 'uptime-fill ' + fillTone); + fill.style.width = pct === null ? '0%' : Math.max(1, Math.min(100, pct)) + '%'; + bar.appendChild(fill); + uptime.appendChild(bar); + uptime.appendChild(el('span', 'uptime-text', '24h ' + fmtPct(pct) + ' · 7d ' + fmtPct(service.uptime ? service.uptime['7d'] : null))); + + row.appendChild(main); + row.appendChild(state); + row.appendChild(metric); + row.appendChild(uptime); + container.appendChild(row); + }); + } + + async function loadStatus() { + try { + var status = await get('/status'); + var servers = status.servers || []; + var services = status.services || []; + var overall = status.overall || {}; + var tone = toneFor(overall.status === 'operational' ? 'operational' : overall.status); + var pill = $('overallPill'); + pill.className = 'overall-pill ' + (tone === 'ok' ? 'ok' : tone); + + var overallText = 'Status unknown'; + if (overall.status === 'operational') overallText = 'All systems nominal'; + else if (overall.status === 'degraded') overallText = 'Partial degradation'; + else if (overall.status === 'offline') overallText = 'Outage detected'; + setText('overallText', overallText); + setText('lastUpdated', 'updated ' + fmtDateTime(status.generatedAt)); + setText('networkTag', status.network && status.network.onHomeNetwork === true ? 'home network' : status.network && status.network.onHomeNetwork === false ? 'remote network' : 'network unknown'); + + var upServices = services.filter(function (s) { return s.status === 'operational'; }).length; + var upServers = servers.filter(function (s) { return s.status === 'online'; }).length; + setText('statServices', upServices + '/' + services.length); + setText('statServers', upServers + '/' + servers.length); + setText('statServicesNote', overall.counts && overall.counts.degraded ? overall.counts.degraded + ' degraded' : 'website checks'); + setText('statServersNote', status.network && status.network.onHomeNetwork === false ? 'off home network' : 'home network'); + + renderServerRows(status); + renderServiceRows(status); + + var notice = $('networkNotice'); + if (status.network && status.network.onHomeNetwork === false) { + notice.hidden = false; + notice.textContent = 'This machine does not appear to be on the home network. Home server checks are marked unknown instead of offline, so a failed ping is not reported as a server outage.'; + } else if (status.network && status.network.onHomeNetwork === null) { + notice.hidden = false; + notice.textContent = 'Home network context is not available yet. Server checks may be unknown until the first monitor pass completes.'; + } else { + notice.hidden = true; + } + } catch (err) { + renderRowsError($('serverRows'), 'Status API unavailable: ' + err.message); + renderRowsError($('serviceRows'), 'Status API unavailable: ' + err.message); + $('overallPill').className = 'overall-pill bad'; + setText('overallText', 'API unreachable'); + } + } + + async function loadGitHub() { + try { + var results = await Promise.all([get('/github/overview'), get('/github/activity')]); + var overview = results[0]; + var activity = results[1]; + var totals = overview.totals || {}; + var profile = overview.profile || {}; + + setText('ghPublicRepos', fmtNumber(totals.publicRepos ?? profile.publicRepos)); + setText('ghTracked', fmtNumber(totals.trackedRepos)); + setText('ghStars', fmtNumber(totals.stars)); + setText('ghForks', fmtNumber(totals.forks)); + setText('statStars', fmtNumber(totals.stars)); + setText('statStarsNote', (totals.trackedRepos || 0) + ' tracked repos'); + + if (profile.login) { + var profileLink = $('githubProfileLink'); + profileLink.href = 'https://github.com/' + profile.login; + profileLink.textContent = '@' + profile.login + ' →'; + } + + var chartRows = (activity.activity && activity.activity.days) || []; + renderBarChart($('githubChart'), chartRows, 'events', null, 'day', 'events'); + + var rate = overview.rateLimit || {}; + if (rate.authenticated && rate.remaining !== null && rate.remaining !== undefined) { + setText('githubRate', 'API ' + rate.remaining + ' left'); + } else if (rate.authenticated) { + setText('githubRate', 'authenticated API'); + } else { + setText('githubRate', 'anonymous API'); + } + + var commits = overview.recentCommits || []; + var feed = $('commitFeed'); + feed.replaceChildren(); + if (!commits.length) { + feed.appendChild(el('li', 'empty', 'No public push events in the GitHub events window.')); + } else { + commits.slice(0, 8).forEach(function (commit) { + feed.appendChild(feedItem( + commit.project + ' · ' + (commit.sha || ''), + agoText(commit.date), + commit.message || '(no message)', + commit.url + )); + }); + } + + var top = overview.topActive || []; + var repoFeed = $('repoActivity'); + repoFeed.replaceChildren(); + if (!top.length) { + repoFeed.appendChild(el('li', 'empty', 'No repository activity in the last 30 days.')); + } else { + top.slice(0, 6).forEach(function (entry) { + repoFeed.appendChild(feedItem( + entry.project, + (entry.events || 0) + ' events', + (entry.pushes || 0) + ' pushes · ' + entry.repo, + 'https://github.com/' + entry.repo + )); + }); + } + + var chips = $('languageChips'); + chips.replaceChildren(); + var languages = overview.languages || []; + if (!languages.length) chips.appendChild(el('span', 'chip muted', '—')); + languages.slice(0, 7).forEach(function (language) { + chips.appendChild(el('span', 'chip', language.name + ' ×' + language.count)); + }); + + var generated = overview.generatedAt ? 'Cached ' + agoText(overview.generatedAt) + '. ' : ''; + $('githubFoot').textContent = generated + 'Server-cached GitHub REST data. The token is never sent to the browser.'; + } catch (err) { + renderFeedError($('commitFeed'), 'GitHub API unavailable: ' + err.message); + renderFeedError($('repoActivity'), 'GitHub API unavailable.'); + $('githubChart').replaceChildren(); + $('githubFoot').textContent = 'GitHub data is unavailable right now. This is not being replaced with mock data.'; + } + } + + async function loadFedl() { + try { + var stats = await get('/fedl/stats'); + var totals = stats.totals || {}; + setText('fedlLevels', fmtNumber(totals.rankedLevels)); + setText('fedlRecords', fmtNumber(totals.records)); + setText('fedlPlayers', fmtNumber(totals.players)); + setText('fedlSubmissions', fmtNumber(totals.submissions)); + setText('statLevels', fmtNumber(totals.rankedLevels)); + setText('statLevelsNote', (totals.records || 0) + ' approved runs'); + + var top = $('fedlTop'); + top.replaceChildren(); + var levels = stats.topLevels || []; + if (!levels.length) { + top.appendChild(el('li', 'empty', 'No ranked levels returned.')); + } else { + levels.slice(0, 8).forEach(function (level) { + var li = el('li'); + li.appendChild(el('span', 'rank', '#' + (level.position ?? '?'))); + var link = el('a', 'rank-name', level.title); + if (level.url) { + link.href = level.url; + link.target = '_blank'; + link.rel = 'noopener'; + } + li.appendChild(link); + top.appendChild(li); + }); + } + + var changes = stats.changes || { counts: {}, comparedTo: null }; + var changeFeed = $('fedlChanges'); + changeFeed.replaceChildren(); + if (!changes.comparedTo) { + changeFeed.appendChild(el('li', 'empty', 'Baseline snapshot stored. Additions, removals, and rank changes will appear after the next refresh.')); + } else { + var items = []; + (changes.added || []).forEach(function (item) { + items.push({ label: '+ ' + item.title, note: 'added at #' + (item.position ?? '?'), cls: 'ok' }); + }); + (changes.removed || []).forEach(function (item) { + items.push({ label: '− ' + item.title, note: 'removed from #' + (item.position ?? '?'), cls: 'bad' }); + }); + (changes.rankChanges || []).forEach(function (item) { + items.push({ + label: (item.delta > 0 ? '↑ ' : '↓ ') + item.title, + note: '#' + item.from + ' → #' + item.to, + cls: item.delta > 0 ? 'ok' : 'warn' + }); + }); + if (!items.length) { + changeFeed.appendChild(el('li', 'empty', 'No list changes since the previous snapshot.')); + } else { + items.slice(0, 8).forEach(function (item) { + var li = el('li'); + var row = el('div', 'feed-top'); + row.appendChild(el('span', 'feed-name', item.label)); + row.appendChild(el('span', 'feed-meta', item.note)); + li.appendChild(row); + changeFeed.appendChild(li); + }); + } + } + + var foot = 'FEDL API: /list and /runs · refreshed ' + agoText(stats.generatedAt); + if (stats.stale) foot += ' · serving cached data after a failed refresh'; + $('fedlFoot').textContent = foot; + } catch (err) { + renderFeedError($('fedlTop'), 'FEDL data unavailable: ' + err.message); + renderFeedError($('fedlChanges'), 'FEDL data unavailable.'); + } + } + + async function loadAnalytics() { + try { + var results = await Promise.all([ + get('/analytics/overview'), + get('/analytics/pages?days=30&limit=8') + ]); + var overview = results[0]; + var pages = results[1]; + var totals = overview.totals || {}; + setText('viewsTotal', fmtNumber(totals.pageviews)); + setText('viewsToday', fmtNumber(totals.pageviewsToday)); + setText('views7d', fmtNumber(totals.pageviews7d)); + setText('visitors30d', fmtNumber(totals.uniqueVisitors30d)); + setText('statViews', fmtNumber(totals.pageviewsToday)); + setText('statViewsNote', fmtNumber(totals.pageviews7d) + ' in 7 days'); + setText('statVisitors', fmtNumber(totals.uniqueVisitors30d)); + setText('statVisitorsNote', 'daily hashes · 30d'); + + var retention = overview.retentionDays || 30; + setText('analyticsRetention', retention + '-day retention'); + var daily = overview.daily || []; + var peak = 0; + daily.forEach(function (day) { peak = Math.max(peak, day.views || 0); }); + setText('analyticsPeak', peak ? 'peak ' + peak + ' views/day' : 'no traffic recorded'); + renderBarChart($('analyticsChart'), daily, 'views', 'visitors', 'day', 'pageviews'); + + var pageRows = pages.pages || []; + var top = $('topPages'); + top.replaceChildren(); + if (!pageRows.length) { + top.appendChild(el('li', 'empty', 'No pageviews recorded in the last 30 days.')); + } else { + pageRows.forEach(function (page) { + top.appendChild(feedItem( + page.path, + fmtNumber(page.views) + ' views', + fmtNumber(page.visitors) + ' visitors · ' + fmtPct(page.share) + ' share' + )); + }); + } + + var recent = overview.recentActivity || []; + var feed = $('recentHits'); + feed.replaceChildren(); + if (!recent.length) { + feed.appendChild(el('li', 'empty', 'No recent traffic.')); + } else { + recent.slice(0, 8).forEach(function (hit) { + feed.appendChild(feedItem( + hit.path, + agoText(hit.created_at), + hit.referrer_domain ? 'via ' + hit.referrer_domain : 'direct / no referrer' + )); + }); + } + } catch (err) { + renderFeedError($('topPages'), 'Analytics unavailable: ' + err.message); + renderFeedError($('recentHits'), 'Analytics unavailable.'); + $('analyticsChart').replaceChildren(); + } + } + + async function loadProjects() { + try { + var data = await get('/projects'); + var projects = data.projects || []; + var grid = $('projectGrid'); + grid.replaceChildren(); + setText('projectCount', projects.length + ' visible'); + projects.forEach(function (project) { + var node = document.createElement(project.website ? 'a' : 'div'); + node.className = 'project-card'; + if (project.website) { + node.href = project.website; + node.target = '_blank'; + node.rel = 'noopener'; + } + var top = el('div', 'pc-top'); + top.appendChild(el('span', 'pc-name', project.name)); + var health = project.health; + if (health) { + top.appendChild(el('span', 'status-dot ' + toneFor(health))); + } + node.appendChild(top); + node.appendChild(el('div', 'pc-desc', project.description || 'No description.')); + var meta = []; + if (project.github) meta.push(project.github.owner + '/' + project.github.repo); + if (health) meta.push(labelFor(health)); + if (project.api) meta.push(project.api.type + ' API'); + node.appendChild(el('div', 'pc-meta', meta.join(' · ') || 'registry entry')); + grid.appendChild(node); + }); + if (!projects.length) grid.appendChild(el('div', 'empty', 'No visible projects configured.')); + } catch (err) { + var grid = $('projectGrid'); + grid.replaceChildren(); + grid.appendChild(el('div', 'empty error', 'Project registry unavailable: ' + err.message)); + } + } + + async function loadAll() { + if (refreshing) return; + refreshing = true; + countdown = REFRESH_SECONDS; + var button = $('refreshBtn'); + button.disabled = true; + try { + await Promise.allSettled([loadStatus(), loadGitHub(), loadFedl(), loadAnalytics(), loadProjects()]); + hasLoaded = true; + } finally { + refreshing = false; + button.disabled = false; + } + } + + $('refreshBtn').addEventListener('click', loadAll); + + setInterval(function () { + if (document.hidden) return; + countdown -= 1; + if (countdown <= 0) { + countdown = REFRESH_SECONDS; + loadAll(); + } + var node = $('refreshCountdown'); + if (node) node.textContent = refreshing ? 'refreshing…' : 'auto-refresh ' + countdown + 's'; + }, 1000); + + document.addEventListener('visibilitychange', function () { + if (!document.hidden) { + countdown = REFRESH_SECONDS; + if (!hasLoaded) loadAll(); + } + }); + + loadAll(); +})(); diff --git a/docs/API.md b/docs/API.md new file mode 100644 index 0000000..1f20e4a --- /dev/null +++ b/docs/API.md @@ -0,0 +1,656 @@ +# API reference + +The backend serves both the static site and a JSON API from the same origin. +The default local base URL is `http://127.0.0.1:8787`. + +All API responses are JSON with `Cache-Control: no-store` unless noted. There +are no API keys, cookies, or visitor-supplied URLs involved in public read +endpoints. The only cookie in the system is the Moon Vault session cookie. + +## Conventions + +### Authentication + +Public read endpoints require no authentication. The Moon Vault endpoints set +and read a signed, HttpOnly session cookie named `miles_vault` (configurable +with `VAULT_COOKIE_NAME`). + +Protected content: + +- `GET /vault` — authenticated vault HTML. Redirects to `/moon-vault.html` + with `302` when there is no valid session. +- `GET /games/*` — authenticated game files. Redirects to + `/moon-vault.html` with `302` when there is no valid session. + +### Errors + +All API errors use one shape: + +```json +{ + "error": { + "code": "not_found", + "message": "API endpoint not found", + "details": {} + } +} +``` + +`details` is optional and is omitted for server errors. Internal errors never +include stack traces or secret values. + +| Status | Typical `code` values | +| --- | --- | +| 400 | `bad_request` | +| 401 | `unauthorized` | +| 403 | `forbidden` | +| 404 | `not_found`, `github_not_found` | +| 405 | `method_not_allowed` | +| 429 | `rate_limited` (includes `Retry-After`) | +| 500 | `internal_error` | +| 503 | `unavailable` | + +### CORS + +Cross-origin API requests are accepted only from the configured allowlist: +`https://milesallen.site`, `https://www.milesallen.site`, local development +origins, and the request's own origin. Unknown origins receive `403`. + +`OPTIONS` preflight requests receive `204` with `Access-Control-Allow-Origin`, +`Access-Control-Allow-Methods: GET, POST, OPTIONS`, and +`Access-Control-Allow-Headers: Content-Type`. + +### Rate limits + +Limits are per client IP and use `429` with a `Retry-After` header when +exceeded. + +| Route group | Default | +| --- | --- | +| Public API | 300 requests / minute | +| `POST /api/analytics/hit` | 120 requests / minute | +| `POST /api/vault/login` | 15 requests / 15 minutes | +| Vault failed attempts | 5 / 15 minutes per hashed IP (configurable) | + +When `TRUST_PROXY=true`, the client IP is read from `CF-Connecting-IP` or the +first `X-Forwarded-For` value. Leave it false when the Node process is directly +exposed, otherwise clients can spoof their IP. + +### Security headers + +All responses include: + +```text +X-Content-Type-Options: nosniff +X-Frame-Options: DENY +Referrer-Policy: strict-origin-when-cross-origin +Permissions-Policy: geolocation=(), microphone=(), camera=() +Cross-Origin-Opener-Policy: same-origin +Cross-Origin-Resource-Policy: same-origin +X-Request-Id: <16 hex characters> +``` + +In production, `Strict-Transport-Security: max-age=31536000; includeSubDomains` +is added. + +--- + +## Index and health + +### `GET /api` + +Returns service metadata and the endpoint list. + +```json +{ + "name": "milesallen.site dashboard API", + "version": "1.0.0", + "endpoints": ["/api/status", "/api/status/servers", "..."] +} +``` + +### `GET /api/health` + +```json +{ + "status": "ok", + "uptimeSeconds": 123, + "time": "2026-11-08T04:50:13.155Z" +} +``` + +Also accepts `HEAD`. + +--- + +## Infrastructure and service status + +### `GET /api/status` + +Combined snapshot used by the dashboard. + +```json +{ + "generatedAt": "2026-11-08T04:50:13.145Z", + "overall": { + "status": "operational", + "counts": { "operational": 5, "degraded": 0, "offline": 0, "unknown": 0, "online": 2 }, + "total": 7, + "healthy": 5, + "checkedAt": "2026-11-08T04:49:21.746Z" + }, + "network": { + "onHomeNetwork": true, + "monitoredSubnet": "10.0.0.0/24" + }, + "servers": [ + { + "id": "home-1", + "name": "Home Server 1", + "ip": "10.0.0.87", + "status": "online", + "reason": "ok", + "networkContext": true, + "lastCheckAt": "2026-11-08T04:49:21.000Z", + "lastSuccessAt": "2026-11-08T04:49:21.000Z", + "lastChangeAt": "2026-11-08T04:47:24.000Z", + "previousStatus": null, + "responseMs": 2.1, + "uptime": { "24h": 100, "7d": 100, "30d": 100 }, + "checks": 120 + } + ], + "services": [ + { + "id": "fedl", + "name": "FEDL", + "url": "https://fedl.site/", + "status": "operational", + "reason": "ok", + "lastCheckAt": "2026-11-08T04:49:21.000Z", + "lastSuccessAt": "2026-11-08T04:49:21.000Z", + "lastChangeAt": "2026-11-08T04:47:24.000Z", + "previousStatus": null, + "responseMs": 180, + "httpStatus": 200, + "uptime": { "24h": 100, "7d": 100, "30d": 100 }, + "checks": 60 + } + ] +} +``` + +Status values: + +| Component | Values | +| --- | --- | +| Server | `online`, `offline`, `unknown` | +| Service | `operational`, `degraded`, `offline`, `unknown` | +| Overall | `operational`, `degraded`, `offline`, `unknown` | + +Server failures are reported as `unknown` with +`reason: "not_on_home_network"` when the Node host is not on `HOME_SUBNET`. +Monitoring failures such as a missing `ping` binary are reported as `unknown` +with `reason` beginning `monitor_error:` so a broken monitor is not mistaken for +a down server. + +Uptime percentages are `null` when there is no data for the window. + +### `GET /api/status/servers` + +```json +{ + "generatedAt": "2026-11-08T04:50:13.149Z", + "servers": [ /* same server objects as /api/status */ ] +} +``` + +### `GET /api/status/services` + +```json +{ + "generatedAt": "2026-11-08T04:50:13.149Z", + "services": [ /* same service objects as /api/status */ ] +} +``` + +### `GET /api/status/history?days=30` + +`days` is clamped to 1–90. The response always contains one entry per day for +every configured server and service. + +```json +{ + "generatedAt": "2026-11-08T04:50:13.149Z", + "days": 30, + "servers": { + "home-1": [ + { "day": "2026-10-10", "availability": 100, "up": 1440, "total": 1440 } + ] + }, + "services": { + "fedl": [ + { "day": "2026-10-10", "availability": 100, "up": 720, "total": 720 } + ] + } +} +``` + +`availability` is `null` for a day with no checks. + +--- + +## GitHub + +Data comes from the official GitHub REST API through the server. Responses are +cached in SQLite and served stale when GitHub is unavailable or rate limited. +The token is never included in any response. + +### `GET /api/github/overview` + +```json +{ + "generatedAt": "2026-11-08T04:49:20.871Z", + "username": "mileswolfallen2", + "profile": { + "login": "mileswolfallen2", + "name": "wolf_reaper90", + "avatarUrl": "https://avatars.githubusercontent.com/u/115095719?v=4", + "bio": "A dev and 3D artist from Minnesota", + "company": null, + "location": "Minnesota", + "blog": "milesallen.site", + "followers": 16, + "following": 42, + "publicRepos": 165, + "createdAt": "2022-10-05T15:02:14Z" + }, + "rateLimit": { + "authenticated": true, + "remaining": 4949, + "resetAt": "2026-11-08T05:31:15.000Z" + }, + "totals": { + "stars": 18, + "forks": 2, + "openIssues": 13, + "trackedRepos": 14, + "publicRepos": 165 + }, + "languages": [{ "name": "JavaScript", "count": 6 }], + "recentCommits": [ + { + "repo": "mileswolfallen2/miles-web", + "project": "milesallen.site", + "branch": "main", + "sha": "abcdef1", + "message": "Commit subject", + "author": "Miles", + "date": "2026-11-08T03:00:00Z", + "url": "https://github.com/mileswolfallen2/miles-web/commit/abcdef1" + } + ], + "recentlyUpdated": [ + { "id": "miles-web", "name": "milesallen.site", "pushedAt": "2026-11-08T03:00:00Z", "latestCommit": {} } + ], + "topActive": [{ "repo": "mileswolfallen2/miles-web", "events": 4, "pushes": 2, "project": "milesallen.site" }] +} +``` + +`recentCommits` is capped at 12 and can be empty when GitHub's public events +window has no push events for the account. + +### `GET /api/github/activity` + +```json +{ + "generatedAt": "2026-11-08T04:49:20.871Z", + "username": "mileswolfallen2", + "rateLimit": {}, + "recentCommits": [], + "activity": { + "days": [{ "day": "2026-11-08", "events": 2, "pushes": 1 }], + "byRepo": [{ "repo": "mileswolfallen2/miles-web", "events": 2, "pushes": 1, "project": "milesallen.site" }] + } +} +``` + +`activity.days` always contains 30 entries. + +### `GET /api/github/repositories` + +```json +{ + "generatedAt": "2026-11-08T04:49:20.871Z", + "rateLimit": {}, + "repositories": [ + { + "id": "miles-web", + "name": "milesallen.site", + "description": "This portfolio: static HTML, hand-written CSS, no build step.", + "fullName": "mileswolfallen2/miles-web", + "url": "https://github.com/mileswolfallen2/miles-web", + "website": "https://milesallen.site", + "language": "HTML", + "stars": 0, + "forks": 0, + "openIssues": 0, + "watchers": 0, + "defaultBranch": "main", + "archived": false, + "fork": false, + "topics": [], + "pushedAt": "2026-11-08T03:00:00Z", + "updatedAt": "2026-11-08T03:00:00Z", + "createdAt": "2025-01-01T00:00:00Z", + "latestCommit": {}, + "release": null, + "contributors": null, + "featured": false + } + ] +} +``` + +Only projects marked `visible` and configured with a GitHub repo are enriched. +`release` and `contributors` are populated only when `GITHUB_ENRICH=true` and a +token is configured. Per-repo enrichment failures may appear in an `errors` +array on that repository instead of failing the whole response. + +--- + +## Projects + +### `GET /api/projects` + +Returns visible projects from `server/config/projects.json` (seeded into +SQLite), ordered by `display_order`. + +```json +{ + "generatedAt": "2026-11-08T04:50:13.153Z", + "projects": [ + { + "id": "fedl", + "name": "FEDL", + "description": "Geometry Dash demon list ...", + "github": { + "owner": "mileswolfallen2", + "repo": "fedl", + "url": "https://github.com/mileswolfallen2/fedl" + }, + "website": "https://fedl.site", + "api": { "type": "fedl", "base": "https://server.fedl.site/fedl/api" }, + "featured": true, + "health": "operational" + } + ] +} +``` + +`github` and `api` are `null` when not configured. `health` is the matching +website-check status or `null` when the project has no monitored website. + +### `GET /api/projects/:id` + +Returns one visible project by registry id. Returns `404` when the project does +not exist or is hidden. + +```json +{ + "project": { + "id": "fedl", + "name": "FEDL", + "description": "Geometry Dash demon list ...", + "github": { "owner": "mileswolfallen2", "repo": "fedl", "url": "https://github.com/mileswolfallen2/fedl" }, + "website": "https://fedl.site", + "api": { "type": "fedl", "base": "https://server.fedl.site/fedl/api" }, + "featured": true + } +} +``` + +--- + +## FEDL + +FEDL data is fetched only from the configured real API: + +- `GET {FEDL_API_BASE}/list` +- `GET {FEDL_API_BASE}/runs` + +Expected upstream shapes are `{ "items": [...] }`. The server stores snapshots, +computes diffs between the latest two snapshots, and serves the last good stats +if an upstream refresh fails. + +### `GET /api/fedl/stats` + +```json +{ + "generatedAt": "2026-11-08T04:46:24.485Z", + "site": "https://fedl.site", + "apiBase": "https://server.fedl.site/fedl/api", + "github": { "owner": "mileswolfallen2", "repo": "fedl" }, + "totals": { + "rankedLevels": 342, + "records": 3841, + "submissions": 3843, + "rejected": 2, + "pending": 0, + "players": 769 + }, + "topLevels": [ + { "title": "GRIEF", "position": 1, "url": "https://youtu.be/gB8slBPlOjc" } + ], + "recentRecords": [ + { + "id": "run_1", + "playerName": "player1", + "levelTitle": "Alpha Demon", + "percent": "100", + "videoUrl": "https://youtu.be/run1", + "status": "approved", + "notes": "", + "submittedAt": "2026-11-01T00:00:00.000Z", + "updatedAt": "2026-11-01T00:00:00.000Z", + "reviewedBy": null + } + ], + "latestUpdates": [], + "changes": { + "comparedTo": "2026-11-07T12:00:00.000Z", + "added": [{ "title": "Delta Demon", "position": 4 }], + "removed": [{ "title": "Gamma Demon", "position": 3 }], + "rankChanges": [{ "title": "Beta Demon", "from": 2, "to": 1, "delta": 1 }], + "counts": { "added": 1, "removed": 1, "rankChanges": 1 } + }, + "stale": false +} +``` + +- `comparedTo` is `null` until there are at least two snapshots. +- `stale` is `true` when the served data is a cached copy after a failed + refresh. +- `topLevels` is capped at 15, `recentRecords` at 12, and `latestUpdates` at 10. +- Diff lists are capped at 25 entries each. + +### `GET /api/fedl/activity` + +```json +{ + "generatedAt": "2026-11-08T04:46:24.485Z", + "stale": false, + "site": "https://fedl.site", + "github": { "owner": "mileswolfallen2", "repo": "fedl" }, + "changes": {}, + "recentRecords": [], + "latestUpdates": [] +} +``` + +--- + +## Analytics + +Analytics is cookieless and stores no raw IP addresses. See the privacy notes in +the README. + +### `POST /api/analytics/hit` + +Request: + +```http +POST /api/analytics/hit +Content-Type: application/json + +{ + "path": "/projects/fedl.html?utm=1#top", + "referrer": "https://www.google.com/search?q=test" +} +``` + +`path` is required and must be a same-site path. Query strings and fragments are +stripped, duplicate slashes are collapsed, `/index.html` becomes `/`, and a +trailing slash is removed except for `/`. `referrer` is optional; only its +hostname is retained. + +Response `202`: + +```json +{ "recorded": true, "reason": null } +``` + +`reason` can be `"bot"` or `"duplicate"` when the hit is intentionally ignored. +An invalid path returns `400`. Bots receive `202` with +`{ "recorded": false, "reason": "bot" }` rather than an error. + +### `GET /api/analytics/overview` + +```json +{ + "generatedAt": "2026-11-08T04:50:13.154Z", + "retentionDays": 30, + "totals": { + "pageviews": 1, + "pageviewsToday": 1, + "pageviews7d": 1, + "pageviews30d": 1, + "uniqueVisitorsToday": 1, + "uniqueVisitors7d": 1, + "uniqueVisitors30d": 1 + }, + "daily": [{ "day": "2026-11-08", "views": 1, "visitors": 1 }], + "topPages": [{ "path": "/", "views": 1, "visitors": 1 }], + "recentActivity": [ + { + "path": "/", + "referrer_domain": "www.google.com", + "created_at": "2026-11-08T04:49:35.266Z" + } + ] +} +``` + +`daily` always has 30 entries. `topPages` is limited to 10 and `recentActivity` +to 20 rows. + +### `GET /api/analytics/pages?days=30&limit=50` + +`days` is clamped to the configured retention period (default 30). `limit` is +clamped to 1–200. + +```json +{ + "generatedAt": "2026-11-08T04:50:13.155Z", + "range": { + "days": 30, + "from": "2026-10-10T00:00:00.000Z", + "to": "2026-11-09T00:00:00.000Z" + }, + "totalPageviews": 1, + "pages": [ + { + "path": "/", + "views": 1, + "visitors": 1, + "share": 100, + "lastSeen": "2026-11-08T04:49:35.266Z" + } + ] +} +``` + +--- + +## Moon Vault + +### `GET /api/vault/session` + +```json +{ "enabled": true, "authenticated": false, "expiresAt": null } +``` + +`enabled` is false when no Argon2 hash is configured. `expiresAt` is an ISO +timestamp when authenticated. + +### `POST /api/vault/login` + +Request: + +```http +POST /api/vault/login +Content-Type: application/json + +{ "password": "the passphrase" } +``` + +Success `200`: + +```json +{ "ok": true, "expiresAt": "2026-11-08T16:49:45.039Z" } +``` + +Response headers include: + +```text +Set-Cookie: miles_vault=..; Path=/; Max-Age=43200; HttpOnly; SameSite=Strict +``` + +`Secure` is appended when `COOKIE_SECURE=true`. + +Failures: + +- `401 unauthorized` — wrong passphrase or malformed password. +- `429 rate_limited` — too many attempts, with `Retry-After`. +- `503 vault_disabled` — no hash is configured (`VAULT_PASSWORD_HASH` missing). + +The session cookie is a random server-side session id plus a random token, both +signed with `SESSION_SECRET`. Only a SHA-256 hash of the token is stored in +SQLite. The session survives server restarts until it expires. + +### `POST /api/vault/logout` + +```json +{ "ok": true } +``` + +Clears the cookie and deletes the server-side session. + +--- + +## Static and protected pages + +| Route | Behavior | +| --- | --- | +| `GET /` | Serves `index.html` with `Cache-Control: no-cache` | +| `GET /dashboard.html` | Dashboard UI | +| `GET /moon-vault.html` | Public vault lock screen; contains no passphrase | +| `GET /vault` | `200` authenticated vault HTML, otherwise `302` to `/moon-vault.html` | +| `GET /games/*` | `200` authenticated game assets, otherwise `302` to `/moon-vault.html` | +| `GET /analytics.js` | Privacy-friendly pageview beacon | +| Missing file | Serves `404.html` with status `404` | + +Static serving blocks path traversal and private paths (`.env`, `.git`, +`node_modules`, `server`, `tests`, `data`, `docs`, `share-server`, +`package.json`, database files). HTML is served with `no-cache`; other files use +`public, max-age=3600`. Range requests are supported for media files. diff --git a/docs/DEPLOYMENT.md b/docs/DEPLOYMENT.md new file mode 100644 index 0000000..231a2ee --- /dev/null +++ b/docs/DEPLOYMENT.md @@ -0,0 +1,554 @@ +# Deployment guide — Debian 13 + +This guide describes how to run the backend on a Debian 13 host behind Caddy or +Cloudflare Tunnel. It is written to be followed and verified step by step. The +repository does not perform the deployment for you. + +The app is a single Node.js process that serves the static site and the API from +the same origin. SQLite is the only database. There is no Docker, external +database, or frontend build step. + +## 1. Target layout + +| Path | Purpose | +| --- | --- | +| `/opt/miles-web` | Repository, static site, backend, `.env` | +| `/var/lib/miles-dashboard/dashboard.db` | SQLite database | +| `/var/backups/miles-dashboard/` | SQLite backups | +| `/etc/systemd/system/miles-dashboard.service` | systemd unit | +| `/etc/caddy/Caddyfile` | Caddy reverse proxy (if used) | +| `/etc/cloudflared/config.yml` | Cloudflare Tunnel config (if used) | + +Use Caddy **or** Cloudflare Tunnel as the public entry point. Running both is +possible but adds a second moving part; if you do, point the tunnel at Caddy and +do not expose the Node process directly. + +## 2. Prerequisites + +```bash +sudo apt update +sudo apt install -y git curl ca-certificates build-essential python3 iputils-ping sqlite3 +``` + +Check `ping` exists: + +```bash +command -v ping +ping -c 1 10.0.0.87 +``` + +### Node.js 20 or newer + +Debian's `nodejs` package may be old enough to be a problem. Verify: + +```bash +node -v +``` + +If it is below 20, install Node 20 LTS from NodeSource: + +```bash +curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash - +sudo apt install -y nodejs +node -v +npm -v +``` + +Do not use `sudo npm`. Install dependencies as the service user. + +## 3. Service user and directories + +```bash +sudo useradd --system --create-home \ + --home-dir /var/lib/miles-dashboard \ + --shell /usr/sbin/nologin miles +sudo mkdir -p /opt/miles-web /var/lib/miles-dashboard /var/backups/miles-dashboard +sudo chown -R miles:miles /opt/miles-web /var/lib/miles-dashboard /var/backups/miles-dashboard +``` + +Clone the repository into `/opt/miles-web` (the directory must be empty): + +```bash +sudo -u miles git clone /opt/miles-web +cd /opt/miles-web +sudo -u miles npm ci --omit=dev +``` + +If you are deploying from a checkout rather than a remote, copy the files and +then run `npm ci --omit=dev` as `miles`. + +### If native modules fail to build + +`better-sqlite3` and `argon2` compile native code. If installation fails: + +```bash +sudo apt install -y build-essential python3 +cd /opt/miles-web +sudo -u miles npm rebuild better-sqlite3 argon2 +``` + +## 4. Environment file + +```bash +cd /opt/miles-web +sudo -u miles cp .env.example .env +sudo -u miles chmod 600 .env +sudo -u miles editor .env +``` + +Production values to set: + +```dotenv +NODE_ENV=production +HOST=127.0.0.1 +PORT=8787 +PUBLIC_ORIGIN=https://milesallen.site +TRUST_PROXY=true +DB_PATH=/var/lib/miles-dashboard/dashboard.db +SITE_ROOT=/opt/miles-web +COOKIE_SECURE=true +GITHUB_USERNAME=mileswolfallen2 +GITHUB_TOKEN= +VAULT_PASSWORD_HASH= +``` + +Generate the session secret: + +```bash +openssl rand -hex 32 +``` + +Put the output in `SESSION_SECRET`. It must be at least 32 characters in +production. Do not reuse the development secret. + +Generate the vault hash without putting the passphrase in shell history: + +```bash +read -rsp "Vault passphrase: " VAULT_PASS; echo +printf '%s' "$VAULT_PASS" | sudo -u miles npm run hash-password +unset VAULT_PASS +``` + +Copy the printed `VAULT_PASSWORD_HASH=...` line into `.env`. + +Notes: + +- `HOST=127.0.0.1` is correct when Caddy or Cloudflare Tunnel runs on the same + host. Do not bind `0.0.0.0` unless you intend to expose port 8787 directly. +- `TRUST_PROXY=true` is safe only behind a trusted local proxy that overwrites + `CF-Connecting-IP` or `X-Forwarded-For`. On a directly exposed listener it + would let clients spoof their IP. +- `COOKIE_SECURE=true` requires HTTPS in the browser. Use it in production. +- `GITHUB_TOKEN` is optional for public data but raises the rate limit. A + classic token with no scopes is sufficient. Never put it in frontend files. +- `VAULT_PASSWORD_HASH` must start with `$argon2`. If it is missing, the vault + is disabled and refuses logins. + +## 5. Initialize the database + +```bash +cd /opt/miles-web +sudo -u miles npm run db:migrate +``` + +Expected output includes the database path and the table list. The directory +`/var/lib/miles-dashboard` must be writable by `miles`. + +SQLite runs in WAL mode. The app creates `dashboard.db`, `dashboard.db-wal`, +and `dashboard.db-shm`. Back up all three safely with the SQLite backup command +in section 9; do not copy only the main file while the service is running. + +## 6. systemd service + +Create `/etc/systemd/system/miles-dashboard.service`: + +```ini +[Unit] +Description=milesallen.site dashboard +Documentation=https://github.com/mileswolfallen2/miles-web +After=network-online.target +Wants=network-online.target + +[Service] +Type=simple +User=miles +Group=miles +WorkingDirectory=/opt/miles-web +EnvironmentFile=/opt/miles-web/.env +ExecStart=/usr/bin/node server/index.js +Restart=on-failure +RestartSec=5 +TimeoutStopSec=20 +KillSignal=SIGTERM +StandardOutput=journal +StandardError=journal + +# Hardening. /opt/miles-web is read-only to the service; the DB directory is +# the only writable path. +NoNewPrivileges=yes +PrivateTmp=yes +ProtectSystem=strict +ProtectHome=yes +ReadWritePaths=/var/lib/miles-dashboard +CapabilityBoundingSet=CAP_NET_RAW +AmbientCapabilities=CAP_NET_RAW + +[Install] +WantedBy=multi-user.target +``` + +`CAP_NET_RAW` lets the child `ping` process send ICMP without running the whole +service as root. If your host's `ping` works through unprivileged ICMP sockets +and you prefer not to grant any capability, remove the two capability lines and +verify monitoring still works. If pings fail only under systemd, see +[Troubleshooting](#12-troubleshooting). + +Reload and start: + +```bash +sudo systemctl daemon-reload +sudo systemctl enable --now miles-dashboard +sudo systemctl status miles-dashboard --no-pager +sudo journalctl -u miles-dashboard -n 100 --no-pager +``` + +Expected log line: + +```text +dashboard listening url=http://127.0.0.1:8787 env=production vault=enabled github=authenticated +``` + +Verify locally: + +```bash +curl -fsS http://127.0.0.1:8787/api/health +curl -fsS http://127.0.0.1:8787/api/status | head -c 500 +``` + +The smoke script is intended for local verification. On a production database +it records one synthetic `/smoke-test` analytics pageview: + +```bash +cd /opt/miles-web +sudo -u miles npm run smoke +``` + +## 7. Reverse proxy with Caddy + +Install Caddy from the official repository: + +```bash +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 +``` + +Replace `/etc/caddy/Caddyfile`: + +```caddyfile +milesallen.site, www.milesallen.site { + encode zstd gzip + reverse_proxy 127.0.0.1:8787 +} +``` + +Caddy obtains and renews TLS certificates automatically. Validate and reload: + +```bash +sudo caddy validate --config /etc/caddy/Caddyfile +sudo systemctl reload caddy +sudo journalctl -u caddy -n 50 --no-pager +``` + +Make sure DNS points `milesallen.site` and `www.milesallen.site` at the host +before Caddy tries to issue certificates. Open only the ports you need: + +```bash +sudo ufw allow 22/tcp +sudo ufw allow 80/tcp +sudo ufw allow 443/tcp +sudo ufw enable +``` + +Do **not** expose port 8787. + +With Caddy in front: + +- `TRUST_PROXY=true` +- `COOKIE_SECURE=true` +- `PUBLIC_ORIGIN=https://milesallen.site` +- Keep `HOST=127.0.0.1` + +Caddy sets `X-Forwarded-For`; the app reads it only when `TRUST_PROXY=true`. + +## 8. Cloudflare Tunnel alternative + +Use this instead of public ports and Caddy. The origin can stay on loopback and +no inbound 80/443 is required. + +Install `cloudflared` using Cloudflare's current Debian instructions, then: + +```bash +cloudflared tunnel login +cloudflared tunnel create miles-dashboard +cloudflared tunnel route dns miles-dashboard milesallen.site +cloudflared tunnel route dns miles-dashboard www.milesallen.site +``` + +Create `/etc/cloudflared/config.yml`: + +```yaml +tunnel: +credentials-file: /etc/cloudflared/.json +ingress: + - hostname: milesallen.site + service: http://127.0.0.1:8787 + - hostname: www.milesallen.site + service: http://127.0.0.1:8787 + - service: http_status:404 +``` + +Validate and install the service: + +```bash +sudo cloudflared tunnel ingress validate +sudo cloudflared service install +sudo systemctl enable --now cloudflared +sudo systemctl status cloudflared --no-pager +``` + +Keep `HOST=127.0.0.1`, set `TRUST_PROXY=true` (Cloudflare sets +`CF-Connecting-IP`), and keep `COOKIE_SECURE=true`. No `ufw` rule for 8787, +80, or 443 is needed for the tunnel path. + +## 9. Persistence, backups, and restore + +### What persists + +- `projects`, `services`, and `servers` are seeded from the JSON registry on + every startup. +- Checks, pageviews, cache entries, FEDL snapshots, and vault sessions live in + `dashboard.db`. +- `.env` holds secrets and deployment configuration. It is not in git. + +### Retention enforced by the app + +A cleanup pass runs every six hours and at startup: + +- Analytics rows older than `ANALYTICS_RETENTION_DAYS` (default 30). +- Monitor checks older than `MONITOR_RETENTION_DAYS` (default 90). +- FEDL snapshots are pruned to the newest 50. +- Expired vault sessions and vault attempts older than 24 hours. + +### Online SQLite backup + +```bash +sudo mkdir -p /var/backups/miles-dashboard +sudo sqlite3 /var/lib/miles-dashboard/dashboard.db \ + ".backup '/var/backups/miles-dashboard/dashboard-$(date +%F-%H%M).db'" +``` + +This is safe while the service is running. Verify the backup: + +```bash +sudo sqlite3 /var/backups/miles-dashboard/dashboard-YYYY-MM-DD-HHMM.db \ + "PRAGMA integrity_check; SELECT COUNT(*) FROM pageviews;" +``` + +Daily cron example (`/etc/cron.d/miles-dashboard-backup`): + +```cron +17 3 * * * miles /usr/bin/sqlite3 /var/lib/miles-dashboard/dashboard.db ".backup '/var/backups/miles-dashboard/dashboard-$(date +\%F).db'" && find /var/backups/miles-dashboard -name 'dashboard-*.db' -mtime +14 -delete +``` + +The `%` characters must be escaped as `\%` in cron. + +### Restore + +```bash +sudo systemctl stop miles-dashboard +sudo rm -f /var/lib/miles-dashboard/dashboard.db-wal /var/lib/miles-dashboard/dashboard.db-shm +sudo cp /var/lib/miles-dashboard/dashboard.db /var/lib/miles-dashboard/dashboard.db.before-restore +sudo cp /var/backups/miles-dashboard/dashboard-YYYY-MM-DD.db /var/lib/miles-dashboard/dashboard.db +sudo chown miles:miles /var/lib/miles-dashboard/dashboard.db +sudo systemctl start miles-dashboard +curl -fsS http://127.0.0.1:8787/api/health +``` + +## 10. Upgrades + +```bash +cd /opt/miles-web +sudo -u miles git pull --ff-only +sudo -u miles npm ci --omit=dev +sudo -u miles npm run db:migrate +sudo systemctl restart miles-dashboard +sudo journalctl -u miles-dashboard -n 50 --no-pager +``` + +Run `npm test` on a development machine before deploying changes. Migrations are +idempotent and tracked in `schema_migrations`. + +After a Node major-version upgrade, rebuild native modules if needed: + +```bash +cd /opt/miles-web +sudo -u miles npm rebuild better-sqlite3 argon2 +sudo systemctl restart miles-dashboard +``` + +## 11. Verification checklist + +Run these after deployment: + +```bash +# Process and logs +sudo systemctl status miles-dashboard --no-pager +sudo journalctl -u miles-dashboard -n 50 --no-pager + +# Local health +curl -fsS http://127.0.0.1:8787/api/health +curl -fsS http://127.0.0.1:8787/api/status + +# Public site through the proxy +curl -fsS https://milesallen.site/api/health +curl -fsS -o /dev/null -w '%{http_code}\n' https://milesallen.site/ +curl -fsS -o /dev/null -w '%{http_code}\n' https://milesallen.site/dashboard.html + +# Vault is locked without a session +curl -s -o /dev/null -w '%{http_code} %{redirect_url}\n' https://milesallen.site/vault +curl -s -o /dev/null -w '%{http_code} %{redirect_url}\n' https://milesallen.site/games/dino.html + +# Private files are not served +curl -s -o /dev/null -w '%{http_code}\n' https://milesallen.site/.env +curl -s -o /dev/null -w '%{http_code}\n' https://milesallen.site/server/config.js +curl -s -o /dev/null -w '%{http_code}\n' https://milesallen.site/data/dashboard.db +``` + +Expected result for the private-file checks is `403`. The vault and game checks +should return `302` to `/moon-vault.html` before login. + +Then verify in a browser: + +- The dashboard loads and shows live values (or explicit unavailable states). +- Home-server checks are `online` when the server is on the home LAN. +- The vault login works with the production passphrase; the session survives a + server restart; logout returns to the lock page. +- A game loads only after login. +- The analytics totals increase after a page view (allow for deduplication and + bot filtering). + +## 12. Troubleshooting + +### `better-sqlite3` or `argon2` fails to install + +```bash +sudo apt install -y build-essential python3 +cd /opt/miles-web +sudo -u miles npm rebuild better-sqlite3 argon2 +``` + +### Servers show `unknown` with `monitor_error:ping_unavailable` + +The monitor could not run `ping`. Check: + +```bash +command -v ping +ping -c 1 10.0.0.87 +getcap "$(command -v ping)" 2>/dev/null || true +sysctl net.ipv4.ping_group_range +``` + +Fix options, in order of preference: + +1. Allow unprivileged ICMP for the service group by setting + `net.ipv4.ping_group_range` appropriately. +2. Keep the systemd `AmbientCapabilities=CAP_NET_RAW` and + `CapabilityBoundingSet=CAP_NET_RAW` lines. +3. Remove `NoNewPrivileges=yes` temporarily to test whether it is blocking a + setuid/capability-based `ping`, then choose a narrower fix. + +Never make the Node process run as root just to ping two hosts. + +### Servers show `unknown` with `not_on_home_network` + +The host's local addresses do not match `HOME_SUBNET`. Set it to the real +subnet (for example `HOME_SUBNET=10.0.0.0/24`) and restart. This is intentional: +a failed ping from a remote network is not reported as a home-server outage. + +### Website checks all fail + +Check outbound HTTPS and DNS from the server: + +```bash +curl -I https://milesallen.site/ +curl -I https://fedl.site/ +curl -I https://server.fedl.site/fedl/api/list +``` + +The app only checks configured URLs. It never accepts a visitor-supplied URL. + +### Vault is disabled + +The log says `vault: disabled` or the API returns `503 vault_disabled` when no +`VAULT_PASSWORD_HASH` is set. Generate one with `npm run hash-password`, add it +to `.env`, and restart. The hash must start with `$argon2`. + +### Login succeeds but the browser is not authenticated + +- If serving over plain HTTP with `COOKIE_SECURE=true`, the browser discards + the cookie. Use HTTPS or set `COOKIE_SECURE=false` for local-only testing. +- Confirm the browser is using the same origin as `PUBLIC_ORIGIN`. +- Confirm `SESSION_SECRET` did not change and the database was not wiped. +- Check that `TRUST_PROXY` matches the actual proxy setup. + +### API returns `403 forbidden` cross-origin + +The request origin is not in the allowlist. Set `PUBLIC_ORIGIN` and +`ALLOWED_ORIGINS` to the real HTTPS origins. Same-origin requests are always +accepted. + +### `SQLITE_BUSY` or database locked + +Run one service instance only. The app uses WAL mode and short statements; a +second process writing the same file is the usual cause. Do not run +`npm run dev` and the systemd service against the same database. + +### GitHub data is stale or missing + +- Check the token and rate limit: `curl -H "Authorization: Bearer $TOKEN" https://api.github.com/rate_limit`. +- Without a token, the anonymous limit is low and the dashboard will serve + cached data. +- `GITHUB_ENRICH=true` requires a token and makes more API calls. + +### FEDL data is stale + +The dashboard sets `stale: true` and serves the last good snapshot when the FEDL +API is unreachable. Check the upstream API directly: + +```bash +curl -fsS https://server.fedl.site/fedl/api/list | head -c 200 +curl -fsS https://server.fedl.site/fedl/api/runs | head -c 200 +``` + +## 13. Security checklist + +- [ ] `.env` is mode `600`, owned by the service user, and not in git. +- [ ] `SESSION_SECRET` is a fresh 32+ byte random value. +- [ ] `VAULT_PASSWORD_HASH` is Argon2id and the plaintext passphrase is not in + any file, git history, or shell history. +- [ ] `HOST=127.0.0.1` and port 8787 is not reachable from the internet. +- [ ] `COOKIE_SECURE=true` and the public site is HTTPS. +- [ ] `TRUST_PROXY=true` only behind Caddy/Cloudflare Tunnel. +- [ ] GitHub token is server-only, minimal scope, and never in frontend code. +- [ ] Backups are enabled and a restore has been tested. +- [ ] `/vault` and `/games/*` redirect without a session. +- [ ] Vault and game responses send `Cache-Control: no-store`, so protected + content is not replayed from browser cache after logout. +- [ ] `/.env`, `/server/`, and `/data/` return `403`. +- [ ] `npm test` passes on the deployed revision. +- [ ] Node.js receives security updates. diff --git a/index.html b/index.html index 834a197..295c055 100644 --- a/index.html +++ b/index.html @@ -1621,6 +1621,8 @@