calendar
All repositories: gitoria
10.7 KB
// lib/push.hl — WEB PUSH: reminders that reach the phone while the calendar page is closed (ticket calendar#9, part 2).// The page hands over its push subscription (face calPushSave); the server's clock (below) sends every reminder that came due// to every subscribed device of the event's owner (hl:web `sendPush`: VAPID + aes128gcm); the service worker shows it.// One table, storage/mpackdb/push.db, pk @id, unique index endpoint, index owner:// { owner (users @id), endpoint, p256dh, auth (base64url, as the browser gave them), zone (the device's IANA zone: it// reads the days of all-day events), since (epoch ms: the reminders up to here were sent or are not wanted),// created }// THE CLOCK (CALENDAR_PUSH_EVERY seconds, default 30; the gates 0.5): per subscription the reminders with since < time <= now// for events that have not started yet, one per event (the newest) — the same rule as the page's own missed reminders// (reminders.hl `missed`, the same code as the page). `since` moves up only when every send of the round was accepted or the subscription is gone, so a// push service that answers 5xx is tried again next round; at most 15 minutes late (CALENDAR_PUSH_LATE), then it is dropped.// 404 / 410 → the subscription is deleted. The notification's `tag` is the page's own (event:time): a device whose page// is open and shows the same reminder through its timer shows ONE notification (same tag replaces).// Settings (environment / .env, like every setting of the calendar; README "Web Push"): CALENDAR_PUSH_PUBLIC (VAPID public key,// base64url), CALENDAR_PUSH_PRIVATE (the 32-byte scalar, base64url), CALENDAR_PUSH_SUBJECT ('mailto:…' or 'https://…').// Without all three there is no push: the page works as before and the button only asks for the browser's permission.import { MPackDB } from 'hl:mpackdb'import { sendPush } from 'hl:web'import { now, every, local, isZone as knownZone } from 'hl:time'import { envOr, storageDir, firstOf, countOfList } from './util.hl'import { upcoming } from './events.hl'import { publicPushHost } from './push-guard.hl'import { pad } from '../components/month-view/dates.hl'import { shift, missed } from '../components/month-view/reminders.hl'static pushTable = new MPackDB(file = storageDir + '/push.db', primaryKey = '@id', indexes = ['!endpoint', 'owner'])static maxPerUser = 10static lateMs = toNumber(envOr('CALENDAR_PUSH_LATE', '900')) * 1000// http endpoints only for the gates' fake push service; a browser's push service is always httpsstatic allowHttp = envOr('CALENDAR_PUSH_ALLOW_HTTP', '') == '1'static isB64Url = (s, min, max) => {if (s == null || hlTypeName(s) != 'String' || s.length < min || s.length > max) { return false }let i = 0while (i < s.length) {let c = s.charCodeAt(i)if (!((c >= 48 && c <= 57) || (c >= 65 && c <= 90) || (c >= 97 && c <= 122) || c == 45 || c == 95)) { return false }i = i + 1}return true}// the page's subscription ({ endpoint, keys = { p256dh, auth } }) and its zone → stored for the user (one row per endpoint:// a device that signs in as someone else takes it over). Answers { ok } or { error }.static savePush = (userId, sub, zone) => {if (sub == null || hlTypeName(sub) != 'Hybrid' || sub.keys == null || hlTypeName(sub.keys) != 'Hybrid') { return { error = 'no push subscription' } }e = sub.endpointif (e == null || hlTypeName(e) != 'String' || e.length > 1000 || !(e.startsWith('https://') || (allowHttp && e.startsWith('http://')))) { return { error = 'the push endpoint is not an https address' } }if (!(allowHttp && e.startsWith('http://')) && !publicPushHost(e)) { return { error = 'the push endpoint is not a public push service address' } }if (!isB64Url(sub.keys.p256dh, 80, 100) || !isB64Url(sub.keys.auth, 16, 40)) { return { error = 'the push keys are not base64url' } }if (zone == null || hlTypeName(zone) != 'String' || !knownZone(zone)) { return { error = 'the time zone is missing' } }old = firstOf(pushTable.find('endpoint', e))if (old != null) {if (old.owner == userId && old.p256dh == sub.keys.p256dh && old.auth == sub.keys.auth && old.zone == zone) { return { ok = true } }pushTable.update(old.id, { owner = userId endpoint = e p256dh = sub.keys.p256dh auth = sub.keys.auth zone = zone since = old.owner == userId ? old.since : now() created = old.created test = old.owner == userId && old.test != null ? old.test : 0 testAt = old.owner == userId && old.testAt != null ? old.testAt : 0 })return { ok = true }}if (countOfList(pushTable.find('owner', userId)) >= maxPerUser) { return { error = 'too many devices with reminders' } }if (pushTable.put({ owner = userId endpoint = e p256dh = sub.keys.p256dh auth = sub.keys.auth zone = zone since = now() created = now() }) == null) { return { error = 'could not store the push subscription: ' + pushTable.lastError() } }return { ok = true }}// this device stops getting pushesstatic dropPush = (userId, endpoint) => {old = endpoint != null && hlTypeName(endpoint) == 'String' ? firstOf(pushTable.find('endpoint', endpoint)) : nullif (old != null && old.owner == userId) { pushTable.delete(old.id) }return { ok = true }}// "Send a test notification" (the button on the phone): the device's own row is marked to get ONE test push `testDelayMs` from now// (long enough to leave the app: it must arrive like a reminder, with the calendar closed). Only the owner's own device.static testDelayMs = toNumber(envOr('CALENDAR_PUSH_TEST_DELAY', '10')) * 1000static testPush = (userId, endpoint) => {old = endpoint != null && hlTypeName(endpoint) == 'String' ? firstOf(pushTable.find('endpoint', endpoint)) : nullif (old == null || old.owner != userId) { return { error = 'this device is not subscribed: turn the notifications on first' } }// rate limit: one test per device per 30 s (a test still waiting counts: testAt is set when it is asked for)if (old.testAt != null && old.testAt > now() - 30000) { return { error = 'a test was just sent: wait 30 seconds' } }pushTable.update(old.id, { owner = old.owner endpoint = old.endpoint p256dh = old.p256dh auth = old.auth zone = old.zone since = old.since created = old.created test = now() + testDelayMs testAt = now() })return { ok = true }}static hasPush = (userId, endpoint) => {old = endpoint != null && hlTypeName(endpoint) == 'String' ? firstOf(pushTable.find('endpoint', endpoint)) : nullreturn old != null && old.owner == userId}// P1: up to when the server has already handled this device's reminders (sent them as pushes): the page must not show those a// second time as "missed" (the push was shown, tapped or swiped away, then the page opened and showed it again). 0 = unknown:// no such device, or the server has not looked for longer than a push may be late (then the page's own late show stays the net).static pushedUntil = (userId, endpoint) => {old = endpoint != null && hlTypeName(endpoint) == 'String' ? firstOf(pushTable.find('endpoint', endpoint)) : nullif (old == null || old.owner != userId || old.since == null || old.since < now() - lateMs) { return { since = 0 } }return { since = old.since }}// the date of an instant in a zone, 'YYYY-MM-DD'static dateIn = (ms, zone) => {l = local(ms, zone)return l.year + '-' + pad(l.month) + '-' + pad(l.day)}// the words of a reminder at the time it is sent: on time → "Starts in 1 hour", else "Starts at 14:00"static wordsOf = (q, nowMs) => { return nowMs - q.at < 300000 ? q.body : q.late }// one subscription's round: send what is due. Answers the new `since`, or null when it was deleted.static roundOf = (s, nowMs, byOwner) => {if (byOwner[s.owner] == null) {t = dateIn(nowMs, 'UTC')byOwner[s.owner] = upcoming(s.owner, shift(t, -2), shift(t, 35))}events = []let i = 0while (i < byOwner[s.owner].length) {let v = byOwner[s.owner][i]events.push({ id = v.id title = v.title allDay = v.allDay startDate = v.startDate startTime = v.startTime place = v.place zone = v.zone rows = v.rows })i = i + 1}sinceMs = s.since < nowMs - lateMs ? nowMs - lateMs : s.sincedue = missed(events, sinceMs, nowMs, dateIn(nowMs, s.zone), s.zone)sub = { endpoint = s.endpoint keys = { p256dh = s.p256dh auth = s.auth } }let allSent = truei = 0while (i < due.length) {let q = due[i]let ttl = (q.start - nowMs - (q.start - nowMs) % 1000) / 1000if (ttl > 86400) { ttl = 86400 }if (ttl < 60) { ttl = 60 }r = sendPush(sub, JSON.stringify({ title = q.title body = wordsOf(q, nowMs) url = '/' tag = q.key icon = '/icons/icon-192.png' }), { ttl = ttl urgency = 'high' })if (r.gone) {pushTable.delete(s.id)return null}if (!r.ok) { allSent = false console.log('push not sent (' + r.status + '): ' + r.error) }else { console.log('push sent (' + r.status + ') for ' + q.key) }i = i + 1}return allSent ? nowMs : s.since}// CALENDAR_JOBS=0 (the standby container, compose profile standby): the clock does nothing, so only the main container sends remindersstatic jobsOn = envOr('CALENDAR_JOBS', '1') != '0'static round = () => {if (!jobsOn) { return null }nowMs = now()subs = pushTable.find(null, null)byOwner = {}let i = 0while (i < subs.length) {let s = subs[i]let next = roundOf(s, nowMs, byOwner)if (next != null && next != s.since) {pushTable.update(s.id, { owner = s.owner endpoint = s.endpoint p256dh = s.p256dh auth = s.auth zone = s.zone since = next created = s.created test = s.test != null ? s.test : 0 testAt = s.testAt != null ? s.testAt : 0 })}i = i + 1}}// the test pushes that came due: what the phone will show is the title "Calendar test" and the body "Push works on this device"static testRound = () => {if (!jobsOn) { return null }nowMs = now()subs = pushTable.find(null, null)let i = 0while (i < subs.length) {let s = subs[i]if (s.test != null && s.test > 0 && s.test <= nowMs) {pushTable.update(s.id, { owner = s.owner endpoint = s.endpoint p256dh = s.p256dh auth = s.auth zone = s.zone since = s.since created = s.created test = 0 testAt = s.testAt != null ? s.testAt : 0 })r = sendPush({ endpoint = s.endpoint keys = { p256dh = s.p256dh auth = s.auth } }, JSON.stringify({ title = 'Calendar test' body = 'Push works on this device' url = '/' tag = 'calendar-test' icon = '/icons/icon-192.png' }), { ttl = 120 urgency = 'high' })if (r.gone) { pushTable.delete(s.id) console.log('push test: the subscription is gone (' + r.status + ')') }else if (!r.ok) { console.log('push test not sent (' + r.status + '): ' + r.error) }else { console.log('push test sent (' + r.status + ')') }}i = i + 1}}// THE CLOCK: project.hl constructs this file once (`push = new Push()`)static ticker = every(toNumber(envOr('CALENDAR_PUSH_EVERY', '30')))on ticker.tick(t) { round() }static testTicker = every(2)on testTicker.tick(t) { testRound() }
Branches
Latest commits
- edb7c947calendar: the sign-in callback keeps the session it finds and signs it in (same cookie, nothing signed out; ident#28); security gate 56+4 failing → 60 passedmre
- bf8cc0fcStyles move into their components: the shell's styles into main.hl, the events and the editors into the month view's Style block; styles.hl keeps only the theme inherit, the accent and the message line; .gitignore ignores a bin symlink too; tests/styles-shots.mjs for the before/after pixel comparemre
- 5d8579d7README: login.js stays by caramboleyo's explicit rulemre
- cc759328Merge sb3-standby: calendar deploys through its standbymre
- f2fcdc6dcalendar: a standby container (port 45015, profile standby, reminder clock off) and a /health page; deploy hands over through standby-swap.sh without a gapmre
- 229643f7Merge branch 'cal-14'mre
- 1110b26fcalendar#14: the month name no longer breaks into two lines on a phone (Reminder settings drops to its own row when the header is too narrow), gate checks for one-line title and all header controls on screenmre
- 490c658aident#31: the selector's sign-in returns to the page the user started on (return attribute = the login callback with next), gate checkmre
- 18095868calendar: Reminder settings button opens its dialog again (the dialog's open handler still closed the removed user menu and stopped); old e2e and gate scripts use the new headermre
- 6eee4b5acalendar header: the selector alone top right plus Log out as before the theme missions; Reminder settings back on the month page (WIP: the settings test still fails)mre
- 0b909decident selector back in the header (creator 2026-10-24): selector top right signed in and out on phone and desktop, no second Log in button, new gate checks (WIP: gates not re-run after the last edits)mre
- 0c8f9364Merge branch 'sy-sync'mre
- 9fab1c8fsync components.hybriel 4922f9c into the month view: prev / next 44 px targets, names formatted in UTC (a UTC+12 zone showed the wrong first weekday); the calendar keeps its own language handling (Accept-Language / browser) and the P1/C13 reminder code; gate: 44 px check (SY)mre
- 27d3e294theme: sync from layouts 4994037 (list rows stack, td word-keep, heading code, edited tap target)mre
- 2ac9c1bbdeploy: security gate (tests/security.mjs)mre
- 6b0a2571merge sc-sec (calendar security) with 99-year sessionsmre
- 92001e52sessions last 99 years (creator 2026-10-23: logins never expire; only sign out ends them)mre
- 0f76c99dSecurity audit SC: push endpoint SSRF guard, uploadMax 0, Secure cookie, login session rotation + rate limit, event cap, nosniff, security gatemre
- 2dd53dccP1: one reminder shows once: arm() one at a time, the page skips reminders the server already pushed; push-twice gatemre
- 3a29760aC13 report (handoff)mre