Skip to content

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.

fix(push): "rest over" rings only the device that rested

Boris 'B' Kurktchieva907ba42f006
diff --git a/api/openapi.yaml b/api/openapi.yaml
index abb279e45..b51e9f990 100644
--- a/api/openapi.yaml
+++ b/api/openapi.yaml
@@ -1809,7 +1809,8 @@ paths:
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.
+ rest. Optional; anything that is not a short token is ignored, and a
+ re-send of an endpoint without one keeps the id its row already has.
responses:
'200':
description: Stored.
@@ -1836,7 +1837,11 @@ paths:
`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.
+ notifications switch as on, and re-registers when the answer is no. A stored
+ subscription also names the `deviceId` it is stored with, and the client
+ re-registers when that is not its own: a row stored without one (from before
+ device ids) sends that device's rest-timer alerts to every subscription of the
+ account.
parameters:
- in: query
name: endpoint
@@ -1849,8 +1854,18 @@ paths:
application/json:
schema:
type: object
+ required: [subscribed]
properties:
subscribed: { type: boolean }
+ deviceId:
+ type: ['string', 'null']
+ description: >-
+ Present when `subscribed` is true: the device id the subscription is
+ stored with, `null` when it has none.
+ examples:
+ stored: { value: { subscribed: true, deviceId: "3f9c1d2e7b0a4c6d9e8f1a2b3c4d5e6f" } }
+ storedWithoutDevice: { value: { subscribed: true, deviceId: null } }
+ notStored: { value: { subscribed: false } }
'401': { $ref: '#/components/responses/Unauthorized' }
/api/push/unsubscribe:
diff --git a/api/server.js b/api/server.js
index debdd4840..e3c3126f5 100644
--- a/api/server.js
+++ b/api/server.js
@@ -2090,6 +2090,9 @@ const routes = {
// 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);
+ // No usable id in the request (none, or not a short token) leaves the id the row already
+ // has: the request is a re-send, not a request to forget which device the row is.
+ const storedDevice = deviceId || prev?.deviceId;
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
@@ -2099,7 +2102,7 @@ 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, ...(deviceId ? { deviceId } : {}), created: prev?.created || new Date().toISOString() });
+ db.subs.push({ userId: user.id, endpoint: sub.endpoint, keys, ...(storedDevice ? { deviceId: storedDevice } : {}), created: prev?.created || new Date().toISOString() });
saveDb();
json(res, 200, { ok: true });
},
@@ -2107,11 +2110,16 @@ const routes = {
// 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".
+ // A stored row also says which device it is filed under, `null` for none: a row from before
+ // device ids, or one the worker re-sent without its id, sends that device's rest-timer alert
+ // to every device of the account (sendPush), and the client re-sends its subscription with its
+ // id when this is not its own.
'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) });
+ const row = db.subs.find(s => s.userId === user.id && s.endpoint === endpoint);
+ json(res, 200, row ? { subscribed: true, deviceId: row.deviceId || null } : { subscribed: false });
},
'POST /api/push/unsubscribe': async (req, res) => {
diff --git a/api/test/server-push-status.test.js b/api/test/server-push-status.test.js
index ce6c7d58e..ef6b45ef6 100644
--- a/api/test/server-push-status.test.js
+++ b/api/test/server-push-status.test.js
@@ -55,7 +55,7 @@ test('status tells whether the server holds the endpoint; subscribe is an upsert
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), { subscribed: true, deviceId: 'dev_aaaaaaaa' });
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');
@@ -75,6 +75,63 @@ test('status tells whether the server holds the endpoint; subscribe is an upsert
assert.equal((await fetch(`${h.api}/api/push/status?endpoint=x`)).status, 401);
});
+// Rows from before device ids, or re-sent by the worker without one, used to stay that way:
+// the boot sync saw the endpoint stored and wrote nothing. Status now names the row's device, so
+// the owner's browser re-sends the same subscription with its id and the row is repaired in place.
+test('a row stored without a device id: status says so, and the owner re-sending it gives it one', async t => {
+ const endpoint = 'https://push.example/legacy';
+ const browserKeys = { p256dh: 'p-legacy', auth: 'a-legacy' };
+ const created = '2025-01-01T00:00:00.000Z';
+ const h = await startServer(t, [{ userId: 'u_test_1', endpoint, keys: browserKeys, created }]);
+
+ assert.deepEqual(await status(h, endpoint), { subscribed: true, deviceId: null });
+ assert.deepEqual(await status(h, endpoint, other), { subscribed: false }, 'another account does not see it');
+
+ assert.equal((await post(h, '/api/push/subscribe', { subscription: { endpoint, keys: browserKeys }, deviceId: 'dev_phone000' })).status, 200);
+ assert.deepEqual(await status(h, endpoint), { subscribed: true, deviceId: 'dev_phone000' });
+ assert.deepEqual(readDb(h).subs, [{ userId: 'u_test_1', endpoint, keys: browserKeys, deviceId: 'dev_phone000', created }],
+ 'one row, the same account, the same keys, its original created, and now a device id');
+});
+
+// A re-send with no usable device id used to store the row without one, so a single request with
+// a malformed id (or none) made the owner's phone lose its own rest-timer routing. deviceIdOf
+// ignores such an id everywhere else (200, not 400), and ignoring it here means keeping the one
+// the row already has.
+test('a re-send without a usable device id keeps the id the row has', async t => {
+ const endpoint = 'https://push.example/kept';
+ const browserKeys = { p256dh: 'p-kept', auth: 'a-kept' };
+ const created = '2025-03-03T00:00:00.000Z';
+ const h = await startServer(t, [{ userId: 'u_test_1', endpoint, keys: browserKeys, deviceId: 'dev_phone000', created }]);
+
+ for (const deviceId of ['bad!', { evil: true }, undefined]) {
+ const r = await post(h, '/api/push/subscribe', { subscription: { endpoint, keys: browserKeys }, deviceId });
+ assert.equal(r.status, 200, `deviceId ${JSON.stringify(deviceId)}`);
+ assert.deepEqual(await r.json(), { ok: true });
+ assert.deepEqual(readDb(h).subs, [{ userId: 'u_test_1', endpoint, keys: browserKeys, deviceId: 'dev_phone000', created }],
+ `deviceId ${JSON.stringify(deviceId)} leaves the row as it was`);
+ }
+ // a usable one still replaces it
+ assert.equal((await post(h, '/api/push/subscribe', { subscription: { endpoint, keys: browserKeys }, deviceId: 'dev_phone001' })).status, 200);
+ 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 => {
+ // 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() };
+ const h = await startServer(t, [phone, desk]);
+ const sent = () => (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);
+ 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((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}`);
+});
+
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.
diff --git a/frontend/public/sw.js b/frontend/public/sw.js
index 1e9afa156..a404f13cb 100644
--- a/frontend/public/sw.js
+++ b/frontend/public/sw.js
@@ -5,6 +5,11 @@
every deploy is a new worker with its own cache and the previous build's files are dropped on
activate; the media cache (`MEDIA`) is kept across builds. */
const CACHE = 'opengym-rt-__BUILD__'
+// Where the page leaves this browser's push device id (lib/push.js shareDeviceId) for the
+// pushsubscriptionchange handler below, which has no localStorage to read it from. Not a build
+// cache, so activate's sweep leaves it alone.
+const DEVICE_CACHE = 'opengym-device'
+const DEVICE_URL = '/opengym-device-id'
/* Exercise media (img/, gif/) lives in a cache of its own that outlives builds (#281). It used to
share the build's cache, so every update swept every animation along with the old bundle, and
@@ -79,7 +84,9 @@ self.addEventListener('activate', e => {
// next load with a network.
const c = await caches.open(CACHE)
if (await c.match('index.html')) {
- const old = (await caches.keys()).filter(k => k !== CACHE && k !== MEDIA)
+ // DEVICE_CACHE holds this browser's device id (the push re-register below needs it): not a
+ // build, so an update never sweeps it.
+ const old = (await caches.keys()).filter(k => k !== CACHE && k !== MEDIA && k !== DEVICE_CACHE)
// A build from before MEDIA existed kept its media in its own cache: move it across first,
// so the first update to this worker does not cost what the device already had offline.
await Promise.all(old.map(k => adoptMedia(k).catch(() => {})))
@@ -179,14 +186,17 @@ self.addEventListener('notificationclick', e => {
}))
})
// The push service rotated the subscription (key change, expiry): subscribe again with the same
-// server key and tell the server, so the row it holds keeps pointing at this browser.
+// server key and tell the server, so the row it holds keeps pointing at this browser. With the
+// device id the page registers with: without one, this browser's rest-timer alert goes to every
+// device of the account until the page's next boot sync sees the missing id and sends it again.
self.addEventListener('pushsubscriptionchange', e => {
e.waitUntil((async () => {
const old = e.oldSubscription || (await self.registration.pushManager.getSubscription())
const key = e.newSubscription?.options?.applicationServerKey || old?.options?.applicationServerKey
if (!key) return
const sub = e.newSubscription || await self.registration.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: key })
- await fetch('api/push/subscribe', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ subscription: sub.toJSON() }) }).catch(() => {})
+ const deviceId = await caches.open(DEVICE_CACHE).then(c => c.match(DEVICE_URL)).then(r => r ? r.text() : undefined).catch(() => undefined)
+ await fetch('api/push/subscribe', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ subscription: sub.toJSON(), deviceId }) }).catch(() => {})
})())
})
diff --git a/frontend/src/lib/push.js b/frontend/src/lib/push.js
index 83135185e..78ee08432 100644
--- a/frontend/src/lib/push.js
+++ b/frontend/src/lib/push.js
@@ -19,10 +19,15 @@ const bytesToUrlBase64 = buf => btoa(String.fromCharCode(...new Uint8Array(buf))
// 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'
+// The shape the server keeps, mirrored from deviceIdOf in api/server.js: anything else it treats
+// as no id at all. A stored value outside it (set by hand, or left by some other build) went out
+// as it was, so the row kept no id, the boot sync saw that and sent it again, on every boot, and
+// the rest timer's alert went to every device. Such a value is replaced like a missing one.
+const DEVICE_ID_RULE = /^[A-Za-z0-9_-]{8,64}$/
export function deviceId() {
try {
let id = localStorage.getItem(DEVICE_KEY)
- if (!id) {
+ if (!id || !DEVICE_ID_RULE.test(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)
}
@@ -30,6 +35,19 @@ export function deviceId() {
} catch { return undefined }
}
+// The worker re-registers a subscription the push service rotated (public/sw.js,
+// pushsubscriptionchange), usually with no page open, and it cannot read localStorage. It finds
+// the device id here instead, in a cache of its own that its activate sweep leaves alone. Left
+// every time this browser holds a subscription the server should have, so a browser subscribed
+// before the worker looked for it has it by its next boot.
+const DEVICE_CACHE = 'opengym-device'
+const DEVICE_URL = '/opengym-device-id'
+async function shareDeviceId() {
+ const id = deviceId()
+ if (!id) return
+ try { await (await caches.open(DEVICE_CACHE)).put(DEVICE_URL, new Response(id)) } catch { /* no Cache API: the worker sends none, as before */ }
+}
+
// 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([
@@ -46,6 +64,7 @@ export async function enablePush() {
const reg = await readyWorker()
const { key } = await api('/api/push/public-key')
const subscription = await reg.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: urlBase64ToUint8Array(key) })
+ await shareDeviceId()
await register(subscription)
}
@@ -64,7 +83,8 @@ export async function disablePush() {
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 already has this endpoint under this browser's device id → true, no write;
+ - the server has it under no device id or another one → sent again with this one, true;
- 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.
@@ -74,6 +94,7 @@ export async function syncPushSubscription() {
const reg = await readyWorker()
let sub = await reg.pushManager.getSubscription()
if (!sub) return false
+ await shareDeviceId()
const { key } = await api('/api/push/public-key')
const mine = sub.options?.applicationServerKey
if (mine && key && bytesToUrlBase64(mine) !== key.replace(/=+$/, '')) {
@@ -82,8 +103,16 @@ export async function syncPushSubscription() {
await register(sub)
return true
}
- const { subscribed } = await api('/api/push/status?endpoint=' + encodeURIComponent(sub.endpoint))
- if (!subscribed) await register(sub)
+ // A row the server stores under no device id, or another one, is sent again with this
+ // browser's: the same endpoint and keys, and the server's upsert keeps the row's created date.
+ // Without the id the server cannot tell this browser's rest-timer alert from the account's, and
+ // sends it to every device. Such rows come from before device ids, or from the worker re-sending
+ // a rotated subscription with no id to hand, and the check used to stop at "subscribed". An api
+ // from before this answer sends no deviceId at all (not null): it cannot say, and a re-send it
+ // never reports back would be a db.json write on every boot.
+ const { subscribed, deviceId: storedAs } = await api('/api/push/status?endpoint=' + encodeURIComponent(sub.endpoint))
+ const id = deviceId()
+ if (!subscribed || (id && storedAs !== undefined && storedAs !== id)) await register(sub)
return true
}
diff --git a/frontend/src/lib/push.test.js b/frontend/src/lib/push.test.js
index b4b7d71f3..f8e06eebc 100644
--- a/frontend/src/lib/push.test.js
+++ b/frontend/src/lib/push.test.js
@@ -1,13 +1,13 @@
// @vitest-environment happy-dom
// @vitest-environment-options { "url": "https://gym.test/" }
-import { describe, it, expect, vi, beforeEach } from 'vitest'
+import { describe, it, expect, vi, beforeEach, afterEach } 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 }
+ if (path.startsWith('/api/push/status')) return serverHas ? { subscribed: true, deviceId: serverDevice === MINE ? localStorage.getItem('gym_device') : serverDevice } : { subscribed: false }
return { ok: true }
})
}))
@@ -18,6 +18,9 @@ const keyBytes = b64 => {
return Uint8Array.from(atob(padded), c => c.charCodeAt(0)).buffer
}
let serverHas = true
+// The device id the server's row carries when it holds the endpoint; MINE is this browser's own.
+const MINE = Symbol('this browser')
+let serverDevice = MINE
let sub = null
const makeSub = key => ({
endpoint: 'https://push.example/e1', options: { applicationServerKey: keyBytes(key) },
@@ -31,9 +34,14 @@ const reg = {
}
}
+// The endpoints this run sent to POST /api/push/subscribe, in order.
+const posts = () => calls.filter(c => c[0] === '/api/push/subscribe').map(c => c[2].subscription.endpoint)
+
beforeEach(() => {
calls.length = 0
+ reg.pushManager.subscribe.mockClear()
serverHas = true
+ serverDevice = MINE
sub = null
localStorage.clear()
Object.defineProperty(navigator, 'serviceWorker', { value: { ready: Promise.resolve(reg) }, configurable: true })
@@ -49,6 +57,60 @@ describe('deviceId', () => {
expect(deviceId()).toBe(a)
expect(localStorage.getItem('gym_device')).toBe(a)
})
+
+ it('keeps a stored id of the shape the server accepts', async () => {
+ const { deviceId } = await import('./push.js')
+ localStorage.setItem('gym_device', 'dev_aaaaaaaa')
+ expect(deviceId()).toBe('dev_aaaaaaaa')
+ })
+})
+
+// A server that applies the writes the way api/server.js does: the endpoint is stored from the
+// first POST on, under the device id sent if it has the shape deviceIdOf accepts, and under none
+// otherwise. Whatever state a boot starts from, the second boot must find nothing to write.
+describe('against a server that applies the writes, the second boot writes nothing', () => {
+ const serverKeeps = v => (typeof v === 'string' && /^[A-Za-z0-9_-]{8,64}$/.test(v) ? v : null)
+ const bootTwice = async () => {
+ const { syncPushSubscription } = await import('./push.js')
+ const { api } = await import('./api.js')
+ const real = api.getMockImplementation()
+ api.mockImplementation(async (path, opts) => {
+ const answer = await real(path, opts)
+ if (path === '/api/push/subscribe') { serverHas = true; serverDevice = serverKeeps(JSON.parse(opts.body).deviceId) }
+ return answer
+ })
+ try {
+ expect(await syncPushSubscription()).toBe(true)
+ const first = posts().length
+ expect(await syncPushSubscription()).toBe(true)
+ return [first, posts().length - first]
+ } finally { api.mockImplementation(real) }
+ }
+
+ it.each([
+ ['stored under no id', () => { serverDevice = null }],
+ ['stored under another id', () => { serverDevice = 'someoneelse01' }],
+ ['not stored', () => { serverHas = false }]
+ ])('%s: one write, then none', async (_, seed) => {
+ sub = makeSub(KEY)
+ seed()
+ expect(await bootTwice()).toEqual([1, 0])
+ })
+
+ // A hand-set id the server refuses was sent as it was, the row kept no id, and every boot sent
+ // it again. It is replaced by one the server keeps, once, and that one is kept after.
+ it.each([['bad!'], ['short77'], ['a'.repeat(65)], ['abc.defghijk']])('a stored id the server refuses (%s) is replaced once, and the sync settles', async stored => {
+ const { deviceId } = await import('./push.js')
+ localStorage.setItem('gym_device', stored)
+ sub = makeSub(KEY)
+ serverDevice = null
+ expect(await bootTwice()).toEqual([1, 0])
+ const id = localStorage.getItem('gym_device')
+ expect(id).not.toBe(stored)
+ expect(serverKeeps(id)).toBe(id)
+ expect(calls.find(c => c[0] === '/api/push/subscribe')[2].deviceId).toBe(id)
+ expect(deviceId()).toBe(id)
+ })
})
describe('syncPushSubscription', () => {
@@ -61,13 +123,59 @@ describe('syncPushSubscription', () => {
expect(calls).toEqual([])
})
- it('asks the server and does not write when it already holds the endpoint', async () => {
+ it('asks the server and does not write when it already holds the endpoint under this browser\'s device id', 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'])
})
+ // A row from before device ids (or one the worker re-sent without its id) read as stored, so it
+ // was never written again: the server could not tell this browser's rest-timer alert from the
+ // account's and sent it to every device.
+ it('sends the same subscription again, with the device id, when the server holds it under none', async () => {
+ const { syncPushSubscription, deviceId } = await import('./push.js')
+ sub = makeSub(KEY)
+ serverDevice = null
+ 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', 'POST /api/push/subscribe'])
+ expect(calls.at(-1)[2]).toEqual({ subscription: { endpoint: 'https://push.example/e1', keys: { p256dh: 'p', auth: 'a' } }, deviceId: deviceId() })
+ expect(reg.pushManager.subscribe).not.toHaveBeenCalled()
+ expect(sub.unsubscribe).not.toHaveBeenCalled()
+ })
+
+ it('and when the server holds it under another device id', async () => {
+ const { syncPushSubscription, deviceId } = await import('./push.js')
+ sub = makeSub(KEY)
+ serverDevice = 'someoneelse01'
+ expect(await syncPushSubscription()).toBe(true)
+ expect(posts()).toEqual(['https://push.example/e1'])
+ expect(calls.at(-1)[2].deviceId).toBe(deviceId())
+ expect(reg.pushManager.subscribe).not.toHaveBeenCalled()
+ })
+
+ it('does not write when an older api answers without a device id at all', async () => {
+ const { syncPushSubscription } = await import('./push.js')
+ sub = makeSub(KEY)
+ serverDevice = undefined
+ expect(await syncPushSubscription()).toBe(true)
+ expect(posts()).toEqual([])
+ })
+
+ it('does not write where this browser has no device id to give (storage refused)', async () => {
+ const { syncPushSubscription } = await import('./push.js')
+ sub = makeSub(KEY)
+ serverDevice = null
+ const real = Object.getOwnPropertyDescriptor(window, 'localStorage')
+ Object.defineProperty(window, 'localStorage', { configurable: true, get() { throw new Error('The operation is insecure.') } })
+ try {
+ expect(await syncPushSubscription()).toBe(true)
+ } finally {
+ Object.defineProperty(window, 'localStorage', real)
+ }
+ expect(posts()).toEqual([])
+ })
+
it('re-registers a subscription the server lost, with the device id', async () => {
const { syncPushSubscription, deviceId } = await import('./push.js')
sub = makeSub(KEY)
@@ -91,6 +199,44 @@ describe('syncPushSubscription', () => {
})
})
+// The worker re-registers a subscription the push service rotated, with no page open and no
+// localStorage to read the device id from, so the page leaves the id in a cache the worker reads
+// (public/sw.js, pushsubscriptionchange). Without it the row the worker sent lost its device id.
+describe('the device id the worker re-registers with', () => {
+ let stored
+ const fakeCaches = { open: vi.fn(async name => ({ put: async (url, res) => { stored.push([name, String(url), await res.text()]) } })) }
+ beforeEach(() => { stored = []; globalThis.caches = fakeCaches })
+ afterEach(() => { delete globalThis.caches })
+
+ it('is left for the worker when the browser holds a subscription at boot', async () => {
+ const { syncPushSubscription, deviceId } = await import('./push.js')
+ sub = makeSub(KEY)
+ expect(await syncPushSubscription()).toBe(true)
+ expect(stored).toEqual([['opengym-device', '/opengym-device-id', deviceId()]])
+ })
+
+ it('and when the switch is turned on', async () => {
+ const { enablePush, deviceId } = await import('./push.js')
+ await enablePush()
+ expect(stored).toEqual([['opengym-device', '/opengym-device-id', deviceId()]])
+ })
+
+ it('is not left where the browser holds no subscription', async () => {
+ const { syncPushSubscription } = await import('./push.js')
+ expect(await syncPushSubscription()).toBe(false)
+ expect(stored).toEqual([])
+ })
+
+ it('a Cache API that refuses (private mode) changes nothing else', async () => {
+ const { syncPushSubscription } = await import('./push.js')
+ globalThis.caches = { open: async () => { throw new DOMException('denied', 'SecurityError') } }
+ sub = makeSub(KEY)
+ serverHas = false
+ expect(await syncPushSubscription()).toBe(true)
+ expect(calls.filter(c => c[0] === '/api/push/subscribe')).toHaveLength(1)
+ })
+})
+
describe('pushSupported', () => {
it('needs the service worker, PushManager, Notification and an https origin', async () => {
const { pushSupported } = await import('./push.js')
diff --git a/frontend/src/lib/sw.test.js b/frontend/src/lib/sw.test.js
index 4af538343..c0185b995 100644
--- a/frontend/src/lib/sw.test.js
+++ b/frontend/src/lib/sw.test.js
@@ -4,6 +4,7 @@
* without having a working one to put there: its cache is what a home-screen app reopened
* without a network comes back from. So an install that did not get the shell fails, and the
* previous build's cache is swept only once this build's shell is in its own. */
+import { readFileSync } from 'node:fs'
import { beforeEach, describe, expect, it } from 'vitest'
class FakeCache {
@@ -159,3 +160,64 @@ describe('sw.js install and activate', () => {
expect((await globalThis.caches.open(CACHE)).keys()).toContain('index.html')
})
})
+
+// The push service rotates a subscription (expiry, a key change) and the worker re-registers it,
+// usually with no page open. It sent no device id, so the server's row lost it and the rest-timer
+// alert for that account went to every device until a page next booted. The page leaves the id
+// in a cache the worker can read (lib/push.js shareDeviceId).
+describe('sw.js re-registers a rotated push subscription with the page\'s device id', () => {
+ const rotated = {
+ endpoint: 'https://push.example/e2',
+ options: { applicationServerKey: new Uint8Array([1, 2, 3]).buffer },
+ toJSON: () => ({ endpoint: 'https://push.example/e2', keys: { p256dh: 'p2', auth: 'a2' } })
+ }
+ const rotate = async () => {
+ const sent = []
+ globalThis.fetch = async (url, init) => { sent.push([String(url), JSON.parse(init.body)]); return { ok: true, status: 200 } }
+ await fire('pushsubscriptionchange', { oldSubscription: { endpoint: 'https://push.example/e1', options: rotated.options }, newSubscription: rotated })
+ return sent
+ }
+ // The same cache name and key on both sides, read out of the two files, so the page and the
+ // worker cannot drift apart without this failing.
+ const constant = (src, name) => src.match(new RegExp('const ' + name + " = '([^']+)'"))?.[1]
+ const pageSrc = readFileSync(new URL('./push.js', import.meta.url), 'utf8')
+ const swSrc = readFileSync(new URL('../../public/sw.js', import.meta.url), 'utf8')
+ const DEVICE_CACHE = constant(pageSrc, 'DEVICE_CACHE')
+ const DEVICE_URL = constant(pageSrc, 'DEVICE_URL')
+
+ it('the page and the worker look in the same place', () => {
+ expect(DEVICE_CACHE).toBeTruthy()
+ expect(DEVICE_URL).toBeTruthy()
+ expect(constant(swSrc, 'DEVICE_CACHE')).toBe(DEVICE_CACHE)
+ expect(constant(swSrc, 'DEVICE_URL')).toBe(DEVICE_URL)
+ })
+
+ it('sends the device id the page left', async () => {
+ await loadSW()
+ await (await globalThis.caches.open(DEVICE_CACHE)).put(DEVICE_URL, new Response('dev1234abcd'))
+ expect(await rotate()).toEqual([['api/push/subscribe', {
+ subscription: { endpoint: 'https://push.example/e2', keys: { p256dh: 'p2', auth: 'a2' } },
+ deviceId: 'dev1234abcd'
+ }]])
+ })
+
+ it('with nothing left there, sends the subscription alone, as before', async () => {
+ await loadSW()
+ const sent = await rotate()
+ expect(sent).toHaveLength(1)
+ expect(sent[0][1]).toEqual({ subscription: { endpoint: 'https://push.example/e2', keys: { p256dh: 'p2', auth: 'a2' } } })
+ })
+
+ it('a new build\'s activate sweeps the old build\'s cache and keeps the device id', async () => {
+ await loadSW()
+ await previousBuild()
+ await (await globalThis.caches.open(DEVICE_CACHE)).put(DEVICE_URL, new Response('dev1234abcd'))
+ globalThis.fetch = async u => (String(u) === 'index.html'
+ ? { ok: true, status: 200, redirected: false, text: async () => shellHtml }
+ : { ok: true, status: 200, clone: () => ({}) })
+ await fire('install')
+ await fire('activate')
+ expect((await globalThis.caches.keys()).sort()).toEqual([CACHE, DEVICE_CACHE].sort())
+ expect(await (await (await globalThis.caches.open(DEVICE_CACHE)).match(DEVICE_URL)).text()).toBe('dev1234abcd')
+ })
+})
diff --git a/website/api.html b/website/api.html
index 9a2713946..9c31b2207 100644
--- a/website/api.html
+++ b/website/api.html
@@ -1597,7 +1597,7 @@ main.api-main .lead { color: var(--fg-2); max-width: 58ch; margin: 14px 0 0; fon
<div class="prow">
<span class="p-name">deviceId</span>
<span class="p-type">string</span>
- <span class="p-desc">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.</span>
+ <span class="p-desc">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, and a re-send of an endpoint without one keeps the id its row already has.</span>
</div>
</div>
<p class="ep-h">Responses</p>
@@ -1626,7 +1626,7 @@ main.api-main .lead { color: var(--fg-2); max-width: 58ch; margin: 14px 0 0; fon
<span class="ep-sum">Does the server hold this subscription?</span>
</summary>
<div class="ep-body">
-<p>Whether the caller's account has a stored subscription with exactly this <code>endpoint</code>. The browser's <code>PushManager.getSubscription()</code> 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.</p>
+<p>Whether the caller's account has a stored subscription with exactly this <code>endpoint</code>. The browser's <code>PushManager.getSubscription()</code> 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. A stored subscription also names the <code>deviceId</code> it is stored with, and the client re-registers when that is not its own: a row stored without one (from before device ids) sends that device's rest-timer alerts to every subscription of the account.</p>
<p class="ep-auth"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="4" y="11" width="16" height="10" rx="2.5"/><path d="M8 11V7a4 4 0 0 1 8 0v4"/></svg><span>Requires a session — the cookie set at sign-in, or <code>Authorization: Bearer &lt;token&gt;</code> from mobile-app pairing.</span></p>
<p class="ep-h">Query parameters</p><div class="ptab">
<div class="prow">
@@ -1640,7 +1640,7 @@ main.api-main .lead { color: var(--fg-2); max-width: 58ch; margin: 14px 0 0; fon
<div class="ptab">
<div class="prow rrow">
<span class="r-code s2">200</span>
- <span class="p-desc">The answer.<span class="r-sig">{ subscribed: boolean }</span></span>
+ <span class="p-desc">The answer.<span class="r-sig">{ subscribed: boolean, deviceId: string | null }</span></span>
</div>
<div class="prow rrow">
<span class="r-code s4">401</span>