Compare commits

..
17 Commits
Author SHA1 Message Date
Duarte Santos fbc615aa26 Release v1.1.1 2026-07-21 12:48:12 +02:00
Duarte Santos e83d642e1b Remove push delivery latency disclaimer from Settings
Confirmed working reliably after the 10s check-interval + high-urgency
push fixes.
2026-07-21 12:45:57 +02:00
Duarte Santos 95c4b2b279 Add honest delivery-latency disclaimer under push notification settings
Web Push through Apple/Google isn't instant or guaranteed even with
high urgency — set the expectation up front instead of letting people
assume it's unreliable/broken when it lags.
2026-07-21 12:34:32 +02:00
Duarte Santos c5cf31e2ca Tighten reminder timing: 10s check interval + high-urgency push
Reminder loop only checked once a minute, unaligned to the minute
boundary, so it could sit up to 59s on the target time before noticing
- now capped at ~9s. Also mark pushes as urgency:'high', the one lever
we actually have over delivery speed (iOS/Android throttle low-urgency
background push harder under battery saving). Remaining delivery lag
after that is Apple/Google's own push relay scheduling, not something
we control from here.
2026-07-21 12:25:24 +02:00
Duarte Santos 10fa150d09 Flush pending state save immediately when tab backgrounds/closes
Settings changes (like the reminder time) were saved via a 1.5s
debounce; closing or switching away from the tab right after an edit
could kill that pending save before it reached the server, silently
losing the change. Now flushed on visibilitychange instead of relying
on the timer alone.

Also confirmed via a live server-side test (bypassing the client
entirely) that the reminder loop itself fires correctly — trimmed the
verbose per-tick debug log added for that test, kept the one for an
actual match.
2026-07-21 12:00:49 +02:00
Duarte Santos 5a7ce13ca2 Update docs: reminder timezone is now auto-detected per user, not a server env var 2026-07-21 11:47:26 +02:00
Duarte Santos 0ac531acb8 Fix workout reminder using the server's timezone instead of the user's
The reminder compared 'now' against a single TZ env var, so it only
worked correctly for whoever's local time happened to match the
server's. The browser now reports its own IANA timezone (auto-
detected, no picker) and stores it with the reminder; the server
computes each user's local time/date individually via Intl, and the
client re-stamps it on every app load so it follows you when you
travel.
2026-07-21 11:46:45 +02:00
Duarte Santos 7dea9ccfcc Log push send failures instead of swallowing them silently
sendPush caught every webpush.sendNotification error to clean up
expired subscriptions, but never logged anything for other failure
modes — made a delivery problem indistinguishable from 'nothing to
send' when debugging.
2026-07-21 11:42:40 +02:00
Duarte Santos 17cad3fa3a Fix multi-arch web image build: pin builder stage to native platform
vite build was failing under QEMU-emulated arm64 (npm install mangles
esbuild/rollup's platform-specific native binaries under emulation,
surfacing as an unrelated tinyglobby module-resolution error). The
build output is static files, arch-independent, so there's no reason
to build it under emulation at all.
2026-07-21 11:24:37 +02:00
Duarte Santos 0c240ba6f8 Release v1.1.0 2026-07-21 11:20:24 +02:00
Duarte Santos 8e20c2c304 Publish prebuilt Docker images to GHCR
GitHub Actions builds and pushes multi-arch (amd64/arm64) api/web
images to ghcr.io on every push to main and on version tags, so
self-hosters can 'docker compose pull' instead of building from
source. compose.yml keeps both image: and build: so building locally
still works via --build.
2026-07-21 11:11:26 +02:00
Duarte Santos 4c2b6344f7 Add push notifications: rest-timer alert + workout-day reminder
Web Push (VAPID) backend: keys auto-generated on first run, per-user
subscriptions, one new dependency (web-push). The rest timer schedules
a server-side push on start/extend and cancels it on skip or on-screen
completion, so it only actually fires if the tab got suspended before
finishing. A per-minute check sends an optional daily reminder on days
with a planned routine that hasn't been logged yet.

Opt in per-profile in Settings — requires a signed-in passkey profile.
2026-07-21 11:07:10 +02:00
Duarte Santos 84c59129e3 Fix rest timer stalling when tab is backgrounded
Anchor the countdown to a real end timestamp instead of a plain
per-tick decrement, and resync on visibilitychange so returning to
a backgrounded tab shows the correct elapsed time immediately.
2026-07-21 09:09:28 +02:00
Duarte Santos dcc3db5893 Add GitHub issue templates (bug report, feature request) 2026-07-21 08:56:55 +02:00
Duarte Santos 7717f868ee Banner kompakter & zentriert (keine leere Fläche mehr rechts) 2026-07-20 21:07:49 +02:00
Duarte Santos 8f6b3c5f30 README-Banner als PNG statt SVG (GitHub rendert relative SVGs im README nicht zuverlässig) 2026-07-20 21:03:16 +02:00
Duarte Santos 060e854022 Fix: grauer Streifen unten bei offenem Popup (iOS Scroll-Lock)
html bekommt jetzt die Theme-Hintergrundfarbe (+ overscroll-behavior:none),
damit der iOS-position:fixed-Scroll-Lock beim Öffnen eines Dialogs keinen
grauen Standard-Hintergrund unter der App freilegt.
2026-07-20 20:55:15 +02:00
23 changed files with 706 additions and 28 deletions

No files matched your search

+6
View File
@@ -18,3 +18,9 @@ RP_NAME=openGym
# RP_NAME=openGym
#
# (Point your proxy at the web container's WEB_PORT. See docs/SELF_HOSTING.md.)
# ── Notifications (optional) ───────────────────────────────────────────────
# Push works out of the box — nothing to set. VAPID keys are generated on first
# run and saved to ./data/vapid.json. Each user's browser reports its own
# timezone automatically, so the workout-day reminder fires at their local
# time regardless of where the server runs or where they're travelling.
+60
View File
@@ -0,0 +1,60 @@
name: Bug report
description: Something in openGym is broken or not working as expected
labels: ["bug"]
body:
- type: textarea
id: what-happened
attributes:
label: What did you do?
description: Steps to reproduce, as precisely as you can.
placeholder: |
1. Go to '...'
2. Click on '...'
3. See error
validations:
required: true
- type: textarea
id: expected
attributes:
label: What did you expect to happen?
validations:
required: true
- type: textarea
id: actual
attributes:
label: What happened instead?
description: Include error messages, console output, or screenshots if you have them.
validations:
required: true
- type: dropdown
id: setup
attributes:
label: How are you running openGym?
options:
- Self-hosted (docker compose)
- Frontend dev server (npm run dev)
- Other / not sure
validations:
required: true
- type: input
id: environment
attributes:
label: Browser & OS
placeholder: e.g. Safari 17 on iOS 18, Chrome 126 on Android
validations:
required: true
- type: checkboxes
id: passkey
attributes:
label: Is this about login / passkeys?
description: >
Most login issues are an `RP_ID`/`ORIGIN` mismatch — check your `.env` against the
domain you're accessing openGym from before reporting. See the
[self-hosting guide](../../docs/SELF_HOSTING.md).
options:
- label: Yes, this is a login/passkey issue and I've already checked RP_ID/ORIGIN
+5
View File
@@ -0,0 +1,5 @@
blank_issues_enabled: false
contact_links:
- name: Questions & contributing
url: https://github.com/DuarteSantos8/openGym/blob/main/CONTRIBUTING.md
about: Read the project layout, dev setup, and guidelines before opening an issue.
@@ -0,0 +1,29 @@
name: Feature request
description: Suggest an idea or improvement for openGym
labels: ["enhancement"]
body:
- type: textarea
id: problem
attributes:
label: What problem does this solve?
description: What are you trying to do that openGym doesn't support today?
validations:
required: true
- type: textarea
id: proposal
attributes:
label: Proposed approach
description: How would you like it to work? Rough ideas are fine.
validations:
required: true
- type: checkboxes
id: deps
attributes:
label: Dependencies
description: >
openGym is intentionally dependency-light — new packages (front or back) are a hard
sell. See [CONTRIBUTING.md](../../CONTRIBUTING.md).
options:
- label: This doesn't require adding a new dependency
+59
View File
@@ -0,0 +1,59 @@
name: Publish Docker images
on:
push:
branches: [main]
tags: ['v*']
workflow_dispatch:
permissions:
contents: read
packages: write
jobs:
build:
runs-on: ubuntu-latest
strategy:
matrix:
include:
- image: api
context: ./api
file: ./api/Dockerfile
- image: web
context: .
file: ./web/Dockerfile
steps:
- uses: actions/checkout@v4
- name: Lowercase owner (registry names must be lowercase)
id: repo
run: echo "owner=$(echo '${{ github.repository_owner }}' | tr '[:upper:]' '[:lower:]')" >> "$GITHUB_OUTPUT"
- uses: docker/setup-qemu-action@v3
- uses: docker/setup-buildx-action@v3
- uses: docker/login-action@v3
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- uses: docker/metadata-action@v5
id: meta
with:
images: ghcr.io/${{ steps.repo.outputs.owner }}/opengym-${{ matrix.image }}
tags: |
type=raw,value=latest,enable={{is_default_branch}}
type=semver,pattern={{version}}
type=semver,pattern={{major}}.{{minor}}
- uses: docker/build-push-action@v6
with:
context: ${{ matrix.context }}
file: ${{ matrix.file }}
platforms: linux/amd64,linux/arm64
push: true
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
cache-from: type=gha,scope=${{ matrix.image }}
cache-to: type=gha,mode=max,scope=${{ matrix.image }}
+26
View File
@@ -1,5 +1,31 @@
# Changelog
## v1.1.1 — 2026-07-21
Reliability fixes for the push notifications shipped in v1.1.0, found through live testing:
- 🌍 Workout day reminder now fires by each user's own browser-detected timezone instead of a
single server-wide one — works correctly regardless of where the server runs, and follows you
automatically if you travel.
- 💾 Settings changes (like the reminder time) are flushed to the server immediately when the tab
backgrounds or closes, instead of relying solely on a 1.5s debounce that could get cut short.
- ⏱️ Reminder check tightened from a 60s to a 10s interval, and pushes are now marked
`urgency: 'high'` — cuts avoidable delay on top of it, though delivery time is ultimately up to
Apple/Google's push relay.
- 🪵 Push send failures are now logged instead of silently swallowed.
## v1.1.0 — 2026-07-21
- 🐳 Prebuilt Docker images published to `ghcr.io/duartesantos8/opengym-{api,web}` (amd64 + arm64)
via GitHub Actions, so self-hosting no longer requires building from source. `docker compose pull`
grabs them; `docker compose up -d --build` still builds locally if you'd rather.
- 🔔 Push notifications: rest-timer-over alert (fires even if the app is closed) and an optional
daily reminder on days you have a workout planned but haven't logged one yet. Opt in per-profile
in Settings — requires a signed-in passkey profile. Backend gains one dependency (`web-push`);
VAPID keys are generated on first run.
- 🐛 Fixed the rest timer stalling when the tab/app is backgrounded — it's now anchored to a real
timestamp instead of a plain per-second counter, so it stays accurate after you come back.
## v1.0.0 — 2026-07-20
First public release. A complete, self-hostable gym & body-weight tracker.
+5 -3
View File
@@ -1,6 +1,6 @@
<div align="center">
<img src="assets/banner.svg" alt="openGym" width="100%">
<img src="assets/banner.png" alt="openGym" width="720">
<br>
@@ -65,12 +65,14 @@ You need [Docker](https://docs.docker.com/get-docker/) with Compose.
git clone https://github.com/DuarteSantos8/openGym
cd openGym
cp .env.example .env
docker compose pull # grab prebuilt images (amd64 + arm64) — skip to build from source instead
docker compose up -d
```
Open **http://localhost:8080**, tap **Create profile**, and you're in. First launch downloads
the exercise media (~140 MB) once and builds the app inside Docker — you don't need Node or a
build step locally.
the exercise media (~140 MB) once. Prefer building the images yourself instead of pulling from
`ghcr.io`? Drop the `pull` step and run `docker compose up -d --build` — you don't need Node or
a build step locally either way.
> Want it reachable from your phone over the internet with passkeys? You'll need an HTTPS
> domain — a two-line change in `.env`. See **[docs/SELF_HOSTING.md](docs/SELF_HOSTING.md)**.
+160 -1
View File
@@ -7,8 +7,10 @@
"": {
"name": "gym-api",
"version": "1.0.0",
"license": "AGPL-3.0-or-later",
"dependencies": {
"@simplewebauthn/server": "^13.1.1"
"@simplewebauthn/server": "^13.1.1",
"web-push": "^3.6.7"
}
},
"node_modules/@hexagon/base64": {
@@ -194,6 +196,25 @@
"node": ">=20.0.0"
}
},
"node_modules/agent-base": {
"version": "7.1.4",
"resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.4.tgz",
"integrity": "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==",
"engines": {
"node": ">= 14"
}
},
"node_modules/asn1.js": {
"version": "5.4.1",
"resolved": "https://registry.npmjs.org/asn1.js/-/asn1.js-5.4.1.tgz",
"integrity": "sha512-+I//4cYPccV8LdmBLiX8CYvf9Sp3vQsrqu2QNXRcrbiWvcx/UdlFiqUJJzxRQxgsZmvhXhn4cSKeSmoFjVdupA==",
"dependencies": {
"bn.js": "^4.0.0",
"inherits": "^2.0.1",
"minimalistic-assert": "^1.0.0",
"safer-buffer": "^2.1.0"
}
},
"node_modules/asn1js": {
"version": "3.0.10",
"resolved": "https://registry.npmjs.org/asn1js/-/asn1js-3.0.10.tgz",
@@ -207,6 +228,102 @@
"node": ">=12.0.0"
}
},
"node_modules/bn.js": {
"version": "4.12.5",
"resolved": "https://registry.npmjs.org/bn.js/-/bn.js-4.12.5.tgz",
"integrity": "sha512-3aRg6/JxfffFD+OlOjOFR3Vo79l39ooBTFucxx+MT3dhCtzn3EmiUPQo+6/OZuI2jbXi3YKgmiTFBgChQMwIRQ=="
},
"node_modules/buffer-equal-constant-time": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/buffer-equal-constant-time/-/buffer-equal-constant-time-1.0.1.tgz",
"integrity": "sha512-zRpUiDwd/xk6ADqPMATG8vc9VPrkck7T07OIx0gnjmJAnHnTVXNQG3vfvWNuiZIkwu9KrKdA1iJKfsfTVxE6NA=="
},
"node_modules/debug": {
"version": "4.4.3",
"resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",
"integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",
"dependencies": {
"ms": "^2.1.3"
},
"engines": {
"node": ">=6.0"
},
"peerDependenciesMeta": {
"supports-color": {
"optional": true
}
}
},
"node_modules/ecdsa-sig-formatter": {
"version": "1.0.11",
"resolved": "https://registry.npmjs.org/ecdsa-sig-formatter/-/ecdsa-sig-formatter-1.0.11.tgz",
"integrity": "sha512-nagl3RYrbNv6kQkeJIpt6NJZy8twLB/2vtz6yN9Z4vRKHN4/QZJIEbqohALSgwKdnksuY3k5Addp5lg8sVoVcQ==",
"dependencies": {
"safe-buffer": "^5.0.1"
}
},
"node_modules/http_ece": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/http_ece/-/http_ece-1.2.0.tgz",
"integrity": "sha512-JrF8SSLVmcvc5NducxgyOrKXe3EsyHMgBFgSaIUGmArKe+rwr0uphRkRXvwiom3I+fpIfoItveHrfudL8/rxuA==",
"engines": {
"node": ">=16"
}
},
"node_modules/https-proxy-agent": {
"version": "7.0.6",
"resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.6.tgz",
"integrity": "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==",
"dependencies": {
"agent-base": "^7.1.2",
"debug": "4"
},
"engines": {
"node": ">= 14"
}
},
"node_modules/inherits": {
"version": "2.0.4",
"resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz",
"integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ=="
},
"node_modules/jwa": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/jwa/-/jwa-2.0.1.tgz",
"integrity": "sha512-hRF04fqJIP8Abbkq5NKGN0Bbr3JxlQ+qhZufXVr0DvujKy93ZCbXZMHDL4EOtodSbCWxOqR8MS1tXA5hwqCXDg==",
"dependencies": {
"buffer-equal-constant-time": "^1.0.1",
"ecdsa-sig-formatter": "1.0.11",
"safe-buffer": "^5.0.1"
}
},
"node_modules/jws": {
"version": "4.0.1",
"resolved": "https://registry.npmjs.org/jws/-/jws-4.0.1.tgz",
"integrity": "sha512-EKI/M/yqPncGUUh44xz0PxSidXFr/+r0pA70+gIYhjv+et7yxM+s29Y+VGDkovRofQem0fs7Uvf4+YmAdyRduA==",
"dependencies": {
"jwa": "^2.0.1",
"safe-buffer": "^5.0.1"
}
},
"node_modules/minimalistic-assert": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/minimalistic-assert/-/minimalistic-assert-1.0.1.tgz",
"integrity": "sha512-UtJcAD4yEaGtjPezWuO9wC4nwUnVH/8/Im3yEHQP4b67cXlD/Qr9hdITCU1xDbSEXg2XKNaP8jsReV7vQd00/A=="
},
"node_modules/minimist": {
"version": "1.2.8",
"resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz",
"integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==",
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/ms": {
"version": "2.1.3",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
"integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="
},
"node_modules/pvtsutils": {
"version": "1.3.6",
"resolved": "https://registry.npmjs.org/pvtsutils/-/pvtsutils-1.3.6.tgz",
@@ -228,6 +345,30 @@
"resolved": "https://registry.npmjs.org/reflect-metadata/-/reflect-metadata-0.2.2.tgz",
"integrity": "sha512-urBwgfrvVP/eAyXx4hluJivBKzuEbSQs9rKWCrCkbSxNv8mxPcUZKeuoF3Uy4mJl3Lwprp6yy5/39VWigZ4K6Q=="
},
"node_modules/safe-buffer": {
"version": "5.2.1",
"resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz",
"integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==",
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/feross"
},
{
"type": "patreon",
"url": "https://www.patreon.com/feross"
},
{
"type": "consulting",
"url": "https://feross.org/support"
}
]
},
"node_modules/safer-buffer": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz",
"integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg=="
},
"node_modules/tslib": {
"version": "2.8.1",
"resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz",
@@ -248,6 +389,24 @@
"version": "1.14.1",
"resolved": "https://registry.npmjs.org/tslib/-/tslib-1.14.1.tgz",
"integrity": "sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg=="
},
"node_modules/web-push": {
"version": "3.6.7",
"resolved": "https://registry.npmjs.org/web-push/-/web-push-3.6.7.tgz",
"integrity": "sha512-OpiIUe8cuGjrj3mMBFWY+e4MMIkW3SVT+7vEIjvD9kejGUypv8GPDf84JdPWskK8zMRIJ6xYGm+Kxr8YkPyA0A==",
"dependencies": {
"asn1.js": "^5.3.0",
"http_ece": "1.2.0",
"https-proxy-agent": "^7.0.0",
"jws": "^4.0.0",
"minimist": "^1.2.5"
},
"bin": {
"web-push": "src/cli.js"
},
"engines": {
"node": ">= 16"
}
}
}
}
+3 -2
View File
@@ -1,6 +1,6 @@
{
"name": "gym-api",
"version": "1.0.0",
"version": "1.1.1",
"private": true,
"type": "module",
"main": "server.js",
@@ -9,6 +9,7 @@
"start": "node server.js"
},
"dependencies": {
"@simplewebauthn/server": "^13.1.1"
"@simplewebauthn/server": "^13.1.1",
"web-push": "^3.6.7"
}
}
+145 -1
View File
@@ -8,6 +8,7 @@ import {
generateRegistrationOptions, verifyRegistrationResponse,
generateAuthenticationOptions, verifyAuthenticationResponse
} from '@simplewebauthn/server';
import webpush from 'web-push';
const PORT = +(process.env.PORT || 3000);
const DATA = process.env.DATA_DIR || '/data';
@@ -27,8 +28,9 @@ if (!fs.existsSync(secretFile)) fs.writeFileSync(secretFile, crypto.randomBytes(
const SECRET = fs.readFileSync(secretFile, 'utf8').trim();
const dbFile = path.join(DATA, 'db.json');
let db = { users: [], creds: [] };
let db = { users: [], creds: [], subs: [] };
try { db = JSON.parse(fs.readFileSync(dbFile, 'utf8')); } catch {}
db.subs = db.subs || [];
function saveDb() { atomicWrite(dbFile, JSON.stringify(db, null, 2)); }
function atomicWrite(file, content) {
const tmp = file + '.tmp';
@@ -36,6 +38,101 @@ function atomicWrite(file, content) {
fs.renameSync(tmp, file);
}
const stateFile = uid => path.join(DATA, 'state-' + uid.replace(/[^a-zA-Z0-9_-]/g, '') + '.json');
function readState(uid) {
try { return JSON.parse(fs.readFileSync(stateFile(uid), 'utf8')); } catch { return null; }
}
/* ---------- push notifications (Web Push / VAPID) ---------- */
const vapidFile = path.join(DATA, 'vapid.json');
let vapid;
try { vapid = JSON.parse(fs.readFileSync(vapidFile, 'utf8')); }
catch { vapid = webpush.generateVAPIDKeys(); fs.writeFileSync(vapidFile, JSON.stringify(vapid), { mode: 0o600 }); }
const VAPID_SUBJECT = process.env.VAPID_SUBJECT || (SECURE ? ORIGIN : 'mailto:admin@localhost');
webpush.setVapidDetails(VAPID_SUBJECT, vapid.publicKey, vapid.privateKey);
async function sendPush(userId, payload) {
const subs = db.subs.filter(s => s.userId === userId);
if (!subs.length) return;
const body = JSON.stringify(payload);
let dirty = false;
await Promise.all(subs.map(async sub => {
// urgency 'high' is the one lever we have over delivery speed — iOS/Android throttle
// low-urgency background push more aggressively under battery-saving modes. TTL is left
// at the library default (long) so a briefly-offline device still gets it once reconnected,
// rather than risking it being dropped for the sake of shaving off latency that TTL doesn't
// actually control anyway.
try { await webpush.sendNotification({ endpoint: sub.endpoint, keys: sub.keys }, body, { urgency: 'high' }); }
catch (e) {
console.error('push send failed', userId, e.statusCode, e.body || e.message);
if (e.statusCode === 404 || e.statusCode === 410) {
db.subs = db.subs.filter(s => s.endpoint !== sub.endpoint); dirty = true;
}
}
}));
if (dirty) saveDb();
}
// Rest-timer alerts: client schedules on start/extend, cancels on skip or on-screen completion —
// this only fires when the tab was backgrounded/suspended and never got to cancel it itself.
const restTimers = new Map(); // userId -> Timeout
function scheduleRestTimer(userId, sec) {
const t = restTimers.get(userId);
if (t) clearTimeout(t);
restTimers.set(userId, setTimeout(() => {
restTimers.delete(userId);
sendPush(userId, { title: 'Rest over 💪', body: 'Time for your next set.', tag: 'rest-timer' });
}, sec * 1000));
}
function cancelRestTimer(userId) {
const t = restTimers.get(userId);
if (t) { clearTimeout(t); restTimers.delete(userId); }
}
// "Workout planned today" reminder — one per user per day, at their chosen time.
// Duplicated (not imported) from frontend/src/lib/history.js effectiveRoutineId — tiny pure helper, not worth sharing across the two runtimes.
function effectiveRoutineId(S, iso) {
const ov = S.dayPlan?.[iso];
if (ov === 'rest') return null;
if (ov && S.routines?.some(r => r.id === ov)) return ov;
const wd = new Date(iso + 'T12:00:00').getDay();
return S.week?.[wd] || null;
}
// Computes "now" in an arbitrary IANA zone (e.g. "Europe/Lisbon") instead of the server's own —
// each user's reminder fires by their own clock, wherever they and their phone actually are.
function userNow(tz) {
try {
const parts = new Intl.DateTimeFormat('en-CA', {
timeZone: tz, hour12: false,
year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit'
}).formatToParts(new Date());
const g = t => parts.find(p => p.type === t)?.value;
return { date: `${g('year')}-${g('month')}-${g('day')}`, hhmm: `${g('hour')}:${g('minute')}` };
} catch { return null; } // unknown/invalid tz string — skip this user rather than guess
}
setInterval(() => {
for (const user of db.users) {
if (!db.subs.some(s => s.userId === user.id)) continue;
const S = readState(user.id);
if (!S?.reminder?.on) continue;
const now = userNow(S.reminder.tz || 'UTC');
if (!now || S.reminder.time !== now.hhmm) continue;
if (user.lastReminder === now.date) continue;
if ((S.workouts || []).some(w => w.d === now.date)) continue;
const rid = effectiveRoutineId(S, now.date);
if (!rid) continue; // rest day — nothing planned
const routine = (S.routines || []).find(r => r.id === rid);
console.log('reminder firing', user.id, rid);
user.lastReminder = now.date;
saveDb();
sendPush(user.id, {
title: routine ? `${routine.emoji || '🏋️'} ${routine.name} today` : 'Workout planned today',
body: "It's on your plan — let's go 💪",
tag: 'day-reminder'
});
}
// Checked every 10s (not 60s) — ticks aren't aligned to the top of the minute, so a 60s
// interval could sit on your target minute for up to 59s before noticing. 10s caps that at ~9s.
}, 10000).unref();
/* ---------- sessions (signed cookie) ---------- */
function sign(payload) {
@@ -223,6 +320,53 @@ const routes = {
delete body.state.active; // in-progress workouts stay device-local
atomicWrite(stateFile(user.id), JSON.stringify(body.state));
json(res, 200, { ok: true, ts: body.state._ts || null });
},
'GET /api/push/public-key': async (req, res) => json(res, 200, { key: vapid.publicKey }),
'POST /api/push/subscribe': async (req, res) => {
const user = readSession(req);
if (!user) return json(res, 401, { error: 'not signed in' });
const body = await readBody(req);
const sub = body.subscription;
if (!sub?.endpoint || !sub?.keys?.p256dh || !sub?.keys?.auth) return json(res, 400, { error: 'invalid subscription' });
db.subs = db.subs.filter(s => s.endpoint !== sub.endpoint);
db.subs.push({ userId: user.id, endpoint: sub.endpoint, keys: sub.keys, created: new Date().toISOString() });
saveDb();
json(res, 200, { ok: true });
},
'POST /api/push/unsubscribe': async (req, res) => {
const user = readSession(req);
if (!user) return json(res, 401, { error: 'not signed in' });
const body = await readBody(req);
db.subs = db.subs.filter(s => !(s.userId === user.id && s.endpoint === body.endpoint));
saveDb();
json(res, 200, { ok: true });
},
'POST /api/push/test': async (req, res) => {
const user = readSession(req);
if (!user) return json(res, 401, { error: 'not signed in' });
await sendPush(user.id, { title: 'openGym', body: 'Test notification ✅ — this is what alerts look like.', tag: 'test' });
json(res, 200, { ok: true });
},
'POST /api/push/rest-timer': async (req, res) => {
const user = readSession(req);
if (!user) return json(res, 401, { error: 'not signed in' });
const body = await readBody(req);
const sec = Math.max(1, Math.min(3600, Math.round(+body.seconds || 0)));
if (!sec) return json(res, 400, { error: 'seconds required' });
scheduleRestTimer(user.id, sec);
json(res, 200, { ok: true });
},
'POST /api/push/rest-timer/cancel': async (req, res) => {
const user = readSession(req);
if (!user) return json(res, 401, { error: 'not signed in' });
cancelRestTimer(user.id);
json(res, 200, { ok: true });
}
};
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 135 KiB

+8 -8
View File
@@ -1,15 +1,15 @@
<svg xmlns="http://www.w3.org/2000/svg" width="880" height="220" viewBox="0 0 880 220" role="img" aria-label="openGym — self-hosted gym & body-weight tracker">
<svg xmlns="http://www.w3.org/2000/svg" width="660" height="190" viewBox="0 0 660 190" role="img" aria-label="openGym — self-hosted gym & body-weight tracker">
<defs>
<linearGradient id="bg" x1="0" y1="0" x2="1" y2="1">
<stop offset="0" stop-color="#12151b"/>
<stop offset="1" stop-color="#0c0e12"/>
</linearGradient>
</defs>
<rect width="880" height="220" rx="24" fill="url(#bg)"/>
<rect x="1.5" y="1.5" width="877" height="217" rx="22.5" fill="none" stroke="#2b3140" stroke-width="3"/>
<rect width="660" height="190" rx="22" fill="url(#bg)"/>
<rect x="1.5" y="1.5" width="657" height="187" rx="20.5" fill="none" stroke="#2b3140" stroke-width="3"/>
<!-- dumbbell mark -->
<g transform="translate(112,110)" fill="#a3e635">
<!-- dumbbell mark (centered to the text block) -->
<g transform="translate(122,96) scale(0.8)" fill="#a3e635">
<rect x="-72" y="-10" width="144" height="20" rx="7"/>
<rect x="-80" y="-36" width="20" height="72" rx="7"/>
<rect x="-104" y="-25" width="17" height="50" rx="7"/>
@@ -18,9 +18,9 @@
</g>
<!-- wordmark + tagline -->
<text x="250" y="102" font-family="-apple-system,Segoe UI,Roboto,Helvetica,Arial,sans-serif" font-size="76" font-weight="800" letter-spacing="-2.5">
<text x="224" y="86" font-family="-apple-system,Segoe UI,Roboto,Helvetica,Arial,sans-serif" font-size="62" font-weight="800" letter-spacing="-2">
<tspan fill="#eef1f6">open</tspan><tspan fill="#a3e635">Gym</tspan>
</text>
<text x="253" y="146" font-family="-apple-system,Segoe UI,Roboto,Helvetica,Arial,sans-serif" font-size="25" font-weight="600" fill="#8b94a7">Self-hosted gym &amp; body-weight tracker</text>
<text x="253" y="176" font-family="-apple-system,Segoe UI,Roboto,Helvetica,Arial,sans-serif" font-size="17" font-weight="500" fill="#5c6475">passkey login · own your data · docker · AGPL</text>
<text x="226" y="120" font-family="-apple-system,Segoe UI,Roboto,Helvetica,Arial,sans-serif" font-size="20.5" font-weight="600" fill="#8b94a7">Self-hosted gym &amp; body-weight tracker</text>
<text x="226" y="146" font-family="-apple-system,Segoe UI,Roboto,Helvetica,Arial,sans-serif" font-size="14" font-weight="500" fill="#5c6475">passkey login · own your data · docker · AGPL</text>
</svg>

Before

Width:  |  Height:  |  Size: 1.5 KiB

After

Width:  |  Height:  |  Size: 1.6 KiB

+3
View File
@@ -22,7 +22,9 @@ services:
restart: "no"
# Passkey auth + per-user data (Node, no framework).
# image: prebuilt (docker compose pull). build: from source (docker compose up --build).
api:
image: ghcr.io/duartesantos8/opengym-api:latest
build: ./api
restart: unless-stopped
env_file: .env
@@ -35,6 +37,7 @@ services:
# Builds the React frontend (multi-stage) and serves it, proxying /api → api
# and the exercise media from the shared volume. Single origin for passkeys.
web:
image: ghcr.io/duartesantos8/opengym-web:latest
build:
context: .
dockerfile: web/Dockerfile
+29 -1
View File
@@ -11,11 +11,14 @@ Requirements: [Docker](https://docs.docker.com/get-docker/) with the Compose plu
git clone https://github.com/DuarteSantos8/gym-app opengym
cd opengym
cp .env.example .env
docker compose pull # prebuilt images from ghcr.io (amd64 + arm64) — or skip and build from source
docker compose up -d
```
- First start downloads the exercise images/GIFs (~140 MB) once into `app/img` and `app/gif`.
- Open **http://localhost:8080** and create a profile with a passkey.
- Rather build from source than pull prebuilt images? Skip `docker compose pull` and run
`docker compose up -d --build` instead — no Node needed locally either way.
Check it's healthy:
@@ -99,7 +102,29 @@ 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.)
## 6. Updating
## 6. Notifications
openGym can push two kinds of alert to your phone/desktop, even when the app isn't open:
rest-timer-over, and a reminder on days you have a workout planned but haven't logged one yet.
Turn it on per-profile in **Settings → Notifications** (requires a signed-in passkey profile and
HTTPS — see section 3).
No setup needed server-side, and nothing to configure per timezone: VAPID keys are generated on
first run and saved to `./data/vapid.json`, and each user's browser reports its own timezone
automatically when they turn the reminder on — it fires at their local time, and follows them if
they travel, regardless of what timezone the server itself runs in.
## 7. Updating
Running prebuilt images:
```bash
git pull # picks up compose/config changes
docker compose pull
docker compose up -d
```
Building from source instead:
```bash
git pull
@@ -117,4 +142,7 @@ downloaded media are untouched.
| "verification failed" on login | `RP_ID`/`ORIGIN` don't match the URL in the address bar. Make them exact, restart. |
| Media didn't download | `docker compose logs media`. Re-run `docker compose up -d`, or run `./scripts/fetch-media.sh`. |
| Port 8080 already used | Set `WEB_PORT=9090` in `.env` (and update `ORIGIN` for local testing). |
| No "Notifications" option in Settings | Requires a signed-in profile and HTTPS (or `localhost`) — guest mode and plain HTTP over LAN can't subscribe. |
| Day reminder fires at the wrong time | Toggle it off and on in Settings so it re-detects your browser's timezone (also happens automatically on every app load — see section 6). |
| Want to reset a stuck login | Delete the cookie in your browser; sessions are just signed cookies. |
| `docker compose pull` fails with "denied" / "unauthorized" | The prebuilt images aren't published yet, or need to be, or the GHCR package is still private — build from source instead (`docker compose up -d --build`). |
+1 -1
View File
@@ -1,7 +1,7 @@
{
"name": "opengym-frontend",
"private": true,
"version": "1.0.0",
"version": "1.1.1",
"type": "module",
"scripts": {
"dev": "vite",
+18
View File
@@ -8,6 +8,24 @@ self.addEventListener('activate', e => {
Promise.all(keys.filter(k => k !== CACHE).map(k => caches.delete(k)))
).then(() => self.clients.claim()))
})
self.addEventListener('push', e => {
const data = e.data ? e.data.json() : {}
e.waitUntil(self.registration.showNotification(data.title || 'openGym', {
body: data.body || '',
icon: 'icon-512.png',
badge: 'icon-180.png',
tag: data.tag || 'opengym',
renotify: true
}))
})
self.addEventListener('notificationclick', e => {
e.notification.close()
e.waitUntil(self.clients.matchAll({ type: 'window' }).then(clients => {
const c = clients.find(c => 'focus' in c)
return c ? c.focus() : self.clients.openWindow('./')
}))
})
self.addEventListener('fetch', e => {
const url = new URL(e.request.url)
if (e.request.method !== 'GET' || url.origin !== location.origin) return
+3 -1
View File
@@ -27,7 +27,9 @@ button,.chip,.tile,.item,.wday,.cal-d,.ck,.swatch,.emoji-cell,.hm-c,#tabbar,.ste
@keyframes viewfade{from{opacity:0;transform:translateY(6px)}to{opacity:1;transform:none}}
#app.vfade{animation:viewfade .18s ease}
@media (prefers-reduced-motion: reduce){*{animation:none!important;transition:none!important}}
html{font-size:16px}
/* html carries the theme background too, so the iOS scroll-lock (position:fixed on body)
can never expose a grey strip below the app when a modal opens */
html{font-size:16px;background:var(--bg);overscroll-behavior:none}
body{
background:var(--bg); color:var(--txt);
font-family:-apple-system,BlinkMacSystemFont,'SF Pro Text','Segoe UI',Roboto,sans-serif;
+2
View File
@@ -31,5 +31,7 @@ export function weekKey(d) {
return dt.getFullYear() + '-' + week
}
export const localTZ = () => { try { return Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC' } catch { return 'UTC' } }
export const uid = () => Date.now().toString(36) + Math.random().toString(36).slice(2, 7)
export const ACCENTS = { lime: '#a3e635', sky: '#38bdf8', orange: '#fb923c', violet: '#a78bfa', pink: '#f472b6', red: '#f87171', teal: '#2dd4bf', gold: '#fbbf24' }
+33
View File
@@ -0,0 +1,33 @@
// Web Push subscribe/unsubscribe — requires a signed-in profile (subscriptions are stored
// server-side per user, same as everything else under /api).
import { api } from './api.js'
export const pushSupported = () => 'serviceWorker' in navigator && 'PushManager' in window && 'Notification' in window
export const pushPermission = () => (pushSupported() ? Notification.permission : 'unsupported')
const urlBase64ToUint8Array = b64 => {
const padded = (b64 + '='.repeat((4 - b64.length % 4) % 4)).replace(/-/g, '+').replace(/_/g, '/')
const raw = atob(padded)
return Uint8Array.from([...raw].map(c => c.charCodeAt(0)))
}
export async function enablePush() {
if (!pushSupported()) throw new Error('Push notifications are not supported in this browser')
const perm = await Notification.requestPermission()
if (perm !== 'granted') throw new Error('Notifications permission was not granted')
const reg = await navigator.serviceWorker.ready
const { key } = await api('/api/push/public-key')
const subscription = await reg.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: urlBase64ToUint8Array(key) })
await api('/api/push/subscribe', { method: 'POST', body: JSON.stringify({ subscription: subscription.toJSON() }) })
}
export async function disablePush() {
if (!pushSupported()) return
const reg = await navigator.serviceWorker.ready
const sub = await reg.pushManager.getSubscription()
if (!sub) return
await sub.unsubscribe()
await api('/api/push/unsubscribe', { method: 'POST', body: JSON.stringify({ endpoint: sub.endpoint }) }).catch(() => {})
}
export const sendTestPush = () => api('/api/push/test', { method: 'POST', body: '{}' })
+19 -1
View File
@@ -1,12 +1,14 @@
import { create } from 'zustand'
import { api } from '../lib/api.js'
import { localTZ } from '../lib/format.js'
const KEY = 'gym_state_v1'
export const DEF = {
unit: 'kg', restSec: 90, sound: true,
theme: 'dark', accent: 'lime', targetW: null,
bodyweight: [], routines: [], week: {}, dayPlan: {},
exWeights: {}, workouts: [], active: null
exWeights: {}, workouts: [], active: null,
reminder: { on: false, time: '08:00', tz: null }
}
const clone = o => JSON.parse(JSON.stringify(o))
@@ -33,6 +35,16 @@ export const useStore = create((set, get) => {
}
}
// A setting changed right before switching away/closing the tab must not get lost mid-debounce
// (e.g. setting the reminder time then immediately backgrounding to test it).
document.addEventListener('visibilitychange', () => {
if (document.visibilityState === 'hidden' && pushTm) {
clearTimeout(pushTm)
pushTm = null
get().pushState()
}
})
return {
S: loadState(),
user: (() => { try { return JSON.parse(localStorage.getItem('gym_user')) || null } catch { return null } })(),
@@ -90,6 +102,12 @@ export const useStore = create((set, get) => {
const me = await api('/api/me')
get().setUser(me.user)
await get().pullState()
// Re-stamp the reminder's timezone on every load — keeps it correct if you're travelling,
// without needing to revisit Settings.
const tz = localTZ()
if (get().S.reminder?.on && get().S.reminder.tz !== tz) {
get().update(s => { s.reminder = { ...s.reminder, tz } })
}
} catch (e) {
if (e.status === 401) get().setUser(null)
}
+29 -6
View File
@@ -1,10 +1,17 @@
import { create } from 'zustand'
import { uid } from '../lib/format.js'
import { beep, vibrate } from '../lib/sound.js'
import { api } from '../lib/api.js'
import { useStore } from './useStore.js'
// Fire-and-forget: lets the server push a "rest over" alert if this tab gets suspended
// before the local timer completes. No-ops for guests / offline.
const pushRestTimer = sec => { if (useStore.getState().user) api('/api/push/rest-timer', { method: 'POST', body: JSON.stringify({ seconds: sec }) }).catch(() => {}) }
const cancelPushRestTimer = () => { if (useStore.getState().user) api('/api/push/rest-timer/cancel', { method: 'POST', body: '{}' }).catch(() => {}) }
let toastTm = null
let timerInt = null
let timerTick = null
export const useUI = create((set, get) => ({
sheets: [], // { id, render:(close)=>JSX, kind:'sheet'|'center', locked }
@@ -28,11 +35,14 @@ export const useUI = create((set, get) => ({
startRest(sec) {
get().stopRest()
set({ timer: { left: sec, total: sec } })
timerInt = setInterval(() => {
const endsAt = Date.now() + sec * 1000
set({ timer: { left: sec, total: sec, endsAt } })
pushRestTimer(sec)
timerTick = () => {
const t = get().timer
if (!t) return
const left = t.left - 1
const left = Math.max(0, Math.round((t.endsAt - Date.now()) / 1000))
if (left === t.left) return
const snd = useStore.getState().S.sound
if (left <= 0) {
beep(snd, 880, 0.15); beep(snd, 880, 0.15, 0.25); beep(snd, 1320, 0.4, 0.5)
@@ -40,8 +50,21 @@ export const useUI = create((set, get) => ({
}
if (left <= 3) beep(snd, 660, 0.1)
set({ timer: { ...t, left } })
}, 1000)
}
timerInt = setInterval(timerTick, 1000)
document.addEventListener('visibilitychange', timerTick)
},
addRest(sec) { const t = get().timer; if (t) set({ timer: { left: t.left + sec, total: t.total + sec } }) },
stopRest() { if (timerInt) clearInterval(timerInt); timerInt = null; set({ timer: null }) }
addRest(sec) {
const t = get().timer
if (!t) return
const left = t.left + sec
set({ timer: { ...t, left, total: t.total + sec, endsAt: t.endsAt + sec * 1000 } })
pushRestTimer(left)
},
stopRest() {
if (timerInt) clearInterval(timerInt); timerInt = null
if (timerTick) document.removeEventListener('visibilitychange', timerTick); timerTick = null
if (get().timer) cancelPushRestTimer()
set({ timer: null })
}
}))
+55 -2
View File
@@ -1,9 +1,10 @@
import { useRef } from 'react'
import { useEffect, useRef, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { useStore, DEF, hasData } from '../store/useStore.js'
import { useUI } from '../store/useUI.js'
import { ACCENTS, todayISO } from '../lib/format.js'
import { ACCENTS, todayISO, localTZ } from '../lib/format.js'
import { webauthnOK, passkeyLogin, passkeyRegister, IS_ANDROID } from '../lib/api.js'
import { pushSupported, enablePush, disablePush, sendTestPush } from '../lib/push.js'
import { loadStarterPlan, confirmSheet } from '../sheets.jsx'
export default function Settings() {
@@ -82,6 +83,8 @@ export default function Settings() {
<div className="small dim" style={{ marginTop: 6 }}>Note: switching units only changes the label — logged numbers are not converted.</div>
</div>
{user && <NotificationsCard S={S} update={update} toast={toast} />}
<div className="card">
<h2>Data</h2>
<button className="btn" onClick={doExport}>⬇️ Export backup (JSON)</button>
@@ -100,6 +103,56 @@ export default function Settings() {
</div>
}
function NotificationsCard({ S, update, toast }) {
const [on, setOn] = useState(false)
const [busy, setBusy] = useState(false)
const supported = pushSupported()
useEffect(() => {
if (!supported) return
navigator.serviceWorker.ready.then(reg => reg.pushManager.getSubscription()).then(sub => setOn(!!sub)).catch(() => {})
}, [supported])
const toggle = async () => {
setBusy(true)
try {
if (on) { await disablePush(); setOn(false); toast('Notifications off') }
else { await enablePush(); setOn(true); toast('Notifications on 🔔') }
} catch (e) { toast(e.message || 'Could not change notification settings') }
setBusy(false)
}
const test = async () => {
try { await sendTestPush(); toast('Test sent — should arrive any second') }
catch (e) { toast(e.message || 'Test failed') }
}
return <div className="card">
<h2>Notifications</h2>
{!supported ? <div className="small dim">Not supported in this browser.</div> : <>
<div className="row between" style={{ padding: '8px 0' }}>
<div><span>Push notifications</span><div className="small muted">Rest-timer alerts, even if openGym is closed.</div></div>
<button className={'chip' + (on ? ' on' : '')} disabled={busy} onClick={toggle}>{on ? 'On 🔔' : 'Off 🔕'}</button>
</div>
{on && <>
<div className="row between" style={{ padding: '8px 0' }}>
<span>Workout day reminder</span>
<button className={'chip' + (S.reminder?.on ? ' on' : '')} onClick={() => update(s => { s.reminder = { ...(s.reminder || DEF.reminder), on: !s.reminder?.on, tz: localTZ() } })}>{S.reminder?.on ? 'On' : 'Off'}</button>
</div>
{S.reminder?.on && <div className="row between" style={{ padding: '8px 0' }}>
<span>Reminder time</span>
<input type="time" className="input" style={{ width: 120 }} value={S.reminder?.time || DEF.reminder.time}
onChange={e => update(s => { s.reminder = { ...(s.reminder || DEF.reminder), time: e.target.value, tz: localTZ() } })} />
</div>}
<div className="small dim" style={{ margin: '6px 0' }}>
Only sent on days you have a routine planned and haven't logged a workout yet.
{S.reminder?.on && S.reminder?.tz && <> Timezone: {S.reminder.tz} (auto-detected, updates if you travel).</>}
</div>
<button className="btn sm" onClick={test}>Send test notification</button>
</>}
</>}
</div>
}
function RegisterInline({ close, setUser, pushState, pullState, toast }) {
const nameRef = useRef(null)
const go = async () => {
+8 -1
View File
@@ -1,6 +1,13 @@
# Multi-stage: build the React app, then serve it with nginx.
# Self-hosters never need Node locally — `docker compose up` builds everything.
FROM node:22-alpine AS build
#
# --platform=$BUILDPLATFORM pins the build stage to the host's native arch even when
# cross-building for other targets (e.g. amd64 host building an arm64 image). The build
# output (static JS/CSS/HTML) is arch-independent, so there's no reason to run it under
# QEMU — and QEMU-emulated npm installs are known to corrupt esbuild/rollup's platform-
# specific native binaries, which is what breaks `vite build` with unrelated-looking
# module-resolution errors.
FROM --platform=$BUILDPLATFORM node:22-alpine AS build
WORKDIR /app
COPY frontend/package.json frontend/package-lock.json* ./
RUN npm ci 2>/dev/null || npm install