Push: reminders owed within 15 minutes still arrive, the subscription heals itself on every boot, rest-timer alerts belong to the device that started the rest
- reminder tick: a due reminder is sent for up to 15 minutes after its time (once per local date) instead of only on the exact minute — a restart across that minute used to lose the day; state files are stat'ed and re-read only when they changed - sendPush prunes 403 (stale VAPID key) like 404/410; optional device targeting - POST /api/push/subscribe is an upsert that keeps created and stores a deviceId; GET /api/push/status says whether the server holds an endpoint - rest timers keyed per user+device; cancel without a device id keeps the old account-wide behaviour - sw.js: payload parsed inside waitUntil (never a silent push), pushsubscriptionchange re-subscribes and registers the new endpoint - lib/push.js: syncPushSubscription() (called once per signed-in boot from App.jsx and when Settings opens) re-registers a lost row, replaces a subscription made against another key, pushSupported() is false off https; deviceId() per browser - Settings: the notifications switch shows what the server holds - tests: server-reminder (window, dedupe, trained day), server-push-status (upsert, status, per-device timers), lib/push.test.js
This commit is contained in:
1 parent
c92cfc372a
commit
477fc07f8b
10 files changed
+534
-44
No files matched your search
+39
-8
@@ -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
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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: '{}' })
|
||||
@@ -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:')
|
||||
})
|
||||
})
|
||||
@@ -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
|
||||
|
||||
@@ -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 => {
|
||||
|
||||
Reference in new issue
Block a user