Release v1.2.9: Aktivitaetslog im Admin-Dashboard, Demo wieder online
Wer sich anmeldet, wer es vergeblich versucht und was ein Admin aendert, stand bisher nirgends — der Server hat schlicht nichts protokolliert. Aktivitaetslog: - ./data/audit.log, eine JSON-Zeile pro Event, angehaengt statt neu geschrieben. Bewusst NICHT in db.json: die Datei wird bei jedem Save komplett neu geschrieben, und der Login-Handshake ist unauthentifiziert — ein Log darin haette aus einem Muell-Request einen vollen Rewrite gemacht. - Aufbewahrung ist eine Obergrenze, kein Archiv: AUDIT_MAX (5000) bzw. AUDIT_DAYS (90). - Per Default an (AUDIT_LOG=0 schaltet es ganz ab). IP-Adressen per Default AUS; AUDIT_IP=net speichert nur das Netz, full die ganze Adresse. Nie der User-Agent, nie die Passkey-ID eines Fehlversuchs, nie ein abgelehnter Invite-Code. - Adresse kommt aus CF-Connecting-IP, dann X-Forwarded-For, dann X-Real-IP — ein Cloudflare-Tunnel schreibt den Besucher NICHT in XFF, dort steht sonst nur der Tunnel selbst und sieht dabei voellig plausibel aus. - Loeschen wird selbst protokolliert, die Event-IDs zaehlen weiter: die Luecke bleibt sichtbar. - Neue Karte in views/Admin.jsx (Filter, "Show more"), Aufbereitung in lib/audit.js mit 20 Tests. GET /api/admin/audit und POST /api/admin/audit/clear, beide hinter requireAdmin. Demo: - Die Live-Demo laeuft wieder, jetzt auf der Projektseite selbst statt auf GitHub Pages: opengym.duarte-santos.ch/demo/. Das eingebettete Telefon auf der Startseite geht damit auch wieder — es muss derselbe Host sein, X-Frame-Options ist SAMEORIGIN. Doku: README-Config-Tabelle, .env.example, SELF_HOSTING, SECURITY (inkl. der api/server.js-Zeilenverweise, die wieder stimmen).
This commit is contained in:
1 parent
e709f152c8
commit
8b99a644ed
17 files changed
+658
-67
No files matched your search
@@ -42,6 +42,41 @@ RP_NAME=openGym
|
||||
#
|
||||
# ALLOW_GUEST=0
|
||||
|
||||
# ── Activity log (optional) ────────────────────────────────────────────────
|
||||
# The admin dashboard shows an activity log: who signed in, who tried and
|
||||
# failed, and every admin action (disabling an account, creating or revoking an
|
||||
# invite code). It lives in ./data/audit.log, one JSON object per line, so you
|
||||
# can also just read it with `tail` or `jq`.
|
||||
#
|
||||
# It is ON by default. It records strictly less than this instance already
|
||||
# holds — every profile is in db.json and every workout is in state-<uid>.json,
|
||||
# both readable by any admin — and a log that ships switched off tells you
|
||||
# nothing on the day you need it. Turn it off completely with:
|
||||
#
|
||||
# AUDIT_LOG=0
|
||||
#
|
||||
# Retention is a cap, not an archive. Whichever limit is reached first wins;
|
||||
# set either to 0 to disable that limit:
|
||||
#
|
||||
# AUDIT_MAX=5000 # events kept
|
||||
# AUDIT_DAYS=90 # days kept
|
||||
#
|
||||
# IP addresses are the one thing that is OFF unless you ask, because they are
|
||||
# the only field here that says where somebody physically is. They are also the
|
||||
# only way to tell one failed sign-in from twenty. Three settings:
|
||||
#
|
||||
# AUDIT_IP=off # default — no addresses at all
|
||||
# AUDIT_IP=net # network only: 203.0.113.0/24, 2001:db8:1::/48
|
||||
# AUDIT_IP=full # the whole address
|
||||
#
|
||||
# The address is read from CF-Connecting-IP, then the first entry of
|
||||
# X-Forwarded-For, then X-Real-IP. The web container sets the last two, so the
|
||||
# bundled stack is correct as-is. Cloudflare is first in that list on purpose: a
|
||||
# Cloudflare tunnel does not put the visitor in X-Forwarded-For at all, so that
|
||||
# header would otherwise record the tunnel itself and look perfectly plausible.
|
||||
# Whatever you run in front has to overwrite these headers rather than pass a
|
||||
# client-supplied one through — they are only as trustworthy as your proxy.
|
||||
|
||||
# ── Session length (optional) ──────────────────────────────────────────────
|
||||
# How long a sign-in lasts, in days. Default 90 — long enough that people who
|
||||
# train regularly never see a login screen, short enough that a stolen cookie
|
||||
|
||||
@@ -1,5 +1,10 @@
|
||||
# Publishes the browser-only demo to GitHub Pages: https://duartesantos8.github.io/openGym/
|
||||
#
|
||||
# DORMANT since 2026-08-19, when the GitHub account was suspended. The demo is now built with the
|
||||
# same command below and served from the project's own site at https://opengym.duarte-santos.ch/demo/
|
||||
# (Vite's base is './', so it drops into a subdirectory unchanged). Kept for the day the account
|
||||
# comes back, exactly like the other workflows in this folder.
|
||||
#
|
||||
# Pages serves static files only, so this build has no backend — VITE_DEMO=1 makes the app
|
||||
# boot straight into guest mode with a seeded example history (see frontend/src/lib/demo.js).
|
||||
# The exercise images/GIFs (~140 MB) are never committed here; the demo build points at the
|
||||
|
||||
@@ -1,5 +1,51 @@
|
||||
# Changelog
|
||||
|
||||
## v1.2.9 — 2026-08-23
|
||||
|
||||
If you run openGym for other people, you have had no way to answer "who signed in, and when?" —
|
||||
the server kept no record of anything. It does now: an **activity log** in the admin dashboard,
|
||||
covering sign-ins, sign-outs, the attempts that failed, and every admin action. The other half of
|
||||
this release is that **the live demo is back**, self-hosted this time, after two months offline.
|
||||
|
||||
### Activity log
|
||||
|
||||
- 🧾 **The admin dashboard has an activity log.** Successful and failed sign-ins, profile
|
||||
creations and refused signups, sign-outs (including "sign out everywhere"), and every admin
|
||||
action: disabling or re-enabling an account, creating or revoking an invite code, and clearing
|
||||
the log itself. Filter it by sign-ins, admin actions or failures, and page back through it.
|
||||
- 📄 **It is a plain file.** `./data/audit.log`, one JSON object per line — `tail -f` and `jq`
|
||||
read it directly, which also means it is its own export format. Deliberately *not* part of
|
||||
`db.json`: that file is rewritten in full on every save, and the sign-in handshake is
|
||||
unauthenticated, so a log living in there would have turned one junk request into a full
|
||||
rewrite. Retention is a cap rather than an archive — the last `AUDIT_MAX` events (5,000) or
|
||||
`AUDIT_DAYS` days (90), whichever runs out first.
|
||||
- 🔒 **It records less than you might expect, on purpose.** No IP addresses unless you turn them
|
||||
on (`AUDIT_IP=net` keeps only the network, `full` keeps the address); never the browser's
|
||||
user-agent; and never the passkey id behind a failed sign-in, because that id is a stable handle
|
||||
for one device and storing it would let an admin follow an unknown device from one attempt to
|
||||
the next. A rejected invite code is not stored either — a near-miss guess sitting in a log file
|
||||
helps nobody.
|
||||
- 🧹 **Clearing it is itself logged**, and the event ids keep counting, so an erased stretch always
|
||||
leaves a visible gap.
|
||||
- ⚙️ **On by default when you update, and one variable turns it off.** It records strictly less
|
||||
than your instance already holds — every profile is in `db.json`, every workout is in
|
||||
`state-<uid>.json`, and any admin can already read both — and a log that ships switched off
|
||||
tells you nothing on the day you need it. `AUDIT_LOG=0` disables it completely; no file is
|
||||
written. Nothing leaves your server either way: this is a local file, not telemetry.
|
||||
- Guests still never appear anywhere — guest mode does not talk to the server at all.
|
||||
|
||||
### The live demo is back
|
||||
|
||||
- ▶️ **<https://opengym.duarte-santos.ch/demo/>** — the in-browser demo, running on the project's
|
||||
own site instead of GitHub Pages, which went down in August with the suspended account. Same
|
||||
build as before: no backend, no account, seeded example history, and a reset button in its
|
||||
settings. The embedded demo on the landing page works again too.
|
||||
|
||||
### Housekeeping
|
||||
|
||||
- The self-hosting docs, `SECURITY.md` and `.env.example` cover the activity log, and the
|
||||
`api/server.js` line references in `SECURITY.md` are accurate again.
|
||||
|
||||
## v1.2.8 — 2026-08-22
|
||||
|
||||
A housekeeping release, and two things worth reading even if you skip the rest. openGym has moved
|
||||
|
||||
@@ -42,8 +42,8 @@ No account on someone else's server, no subscription, no ads. Just `docker compo
|
||||
### [🌐 opengym.duarte-santos.ch](https://opengym.duarte-santos.ch) · [📦 Source on gitea.com](https://gitea.com/DuarteSantos/openGym)
|
||||
|
||||
Screenshots, docs and the APK download live on the site.<br>
|
||||
<sub>The browser demo was hosted on GitHub Pages and is offline while that account is
|
||||
suspended — self-host it (below) or sideload the Android app to try it for real.</sub>
|
||||
<sub>Want to poke at it first? The <a href="https://opengym.duarte-santos.ch/demo/">in-browser
|
||||
demo</a> is the real app with example data — no account, nothing to install.</sub>
|
||||
|
||||
</div>
|
||||
|
||||
@@ -79,7 +79,7 @@ as a home-screen app, passkey sign-in, offline support, sync across your phone a
|
||||
- 💪 **Muscle map, three ways** — a front-and-back body diagram you can read as **Balance** (where the volume went, over a week, a month or all time — naming the muscles you *haven't* trained), **Fatigue** (what is still recovering, weighted by how close each set was to your maximum, decaying smoothly rather than expiring at a window edge) or **Strength** (how long since you trained each muscle, and behind every one the exercises that built it with their estimated 1RM). It previews what a routine hits while you build it, and shows what you just trained when you finish. Male or female figure, your pick
|
||||
- 🔔 **Push notifications** — rest-timer alerts even with the app closed, plus an optional reminder on days you have a workout planned but haven't logged one. Opt in per profile; keys are generated on first run, nothing to configure
|
||||
- 🔑 **Passkeys, not passwords** — Face ID / Touch ID / fingerprint login; each profile keeps its own data, synced across devices. Sign-ins last 90 days by default (configurable), and “sign out everywhere” in Settings ends every session on every device at once
|
||||
- 🛠️ **Admin dashboard** (optional) — for whoever runs the instance: who's training right now, per-user history, disable accounts, and invite-only signup. Off by default, so a fresh instance stays open with no admin
|
||||
- 🛠️ **Admin dashboard** (optional) — for whoever runs the instance: who's training right now, per-user history, disable accounts, invite-only signup, and an **activity log** of sign-ins, failed attempts and admin actions. Off by default, so a fresh instance stays open with no admin
|
||||
- 🎨 **Designed, not assembled** — light/dark themes and 8 accent colors saved to your profile, over a hand-drawn icon set instead of emoji, so it looks the same on every phone
|
||||
- 🌍 **12 languages** — full UI translation (EN, DE, ES, FR, IT, PT, PL, TR, RU, ZH, KO, HI); exercise instructions localized in 10 of them, loaded on demand so the app stays fast
|
||||
- 📥 **Bring your history with you** — import from **FitNotes** (Android and iOS), **Strong** and **Hevy**, or body weight straight out of an **Apple Health** export. Exercise names are matched against the library and anything unrecognised becomes one of your own exercises, so nothing in the file is dropped
|
||||
@@ -151,7 +151,8 @@ mobile app is the install-and-done flavor.
|
||||
## Your data
|
||||
|
||||
Lives in `./data` on your host: `db.json` (profiles + public passkeys), `state-<user>.json`
|
||||
(each user's plan, workouts, body weight, settings), and `secret` (the session-cookie key).
|
||||
(each user's plan, workouts, body weight, settings), `audit.log` (the admin activity log — sign-ins
|
||||
and admin actions, no IP addresses unless you ask for them) and `secret` (the session-cookie key).
|
||||
**Back up `./data` and you've backed up everything.** Passkey private keys never touch the
|
||||
server — they stay in your phone's secure hardware / your password manager.
|
||||
|
||||
@@ -172,6 +173,10 @@ All via `.env` (see `.env.example`):
|
||||
| `ADMIN_UIDS` | User ids that get the admin dashboard (comma-separated) | *(none)* |
|
||||
| `INVITE_ONLY` | Require an invite code to create a profile | *(off)* |
|
||||
| `ALLOW_GUEST` | Offer "Continue without account" — set `0` to require a profile | *(on)* |
|
||||
| `AUDIT_LOG` | Record sign-ins and admin actions — set `0` to record nothing | *(on)* |
|
||||
| `AUDIT_MAX` | Events kept in the activity log; `0` for no limit | `5000` |
|
||||
| `AUDIT_DAYS` | Days kept in the activity log; `0` to keep until `AUDIT_MAX` | `90` |
|
||||
| `AUDIT_IP` | Record the caller's address: `off`, `net` (network only) or `full` | `off` |
|
||||
| `VAPID_SUBJECT` | Contact URL sent with push notifications | your `ORIGIN` |
|
||||
|
||||
Push notification keys are generated on first run and saved to `./data/vapid.json` — nothing to set.
|
||||
|
||||
+41
-18
@@ -79,65 +79,88 @@ Read this before hosting openGym for anyone other than yourself.
|
||||
- **Passkeys only.** No passwords, no email addresses, no reset flow. Registration and login are
|
||||
verified server-side by `@simplewebauthn/server` against `expectedOrigin: ORIGIN` and
|
||||
`expectedRPID: RP_ID`, and the authenticator's signature counter is stored and updated on every
|
||||
login (`api/server.js:292-318`, `api/server.js:338-358`).
|
||||
login (`api/server.js:382-432`, `api/server.js:443-492`).
|
||||
- **Sessions are a signed cookie.** `gymsid` carries `<uid>:<expiry>:<version>` plus an
|
||||
HMAC-SHA256 tag over it, compared in constant time (`api/server.js:148-161`). The key is 32
|
||||
HMAC-SHA256 tag over it, compared in constant time (`api/server.js:153-166`). The key is 32
|
||||
random bytes generated on first run and written to `./data/secret` with mode `0600`
|
||||
(`api/server.js:34-36`). The cookie is `HttpOnly` and `SameSite=Lax`, and gets `Secure` **only
|
||||
when `ORIGIN` starts with `https:`** (`api/server.js:29`, `api/server.js:198-201`).
|
||||
(`api/server.js:39-41`). The cookie is `HttpOnly` and `SameSite=Lax`, and gets `Secure` **only
|
||||
when `ORIGIN` starts with `https:`** (`api/server.js:34`, `api/server.js:205-208`).
|
||||
- **Any user can end every session they have.** `POST /api/logout/all` increments that account's
|
||||
session version, and every authenticated request checks the version in the cookie against the
|
||||
one on the user record (`api/server.js:167`, `api/server.js:187-188`), so every cookie ever
|
||||
one on the user record (`api/server.js:172`, `api/server.js:192-193`), so every cookie ever
|
||||
issued for the account — on every device, including a copy someone walked off with — stops
|
||||
verifying at once. Passkeys are untouched; signing back in works immediately.
|
||||
- **Data is isolated per user by the session's uid.** `GET`/`PUT /api/data` only ever touch
|
||||
`state-<uid>.json` for the caller (`api/server.js:375-392`); no route lets a normal user name
|
||||
`state-<uid>.json` for the caller (`api/server.js:517-534`); no route lets a normal user name
|
||||
another user.
|
||||
- **Disabling an account takes effect immediately.** Every authenticated request and every login
|
||||
is rejected for a disabled user (`api/server.js:184`, `api/server.js:357`).
|
||||
is rejected for a disabled user (`api/server.js:189`, `api/server.js:488`).
|
||||
- **There is an activity log.** Sign-ins, sign-outs, failed and refused attempts, and every admin
|
||||
action are appended to `./data/audit.log`, one JSON object per line, and shown in the admin
|
||||
dashboard. It is on by default (`AUDIT_LOG=0` disables it) and capped at `AUDIT_MAX` events /
|
||||
`AUDIT_DAYS` days. Clearing it from the dashboard is itself recorded and the event ids keep
|
||||
counting, so an erased stretch always leaves a visible gap.
|
||||
|
||||
### What it does not do
|
||||
|
||||
- **Nothing in `./data` is encrypted.** It holds `db.json` (users, passkey public keys, push
|
||||
subscriptions, invite codes), one `state-<uid>.json` per user with their complete workout
|
||||
history and body-weight log, `secret`, and `vapid.json`. Anyone who can read that folder — you,
|
||||
history and body-weight log, `audit.log`, `secret`, and `vapid.json`. Anyone who can read that folder — you,
|
||||
whoever holds the backups, whoever gets into the host — can read every user's data, and with
|
||||
`secret` can mint a valid session cookie for any account. **If you host openGym for other
|
||||
people, they are trusting you exactly as much as they'd trust any server operator.**
|
||||
people, they are trusting you exactly as much as they'd trust any server operator.** With the
|
||||
activity log on, `./data/audit.log` adds everyone's sign-in times to that — worth remembering
|
||||
before an archive of `./data` goes somewhere you don't run.
|
||||
- **Admins can read everything.** A user listed in `ADMIN_UIDS` (or flagged `admin: true` in
|
||||
`db.json`) gets every user's full history and body weight, can disable accounts, and can create
|
||||
or revoke invite codes (`api/server.js:460-540`). Off by default — a fresh instance has no admin.
|
||||
or revoke invite codes (`api/server.js:600-722`). Off by default — a fresh instance has no admin.
|
||||
- **Sessions can't be revoked one device at a time.** Revocation is per *account*, not per
|
||||
session: `POST /api/logout/all` kills all of them at once and there is no device list to pick
|
||||
from. `POST /api/logout` on its own only clears the cookie in that one browser
|
||||
(`api/server.js:361`) — a copy taken beforehand keeps working. Sessions last **90 days** by
|
||||
default, settable with `SESSION_DAYS` (`api/server.js:26`); each cookie carries the lifetime it
|
||||
(`api/server.js:498-502`) — a copy taken beforehand keeps working. Sessions last **90 days** by
|
||||
default, settable with `SESSION_DAYS` (`api/server.js:31`); each cookie carries the lifetime it
|
||||
was issued with, so changing the setting doesn't reach cookies that are already out. Deleting
|
||||
`./data/secret` and restarting still works as the instance-wide reset, and disabling an account
|
||||
still locks out one user completely.
|
||||
- **CSRF protection is `SameSite=Lax` and nothing else.** There are no CSRF tokens.
|
||||
- **User verification is preferred, not required.** Both handshakes pass
|
||||
`requireUserVerification: false` (`api/server.js:297`, `api/server.js:343`), so a passkey
|
||||
`requireUserVerification: false` (`api/server.js:396`, `api/server.js:465`), so a passkey
|
||||
released without a biometric or PIN is still accepted. In practice: unlocked device ≈ account
|
||||
access.
|
||||
- **One passkey per profile, and no recovery.** Every successful registration creates a *new*
|
||||
profile (`api/server.js:309-319`); there is no route to attach a second passkey to an existing
|
||||
profile (`api/server.js:421-430`); there is no route to attach a second passkey to an existing
|
||||
one, and no email or reset path. Lose the passkey and that profile is unreachable — only direct
|
||||
surgery on `./data` gets it back.
|
||||
- **Disabling someone isn't a ban.** They can still register a fresh profile with a new passkey
|
||||
unless `INVITE_ONLY=1` is set.
|
||||
unless `INVITE_ONLY=1` is set. It also makes them near-invisible in the activity log: a disabled
|
||||
account is refused at the session check, so nothing it does produces an entry except the failed
|
||||
sign-ins it keeps attempting.
|
||||
- **HTTPS is required and the app doesn't provide it.** The API container speaks plain HTTP and
|
||||
nginx listens on `:80` (`web/nginx.conf`); TLS is your reverse proxy's job. Without it,
|
||||
browsers won't do passkeys at all (except on `http://localhost`) and the session cookie is sent
|
||||
in the clear.
|
||||
- **No rate limiting anywhere.** Nothing throttles logins, registrations or writes, and
|
||||
`POST /api/register/options` still answers whether an invite code is valid
|
||||
(`api/server.js:272`), so an invite-only instance on the open internet should have a rate limit
|
||||
in front of it. New invite codes are 16 hex characters — 64 bits (`api/server.js:525`) — which
|
||||
(`api/server.js:360`), so an invite-only instance on the open internet should have a rate limit
|
||||
in front of it. New invite codes are 16 hex characters — 64 bits (`api/server.js:668`) — which
|
||||
makes guessing one impractical even unthrottled; codes generated by earlier versions are 8
|
||||
characters / 32 bits and still work, so revoke and reissue any that are still unused. The only
|
||||
hard limit
|
||||
in the app is a 5 MB request body (`api/server.js:27`).
|
||||
in the app is a 5 MB request body (`api/server.js:32`).
|
||||
- **The activity log is not an audit archive, and it records less than you might assume.** No IP
|
||||
address unless you set `AUDIT_IP` (`net` truncates to a /24 or /48; the default is `off`, and
|
||||
when it is on the address is taken from `CF-Connecting-IP`, `X-Forwarded-For` or `X-Real-IP` and
|
||||
is therefore only as trustworthy as the proxy in front of you), never
|
||||
the browser's user-agent, and never the passkey id behind a failed sign-in — that id is a stable
|
||||
handle for one device, and storing it would let an admin follow an unknown device from attempt
|
||||
to attempt. So a failed sign-in from a passkey this instance doesn't know is recorded as a time
|
||||
and nothing else. Retention is a cap, not an archive: old events are dropped, not exported. Any
|
||||
admin can clear the whole log from the dashboard. And four of the paths that write to it —
|
||||
the invite check on `POST /api/register/options`, and the expired-challenge and unknown-passkey
|
||||
branches of the register/login handshakes — are reachable **without a session**, so with no rate
|
||||
limit in front (see below) anyone can fill the log with noise. It is an append of ~110 bytes per
|
||||
event to a capped file, never a rewrite of `db.json`, so the cost is a log full of noise rather
|
||||
than a full disk or a slow server.
|
||||
- **A few endpoints answer without a session:** `/api/health` (which includes the total user
|
||||
count), `/api/config` (whether invite-only is on), `/api/push/public-key`, and the
|
||||
register/login handshakes.
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "gym-api",
|
||||
"version": "1.2.8",
|
||||
"version": "1.2.9",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "server.js",
|
||||
|
||||
+197
-16
@@ -197,7 +197,9 @@ function readSession(req) {
|
||||
function requireAdmin(req, res) {
|
||||
const user = readSession(req);
|
||||
if (!user) { json(res, 401, { error: 'not signed in' }); return null; }
|
||||
if (!isAdmin(user)) { json(res, 403, { error: 'forbidden' }); return null; }
|
||||
// Only the 403 is recorded: a 401 is any unauthenticated bot poking /api/admin/*, and
|
||||
// logging those would bury the events an operator actually wants to see.
|
||||
if (!isAdmin(user)) { audit(req, 'admin.denied', { ok: false, user }); json(res, 403, { error: 'forbidden' }); return null; }
|
||||
return user;
|
||||
}
|
||||
function sessionCookie(user) {
|
||||
@@ -256,6 +258,97 @@ function livePresence(uid) {
|
||||
}
|
||||
setInterval(() => { for (const [k, v] of presence) if (Date.now() - v.updatedAt > PRESENCE_TTL) presence.delete(k); }, 30000).unref();
|
||||
|
||||
/* ---------- audit log ---------- */
|
||||
// Who signed in, who tried and failed, and what an admin changed. One JSON object per line in
|
||||
// ./data/audit.log, appended and never rewritten in place. It deliberately does not live in
|
||||
// db.json: that file is rewritten whole on every save, and the login/register handshakes are
|
||||
// unauthenticated and unthrottled by design (see SECURITY.md), so an audit trail in there would
|
||||
// turn one bogus request into a full db.json rewrite. A line torn by a crash costs one event and
|
||||
// is dropped on read.
|
||||
//
|
||||
// On by default. It records strictly less than the instance already holds — every account is in
|
||||
// db.json and every workout is in state-<uid>.json, both readable by any admin — and a security
|
||||
// feature that ships switched off protects nobody. IP addresses are the exception: off unless you
|
||||
// ask for them, because they are the one field here that says where somebody physically is.
|
||||
const AUDIT_ON = !/^(0|false|no|off)$/i.test(process.env.AUDIT_LOG || '');
|
||||
const AUDIT_MAX = Math.max(0, +(process.env.AUDIT_MAX || 5000) || 0); // 0 = no count cap
|
||||
const AUDIT_DAYS = Math.max(0, +(process.env.AUDIT_DAYS || 90) || 0); // 0 = no age cap
|
||||
const AUDIT_IP = /^full$/i.test(process.env.AUDIT_IP || '') ? 'full'
|
||||
: /^(1|true|yes|on|net)$/i.test(process.env.AUDIT_IP || '') ? 'net' : 'off';
|
||||
const auditFile = path.join(DATA, 'audit.log');
|
||||
let auditSeq = 0; // never reset, not even by a clear — a wiped log leaves a visible id gap
|
||||
let auditCount = 0;
|
||||
|
||||
// Which header holds the caller depends on what is in front of the API. CF-Connecting-IP comes
|
||||
// first because a Cloudflare tunnel does NOT forward the client in X-Forwarded-For — that header
|
||||
// then only carries the tunnel's own container, which looks like a valid answer and isn't. After
|
||||
// that, the first entry of X-Forwarded-For is the client and everything behind it is our own hops.
|
||||
// All three are only as trustworthy as the proxy in front: it has to overwrite them rather than
|
||||
// pass a client-supplied one through. In 'net' mode only the network survives — enough to tell
|
||||
// one source from another, not enough to point at a person.
|
||||
function clientIp(req) {
|
||||
if (AUDIT_IP === 'off') return null;
|
||||
const raw = String(req.headers['cf-connecting-ip'] || '').trim()
|
||||
|| String(req.headers['x-forwarded-for'] || '').split(',')[0].trim()
|
||||
|| String(req.headers['x-real-ip'] || '').trim();
|
||||
const ip = raw.replace(/^\[|\]$/g, '').slice(0, 45);
|
||||
if (!/^[0-9a-fA-F:.]{3,45}$/.test(ip)) return null; // never store a header verbatim
|
||||
if (AUDIT_IP === 'full') return ip;
|
||||
if (/^\d{1,3}(\.\d{1,3}){3}$/.test(ip)) return ip.replace(/\.\d{1,3}$/, '.0/24');
|
||||
const g = ip.split(':').filter(Boolean).slice(0, 3).join(':');
|
||||
return g ? g + '::/48' : null;
|
||||
}
|
||||
|
||||
function auditLines() {
|
||||
let text;
|
||||
try { text = fs.readFileSync(auditFile, 'utf8'); } catch { return []; }
|
||||
const rows = [];
|
||||
for (const line of text.split('\n')) {
|
||||
if (!line) continue;
|
||||
try { const r = JSON.parse(line); if (r && r.id && r.ev) rows.push(r); } catch { /* torn line */ }
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
// Retention is a cap, not an archive: age first, then the newest AUDIT_MAX of what's left.
|
||||
function auditKeep(rows) {
|
||||
let out = rows;
|
||||
if (AUDIT_DAYS) { const cut = Date.now() - AUDIT_DAYS * 86400000; out = out.filter(r => r.ts >= cut); }
|
||||
if (AUDIT_MAX && out.length > AUDIT_MAX) out = out.slice(out.length - AUDIT_MAX);
|
||||
return out;
|
||||
}
|
||||
function compactAudit() {
|
||||
const rows = auditLines();
|
||||
for (const r of rows) if (+r.id > auditSeq) auditSeq = +r.id;
|
||||
const keep = auditKeep(rows);
|
||||
auditCount = keep.length;
|
||||
if (keep.length === rows.length) return;
|
||||
try { atomicWrite(auditFile, keep.map(r => JSON.stringify(r)).join('\n') + (keep.length ? '\n' : '')); }
|
||||
catch (e) { console.error('audit compact failed', e.message); }
|
||||
}
|
||||
|
||||
// Never throws: a log that can't be written must not break signing in.
|
||||
function audit(req, ev, f = {}) {
|
||||
if (!AUDIT_ON) return;
|
||||
const rec = { id: ++auditSeq, ts: Date.now(), ev, ok: f.ok !== false };
|
||||
if (f.user) { rec.uid = f.user.id; rec.name = String(f.user.name || '').slice(0, 40); }
|
||||
else {
|
||||
if (f.uid) rec.uid = f.uid;
|
||||
if (f.name) rec.name = String(f.name).slice(0, 40);
|
||||
}
|
||||
if (f.target) { rec.tgt = f.target.id; rec.tname = String(f.target.name || '').slice(0, 40); }
|
||||
if (f.msg) rec.msg = String(f.msg).slice(0, 120);
|
||||
const ip = clientIp(req);
|
||||
if (ip) rec.ip = ip;
|
||||
try { fs.appendFileSync(auditFile, JSON.stringify(rec) + '\n'); }
|
||||
catch (e) { return console.error('audit write failed', e.message); }
|
||||
// Amortized: a 5000-event cap rewrites the file once per ~1250 events.
|
||||
if (AUDIT_MAX && ++auditCount > AUDIT_MAX * 1.25) compactAudit();
|
||||
}
|
||||
if (AUDIT_ON) {
|
||||
compactAudit(); // prune on boot, seed auditSeq/auditCount
|
||||
setInterval(compactAudit, 3600000).unref(); // honour AUDIT_DAYS on an idle instance too
|
||||
}
|
||||
|
||||
/* ---------- routes ---------- */
|
||||
const routes = {
|
||||
'GET /api/health': async (req, res) => json(res, 200, { ok: true, users: db.users.length }),
|
||||
@@ -274,8 +367,11 @@ const routes = {
|
||||
const name = String(body.name || '').trim().slice(0, 40);
|
||||
if (!name) return json(res, 400, { error: 'name required' });
|
||||
const code = String(body.code || '').trim().toUpperCase();
|
||||
if (INVITE_ONLY && !db.invites.some(i => i.code === code && !i.usedBy && !i.revoked))
|
||||
if (INVITE_ONLY && !db.invites.some(i => i.code === code && !i.usedBy && !i.revoked)) {
|
||||
// The rejected code itself is never recorded — a near-miss guess in the log is a liability.
|
||||
audit(req, 'auth.register.denied', { ok: false, name, msg: 'invite-rejected' });
|
||||
return json(res, 403, { error: 'a valid invite code is required' });
|
||||
}
|
||||
const uid = crypto.randomBytes(12).toString('base64url');
|
||||
const options = await generateRegistrationOptions({
|
||||
rpName: RP_NAME, rpID: RP_ID,
|
||||
@@ -291,7 +387,10 @@ const routes = {
|
||||
'POST /api/register/verify': async (req, res) => {
|
||||
const body = await readBody(req);
|
||||
const c = takeChallenge(body.cid);
|
||||
if (!c || !c.uid) return json(res, 400, { error: 'challenge expired — try again' });
|
||||
if (!c || !c.uid) {
|
||||
audit(req, 'auth.register.fail', { ok: false, msg: 'challenge-expired' });
|
||||
return json(res, 400, { error: 'challenge expired — try again' });
|
||||
}
|
||||
let verification;
|
||||
try {
|
||||
verification = await verifyRegistrationResponse({
|
||||
@@ -301,15 +400,28 @@ const routes = {
|
||||
expectedRPID: RP_ID,
|
||||
requireUserVerification: false
|
||||
});
|
||||
} catch (e) { return json(res, 400, { error: 'verification failed: ' + e.message }); }
|
||||
if (!verification.verified) return json(res, 400, { error: 'not verified' });
|
||||
} catch (e) {
|
||||
// e.message can echo attacker-supplied response fields, so only the reason code is kept.
|
||||
audit(req, 'auth.register.fail', { ok: false, name: c.name, msg: 'verify-error' });
|
||||
return json(res, 400, { error: 'verification failed: ' + e.message });
|
||||
}
|
||||
if (!verification.verified) {
|
||||
audit(req, 'auth.register.fail', { ok: false, name: c.name, msg: 'not-verified' });
|
||||
return json(res, 400, { error: 'not verified' });
|
||||
}
|
||||
const { credential } = verification.registrationInfo;
|
||||
if (db.creds.find(x => x.id === credential.id)) return json(res, 409, { error: 'credential already registered' });
|
||||
if (db.creds.find(x => x.id === credential.id)) {
|
||||
audit(req, 'auth.register.fail', { ok: false, name: c.name, msg: 'credential-exists' });
|
||||
return json(res, 409, { error: 'credential already registered' });
|
||||
}
|
||||
// Re-check the invite at the last moment (it may have been used/revoked since options), then burn it.
|
||||
let invite = null;
|
||||
if (INVITE_ONLY) {
|
||||
invite = db.invites.find(i => i.code === c.code && !i.usedBy && !i.revoked);
|
||||
if (!invite) return json(res, 403, { error: 'invite code is no longer valid — ask for a new one' });
|
||||
if (!invite) {
|
||||
audit(req, 'auth.register.fail', { ok: false, name: c.name, msg: 'invite-invalid' });
|
||||
return json(res, 403, { error: 'invite code is no longer valid — ask for a new one' });
|
||||
}
|
||||
}
|
||||
const user = { id: c.uid, name: c.name, created: new Date().toISOString() };
|
||||
if (invite) { user.invitedBy = invite.code; invite.usedBy = user.id; invite.usedAt = user.created; }
|
||||
@@ -321,6 +433,7 @@ const routes = {
|
||||
transports: body.credential?.response?.transports || []
|
||||
});
|
||||
saveDb();
|
||||
audit(req, 'auth.register.ok', { user, msg: invite ? invite.code : null });
|
||||
json(res, 200, { user: { id: user.id, name: user.name, admin: isAdmin(user) } }, { 'Set-Cookie': sessionCookie(user) });
|
||||
},
|
||||
|
||||
@@ -335,9 +448,18 @@ const routes = {
|
||||
'POST /api/login/verify': async (req, res) => {
|
||||
const body = await readBody(req);
|
||||
const c = takeChallenge(body.cid);
|
||||
if (!c) return json(res, 400, { error: 'challenge expired — try again' });
|
||||
if (!c) {
|
||||
audit(req, 'auth.login.fail', { ok: false, msg: 'challenge-expired' });
|
||||
return json(res, 400, { error: 'challenge expired — try again' });
|
||||
}
|
||||
const cred = db.creds.find(x => x.id === body.credential?.id);
|
||||
if (!cred) return json(res, 404, { error: 'unknown passkey — create a profile first' });
|
||||
if (!cred) {
|
||||
// No credential id goes in the log: it is a stable handle for one passkey, and recording it
|
||||
// would let an admin correlate an unknown device across attempts. Nothing here identifies
|
||||
// the caller beyond the timestamp (and the network, if AUDIT_IP is on).
|
||||
audit(req, 'auth.login.fail', { ok: false, msg: 'unknown-credential' });
|
||||
return json(res, 404, { error: 'unknown passkey — create a profile first' });
|
||||
}
|
||||
let verification;
|
||||
try {
|
||||
verification = await verifyAuthenticationResponse({
|
||||
@@ -353,17 +475,36 @@ const routes = {
|
||||
transports: cred.transports
|
||||
}
|
||||
});
|
||||
} catch (e) { return json(res, 400, { error: 'verification failed: ' + e.message }); }
|
||||
if (!verification.verified) return json(res, 400, { error: 'not verified' });
|
||||
} catch (e) {
|
||||
audit(req, 'auth.login.fail', { ok: false, user: db.users.find(u => u.id === cred.userId), uid: cred.userId, msg: 'verify-error' });
|
||||
return json(res, 400, { error: 'verification failed: ' + e.message });
|
||||
}
|
||||
if (!verification.verified) {
|
||||
audit(req, 'auth.login.fail', { ok: false, user: db.users.find(u => u.id === cred.userId), uid: cred.userId, msg: 'not-verified' });
|
||||
return json(res, 400, { error: 'not verified' });
|
||||
}
|
||||
cred.counter = verification.authenticationInfo.newCounter;
|
||||
saveDb();
|
||||
const user = db.users.find(u => u.id === cred.userId);
|
||||
if (!user) return json(res, 500, { error: 'user missing' });
|
||||
if (user.disabled) return json(res, 403, { error: 'this account has been disabled' });
|
||||
if (!user) {
|
||||
audit(req, 'auth.login.fail', { ok: false, uid: cred.userId, msg: 'user-missing' });
|
||||
return json(res, 500, { error: 'user missing' });
|
||||
}
|
||||
if (user.disabled) {
|
||||
audit(req, 'auth.login.fail', { ok: false, user, msg: 'account-disabled' });
|
||||
return json(res, 403, { error: 'this account has been disabled' });
|
||||
}
|
||||
audit(req, 'auth.login.ok', { user });
|
||||
json(res, 200, { user: { id: user.id, name: user.name, admin: isAdmin(user) } }, { 'Set-Cookie': sessionCookie(user) });
|
||||
},
|
||||
|
||||
'POST /api/logout': async (req, res) => json(res, 200, { ok: true }, { 'Set-Cookie': clearCookie }),
|
||||
// Reads the session purely so the sign-out can be recorded; the cookie is cleared either way.
|
||||
// A logout with no valid cookie is a no-op and isn't worth an entry.
|
||||
'POST /api/logout': async (req, res) => {
|
||||
const user = readSession(req);
|
||||
if (user) audit(req, 'auth.logout', { user });
|
||||
json(res, 200, { ok: true }, { 'Set-Cookie': clearCookie });
|
||||
},
|
||||
|
||||
// "Sign out everywhere" — bumps this user's session version, which invalidates every cookie
|
||||
// ever issued for the account, on every device, including a copy someone else walked off with.
|
||||
@@ -374,6 +515,7 @@ const routes = {
|
||||
if (!user) return json(res, 401, { error: 'not signed in' });
|
||||
user.sv = sessionVersion(user) + 1;
|
||||
saveDb();
|
||||
audit(req, 'auth.logout.all', { user });
|
||||
json(res, 200, { ok: true }, { 'Set-Cookie': clearCookie });
|
||||
},
|
||||
|
||||
@@ -499,7 +641,7 @@ const routes = {
|
||||
},
|
||||
|
||||
'POST /api/admin/user/disable': async (req, res) => {
|
||||
if (!requireAdmin(req, res)) return;
|
||||
const admin = requireAdmin(req, res); if (!admin) return;
|
||||
const body = await readBody(req);
|
||||
const u = db.users.find(x => x.id === body.id);
|
||||
if (!u) return json(res, 404, { error: 'no such user' });
|
||||
@@ -507,6 +649,7 @@ const routes = {
|
||||
u.disabled = !!body.disabled;
|
||||
if (u.disabled) presence.delete(u.id); // drop them off "training now" at once
|
||||
saveDb();
|
||||
audit(req, u.disabled ? 'admin.user.disable' : 'admin.user.enable', { user: admin, target: u });
|
||||
json(res, 200, { ok: true, id: u.id, disabled: u.disabled });
|
||||
},
|
||||
|
||||
@@ -531,17 +674,55 @@ const routes = {
|
||||
const invite = { code, note: String(body.note || '').slice(0, 60), createdBy: admin.id, created: new Date().toISOString() };
|
||||
db.invites.push(invite);
|
||||
saveDb();
|
||||
audit(req, 'admin.invite.create', { user: admin, msg: code });
|
||||
json(res, 200, { invite });
|
||||
},
|
||||
|
||||
'POST /api/admin/invites/revoke': async (req, res) => {
|
||||
if (!requireAdmin(req, res)) return;
|
||||
const admin = requireAdmin(req, res); if (!admin) return;
|
||||
const body = await readBody(req);
|
||||
const inv = db.invites.find(i => i.code === String(body.code || '').toUpperCase());
|
||||
if (!inv) return json(res, 404, { error: 'no such code' });
|
||||
if (inv.usedBy) return json(res, 400, { error: 'already used — cannot revoke' });
|
||||
db.invites = db.invites.filter(i => i.code !== inv.code);
|
||||
saveDb();
|
||||
audit(req, 'admin.invite.revoke', { user: admin, msg: inv.code });
|
||||
json(res, 200, { ok: true });
|
||||
},
|
||||
|
||||
/* ---------- activity log ---------- */
|
||||
// Newest first, paged by id. Not by offset: the log grows at the front of this view, so an
|
||||
// offset cursor would repeat a row whenever an event lands between two pages; and not by
|
||||
// timestamp, because two events can share a millisecond. auditKeep() runs on read as well as
|
||||
// on the hourly compaction, so nothing past its retention is ever served.
|
||||
'GET /api/admin/audit': async (req, res) => {
|
||||
if (!requireAdmin(req, res)) return;
|
||||
const q = new URL(req.url, 'http://x').searchParams;
|
||||
const limit = Math.max(1, Math.min(200, +q.get('limit') || 100));
|
||||
const before = +q.get('before') || Infinity;
|
||||
const cat = q.get('cat') || '';
|
||||
let rows = auditKeep(auditLines()).reverse();
|
||||
if (cat === 'fail') rows = rows.filter(r => !r.ok);
|
||||
else if (cat) rows = rows.filter(r => String(r.ev).startsWith(cat + '.'));
|
||||
const page = rows.filter(r => r.id < before).slice(0, limit);
|
||||
json(res, 200, {
|
||||
events: page,
|
||||
total: rows.length,
|
||||
nextBefore: page.length === limit ? page[page.length - 1].id : null,
|
||||
enabled: AUDIT_ON, ip_mode: AUDIT_IP,
|
||||
retention: { max: AUDIT_MAX, days: AUDIT_DAYS },
|
||||
now: Date.now()
|
||||
});
|
||||
},
|
||||
|
||||
// Deleting the log is itself logged, and auditSeq is not reset — so a clear always leaves a
|
||||
// visible gap in the ids and can't be used to quietly erase a trace. There is no export route:
|
||||
// ./data/audit.log already is the export, in a format jq reads directly.
|
||||
'POST /api/admin/audit/clear': async (req, res) => {
|
||||
const admin = requireAdmin(req, res); if (!admin) return;
|
||||
try { fs.unlinkSync(auditFile); } catch { /* nothing logged yet */ }
|
||||
auditCount = 0;
|
||||
audit(req, 'admin.audit.clear', { user: admin });
|
||||
json(res, 200, { ok: true });
|
||||
}
|
||||
};
|
||||
|
||||
+26
-2
@@ -105,6 +105,28 @@ out and locked out everywhere until you re-enable it), and — with `INVITE_ONLY
|
||||
revoking invite codes. Existing accounts keep working when you switch invite-only on. Admin access
|
||||
is gated by your passkey and enforced server-side, so it needs no separate login.
|
||||
|
||||
### The activity log
|
||||
|
||||
The dashboard also keeps an **activity log**: sign-ins, sign-outs, failed attempts, refused
|
||||
signups, and every admin action (disabling an account, creating or revoking an invite code). It
|
||||
lives in `./data/audit.log` as one JSON object per line, so `tail -f data/audit.log` and `jq`
|
||||
work on it directly, and the dashboard reads the same file.
|
||||
|
||||
It is on by default and keeps the last 5,000 events or 90 days, whichever comes first
|
||||
(`AUDIT_LOG=0` turns it off entirely; `AUDIT_MAX` and `AUDIT_DAYS` change the caps). **IP
|
||||
addresses are not recorded** unless you set `AUDIT_IP=net` (network only, e.g. `203.0.113.0/24`)
|
||||
or `AUDIT_IP=full`. Neither the browser's user-agent nor the passkey id of a failed sign-in is
|
||||
ever stored: the first is a fingerprint, and the second would let you follow an unknown device
|
||||
from one attempt to the next.
|
||||
|
||||
Two things worth expecting. **Guests never appear** — guest mode never talks to the server, so
|
||||
there is nothing to log, exactly as there is nothing for the rest of the dashboard to show. And
|
||||
**a disabled account goes quiet**: a disabled user is refused at the session check, so their only
|
||||
entries are the failed sign-ins they keep making.
|
||||
|
||||
Clearing the log from the dashboard records the clear itself, and the event ids keep counting, so
|
||||
a gap is always visible.
|
||||
|
||||
`INVITE_ONLY=1` and `ALLOW_GUEST=0` answer different questions and are usually set together.
|
||||
Invite-only controls who may *create a profile*; it says nothing about the **Continue without
|
||||
account** button, which never creates one. Guest mode keeps everything in that browser and never
|
||||
@@ -149,8 +171,10 @@ Everything is in `./data`:
|
||||
tar czf opengym-backup-$(date +%F).tar.gz data/
|
||||
```
|
||||
|
||||
That archive contains all profiles, passkeys and workout history. Restore by unpacking it back
|
||||
into the project folder. (Individual users can also export their own data as JSON from Settings.)
|
||||
That archive contains all profiles, passkeys and workout history — and, if the activity log is
|
||||
on, `audit.log` with everyone's sign-in times. Worth knowing before you ship the archive to a
|
||||
backup service you don't run. Restore by unpacking it back into the project folder. (Individual
|
||||
users can also export their own data as JSON from Settings.)
|
||||
|
||||
## 7. Notifications
|
||||
|
||||
|
||||
@@ -7,8 +7,8 @@ android {
|
||||
applicationId "ch.duartesantos.opengym"
|
||||
minSdkVersion rootProject.ext.minSdkVersion
|
||||
targetSdkVersion rootProject.ext.targetSdkVersion
|
||||
versionCode 9
|
||||
versionName "1.2.8"
|
||||
versionCode 10
|
||||
versionName "1.2.9"
|
||||
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
|
||||
aaptOptions {
|
||||
// Files and dirs to omit from the packaged assets dir, modified to accommodate modern web apps.
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "opengym-frontend",
|
||||
"private": true,
|
||||
"version": "1.2.8",
|
||||
"version": "1.2.9",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
// Rendering for the admin activity log (GET /api/admin/audit).
|
||||
//
|
||||
// The server stores reason codes, not sentences — `{ ev: 'auth.login.fail', msg: 'unknown-credential' }`
|
||||
// rather than "someone tried a passkey we don't know". Turning those into English
|
||||
// belongs here and not in Admin.jsx: it is the only part of the feature that can be wrong in a way
|
||||
// a person sees, and as a plain module it is testable without mounting the dashboard.
|
||||
//
|
||||
// Like the rest of the admin screen this is English-only — the operator surface deliberately
|
||||
// stays out of the per-language string packs (see the header of views/Admin.jsx). Times still
|
||||
// follow the UI language, the way numbers and dates already do.
|
||||
import { dateLocale } from './i18n-core.js'
|
||||
|
||||
// The first segment of an event name is also the filter chip it belongs to.
|
||||
export const auditCat = ev => String(ev || '').split('.')[0]
|
||||
|
||||
const LABELS = {
|
||||
'auth.login.ok': 'Signed in',
|
||||
'auth.login.fail': 'Sign-in failed',
|
||||
'auth.register.ok': 'Created a profile',
|
||||
'auth.register.fail': 'Profile creation failed',
|
||||
'auth.register.denied': 'Signup refused',
|
||||
'auth.logout': 'Signed out',
|
||||
'auth.logout.all': 'Signed out everywhere',
|
||||
'admin.user.disable': 'Disabled an account',
|
||||
'admin.user.enable': 'Re-enabled an account',
|
||||
'admin.invite.create': 'Created an invite code',
|
||||
'admin.invite.revoke': 'Revoked an invite code',
|
||||
'admin.audit.clear': 'Cleared the activity log',
|
||||
'admin.denied': 'Blocked from the admin dashboard'
|
||||
}
|
||||
// An unknown event is shown raw rather than dropped or rendered as "undefined": a dashboard
|
||||
// that is one version behind the server should still say *something* truthful.
|
||||
export const auditLabel = ev => LABELS[ev] || String(ev || 'Unknown event')
|
||||
|
||||
const REASONS = {
|
||||
'challenge-expired': 'the sign-in took too long and expired',
|
||||
'unknown-credential': 'unknown passkey',
|
||||
'verify-error': 'the passkey could not be verified',
|
||||
'not-verified': 'the passkey was rejected',
|
||||
'user-missing': 'the passkey points at a profile that no longer exists',
|
||||
'account-disabled': 'the account is disabled',
|
||||
'credential-exists': 'that passkey already belongs to a profile',
|
||||
'invite-invalid': 'the invite code was used or revoked in the meantime',
|
||||
'invite-rejected': 'wrong or already-used invite code'
|
||||
}
|
||||
export const auditReason = msg => REASONS[msg] || (msg ? String(msg) : '')
|
||||
|
||||
// → { title, sub }. `sub` is the house "a · b · c" metadata line used by every list row.
|
||||
export function auditLine(e) {
|
||||
if (!e) return { title: '', sub: '' }
|
||||
const parts = []
|
||||
if (e.name) parts.push(e.name)
|
||||
else if (e.uid) parts.push(e.uid)
|
||||
else if (!e.ok) parts.push('unknown caller')
|
||||
if (e.tname) parts.push('→ ' + e.tname)
|
||||
// The reason codes and the invite codes share the msg field; only failures read as a reason.
|
||||
if (e.msg) parts.push(e.ok ? e.msg : auditReason(e.msg))
|
||||
if (e.ip) parts.push(e.ip)
|
||||
return { title: auditLabel(e.ev), sub: parts.join(' · ') }
|
||||
}
|
||||
|
||||
// The activity log is the one place in the app that needs a clock, and fmtDate() renders none —
|
||||
// it is used by every other view and is not worth changing for this.
|
||||
export function fmtWhen(ts, now = Date.now()) {
|
||||
if (!ts) return ''
|
||||
const d = new Date(ts)
|
||||
const time = d.toLocaleTimeString(dateLocale(), { hour: '2-digit', minute: '2-digit' })
|
||||
const n = new Date(now)
|
||||
const sameDay = d.toDateString() === n.toDateString()
|
||||
if (sameDay) return 'today ' + time
|
||||
if (now - ts < 6 * 86400000 && ts <= now) return d.toLocaleDateString(dateLocale(), { weekday: 'short' }) + ' ' + time
|
||||
return d.toLocaleDateString(dateLocale(), { day: 'numeric', month: 'short' }) + ' ' + time
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { auditCat, auditLabel, auditReason, auditLine, fmtWhen } from './audit.js'
|
||||
|
||||
// Every event name and reason code the server can emit (api/server.js, the audit block).
|
||||
// If a new one is added there without a label here, the first test fails rather than the
|
||||
// dashboard quietly printing a dotted identifier at a person.
|
||||
const EVENTS = [
|
||||
'auth.login.ok', 'auth.login.fail', 'auth.register.ok', 'auth.register.fail',
|
||||
'auth.register.denied', 'auth.logout', 'auth.logout.all',
|
||||
'admin.user.disable', 'admin.user.enable', 'admin.invite.create',
|
||||
'admin.invite.revoke', 'admin.audit.clear', 'admin.denied'
|
||||
]
|
||||
const REASONS = [
|
||||
'challenge-expired', 'unknown-credential', 'verify-error', 'not-verified',
|
||||
'user-missing', 'account-disabled', 'credential-exists', 'invite-invalid', 'invite-rejected'
|
||||
]
|
||||
|
||||
describe('auditLabel', () => {
|
||||
it('has a sentence for every event the server emits', () => {
|
||||
for (const ev of EVENTS) {
|
||||
expect(auditLabel(ev), ev).not.toBe(ev)
|
||||
expect(auditLabel(ev)).toMatch(/^[A-Z]/)
|
||||
}
|
||||
})
|
||||
|
||||
it('shows an unknown event raw instead of rendering undefined', () => {
|
||||
// A dashboard one version behind the server must still say something truthful.
|
||||
expect(auditLabel('auth.something.new')).toBe('auth.something.new')
|
||||
expect(auditLabel(undefined)).toBe('Unknown event')
|
||||
expect(auditLabel('')).toBe('Unknown event')
|
||||
})
|
||||
})
|
||||
|
||||
describe('auditCat', () => {
|
||||
it('takes the filter category from the first segment', () => {
|
||||
expect(auditCat('auth.login.ok')).toBe('auth')
|
||||
expect(auditCat('admin.invite.create')).toBe('admin')
|
||||
})
|
||||
it('survives a missing event name', () => {
|
||||
expect(auditCat(undefined)).toBe('')
|
||||
})
|
||||
it('puts every known event in exactly auth or admin', () => {
|
||||
expect([...new Set(EVENTS.map(auditCat))].sort()).toEqual(['admin', 'auth'])
|
||||
})
|
||||
})
|
||||
|
||||
describe('auditReason', () => {
|
||||
it('has plain English for every reason code', () => {
|
||||
for (const m of REASONS) {
|
||||
expect(auditReason(m), m).not.toBe(m)
|
||||
expect(auditReason(m).length).toBeGreaterThan(3)
|
||||
}
|
||||
})
|
||||
it('falls back to the raw code and tolerates none at all', () => {
|
||||
expect(auditReason('brand-new-code')).toBe('brand-new-code')
|
||||
expect(auditReason(undefined)).toBe('')
|
||||
})
|
||||
})
|
||||
|
||||
describe('auditLine', () => {
|
||||
it('names the person who did it', () => {
|
||||
expect(auditLine({ ev: 'auth.login.ok', ok: true, uid: 'u1', name: 'Duarte' }))
|
||||
.toEqual({ title: 'Signed in', sub: 'Duarte' })
|
||||
})
|
||||
|
||||
it('shows both sides of an admin action', () => {
|
||||
const l = auditLine({ ev: 'admin.user.disable', ok: true, uid: 'a', name: 'Duarte', tgt: 'b', tname: 'Ana' })
|
||||
expect(l.title).toBe('Disabled an account')
|
||||
expect(l.sub).toBe('Duarte · → Ana')
|
||||
})
|
||||
|
||||
it('translates the reason on a failure but not the invite code on a success', () => {
|
||||
expect(auditLine({ ev: 'auth.login.fail', ok: false, msg: 'unknown-credential' }).sub)
|
||||
.toBe('unknown caller · unknown passkey')
|
||||
// admin.invite.* put the actual code in msg — that must not be run through auditReason.
|
||||
expect(auditLine({ ev: 'admin.invite.create', ok: true, name: 'Duarte', msg: 'A1B2C3D4' }).sub)
|
||||
.toBe('Duarte · A1B2C3D4')
|
||||
})
|
||||
|
||||
it('says "unknown caller" only when a failure carries no identity', () => {
|
||||
expect(auditLine({ ev: 'auth.login.fail', ok: false }).sub).toBe('unknown caller')
|
||||
// A successful event without a name is not an anonymous attacker, so it stays blank.
|
||||
expect(auditLine({ ev: 'auth.logout', ok: true }).sub).toBe('')
|
||||
})
|
||||
|
||||
it('falls back to the uid when the name was never recorded', () => {
|
||||
expect(auditLine({ ev: 'auth.login.fail', ok: false, uid: 'Xy1', msg: 'user-missing' }).sub)
|
||||
.toBe('Xy1 · the passkey points at a profile that no longer exists')
|
||||
})
|
||||
|
||||
it('appends the network when the operator opted into IPs', () => {
|
||||
expect(auditLine({ ev: 'auth.login.ok', ok: true, name: 'Duarte', ip: '203.0.113.0/24' }).sub)
|
||||
.toBe('Duarte · 203.0.113.0/24')
|
||||
})
|
||||
|
||||
it('renders nothing rather than throwing on a missing record', () => {
|
||||
expect(auditLine(undefined)).toEqual({ title: '', sub: '' })
|
||||
})
|
||||
})
|
||||
|
||||
describe('fmtWhen', () => {
|
||||
const at = (y, m, d, h, min) => new Date(y, m - 1, d, h, min).getTime()
|
||||
const now = at(2026, 8, 23, 15, 0) // Sunday
|
||||
|
||||
it('says "today" for the same calendar day', () => {
|
||||
expect(fmtWhen(at(2026, 8, 23, 9, 5), now)).toMatch(/^today /)
|
||||
expect(fmtWhen(at(2026, 8, 23, 0, 1), now)).toMatch(/^today /)
|
||||
})
|
||||
|
||||
it('uses the weekday inside the last six days', () => {
|
||||
const s = fmtWhen(at(2026, 8, 21, 18, 30), now)
|
||||
expect(s).not.toMatch(/^today/)
|
||||
expect(s).toMatch(/^[A-Za-zÀ-ÿ.]+ \d/)
|
||||
})
|
||||
|
||||
it('falls back to a date once it is older', () => {
|
||||
expect(fmtWhen(at(2026, 8, 12, 14, 32), now)).toMatch(/\d/)
|
||||
expect(fmtWhen(at(2026, 8, 12, 14, 32), now)).not.toMatch(/^today/)
|
||||
})
|
||||
|
||||
it('always carries a time of day — that is the whole point of not reusing fmtDate', () => {
|
||||
for (const ts of [at(2026, 8, 23, 9, 5), at(2026, 8, 21, 18, 30), at(2026, 8, 12, 14, 32)]) {
|
||||
expect(fmtWhen(ts, now)).toMatch(/\d{1,2}[:.]\d{2}/)
|
||||
}
|
||||
})
|
||||
|
||||
it('does not call a future timestamp "3 days ago"', () => {
|
||||
// Clock skew between server and browser is real; a tomorrow must not read as a weekday.
|
||||
expect(fmtWhen(at(2026, 8, 30, 10, 0), now)).not.toMatch(/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun)/)
|
||||
})
|
||||
|
||||
it('returns an empty string for a missing timestamp', () => {
|
||||
expect(fmtWhen(0)).toBe('')
|
||||
expect(fmtWhen(undefined)).toBe('')
|
||||
})
|
||||
})
|
||||
@@ -4,6 +4,7 @@ import { useStore } from '../store/useStore.js'
|
||||
import { useUI } from '../store/useUI.js'
|
||||
import { api } from '../lib/api.js'
|
||||
import { fmtDate, fmtNum, fmtVol, fmtDur } from '../lib/format.js'
|
||||
import { auditCat, auditLine, fmtWhen } from '../lib/audit.js'
|
||||
import { workoutVolume, setsDone } from '../lib/history.js'
|
||||
import { confirmSheet } from '../sheets.jsx'
|
||||
import Icon from '../components/Icon.jsx'
|
||||
@@ -88,6 +89,64 @@ function InvitesCard({ invites, reload }) {
|
||||
</div>
|
||||
}
|
||||
|
||||
// Who signed in, who tried and failed, what an admin changed. A card rather than its own route:
|
||||
// the dashboard is deliberately one page of cards, and the 95 % use of this is a glance at the
|
||||
// last twenty events. Paging follows Library.jsx's house style — "Show more", not page numbers.
|
||||
function AuditCard({ tick }) {
|
||||
const toast = useUI(s => s.toast)
|
||||
const [meta, setMeta] = useState(null) // last response minus the rows: total, retention, …
|
||||
const [rows, setRows] = useState([])
|
||||
const [cat, setCat] = useState('')
|
||||
|
||||
const load = (c, before) => api('/api/admin/audit?limit=50&cat=' + c + (before ? '&before=' + before : ''))
|
||||
.then(r => { setMeta(r); setRows(x => (before ? x.concat(r.events) : r.events)) })
|
||||
.catch(e => toast(e.message))
|
||||
const pick = c => { setCat(c); setRows([]); setMeta(null); load(c) }
|
||||
// Reloads on mount and whenever the header's ↻ bumps the tick. Deliberately not on the 15s
|
||||
// poll that drives "training now": this is history, not presence.
|
||||
useEffect(() => { load(cat) }, [tick])
|
||||
|
||||
const clear = () => confirmSheet({
|
||||
title: 'Clear the activity log?',
|
||||
message: 'Every recorded event is deleted. The clear itself is logged, so the gap stays visible.',
|
||||
confirmText: 'Clear', danger: true,
|
||||
onConfirm: () => api('/api/admin/audit/clear', { method: 'POST', body: '{}' })
|
||||
.then(() => { toast('Activity log cleared'); pick(cat) }).catch(e => toast(e.message))
|
||||
})
|
||||
|
||||
if (meta && !meta.enabled) return null // AUDIT_LOG=0 — the card isn't there at all
|
||||
|
||||
return <div className="card">
|
||||
<div className="row between"><h2 style={{ margin: 0 }}>Activity log</h2>
|
||||
<button className="iconbtn" style={{ width: 32, height: 30, borderRadius: 8, fontSize: 15, color: 'var(--red)' }}
|
||||
onClick={clear} aria-label="clear log"><Icon name="trash" /></button></div>
|
||||
<div className="small muted" style={{ margin: '6px 0 10px' }}>
|
||||
{meta ? fmtNum(meta.total) + ' events'
|
||||
+ (meta.retention.days ? ' · last ' + meta.retention.days + ' days' : '')
|
||||
+ (meta.ip_mode === 'off' ? ' · no IP addresses' : '') : 'Loading…'}</div>
|
||||
<div className="chips" style={{ marginBottom: 10 }}>
|
||||
{[['', 'All'], ['auth', 'Sign-ins'], ['admin', 'Admin'], ['fail', 'Failed']].map(([v, l]) =>
|
||||
<button key={v} className={'chip' + (cat === v ? ' on' : '')} onClick={() => pick(v)}>{l}</button>)}
|
||||
</div>
|
||||
{rows.map(e => {
|
||||
const line = auditLine(e)
|
||||
return <div key={e.id} className="row between" style={{ padding: '8px 2px', borderBottom: '1px solid var(--sep)' }}>
|
||||
<div className="grow">
|
||||
<div className="small" style={{ fontWeight: 600 }}>{line.title}
|
||||
{/* a red pill, not a red row: twenty fumbled Face IDs in a row shouldn't read as an incident */}
|
||||
{!e.ok && <span className="tag" style={{ marginLeft: 6, color: 'var(--red)' }}>failed</span>}
|
||||
{auditCat(e.ev) === 'admin' && <span className="tag acc" style={{ marginLeft: 6 }}>admin</span>}</div>
|
||||
{line.sub && <div className="dim" style={{ fontSize: '.72rem' }}>{line.sub}</div>}
|
||||
</div>
|
||||
<span className="small muted" style={{ flex: 'none', marginLeft: 8 }}>{fmtWhen(e.ts, meta?.now)}</span>
|
||||
</div>
|
||||
})}
|
||||
{meta && !rows.length && <div className="dim small">Nothing logged yet.</div>}
|
||||
{meta?.nextBefore && <div style={{ marginTop: 10 }}>
|
||||
<Button size="sm" onClick={() => load(cat, meta.nextBefore)}>Show more</Button></div>}
|
||||
</div>
|
||||
}
|
||||
|
||||
export default function Admin() {
|
||||
const nav = useNavigate()
|
||||
const user = useStore(s => s.user)
|
||||
@@ -96,6 +155,7 @@ export default function Admin() {
|
||||
const [users, setUsers] = useState(null)
|
||||
const [invites, setInvites] = useState(null)
|
||||
const [inviteOnly, setInviteOnly] = useState(false)
|
||||
const [tick, setTick] = useState(0) // the ↻ button; the activity log listens to it
|
||||
|
||||
const loadUsers = () => api('/api/admin/users').then(d => { setUsers(d.users); setInviteOnly(d.invite_only) }).catch(e => toast(e.message || 'Failed to load'))
|
||||
const loadInvites = () => api('/api/admin/invites').then(d => setInvites(d.invites)).catch(() => {})
|
||||
@@ -113,7 +173,7 @@ export default function Admin() {
|
||||
<button className="iconbtn" onClick={() => nav('/settings')} aria-label="Back"><Icon name="chevronLeft" /></button>
|
||||
<div style={{ flex: 1, marginLeft: 8 }}><h1 style={{ margin: 0 }}>Admin</h1>
|
||||
<div className="sub">{users ? users.length + ' users · ' + activeCount + ' active this week' : 'Loading…'}</div></div>
|
||||
<button className="iconbtn" onClick={() => { loadUsers(); loadInvites() }} aria-label="refresh">↻</button>
|
||||
<button className="iconbtn" onClick={() => { loadUsers(); loadInvites(); setTick(n => n + 1) }} aria-label="refresh">↻</button>
|
||||
</div>
|
||||
|
||||
<div className="tiles" style={{ marginBottom: 12 }}>
|
||||
@@ -143,5 +203,7 @@ export default function Admin() {
|
||||
</div>)}
|
||||
{users && !users.length && <div className="empty">No users yet.</div>}
|
||||
</div>
|
||||
|
||||
<div style={{ marginTop: 14 }}><AuditCard tick={tick} /></div>
|
||||
</div>
|
||||
}
|
||||
@@ -9,6 +9,11 @@ Not in this folder (added at deploy time):
|
||||
- `icon-180.png` / `icon-512.png` — copied from `../frontend/public/` (the same
|
||||
icons the PWA uses, so the browser tab, home screen and app all match)
|
||||
- `openGym.apk` — the signed release build (see `../docs/MOBILE.md`)
|
||||
- `demo/` — the browser-only demo build of the app, embedded in the `#demo` section and
|
||||
reachable on its own at `/demo/`. Built from `../frontend` with `VITE_DEMO=1` and the
|
||||
jsDelivr media bases (see the recipe in `../.github/workflows/pages.yml`), so the ~140 MB
|
||||
of exercise media stays out of it. It has to live on this host: the site frames it, and
|
||||
`X-Frame-Options: SAMEORIGIN` would block it from anywhere else.
|
||||
|
||||
`site.js` fetches the star/issue counts and the release timeline from the public
|
||||
gitea.com API at view time. It pointed at api.github.com until that account was
|
||||
|
||||
+3
-3
@@ -37,9 +37,9 @@
|
||||
<div class="alert" role="alert"><div class="wrap">
|
||||
<div class="alert-tag">⚠️ Important notice</div>
|
||||
<h2>My GitHub account has been suspended — the openGym repo is gone with it</h2>
|
||||
<p><b>github.com/DuarteSantos8/openGym is offline.</b> The repository, the releases and the
|
||||
GitHub-Pages demo are all unreachable — not by choice. openGym itself is unaffected:
|
||||
the app, the APK on this page and every self-hosted install keep working exactly as before.</p>
|
||||
<p><b>github.com/DuarteSantos8/openGym is offline.</b> The repository and the releases are
|
||||
unreachable — not by choice. openGym itself is unaffected: the app, the APK on this page,
|
||||
the demo (now hosted here) and every self-hosted install keep working exactly as before.</p>
|
||||
<p>Until I get the account back, the code lives here — and the Discord is where I will announce
|
||||
the moment it is resolved:</p>
|
||||
<div class="alert-actions">
|
||||
|
||||
+5
-5
@@ -37,9 +37,9 @@
|
||||
<div class="alert" role="alert"><div class="wrap">
|
||||
<div class="alert-tag">⚠️ Important notice</div>
|
||||
<h2>My GitHub account has been suspended — the openGym repo is gone with it</h2>
|
||||
<p><b>github.com/DuarteSantos8/openGym is offline.</b> The repository, the releases and the
|
||||
GitHub-Pages demo are all unreachable — not by choice. openGym itself is unaffected:
|
||||
the app, the APK on this page and every self-hosted install keep working exactly as before.</p>
|
||||
<p><b>github.com/DuarteSantos8/openGym is offline.</b> The repository and the releases are
|
||||
unreachable — not by choice. openGym itself is unaffected: the app, the APK on this page,
|
||||
the demo (now hosted here) and every self-hosted install keep working exactly as before.</p>
|
||||
<p>Until I get the account back, the code lives here — and the Discord is where I will announce
|
||||
the moment it is resolved:</p>
|
||||
<div class="alert-actions">
|
||||
@@ -93,8 +93,8 @@
|
||||
your device with a free Apple ID (Apple expires the signature after 7 days; re-run
|
||||
from Xcode to renew). See
|
||||
<a href="https://gitea.com/DuarteSantos/openGym/src/branch/main/docs/MOBILE.md" rel="noopener">docs/MOBILE.md</a>.</li>
|
||||
<li><b>Just looking?</b> The in-browser demo was hosted on GitHub Pages and is offline
|
||||
while my GitHub account is suspended — the Android app above needs no account either.</li>
|
||||
<li><b>Just looking?</b> Try the <a href="/demo/">in-browser demo</a> — the real app with
|
||||
example data, no account and nothing to install. The Android app above needs no account either.</li>
|
||||
</ul>
|
||||
|
||||
<h2 id="selfhost">Self-host with Docker</h2>
|
||||
|
||||
+10
-14
@@ -51,9 +51,9 @@
|
||||
<div class="alert" role="alert"><div class="wrap">
|
||||
<div class="alert-tag">⚠️ Important notice</div>
|
||||
<h2>My GitHub account has been suspended — the openGym repo is gone with it</h2>
|
||||
<p><b>github.com/DuarteSantos8/openGym is offline.</b> The repository, the releases and the
|
||||
GitHub-Pages demo are all unreachable — not by choice. openGym itself is unaffected:
|
||||
the app, the APK on this page and every self-hosted install keep working exactly as before.</p>
|
||||
<p><b>github.com/DuarteSantos8/openGym is offline.</b> The repository and the releases are
|
||||
unreachable — not by choice. openGym itself is unaffected: the app, the APK on this page,
|
||||
the demo (now hosted here) and every self-hosted install keep working exactly as before.</p>
|
||||
<p>Until I get the account back, the code lives here — and the Discord is where I will announce
|
||||
the moment it is resolved:</p>
|
||||
<div class="alert-actions">
|
||||
@@ -135,18 +135,14 @@
|
||||
|
||||
<section id="demo"><div class="wrap">
|
||||
<p class="kicker">Live demo</p>
|
||||
<h2>Temporarily offline</h2>
|
||||
<p class="lead">The in-browser demo ran on GitHub Pages, which went down with my suspended
|
||||
GitHub account. It comes straight back once the account is restored.</p>
|
||||
<div class="offline">
|
||||
<span class="big">🚧</span>
|
||||
<p><b>Want to try openGym in the meantime?</b> Install the Android app below — it needs no
|
||||
account and no server — or run the self-hosted version with one <code>docker compose up</code>.</p>
|
||||
<div class="hero-btns" style="margin-top:18px">
|
||||
<a class="btn" href="#download">Get openGym</a>
|
||||
<a class="btn ghost" href="https://gitea.com/DuarteSantos/openGym" rel="noopener">Browse the code on Gitea</a>
|
||||
</div>
|
||||
<h2>Try it right here</h2>
|
||||
<p class="lead">This is the real app with seeded example data, running in your browser —
|
||||
poke around, start a workout, change anything.</p>
|
||||
<div class="demo-wrap">
|
||||
<div class="phone"><iframe src="/demo/" title="openGym live demo" loading="lazy"></iframe></div>
|
||||
</div>
|
||||
<p class="demo-note">Demo data lives only in this browser tab-family and can be reset in its
|
||||
Settings. Prefer a full window? <a href="/demo/">Open the demo full-screen →</a></p>
|
||||
</div></section>
|
||||
|
||||
<section id="download"><div class="wrap">
|
||||
|
||||
Reference in new issue
Block a user