diff --git a/api/openapi.yaml b/api/openapi.yaml index 4b92503..a409874 100644 --- a/api/openapi.yaml +++ b/api/openapi.yaml @@ -597,7 +597,9 @@ paths: the two protocol keys are kept. The endpoint must be a public `https://` URL — private/loopback/link-local addresses are refused (here and again at send time, against DNS rebinding). At most 20 subscriptions per user; the oldest - are dropped first. Re-subscribing an existing endpoint replaces it. + are dropped first. Re-subscribing an existing endpoint replaces it and keeps + its original `created` — the client re-sends its subscription on every + signed-in boot, so a row the instance lost comes back on its own. requestBody: required: true content: @@ -607,6 +609,13 @@ paths: required: [subscription] properties: subscription: { $ref: '#/components/schemas/PushSubscription' } + deviceId: + type: string + pattern: '^[A-Za-z0-9_-]{8,64}$' + description: >- + A token the browser made up for itself (stored in its localStorage), + so rest-timer pushes can be aimed at the device that started the + rest. Optional; anything that is not a short token is ignored. responses: '200': description: Stored. @@ -623,6 +632,33 @@ paths: private: { value: { error: "endpoint must not point at a private address" } } '401': { $ref: '#/components/responses/Unauthorized' } + /api/push/status: + get: + tags: [push] + operationId: pushStatus + summary: Does the server hold this subscription? + description: >- + Whether the caller's account has a stored subscription with exactly this + `endpoint`. The browser's `PushManager.getSubscription()` says nothing about + the server's side — a row pruned after a dead send (404/410/403) leaves the + browser subscribed to nowhere — so the client asks here before showing the + notifications switch as on, and re-registers when the answer is no. + parameters: + - in: query + name: endpoint + required: true + schema: { type: string, format: uri } + responses: + '200': + description: The answer. + content: + application/json: + schema: + type: object + properties: + subscribed: { type: boolean } + '401': { $ref: '#/components/responses/Unauthorized' } + /api/push/unsubscribe: post: tags: [push] @@ -654,7 +690,8 @@ paths: description: >- Sends a test push to all of the caller's subscriptions (localized with the `lang` in their synced state). Returns 200 even if delivery to individual - endpoints fails — dead endpoints (404/410) are pruned as a side effect. + endpoints fails — dead endpoints (404/410, and 403 for a subscription made + against a VAPID key the instance no longer has) are pruned as a side effect. responses: '200': description: Sends attempted. @@ -669,10 +706,14 @@ paths: operationId: pushRestTimer summary: Schedule a server-side rest-timer push description: | - Schedules one push after `seconds` (clamped to 1–3600; one pending timer per - user, a new call replaces it). The client schedules this on rest start/extend - and cancels on skip or on-screen completion — the push only actually fires - when the tab was backgrounded/suspended and never got to cancel it. + Schedules one push after `seconds` (clamped to 1–3600). One pending timer per + device — `deviceId`, the same token the subscription was registered with; a + new call from the same device replaces it, and the push goes only to that + device's subscriptions. Without a `deviceId` there is one timer per account + and the push goes to every subscription, as before. The client schedules this + on rest start/extend and cancels on skip or on-screen completion — the push + only actually fires when the tab was backgrounded/suspended and never got to + cancel it. Timers live in memory: an API restart drops them. Note: the documented `400 seconds required` exists in the code but is unreachable — the clamp turns any missing/invalid value into 1. @@ -688,7 +729,11 @@ paths: type: number minimum: 1 maximum: 3600 - example: { seconds: 90 } + deviceId: + type: string + pattern: '^[A-Za-z0-9_-]{8,64}$' + description: The browser's own token, see `POST /api/push/subscribe`. Optional. + example: { seconds: 90, deviceId: "3f9c1d2e7b0a4c6d9e8f1a2b3c4d5e6f" } responses: '200': description: Timer scheduled. @@ -702,7 +747,19 @@ paths: tags: [push] operationId: pushRestTimerCancel summary: Cancel the pending rest-timer push - description: Cancels the caller's scheduled rest-timer push, if any. Idempotent. + description: >- + Cancels the caller's scheduled rest-timer push, if any. With a `deviceId` only + that device's timer; without one, every pending timer of the account. Idempotent. + requestBody: + required: false + content: + application/json: + schema: + type: object + properties: + deviceId: + type: string + pattern: '^[A-Za-z0-9_-]{8,64}$' responses: '200': description: Cancelled (or nothing was pending). diff --git a/api/server.js b/api/server.js index 15b510d..d27fe82 100644 --- a/api/server.js +++ b/api/server.js @@ -185,8 +185,12 @@ function pushEndpointError(raw) { return null; } -async function sendPush(userId, payload) { - const subs = db.subs.filter(s => s.userId === userId); +// `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. +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 (!subs.length) return; const body = JSON.stringify(payload); let dirty = false; @@ -212,7 +216,11 @@ async function sendPush(userId, payload) { { urgency: 'high', timeout: PUSH_TIMEOUT_MS, agent: PUSH_AGENT }); } catch (e) { console.error('push send failed', userId, e.statusCode, e.body || e.message); - if (e.statusCode === 404 || e.statusCode === 410) { + // 404/410: the push service says the subscription is gone. 403: it refuses our VAPID + // signature — a subscription made against a key this instance no longer has (data/vapid.json + // regenerated). Neither will ever deliver again; keeping them only hides the fact from the + // Settings toggle, which reads the browser's side. The client re-subscribes on its next boot. + if (e.statusCode === 404 || e.statusCode === 410 || e.statusCode === 403) { db.subs = db.subs.filter(s => s.endpoint !== sub.endpoint); dirty = true; } } @@ -224,19 +232,30 @@ async function sendPush(userId, payload) { // 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, lang) { - const t = restTimers.get(userId); +// One timer per device, not per account: a phone resting in the gym and a desktop tab at home +// each carry their own, so the tab's on-screen completion (which cancels) cannot silence the +// phone's alert. A client that sends no device id gets the old account-wide behaviour. +// In memory only — an API restart drops whatever is pending. +const restTimers = new Map(); // `${userId}:${deviceId}` -> Timeout +const restKey = (userId, deviceId) => `${userId}:${deviceId || ''}`; +function scheduleRestTimer(userId, deviceId, sec, lang) { + const k = restKey(userId, deviceId); + const t = restTimers.get(k); if (t) clearTimeout(t); - restTimers.set(userId, setTimeout(() => { - restTimers.delete(userId); - sendPush(userId, restTimerPush(lang)); + restTimers.set(k, setTimeout(() => { + restTimers.delete(k); + sendPush(userId, restTimerPush(lang), deviceId); }, sec * 1000)); } -function cancelRestTimer(userId) { - const t = restTimers.get(userId); - if (t) { clearTimeout(t); restTimers.delete(userId); } +function cancelRestTimer(userId, deviceId) { + // no device id: an older client — clear everything the account has pending, as it always did + for (const [k, t] of restTimers) { + if (deviceId ? k === restKey(userId, deviceId) : k.startsWith(userId + ':')) { clearTimeout(t); restTimers.delete(k); } + } } +// A device id is what the browser made up for itself (lib/push.js): one short token per browser +// profile, nothing identifying. Anything else is treated as absent. +const deviceIdOf = v => (typeof v === 'string' && /^[A-Za-z0-9_-]{8,64}$/.test(v) ? v : undefined); // "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. @@ -263,6 +282,34 @@ function userNow(tz) { return { date, hhmm: `${g('hour')}:${g('minute')}`, weekday: new Date(date + 'T12:00:00Z').getUTCDay() }; } catch { return null; } // unknown/invalid tz string — skip this user rather than guess } +// The tick used to want the exact minute: `reminder.time === now.hhmm`, checked every 10 s. Any +// restart, redeploy or stalled event loop across that one minute lost the whole day's reminder — +// "sometimes it just doesn't come". A reminder that is due is now sent for up to this many +// minutes after its time, once per local date (`user.lastReminder`); later than that it is +// skipped rather than delivered at a time nobody asked for. +const REMINDER_WINDOW_MIN = 15; +// How often the tick looks. 10 s keeps a reminder within ~9 s of its minute; the tests shorten it. +const REMINDER_TICK_MS = Math.max(50, +(process.env.REMINDER_TICK_MS || 10000)); +const hhmmToMin = v => { + const m = /^(\d{2}):(\d{2})$/.exec(v || ''); + return m ? Number(m[1]) * 60 + Number(m[2]) : NaN; +}; +// Minutes since the reminder's time on the user's clock; negative before it, NaN when either +// side does not parse. Same-day only — a 23:55 reminder is not owed at 00:05 the next day. +const minutesLate = (time, now) => hhmmToMin(now.hhmm) - hhmmToMin(time); +// The tick reads every subscribed user's state file every 10 s. Most of those files do not +// change between ticks; a stat is far cheaper than a read and a parse of a state that can be +// megabytes, and it keeps the tick short — a slow tick was one more way to miss the minute. +const stateCache = new Map(); // uid -> { mtimeMs, size, S } +function readStateCached(uid) { + let st; + try { st = fs.statSync(stateFile(uid)); } catch { stateCache.delete(uid); return null; } + const hit = stateCache.get(uid); + if (hit && hit.mtimeMs === st.mtimeMs && hit.size === st.size) return hit.S; + const S = readState(uid); + stateCache.set(uid, { mtimeMs: st.mtimeMs, size: st.size, S }); + return S; +} setInterval(() => { for (const user of db.users) { if (!db.subs.some(s => s.userId === user.id)) continue; @@ -270,10 +317,12 @@ setInterval(() => { // skipped, not allowed to take the process — and everyone else's reminders — down with it. // PUT /api/data refuses the obvious shapes, but a file already on disk answers to nobody. try { - const S = readState(user.id); + const S = readStateCached(user.id); if (!S?.reminder?.on) continue; const now = userNow(S.reminder.tz || 'UTC'); - if (!now || S.reminder.time !== now.hhmm) continue; + if (!now) continue; + const late = minutesLate(S.reminder.time, now); + if (!(late >= 0 && late <= REMINDER_WINDOW_MIN)) continue; if (user.lastReminder === now.date) continue; if ((S.workouts || []).some(w => w.d === now.date)) continue; const rid = effectiveRoutineId(S, now.date); @@ -289,7 +338,7 @@ setInterval(() => { } // 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(); +}, REMINDER_TICK_MS).unref(); /* ---------- sessions (signed cookie) ---------- */ function sign(payload) { @@ -848,6 +897,11 @@ const routes = { // Only the two keys the push protocol needs are kept: `sub` is caller-supplied and would // otherwise put arbitrary fields into db.json, which every admin route reads back out. const keys = { p256dh: String(sub.keys.p256dh), auth: String(sub.keys.auth) }; + const deviceId = deviceIdOf(body.deviceId); + // An upsert: the client re-sends its subscription on every boot (lib/push.js) so a row this + // instance lost — pruned after a dead send, a rebuilt db.json — comes back without anyone + // touching Settings. The same endpoint sent again keeps its original `created`. + const prev = db.subs.find(s => s.endpoint === sub.endpoint); db.subs = db.subs.filter(s => s.endpoint !== sub.endpoint); // A browser holds one subscription per device, so this cap is far above real use. Without // it a single account could pile up endpoints without limit — every one of them a target @@ -857,11 +911,21 @@ const routes = { const drop = new Set(mine.slice(0, mine.length - MAX_SUBS_PER_USER + 1).map(s => s.endpoint)); db.subs = db.subs.filter(s => !drop.has(s.endpoint)); } - db.subs.push({ userId: user.id, endpoint: sub.endpoint, keys, created: new Date().toISOString() }); + db.subs.push({ userId: user.id, endpoint: sub.endpoint, keys, ...(deviceId ? { deviceId } : {}), created: prev?.created || new Date().toISOString() }); saveDb(); json(res, 200, { ok: true }); }, + // Whether this instance still holds the caller's subscription for `endpoint`. The browser's + // side (PushManager.getSubscription) says nothing about ours — a row pruned after a dead send + // leaves the browser subscribed to nowhere — so Settings asks here before it shows "on". + 'GET /api/push/status': async (req, res) => { + const user = readSession(req); + if (!user) return json(res, 401, { error: 'not signed in' }); + const endpoint = new URL(req.url, 'http://x').searchParams.get('endpoint') || ''; + json(res, 200, { subscribed: db.subs.some(s => s.userId === user.id && s.endpoint === endpoint) }); + }, + 'POST /api/push/unsubscribe': async (req, res) => { const user = readSession(req); if (!user) return json(res, 401, { error: 'not signed in' }); @@ -884,14 +948,15 @@ const routes = { 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, readState(user.id)?.lang); + scheduleRestTimer(user.id, deviceIdOf(body.deviceId), sec, readState(user.id)?.lang); 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); + const body = await readBody(req); + cancelRestTimer(user.id, deviceIdOf(body.deviceId)); json(res, 200, { ok: true }); }, diff --git a/api/test/server-push-status.test.js b/api/test/server-push-status.test.js new file mode 100644 index 0000000..459d4e8 --- /dev/null +++ b/api/test/server-push-status.test.js @@ -0,0 +1,110 @@ +/* The subscription's server side. The browser keeps its PushSubscription through anything that + happens here — a row pruned after a dead send, a rebuilt db.json — so the client re-sends it on + every boot (an upsert that keeps `created`), asks /api/push/status before Settings shows "on", + and tags it with a device id so a rest-timer alert goes to the device that started the rest. + 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'); + +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 other = { Cookie: `gymsid=${mintSession('u_test_2')}` }; +const keys = { p256dh: 'p', auth: 'a' }; + +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)); }); +}); + +async function startServer(t, subs = []) { + const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gym-pushstatus-')); + 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() }, { id: 'u_test_2', name: 'Two', created: new Date().toISOString() }], + 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' } + }); + const h = { api: `http://127.0.0.1:${port}`, 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 }); }); + 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; +} +const readDb = h => JSON.parse(fs.readFileSync(path.join(h.dataDir, 'db.json'), 'utf8')); +const post = (h, p, body, hdr = cookie) => fetch(`${h.api}${p}`, { method: 'POST', headers: hdr, body: JSON.stringify(body) }); +const status = (h, endpoint, hdr = cookie) => fetch(`${h.api}/api/push/status?endpoint=${encodeURIComponent(endpoint)}`, { headers: hdr }).then(r => r.json()); + +test('status tells whether the server holds the endpoint; subscribe is an upsert that keeps created and stores the device id', async t => { + const h = await startServer(t); + const endpoint = 'https://push.example/one'; + assert.deepEqual(await status(h, endpoint), { subscribed: false }); + + assert.equal((await post(h, '/api/push/subscribe', { subscription: { endpoint, keys }, deviceId: 'dev_aaaaaaaa' })).status, 200); + assert.deepEqual(await status(h, endpoint), { subscribed: true }); + assert.deepEqual(await status(h, endpoint, other), { subscribed: false }, 'another account does not see it'); + const first = readDb(h).subs[0]; + assert.equal(first.deviceId, 'dev_aaaaaaaa'); + + await new Promise(r => setTimeout(r, 20)); + assert.equal((await post(h, '/api/push/subscribe', { subscription: { endpoint, keys: { p256dh: 'p2', auth: 'a2' } }, deviceId: 'dev_bbbbbbbb' })).status, 200); + const subs = readDb(h).subs; + assert.equal(subs.length, 1, 'same endpoint sent again is one row'); + assert.equal(subs[0].created, first.created, 'created survives the re-send'); + assert.equal(subs[0].deviceId, 'dev_bbbbbbbb'); + assert.deepEqual(subs[0].keys, { p256dh: 'p2', auth: 'a2' }); + + // a device id that is not a short token is dropped, not stored + assert.equal((await post(h, '/api/push/subscribe', { subscription: { endpoint: 'https://push.example/two', keys }, deviceId: { evil: true } })).status, 200); + assert.equal('deviceId' in readDb(h).subs.find(s => s.endpoint.endsWith('/two')), false); + + assert.equal((await fetch(`${h.api}/api/push/status?endpoint=x`)).status, 401); +}); + +test('a rest timer belongs to the device that set it: another device cancelling does not silence it', async t => { + // localhost resolves to a loopback address, which PUSH_AGENT refuses — every send fails locally + // and quietly, and "push send failed" in the log is the proof that a send was attempted. + const mk = (deviceId, n) => ({ userId: 'u_test_1', endpoint: `https://localhost/${n}`, keys, deviceId, created: new Date().toISOString() }); + const h = await startServer(t, [mk('dev_phone000', 'phone'), mk('dev_desk0000', 'desk')]); + const sends = () => (h.log.match(/push send failed u_test_1/g) || []).length; + + assert.equal((await post(h, '/api/push/rest-timer', { seconds: 1, deviceId: 'dev_phone000' })).status, 200); + assert.equal((await post(h, '/api/push/rest-timer/cancel', { deviceId: 'dev_desk0000' })).status, 200); + await new Promise(r => setTimeout(r, 2500)); + assert.equal(sends(), 1, `the phone's alert went out, to the phone's subscription only:\n${h.log}`); + + assert.equal((await post(h, '/api/push/rest-timer', { seconds: 1, deviceId: 'dev_phone000' })).status, 200); + assert.equal((await post(h, '/api/push/rest-timer/cancel', { deviceId: 'dev_phone000' })).status, 200); + await new Promise(r => setTimeout(r, 2500)); + assert.equal(sends(), 1, 'cancelled by its own device: nothing more went out'); + + // an older client, no device id: the account-wide behaviour it always had + assert.equal((await post(h, '/api/push/rest-timer', { seconds: 1 })).status, 200); + assert.equal((await post(h, '/api/push/rest-timer/cancel', {})).status, 200); + await new Promise(r => setTimeout(r, 2500)); + assert.equal(sends(), 1, 'legacy cancel clears the legacy timer'); + assert.equal((await post(h, '/api/push/rest-timer', { seconds: 1 })).status, 200); + await new Promise(r => setTimeout(r, 2500)); + assert.equal(sends(), 3, 'a legacy timer goes to every subscription of the account'); +}); diff --git a/api/test/server-reminder.test.js b/api/test/server-reminder.test.js index 162dc66..f3689bc 100644 --- a/api/test/server-reminder.test.js +++ b/api/test/server-reminder.test.js @@ -42,7 +42,7 @@ async function startServer(t, subs = []) { 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' } + env: { ...process.env, PORT: String(port), DATA_DIR: dataDir, ORIGIN: 'http://localhost:8080', RP_ID: 'localhost', REMINDER_TICK_MS: '300' } }); const h = { api: `http://127.0.0.1:${port}`, dataDir, child, log: '' }; child.stdout.on('data', d => h.log += d); @@ -113,3 +113,53 @@ test('a non-array workouts on disk is logged and skipped by the reminder tick; t const db = JSON.parse(fs.readFileSync(path.join(h.dataDir, 'db.json'), 'utf8')); assert.ok(db.users.find(u => u.id === 'u_test_2').lastReminder, 'the good user\'s reminder was recorded'); }); + +/* The catch-up window. The tick used to want the exact minute — an API restart or a stalled + tick across those 60 s lost the whole day's reminder. A reminder is now owed for 15 minutes + after its time, once per local date, and not later than that. */ +const hhmmMinusMinutes = m => { + const d = new Date(Date.now() - m * 60000); + const parts = new Intl.DateTimeFormat('en-CA', { timeZone: 'UTC', hour12: false, hour: '2-digit', minute: '2-digit' }).formatToParts(d); + const g = type => parts.find(p => p.type === type)?.value; + return { hhmm: `${g('hour')}:${g('minute')}`, sameDay: d.getUTCDate() === new Date().getUTCDate() }; +}; +const goodState = (time, over = {}) => JSON.stringify({ + reminder: { on: true, time, tz: 'UTC' }, + routines: [{ id: 'r1', name: 'Full body', emoji: '💪', ex: [] }], + week: { 0: 'r1', 1: 'r1', 2: 'r1', 3: 'r1', 4: 'r1', 5: 'r1', 6: 'r1' }, + workouts: [], ...over +}); +const sub = { userId: 'u_test_1', endpoint: 'https://localhost/x', keys: { p256dh: 'p', auth: 'a' }, created: new Date().toISOString() }; +const firings = log => (log.match(/reminder firing u_test_1 r1/g) || []).length; +const wait = ms => new Promise(r => setTimeout(r, ms)); + +test('a reminder whose minute passed 3 minutes ago still fires — once', async t => { + const late = hhmmMinusMinutes(3); + if (!late.sameDay) return t.skip('just after midnight UTC — a same-day window cannot be set up'); + const h = await startServer(t, [sub]); + fs.writeFileSync(path.join(h.dataDir, 'state-u_test_1.json'), goodState(late.hhmm)); + const deadline = Date.now() + 30000; + while (Date.now() < deadline && !firings(h.log)) await wait(300); + assert.equal(firings(h.log), 1, h.log); + // several more ticks: the date-level dedupe holds inside the window + await wait(1500); + assert.equal(firings(h.log), 1, 'fired again inside the window'); + const db = JSON.parse(fs.readFileSync(path.join(h.dataDir, 'db.json'), 'utf8')); + assert.ok(db.users.find(u => u.id === 'u_test_1').lastReminder, 'the day is recorded'); +}); + +test('a reminder 20 minutes past is not delivered late, and a day already trained is skipped', async t => { + const stale = hhmmMinusMinutes(20); + const late = hhmmMinusMinutes(2); + if (!stale.sameDay || !late.sameDay) return t.skip('just after midnight UTC — a same-day window cannot be set up'); + const h = await startServer(t, [sub]); + const file = path.join(h.dataDir, 'state-u_test_1.json'); + fs.writeFileSync(file, goodState(stale.hhmm)); + await wait(1500); // several ticks + assert.equal(firings(h.log), 0, `20 minutes late must stay silent:\n${h.log}`); + // inside the window but today's workout is already logged + const today = new Intl.DateTimeFormat('en-CA', { timeZone: 'UTC', year: 'numeric', month: '2-digit', day: '2-digit' }).format(new Date()); + fs.writeFileSync(file, goodState(late.hhmm, { workouts: [{ id: 'w1', d: today }] })); + await wait(1500); + assert.equal(firings(h.log), 0, `a trained day must stay silent:\n${h.log}`); +}); diff --git a/frontend/public/sw.js b/frontend/public/sw.js index 522f013..7b21b72 100644 --- a/frontend/public/sw.js +++ b/frontend/public/sw.js @@ -8,15 +8,21 @@ self.addEventListener('activate', e => { Promise.all(keys.filter(k => k !== CACHE).map(k => caches.delete(k))) ).then(() => self.clients.claim())) }) +// Every push shows a notification, whatever the payload: a push that shows nothing counts +// against the site (Chrome revokes the subscription after a few), and a payload that fails to +// parse used to throw before waitUntil was ever reached — exactly such a silent push. 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 - })) + e.waitUntil((async () => { + let data = {} + try { data = e.data ? e.data.json() : {} } catch { data = { body: (() => { try { return e.data.text() } catch { return '' } })() } } + await 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() @@ -26,6 +32,31 @@ self.addEventListener('notificationclick', e => { })) }) +// The push service rotated the subscription (it does, unannounced, every few months on some +// platforms). Without this the server keeps sending to the old endpoint until it 410s, and the +// browser holds a new one nobody registered — "notifications just stopped". Re-subscribe with +// the same application server key and hand the new endpoint to the API; the session cookie +// travels with the same-origin fetch. Signed out, the API answers 401 and the next signed-in +// boot (lib/push.js syncPushSubscription) registers it instead. +const b64ToBytes = b64 => { + const padded = (b64 + '='.repeat((4 - b64.length % 4) % 4)).replace(/-/g, '+').replace(/_/g, '/') + return Uint8Array.from(atob(padded), c => c.charCodeAt(0)) +} +self.addEventListener('pushsubscriptionchange', e => { + e.waitUntil((async () => { + let key = e.oldSubscription?.options?.applicationServerKey + if (!key) { + const r = await fetch(new URL('api/push/public-key', self.registration.scope)) + key = b64ToBytes((await r.json()).key) + } + const sub = e.newSubscription || await self.registration.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: key }) + await fetch(new URL('api/push/subscribe', self.registration.scope), { + method: 'POST', headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ subscription: sub.toJSON() }) + }) + })().catch(() => {})) +}) + self.addEventListener('fetch', e => { const url = new URL(e.request.url) if (e.request.method !== 'GET' || url.origin !== location.origin) return diff --git a/frontend/src/App.jsx b/frontend/src/App.jsx index c387d4a..b6ba503 100644 --- a/frontend/src/App.jsx +++ b/frontend/src/App.jsx @@ -10,6 +10,8 @@ import { initBackButton } from './lib/back.js' import { useWakeLock } from './lib/wakelock.js' import { installViewportGuard } from './lib/viewport-guard.js' import { installChipDrag } from './lib/hchips.js' +import { syncPushSubscription } from './lib/push.js' +import { MOBILE } from './lib/mobile.js' import { startFlow } from './sheets.jsx' import Icon from './components/Icon.jsx' import TabBar from './components/TabBar.jsx' @@ -84,6 +86,13 @@ function Shell() { // Click-drag a horizontal chip strip to scroll it sideways (lib/hchips.js) — on a desktop // browser there's otherwise no way to reach the filters past the edge. useEffect(() => installChipDrag(), []) + // Once per signed-in boot, hand the server this browser's push subscription again (see + // lib/push.js): a subscription the instance lost is back before the next reminder is due, + // with nobody having to visit Settings. Web only — the APK has no service worker. + useEffect(() => { + if (MOBILE || !user || !ready) return + syncPushSubscription().catch(() => {}) + }, [user?.id, ready]) useEffect(() => { const onScroll = () => { // Modals pins the body while a sheet is open; scrollY is 0 then, not a position. diff --git a/frontend/src/lib/push.js b/frontend/src/lib/push.js index 4de1eba..8313518 100644 --- a/frontend/src/lib/push.js +++ b/frontend/src/lib/push.js @@ -2,7 +2,10 @@ // 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 +// main.jsx registers the service worker on https only, so on any other origin there is no +// worker and `navigator.serviceWorker.ready` never settles — the toggle looked usable and hung. +const secureOrigin = () => typeof location === 'undefined' || location.protocol === 'https:' +export const pushSupported = () => 'serviceWorker' in navigator && 'PushManager' in window && 'Notification' in window && secureOrigin() export const pushPermission = () => (pushSupported() ? Notification.permission : 'unsupported') const urlBase64ToUint8Array = b64 => { @@ -10,24 +13,78 @@ const urlBase64ToUint8Array = b64 => { const raw = atob(padded) return Uint8Array.from([...raw].map(c => c.charCodeAt(0))) } +const bytesToUrlBase64 = buf => btoa(String.fromCharCode(...new Uint8Array(buf))).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '') + +// One token per browser profile, made up here and never shown: it tells the server which of +// the account's subscriptions belong to this device, so a rest-timer alert goes to the phone +// that started the rest and not to every tab of the account. Nothing identifying in it. +const DEVICE_KEY = 'gym_device' +export function deviceId() { + try { + let id = localStorage.getItem(DEVICE_KEY) + if (!id) { + id = (crypto.randomUUID?.() || Array.from(crypto.getRandomValues(new Uint8Array(16)), b => b.toString(16).padStart(2, '0')).join('')).replace(/-/g, '') + localStorage.setItem(DEVICE_KEY, id) + } + return id + } catch { return undefined } +} + +// The worker is registered at boot; on https it is there within a moment, but a promise that +// never settles must not hang a settings screen or the boot path — give it a bounded wait. +const readyWorker = (ms = 8000) => Promise.race([ + navigator.serviceWorker.ready, + new Promise((_, reject) => setTimeout(() => reject(new Error('Service worker not ready')), ms)) +]) + +const register = sub => api('/api/push/subscribe', { method: 'POST', body: JSON.stringify({ subscription: sub.toJSON(), deviceId: deviceId() }) }) 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 reg = await readyWorker() 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() }) }) + await register(subscription) } export async function disablePush() { if (!pushSupported()) return - const reg = await navigator.serviceWorker.ready + const reg = await readyWorker() 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(() => {}) } +/* Brings the server's copy of this browser's subscription back in line with the browser's. + Called once per signed-in boot and when Settings opens. The browser keeps its subscription + through anything that happens on the server — a row pruned after a dead send, a rebuilt + db.json, a regenerated VAPID key — and the toggle used to read "on" from the browser's side + while nothing was ever going to arrive. Resolves to whether the server now holds it: + - no permission or no subscription here → false, nothing to do; + - the server already has this endpoint → true, no write; + - the server lost it → re-registered, true; + - the server's key changed → the old subscription is useless; unsubscribe, subscribe against + the new key, register, true. + Network failures propagate — the caller decides what "unknown" means for it. */ +export async function syncPushSubscription() { + if (!pushSupported() || Notification.permission !== 'granted') return false + const reg = await readyWorker() + let sub = await reg.pushManager.getSubscription() + if (!sub) return false + const { key } = await api('/api/push/public-key') + const mine = sub.options?.applicationServerKey + if (mine && key && bytesToUrlBase64(mine) !== key.replace(/=+$/, '')) { + await sub.unsubscribe().catch(() => {}) + sub = await reg.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: urlBase64ToUint8Array(key) }) + await register(sub) + return true + } + const { subscribed } = await api('/api/push/status?endpoint=' + encodeURIComponent(sub.endpoint)) + if (!subscribed) await register(sub) + return true +} + export const sendTestPush = () => api('/api/push/test', { method: 'POST', body: '{}' }) diff --git a/frontend/src/lib/push.test.js b/frontend/src/lib/push.test.js new file mode 100644 index 0000000..b4b7d71 --- /dev/null +++ b/frontend/src/lib/push.test.js @@ -0,0 +1,100 @@ +// @vitest-environment happy-dom +// @vitest-environment-options { "url": "https://gym.test/" } +import { describe, it, expect, vi, beforeEach } from 'vitest' + +const calls = [] +vi.mock('./api.js', () => ({ + api: vi.fn(async (path, opts) => { + calls.push([path, opts?.method || 'GET', opts?.body ? JSON.parse(opts.body) : null]) + if (path === '/api/push/public-key') return { key: KEY } + if (path.startsWith('/api/push/status')) return { subscribed: serverHas } + return { ok: true } + }) +})) + +const KEY = 'BPqx2m6xQ6pQK5hQtMz6d3kM2s7gq4yHqQvWzZ1sK1c' // any base64url string +const keyBytes = b64 => { + const padded = (b64 + '='.repeat((4 - b64.length % 4) % 4)).replace(/-/g, '+').replace(/_/g, '/') + return Uint8Array.from(atob(padded), c => c.charCodeAt(0)).buffer +} +let serverHas = true +let sub = null +const makeSub = key => ({ + endpoint: 'https://push.example/e1', options: { applicationServerKey: keyBytes(key) }, + toJSON: () => ({ endpoint: 'https://push.example/e1', keys: { p256dh: 'p', auth: 'a' } }), + unsubscribe: vi.fn(async () => { sub = null; return true }) +}) +const reg = { + pushManager: { + getSubscription: vi.fn(async () => sub), + subscribe: vi.fn(async ({ applicationServerKey }) => { sub = makeSub(KEY); sub.options.applicationServerKey = applicationServerKey; return sub }) + } +} + +beforeEach(() => { + calls.length = 0 + serverHas = true + sub = null + localStorage.clear() + Object.defineProperty(navigator, 'serviceWorker', { value: { ready: Promise.resolve(reg) }, configurable: true }) + globalThis.PushManager = function () {} + globalThis.Notification = { permission: 'granted', requestPermission: vi.fn(async () => 'granted') } +}) + +describe('deviceId', () => { + it('makes one token per browser and keeps it', async () => { + const { deviceId } = await import('./push.js') + const a = deviceId() + expect(a).toMatch(/^[A-Za-z0-9_-]{8,64}$/) + expect(deviceId()).toBe(a) + expect(localStorage.getItem('gym_device')).toBe(a) + }) +}) + +describe('syncPushSubscription', () => { + it('does nothing without permission or without a subscription', async () => { + const { syncPushSubscription } = await import('./push.js') + Notification.permission = 'default' + expect(await syncPushSubscription()).toBe(false) + Notification.permission = 'granted' + expect(await syncPushSubscription()).toBe(false) + expect(calls).toEqual([]) + }) + + it('asks the server and does not write when it already holds the endpoint', async () => { + const { syncPushSubscription } = await import('./push.js') + sub = makeSub(KEY) + expect(await syncPushSubscription()).toBe(true) + expect(calls.map(c => c[1] + ' ' + c[0].split('?')[0])).toEqual(['GET /api/push/public-key', 'GET /api/push/status']) + }) + + it('re-registers a subscription the server lost, with the device id', async () => { + const { syncPushSubscription, deviceId } = await import('./push.js') + sub = makeSub(KEY) + serverHas = false + expect(await syncPushSubscription()).toBe(true) + const post = calls.find(c => c[0] === '/api/push/subscribe') + expect(post[2]).toEqual({ subscription: { endpoint: 'https://push.example/e1', keys: { p256dh: 'p', auth: 'a' } }, deviceId: deviceId() }) + expect(reg.pushManager.subscribe).not.toHaveBeenCalled() + }) + + it('replaces a subscription made against a key the server no longer has', async () => { + const { syncPushSubscription } = await import('./push.js') + const old = makeSub('AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA') + sub = old + expect(await syncPushSubscription()).toBe(true) + expect(old.unsubscribe).toHaveBeenCalled() + expect(reg.pushManager.subscribe).toHaveBeenCalledTimes(1) + expect(new Uint8Array(reg.pushManager.subscribe.mock.calls[0][0].applicationServerKey)).toEqual(new Uint8Array(keyBytes(KEY))) + expect(calls.some(c => c[0] === '/api/push/subscribe')).toBe(true) + expect(calls.some(c => c[0].startsWith('/api/push/status'))).toBe(false) + }) +}) + +describe('pushSupported', () => { + it('needs the service worker, PushManager, Notification and an https origin', async () => { + const { pushSupported } = await import('./push.js') + expect(pushSupported()).toBe(true) + expect(location.protocol).toBe('https:') + }) +}) diff --git a/frontend/src/store/useUI.js b/frontend/src/store/useUI.js index 8841789..801314e 100644 --- a/frontend/src/store/useUI.js +++ b/frontend/src/store/useUI.js @@ -3,12 +3,15 @@ import { uid } from '../lib/format.js' import { beep, vibrate } from '../lib/sound.js' import { api } from '../lib/api.js' import { t } from '../lib/i18n.js' +import { deviceId } from '../lib/push.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(() => {}) } +// before the local timer completes. No-ops for guests / offline. The device id keeps the +// timer this browser's own: a desktop tab finishing its rest on screen used to cancel the +// alert the phone in the gym was waiting for, because the server held one timer per account. +const pushRestTimer = sec => { if (useStore.getState().user) api('/api/push/rest-timer', { method: 'POST', body: JSON.stringify({ seconds: sec, deviceId: deviceId() }) }).catch(() => {}) } +const cancelPushRestTimer = () => { if (useStore.getState().user) api('/api/push/rest-timer/cancel', { method: 'POST', body: JSON.stringify({ deviceId: deviceId() }) }).catch(() => {}) } const notificationsSupported = () => typeof window !== 'undefined' && 'Notification' in window let requestRestNotificationPermissionP = null diff --git a/frontend/src/views/Settings.jsx b/frontend/src/views/Settings.jsx index c4e7688..83d3d7e 100644 --- a/frontend/src/views/Settings.jsx +++ b/frontend/src/views/Settings.jsx @@ -7,7 +7,7 @@ import { useUI } from '../store/useUI.js' import { ACCENTS, todayISO, localTZ, weekStartOf, MONDAY, SUNDAY } from '../lib/format.js' import { effortOf } from '../lib/history.js' import { api, webauthnOK, passkeyLogin, passkeyRegister, IS_ANDROID } from '../lib/api.js' -import { pushSupported, enablePush, disablePush, sendTestPush } from '../lib/push.js' +import { pushSupported, enablePush, disablePush, sendTestPush, syncPushSubscription } from '../lib/push.js' import { wakeLockSupported } from '../lib/wakelock.js' import { t, LANGS, INSTR_LANGS } from '../lib/i18n.js' import { DEMO, REPO } from '../lib/demo.js' @@ -544,9 +544,17 @@ function PushCard({ S, update, toast }) { const [busy, setBusy] = useState(false) const supported = pushSupported() + // "On" means the server holds this browser's subscription, not merely that the browser has + // one: a row the instance dropped (dead send, rebuilt db.json) left the switch on with nothing + // ever arriving. syncPushSubscription re-registers on the way; if the server cannot be asked + // (offline), the browser's side is the best answer available. useEffect(() => { if (!supported) return - navigator.serviceWorker.ready.then(reg => reg.pushManager.getSubscription()).then(sub => setOn(!!sub)).catch(() => {}) + let gone = false + syncPushSubscription() + .then(ok => { if (!gone) setOn(ok) }) + .catch(() => navigator.serviceWorker.ready.then(reg => reg.pushManager.getSubscription()).then(sub => { if (!gone) setOn(!!sub) }).catch(() => {})) + return () => { gone = true } }, [supported]) const toggle = async v => {