gitoria

calendar

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit92001e5292001e52sessions last 99 years (creator 2026-10-23: logins never expire; only sign out ends them)mre92001e52/lib/push.hl

10.3 KB

  1. // lib/push.hl — WEB PUSH: reminders that reach the phone while the calendar page is closed (ticket calendar#9, part 2).
  2. // The page hands over its push subscription (face calPushSave); the server's clock (below) sends every reminder that came due
  3. // to every subscribed device of the event's owner (hl:web `sendPush`: VAPID + aes128gcm); the service worker shows it.
  4. // One table, storage/mpackdb/push.db, pk @id, unique index endpoint, index owner:
  5. // { owner (users @id), endpoint, p256dh, auth (base64url, as the browser gave them), zone (the device's IANA zone: it
  6. // reads the days of all-day events), since (epoch ms: the reminders up to here were sent or are not wanted),
  7. // created }
  8. // THE CLOCK (CALENDAR_PUSH_EVERY seconds, default 30; the gates 0.5): per subscription the reminders with since < time <= now
  9. // for events that have not started yet, one per event (the newest) — the same rule as the page's own missed reminders
  10. // (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
  11. // push service that answers 5xx is tried again next round; at most 15 minutes late (CALENDAR_PUSH_LATE), then it is dropped.
  12. // 404 / 410 → the subscription is deleted. The notification's `tag` is the page's own (event:time): a device whose page
  13. // is open and shows the same reminder through its timer shows ONE notification (same tag replaces).
  14. // Settings (environment / .env, like every setting of the calendar; README "Web Push"): CALENDAR_PUSH_PUBLIC (VAPID public key,
  15. // base64url), CALENDAR_PUSH_PRIVATE (the 32-byte scalar, base64url), CALENDAR_PUSH_SUBJECT ('mailto:…' or 'https://…').
  16. // Without all three there is no push: the page works as before and the button only asks for the browser's permission.
  17. import { MPackDB } from 'hl:mpackdb'
  18. import { sendPush } from 'hl:web'
  19. import { now, every, local, isZone as knownZone } from 'hl:time'
  20. import { envOr, storageDir, firstOf, countOfList } from './util.hl'
  21. import { upcoming } from './events.hl'
  22. import { pad } from '../components/month-view/dates.hl'
  23. import { shift, missed } from '../components/month-view/reminders.hl'
  24. static pushTable = new MPackDB(file = storageDir + '/push.db', primaryKey = '@id', indexes = ['!endpoint', 'owner'])
  25. static maxPerUser = 10
  26. static lateMs = toNumber(envOr('CALENDAR_PUSH_LATE', '900')) * 1000
  27. // http endpoints only for the gates' fake push service; a browser's push service is always https
  28. static allowHttp = envOr('CALENDAR_PUSH_ALLOW_HTTP', '') == '1'
  29. static isB64Url = (s, min, max) => {
  30. if (s == null || hlTypeName(s) != 'String' || s.length < min || s.length > max) { return false }
  31. let i = 0
  32. while (i < s.length) {
  33. let c = s.charCodeAt(i)
  34. if (!((c >= 48 && c <= 57) || (c >= 65 && c <= 90) || (c >= 97 && c <= 122) || c == 45 || c == 95)) { return false }
  35. i = i + 1
  36. }
  37. return true
  38. }
  39. // the page's subscription ({ endpoint, keys = { p256dh, auth } }) and its zone → stored for the user (one row per endpoint:
  40. // a device that signs in as someone else takes it over). Answers { ok } or { error }.
  41. static savePush = (userId, sub, zone) => {
  42. if (sub == null || hlTypeName(sub) != 'Hybrid' || sub.keys == null || hlTypeName(sub.keys) != 'Hybrid') { return { error = 'no push subscription' } }
  43. e = sub.endpoint
  44. if (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' } }
  45. if (!isB64Url(sub.keys.p256dh, 80, 100) || !isB64Url(sub.keys.auth, 16, 40)) { return { error = 'the push keys are not base64url' } }
  46. if (zone == null || hlTypeName(zone) != 'String' || !knownZone(zone)) { return { error = 'the time zone is missing' } }
  47. old = firstOf(pushTable.find('endpoint', e))
  48. if (old != null) {
  49. if (old.owner == userId && old.p256dh == sub.keys.p256dh && old.auth == sub.keys.auth && old.zone == zone) { return { ok = true } }
  50. 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 })
  51. return { ok = true }
  52. }
  53. if (countOfList(pushTable.find('owner', userId)) >= maxPerUser) { return { error = 'too many devices with reminders' } }
  54. 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() } }
  55. return { ok = true }
  56. }
  57. // this device stops getting pushes
  58. static dropPush = (userId, endpoint) => {
  59. old = endpoint != null && hlTypeName(endpoint) == 'String' ? firstOf(pushTable.find('endpoint', endpoint)) : null
  60. if (old != null && old.owner == userId) { pushTable.delete(old.id) }
  61. return { ok = true }
  62. }
  63. // "Send a test notification" (the button on the phone): the device's own row is marked to get ONE test push `testDelayMs` from now
  64. // (long enough to leave the app: it must arrive like a reminder, with the calendar closed). Only the owner's own device.
  65. static testDelayMs = toNumber(envOr('CALENDAR_PUSH_TEST_DELAY', '10')) * 1000
  66. static testPush = (userId, endpoint) => {
  67. old = endpoint != null && hlTypeName(endpoint) == 'String' ? firstOf(pushTable.find('endpoint', endpoint)) : null
  68. if (old == null || old.owner != userId) { return { error = 'this device is not subscribed: turn the notifications on first' } }
  69. // rate limit: one test per device per 30 s (a test still waiting counts: testAt is set when it is asked for)
  70. if (old.testAt != null && old.testAt > now() - 30000) { return { error = 'a test was just sent: wait 30 seconds' } }
  71. 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() })
  72. return { ok = true }
  73. }
  74. static hasPush = (userId, endpoint) => {
  75. old = endpoint != null && hlTypeName(endpoint) == 'String' ? firstOf(pushTable.find('endpoint', endpoint)) : null
  76. return old != null && old.owner == userId
  77. }
  78. // P1: up to when the server has already handled this device's reminders (sent them as pushes): the page must not show those a
  79. // second time as "missed" (the push was shown, tapped or swiped away, then the page opened and showed it again). 0 = unknown:
  80. // 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).
  81. static pushedUntil = (userId, endpoint) => {
  82. old = endpoint != null && hlTypeName(endpoint) == 'String' ? firstOf(pushTable.find('endpoint', endpoint)) : null
  83. if (old == null || old.owner != userId || old.since == null || old.since < now() - lateMs) { return { since = 0 } }
  84. return { since = old.since }
  85. }
  86. // the date of an instant in a zone, 'YYYY-MM-DD'
  87. static dateIn = (ms, zone) => {
  88. l = local(ms, zone)
  89. return l.year + '-' + pad(l.month) + '-' + pad(l.day)
  90. }
  91. // the words of a reminder at the time it is sent: on time → "Starts in 1 hour", else "Starts at 14:00"
  92. static wordsOf = (q, nowMs) => { return nowMs - q.at < 300000 ? q.body : q.late }
  93. // one subscription's round: send what is due. Answers the new `since`, or null when it was deleted.
  94. static roundOf = (s, nowMs, byOwner) => {
  95. if (byOwner[s.owner] == null) {
  96. t = dateIn(nowMs, 'UTC')
  97. byOwner[s.owner] = upcoming(s.owner, shift(t, -2), shift(t, 35))
  98. }
  99. events = []
  100. let i = 0
  101. while (i < byOwner[s.owner].length) {
  102. let v = byOwner[s.owner][i]
  103. 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 })
  104. i = i + 1
  105. }
  106. sinceMs = s.since < nowMs - lateMs ? nowMs - lateMs : s.since
  107. due = missed(events, sinceMs, nowMs, dateIn(nowMs, s.zone), s.zone)
  108. sub = { endpoint = s.endpoint keys = { p256dh = s.p256dh auth = s.auth } }
  109. let allSent = true
  110. i = 0
  111. while (i < due.length) {
  112. let q = due[i]
  113. let ttl = (q.start - nowMs - (q.start - nowMs) % 1000) / 1000
  114. if (ttl > 86400) { ttl = 86400 }
  115. if (ttl < 60) { ttl = 60 }
  116. 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' })
  117. if (r.gone) {
  118. pushTable.delete(s.id)
  119. return null
  120. }
  121. if (!r.ok) { allSent = false console.log('push not sent (' + r.status + '): ' + r.error) }
  122. else { console.log('push sent (' + r.status + ') for ' + q.key) }
  123. i = i + 1
  124. }
  125. return allSent ? nowMs : s.since
  126. }
  127. static round = () => {
  128. nowMs = now()
  129. subs = pushTable.find(null, null)
  130. byOwner = {}
  131. let i = 0
  132. while (i < subs.length) {
  133. let s = subs[i]
  134. let next = roundOf(s, nowMs, byOwner)
  135. if (next != null && next != s.since) {
  136. 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 })
  137. }
  138. i = i + 1
  139. }
  140. }
  141. // the test pushes that came due: what the phone will show is the title "Calendar test" and the body "Push works on this device"
  142. static testRound = () => {
  143. nowMs = now()
  144. subs = pushTable.find(null, null)
  145. let i = 0
  146. while (i < subs.length) {
  147. let s = subs[i]
  148. if (s.test != null && s.test > 0 && s.test <= nowMs) {
  149. 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 })
  150. 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' })
  151. if (r.gone) { pushTable.delete(s.id) console.log('push test: the subscription is gone (' + r.status + ')') }
  152. else if (!r.ok) { console.log('push test not sent (' + r.status + '): ' + r.error) }
  153. else { console.log('push test sent (' + r.status + ')') }
  154. }
  155. i = i + 1
  156. }
  157. }
  158. // THE CLOCK: project.hl constructs this file once (`push = new Push()`)
  159. static ticker = every(toNumber(envOr('CALENDAR_PUSH_EVERY', '30')))
  160. on ticker.tick(t) { round() }
  161. static testTicker = every(2)
  162. on testTicker.tick(t) { testRound() }

Branches

Latest commits

  • 92001e52sessions last 99 years (creator 2026-10-23: logins never expire; only sign out ends them)mre
  • 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
  • 33ab66ffCalendar: notification controls move from the month view into Reminder settings (user menu), one consistent state, state read when the dialog opensmre
  • 682a5b43reports: calendar gate countsmre
  • 876d22b2reports/H1-hydrate.mdmre
  • ef0cae45tests/dst.mjs: wait for hydration instead of a fixed 2.5 s sleep before clicking #gomre
  • d9cadecatests/cdp.mjs: HL_CPU_THROTTLE=<rate> optional CPU throttling for gate runsmre
  • efa61227re-vendor Hybriel 5406d146 (hl:web batches 9+10: #72 emits while the socket is closed delivered after reconnect, browser boot linear, faster list appends; contains int 6–14 + m406)mre
  • 7808adbecalendar#12: report 011, LOG, STATUS, push-shots-testmre
  • df2e4fa0calendar#12: test push rate limit (1 per 30 s per device), owner-only gate checksmre
  • acb957cfcalendar#12: Send a test notification on a subscribed device (one push in ~10 s, owner's own device), push gate part 4mre
  • 0b222eb8tests: e2e-theme CDP port default from E2E_THEME_CDP_PORT (8756 unchanged)mre
  • 8b8a5abare-vendor Hybriel 6f8a0689 (int 6–11: streaming cursors, #203 index heal + close() fix, fd403 listDir/cursor fds, hl:time browser side, hl:web batches 5+6)mre
  • a69b27f9docker-compose: nofile 65536 (Hybriel int 6+ boot opened >1024 files in the tracker)mre
  • 1a97edfdcalendar mission 010: reminder rows at 390 px (the 7-column month grid no longer catches the reminder lists), gate checks, settings-shots, reportmre
  • 61b21404calendar mission 009: reminder times on hl:time in the browser (lib/push-plan.hl and the Intl code removed), DST gate tests/dst.mjs, E2E script, reportmre
  • 875353c1calendar mission 009: re-vendor Hybriel master 022a3ac1 (int 6 6b396322 hl:time browser side, int 7 65e8ec21; bin sha256 6e0f77d7, plugins whole)mre
  • ce16a4efdeploy: backup copies index files first and *.mpack data last (hot-copy skew, hybriel #203)mre
  • f490bc8cdeploy: Web Push gate tests/push.mjs (PUSH_GATE_PORT)mre