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
Push: the rest-over alert never rings another device (#348)
Duarte Santosf29ec3b1b6ed
diff --git a/api/server.js b/api/server.jsindex 8df301ccf..ee0953955 100644--- a/api/server.js+++ b/api/server.js@@ -258,11 +258,13 @@ function pushEndpointError(raw) {}// `deviceId` narrows the send to the subscriptions one browser registered (the rest-timer alert-// belongs to the device that started the rest); a subscription stored without one — an older-// client — still gets everything, as before.+// belongs to the device that started the rest, #348); a subscription stored without one (an+// older client) still gets everything, as before. A resting device with no subscription of its+// own gets nothing: the phone in the bag must not ring for a rest timed on the desktop. The+// client re-sends its subscription with its id on every boot, so an id that changed heals there.async function sendPush(userId, payload, deviceId) {let subs = db.subs.filter(s => s.userId === userId);- if (deviceId && subs.some(s => s.deviceId === deviceId)) subs = subs.filter(s => s.deviceId === deviceId);+ if (deviceId) subs = subs.filter(s => !s.deviceId || s.deviceId === deviceId);if (!subs.length) return;const body = JSON.stringify(payload);let dirty = false;diff --git a/api/test/server-push-device.test.js b/api/test/server-push-device.test.jsnew file mode 100644index 000000000..e2175677d--- /dev/null+++ b/api/test/server-push-device.test.js@@ -0,0 +1,67 @@+/* #348: the "rest over" push belongs to the device that started the rest. When that device had no+ subscription of its own, sendPush fell back to every subscription of the account, so the phone+ rang for a rest timed on the desktop. The subscriptions here have private endpoints: the send+ path refuses and prunes each one it would have contacted, without opening a socket, so what is+ left in db.json says which ones it tried. Real server.js in a child. */+import { test } from 'node:test';+import assert from 'node:assert/strict';+import crypto from 'node:crypto';+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';+import { boundPort } from './helpers.mjs';++const API = path.join(path.dirname(fileURLToPath(import.meta.url)), '..');+const SECRET = crypto.randomBytes(32).toString('hex');++function mintSession(uid) {+ const payload = `${uid}:${Date.now() + 86400000}:0`;+ return payload + '.' + crypto.createHmac('sha256', SECRET).update(payload).digest('base64url');+}+const cookie = { Cookie: `gymsid=${mintSession('u_test_1')}` };+const sub = (endpoint, deviceId) => ({+ userId: 'u_test_1', endpoint, keys: { p256dh: 'p', auth: 'a' }, ...(deviceId ? { deviceId } : {}), created: new Date().toISOString()+});++async function startServer(t, subs) {+ const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gym-pushdev-'));+ fs.writeFileSync(path.join(dataDir, 'secret'), SECRET, { mode: 0o600 });+ fs.writeFileSync(path.join(dataDir, 'db.json'), JSON.stringify({+ users: [{ id: 'u_test_1', name: 'One', created: new Date().toISOString() }], creds: [], invites: [], subs+ }));+ fs.writeFileSync(path.join(dataDir, 'state-u_test_1.json'), JSON.stringify({ _rev: 1, lang: 'en', workouts: [], routines: [] }));+ const child = spawn(process.execPath, ['server.js'], {+ cwd: API, stdio: ['ignore', 'pipe', 'pipe'],+ env: { ...process.env, PORT: '0', DATA_DIR: dataDir, ORIGIN: 'http://localhost:8080', RP_ID: 'localhost', AUDIT_LOG: '0', REMINDER_TICK_MS: '100000' }+ });+ const h = { api: '', dataDir, 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 }); });+ h.port = await boundPort(child, () => h.log);+ h.api = `http://127.0.0.1:${h.port}`;+ return h;+}++async function restOn(h, deviceId) {+ const r = await fetch(`${h.api}/api/push/rest-timer`, {+ method: 'POST', headers: { ...cookie, 'Content-Type': 'application/json', Origin: 'http://localhost:8080' },+ body: JSON.stringify({ seconds: 1, deviceId })+ });+ assert.equal(r.status, 200);+ await new Promise(res => setTimeout(res, 2500)); // fires at 1 s, then prunes what it tried+ return JSON.parse(fs.readFileSync(path.join(h.dataDir, 'db.json'), 'utf8')).subs.map(s => s.endpoint).sort();+}++test('a rest on a device without a subscription rings no other device', async t => {+ const h = await startServer(t, [sub('https://10.0.0.2/phone', 'phoneBBBBBB'), sub('https://10.0.0.3/old')]);+ // The desktop has none: the phone is left alone, the subscription from an older client still rings.+ assert.deepEqual(await restOn(h, 'desktopAAAA'), ['https://10.0.0.2/phone']);+});++test('a rest on a subscribed device rings that device and nobody else', async t => {+ const h = await startServer(t, [sub('https://10.0.0.2/phone', 'phoneBBBBBB'), sub('https://10.0.0.4/desk', 'desktopAAAA')]);+ assert.deepEqual(await restOn(h, 'desktopAAAA'), ['https://10.0.0.2/phone']);+});diff --git a/api/test/server-push-status.test.js b/api/test/server-push-status.test.jsindex ef6b45ef6..1f01c0cec 100644--- a/api/test/server-push-status.test.js+++ b/api/test/server-push-status.test.js@@ -115,7 +115,7 @@ test('a re-send without a usable device id keeps the id the row has', async t =>assert.deepEqual(await status(h, endpoint), { subscribed: true, deviceId: 'dev_phone001' });});-test('a rest started on a device whose row has no id goes to every device; once repaired, to its own only', async t => {+test('a rest started on a device whose row has no id rings that row, never another device\'s (#348)', async t => {// Same method as the rest-timer test below: every send to localhost fails and is logged.const phone = { userId: 'u_test_1', endpoint: 'https://localhost/phone', keys, created: new Date().toISOString() };const desk = { userId: 'u_test_1', endpoint: 'https://localhost/desk', keys, deviceId: 'dev_desk0000', created: new Date().toISOString() };@@ -124,12 +124,12 @@ test('a rest started on a device whose row has no id goes to every device; onceassert.equal((await post(h, '/api/push/rest-timer', { seconds: 1, deviceId: 'dev_phone000' })).status, 200);await new Promise(r => setTimeout(r, 2500));- assert.equal(sent(), 2, `no row carries the phone's id, so the desk got the phone's alert too:\n${h.log}`);+ assert.equal(sent(), 1, `no row carries the phone's id: the id-less row (an older client) rings, the desk does not:\n${h.log}`);assert.equal((await post(h, '/api/push/subscribe', { subscription: { endpoint: phone.endpoint, keys }, deviceId: 'dev_phone000' })).status, 200);assert.equal((await post(h, '/api/push/rest-timer', { seconds: 1, deviceId: 'dev_phone000' })).status, 200);await new Promise(r => setTimeout(r, 2500));- assert.equal(sent(), 3, `after the repair the phone's alert goes to the phone alone:\n${h.log}`);+ assert.equal(sent(), 2, `after the repair the phone's alert goes to the phone alone:\n${h.log}`);});test('a rest timer belongs to the device that set it: another device cancelling does not silence it', async t => {