Open-source gym & body-weight tracker, now in the App Store (iPhone + Apple Watch) and as an Android APK. Plan routines, log workouts, see which muscles are trained, import from Strong/Hevy/FitNotes. Self-host it or use it on the phone alone.
JavaScript apple-watchbodyweightdockerfitnessfitness-trackergymhealthiosmcpnodejspasskeysprogressive-web-applicationspwareactself-hostedself-hostingvitewebauthnweightliftingworkout-tracker
Pairing: a phone in use keeps its token — the server renews it past half its life, and sign out everywhere still ends it
Duarte Santos7755fe68596f
diff --git a/api/openapi.yaml b/api/openapi.yamlindex 38973c8c7..d627992a7 100644--- a/api/openapi.yaml+++ b/api/openapi.yaml@@ -145,7 +145,11 @@ paths:tags: [auth]operationId: getMesummary: Who am I?- description: Resolves the current session to a user.+ description: |+ Resolves the current session to a user. A paired phone (bearer token) whose token is+ past half of `SESSION_DAYS` also receives a fresh `token` to use from now on; it carries+ the account's current session version, so "sign out everywhere" revokes it like the old+ one. Cookie sessions never get one.responses:'200':description: A valid session.@@ -155,6 +159,7 @@ paths:type: objectproperties:user: { $ref: '#/components/schemas/SessionUser' }+ token: { type: string, description: 'Bearer sessions past half their lifetime only — the renewed token.' }'401': { $ref: '#/components/responses/Unauthorized' }/api/register/options:diff --git a/api/server.js b/api/server.jsindex b940cd7a6..716c13d49 100644--- a/api/server.js+++ b/api/server.js@@ -409,11 +409,14 @@ function cookieToken(req) {}return null;}-function readSession(req) {+// The session behind a request: { user, exp, bearer } — `bearer` when it came in an Authorization+// header (a paired phone) rather than the cookie — or null for no valid session at all.+function sessionOf(req) {// The paired mobile app has no cookie jar shared with the API's origin, so it carries the same// signed token in an Authorization header instead — same payload, same verification below.const auth = req.headers.authorization || '';- const tok = cookieToken(req) || (auth.startsWith('Bearer ') ? auth.slice(7).trim() : null);+ const cookie = cookieToken(req);+ const tok = cookie || (auth.startsWith('Bearer ') ? auth.slice(7).trim() : null);if (!tok) return null;const payload = verifySig(tok);if (!payload) return null;@@ -426,7 +429,10 @@ function readSession(req) {// payload (it still had to pass the HMAC, so this is belt-and-braces) and is refused outright.const claimed = ver === undefined ? 0 : Number(ver);if (!Number.isInteger(claimed) || claimed !== sessionVersion(user)) return null;- return user;+ return { user, exp: +exp, bearer: !cookie };+}+function readSession(req) {+ return sessionOf(req)?.user || null;}// Guard for /api/admin/* — resolves the caller and 401/403s if they aren't an admin.function requireAdmin(req, res) {@@ -693,10 +699,19 @@ const routes = {json(res, 200, { invite_only: INVITE_ONLY, allow_guest: ALLOW_GUEST, ...(coach ? { coach } : {}) });},+ // A paired phone's token was minted once, at pairing, and nothing ever renewed it: after+ // SESSION_DAYS the server refused a phone that had been in use every day. The phone asks this+ // on every start, so once its token is past half its life the answer carries a new one+ // (`token`), which the phone saves in place of the old. makeSession() writes the account's+ // current session version into it, so "sign out everywhere" ends a renewed token exactly as it+ // ended the old one — and a revoked token never gets this far. A browser's cookie is left+ // alone: signing in renews it, as before.'GET /api/me': async (req, res) => {- const user = readSession(req);- if (!user) return json(res, 401, { error: 'not signed in' });- json(res, 200, { user: { id: user.id, name: user.name, admin: isAdmin(user) } });+ const s = sessionOf(req);+ if (!s) return json(res, 401, { error: 'not signed in' });+ const { user } = s;+ const renew = s.bearer && s.exp - Date.now() < SESSION_DAYS * 86400000 / 2;+ json(res, 200, { user: { id: user.id, name: user.name, admin: isAdmin(user) }, ...(renew ? { token: makeSession(user) } : {}) });},'POST /api/register/options': async (req, res) => {diff --git a/api/test/server-token-refresh.test.js b/api/test/server-token-refresh.test.jsnew file mode 100644index 000000000..542263b30--- /dev/null+++ b/api/test/server-token-refresh.test.js@@ -0,0 +1,110 @@+/* A paired phone's bearer token used to live exactly SESSION_DAYS from the pairing and then be+ refused, however often the phone had been used. GET /api/me — which the phone asks on every+ start — now hands a bearer session past half its lifetime a fresh token. Revocation must+ survive that: the renewed token carries the account's session version, so "sign out+ everywhere" ends it, and a token already revoked is never renewed. Real server.js in a child. */+import { test } from 'node:test';+import assert from 'node:assert/strict';+import crypto from 'node:crypto';+import net from 'node:net';+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';+import { spawn } from 'node:child_process';+import { fileURLToPath } from 'node:url';++const API = path.join(path.dirname(fileURLToPath(import.meta.url)), '..');+const SECRET = crypto.randomBytes(32).toString('hex');+const DAY = 86400000;+const SESSION_DAYS = 10;++// Same construction as server.js makeSession(): payload `uid:exp:sv`, HMAC-SHA256 over SECRET.+function mint(uid, { daysLeft, sv = 0 }) {+ const payload = `${uid}:${Date.now() + daysLeft * DAY}:${sv}`;+ return payload + '.' + crypto.createHmac('sha256', SECRET).update(payload).digest('base64url');+}+const verifies = token => {+ const i = token.lastIndexOf('.');+ const payload = token.slice(0, i);+ return token.slice(i + 1) === crypto.createHmac('sha256', SECRET).update(payload).digest('base64url');+};+const bearer = token => ({ Authorization: 'Bearer ' + token });++const freePort = () => new Promise(r => {+ const s = net.createServer(); s.listen(0, '127.0.0.1', () => { const p = s.address().port; s.close(() => r(p)); });+});++const USERS = [+ { id: 'u_phone', name: 'Phone', created: new Date().toISOString() },+ { id: 'u_bumped', name: 'Bumped', created: new Date().toISOString(), sv: 1 }+];++async function startServer(t) {+ const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gym-renew-'));+ fs.writeFileSync(path.join(dataDir, 'secret'), SECRET, { mode: 0o600 });+ fs.writeFileSync(path.join(dataDir, 'db.json'), JSON.stringify({ users: USERS, creds: [], subs: [], invites: [] }));+ const port = await freePort();+ const child = spawn(process.execPath, ['server.js'], {+ cwd: API, stdio: ['ignore', 'pipe', 'pipe'],+ env: { ...process.env, PORT: String(port), DATA_DIR: dataDir, ORIGIN: 'http://localhost:8080', RP_ID: 'localhost', SESSION_DAYS: String(SESSION_DAYS) }+ });+ const h = { api: `http://127.0.0.1:${port}`, log: '' };+ child.stdout.on('data', d => h.log += d);+ child.stderr.on('data', d => h.log += d);+ t.after(() => { child.kill('SIGKILL'); fs.rmSync(dataDir, { recursive: true, force: true }); });+ let up = false;+ for (let i = 0; i < 100 && !up; i++) {+ try { up = (await fetch(`${h.api}/api/health`)).ok; } catch { /* not up yet */ }+ if (!up) await new Promise(r => setTimeout(r, 100));+ }+ assert.ok(up, `server never came up:\n${h.log}`);+ return h;+}++test('a bearer token past half its lifetime gets a fresh one from /api/me; a younger one and a cookie do not', async t => {+ const h = await startServer(t);+ const me = headers => fetch(`${h.api}/api/me`, { headers });++ // Four of ten days left: past half. The new token verifies, lasts the full SESSION_DAYS+ // from now, keeps the account's session version, and is itself accepted.+ const old = await me(bearer(mint('u_phone', { daysLeft: 4 })));+ assert.equal(old.status, 200);+ const body = await old.json();+ assert.equal(body.user.id, 'u_phone');+ assert.equal(typeof body.token, 'string');+ assert.ok(verifies(body.token));+ const [uid, exp, sv] = body.token.split('.')[0].split(':');+ assert.equal(uid, 'u_phone');+ assert.equal(sv, '0');+ assert.ok(Math.abs(+exp - (Date.now() + SESSION_DAYS * DAY)) < 60000);+ const again = await me(bearer(body.token));+ assert.equal(again.status, 200);+ assert.equal((await again.json()).token, undefined); // brand new — nothing to renew++ // Eight of ten days left: not yet.+ const young = await me(bearer(mint('u_phone', { daysLeft: 8 })));+ assert.deepEqual(Object.keys(await young.json()), ['user']);++ // A browser's cookie is renewed by signing in, not here.+ const cookie = await me({ Cookie: `gymsid=${mint('u_phone', { daysLeft: 1 })}` });+ assert.equal(cookie.status, 200);+ assert.equal((await cookie.json()).token, undefined);+});++test('revocation still works: an old session version is refused, and "sign out everywhere" ends a renewed token', async t => {+ const h = await startServer(t);+ const me = headers => fetch(`${h.api}/api/me`, { headers });++ // Revoked before it was ever renewed: refused, and no new token handed out.+ const revoked = await me(bearer(mint('u_bumped', { daysLeft: 2, sv: 0 })));+ assert.equal(revoked.status, 401);+ assert.equal((await revoked.json()).token, undefined);++ // Renewed first, then the account signs out everywhere: the renewed token dies with it.+ const r = await me(bearer(mint('u_phone', { daysLeft: 1 })));+ const { token } = await r.json();+ assert.equal((await me(bearer(token))).status, 200);+ const out = await fetch(`${h.api}/api/logout/all`, { method: 'POST', headers: { Cookie: `gymsid=${mint('u_phone', { daysLeft: 9 })}` } });+ assert.equal(out.status, 200);+ assert.equal((await me(bearer(token))).status, 401);+});diff --git a/frontend/src/lib/remote.js b/frontend/src/lib/remote.jsindex 22ef5a989..038e854e1 100644--- a/frontend/src/lib/remote.js+++ b/frontend/src/lib/remote.js@@ -36,6 +36,15 @@ export async function forgetRemote() {setRemoteAuth('', null)}+// The server renewed the token (GET /api/me hands one out once the old is past half its life):+// every request from now on carries it, and the pairing file keeps it for the next start. The+// old one stays valid until its own expiry, so a write that fails here costs nothing but a+// renewal on a later start.+export async function renewToken(remote, token) {+ setRemoteAuth(remote.base, token)+ await saveRemoteFile({ ...remote, token })+}+// Redeems the pairing code, wires api.js at the resolved base, and persists the connection so// boot() can restore it on the next launch.export async function connect(rawUrl, code) {diff --git a/frontend/src/store/useStore.js b/frontend/src/store/useStore.jsindex d0b3283be..fe7eb3e12 100644--- a/frontend/src/store/useStore.js+++ b/frontend/src/store/useStore.js@@ -9,7 +9,7 @@ import { MOBILE, initReminderSync, nativeLoad, nativeSave, onAppActive, readJsonimport { mergeStates, localExtras, stampRoutines } from '../lib/sync-merge.js'import { countChanges, syncFingerprint } from '../lib/sync-changes.js'import { appBase } from '../lib/app-base.js'-import { loadRemote, chooseLocal, forgetRemote, connect, normalizeServerUrl } from '../lib/remote.js'+import { loadRemote, chooseLocal, forgetRemote, connect, normalizeServerUrl, renewToken } from '../lib/remote.js'import { loadCoachDevice, saveCoachDevice, coachDeviceSettings } from '../lib/coach-device.js'import { WC_DEFAULT } from '../lib/workout-controls.js'@@ -881,6 +881,9 @@ export const useStore = create((set, get) => {try {const me = await api('/api/me') // also catches a token revoked elsewhere (sign out everywhere)if (!me.user?.id) throw Object.assign(new Error('no user'), { status: 200, code: 'bad-response' })+ // A token past half its life comes back renewed: kept, it never runs out on a phone+ // that is used at all.+ if (typeof me.token === 'string' && me.token) await renewToken(remote, me.token)get().setUser(me.user)// The paired server's /api/config, the same one the web boot reads: without it the// phone never learned whether the server offers the Coach and told everyone "yourdiff --git a/frontend/src/store/useStore.mobile-remote.test.jsx b/frontend/src/store/useStore.mobile-remote.test.jsxindex ae0a07907..b5bb60dc9 100644--- a/frontend/src/store/useStore.mobile-remote.test.jsx+++ b/frontend/src/store/useStore.mobile-remote.test.jsx@@ -367,6 +367,31 @@ describe('remote-mode boot and the durable file mirror', () => {})})+describe('a token the server renews', () => {+ it('is saved to the pairing file at boot and carried by every request after it', async () => {+ pairedPhone()+ const srv = serverWith(SERVER_STATE)+ h.server = (path, method, init) => (path === '/api/me' ? json(200, { user: USER, token: 'TOKEN-RENEWED' }) : srv.handle(path, method, init))+ const useStore = await freshStore()+ await useStore.getState().boot()++ expect(readFile('opengym-remote.json')).toEqual({ mode: 'remote', base: BASE, token: 'TOKEN-RENEWED', user: USER })+ h.calls = []+ useStore.getState().update(s => { s.workouts.push(workout('w2', '2026-09-15')) })+ await useStore.getState().pushState()+ expect(serverCalls()).toEqual([expect.objectContaining({ method: 'PUT', auth: 'Bearer TOKEN-RENEWED' })])+ })++ it('an answer without one leaves the pairing as it was', async () => {+ pairedPhone()+ serverWith(SERVER_STATE)+ const useStore = await freshStore()+ await useStore.getState().boot()+ expect(readFile('opengym-remote.json')).toMatchObject({ token: 'TOKEN-OLD' })+ expect(serverCalls().every(c => c.auth === 'Bearer TOKEN-OLD')).toBe(true)+ })+})+describe('a request that never answers', () => {it('gives up after its timeout: the change stays owed, the phone says it is offline, and the next push goes out', async () => {pairedPhone()