gitoria

calendar

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commitedb7c947edb7c947calendar: 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 passedmreedb7c947/lib/push.hl

10.7 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 { publicPushHost } from './push-guard.hl'
  23. import { pad } from '../components/month-view/dates.hl'
  24. import { shift, missed } from '../components/month-view/reminders.hl'
  25. static pushTable = new MPackDB(file = storageDir + '/push.db', primaryKey = '@id', indexes = ['!endpoint', 'owner'])
  26. static maxPerUser = 10
  27. static lateMs = toNumber(envOr('CALENDAR_PUSH_LATE', '900')) * 1000
  28. // http endpoints only for the gates' fake push service; a browser's push service is always https
  29. static allowHttp = envOr('CALENDAR_PUSH_ALLOW_HTTP', '') == '1'
  30. static isB64Url = (s, min, max) => {
  31. if (s == null || hlTypeName(s) != 'String' || s.length < min || s.length > max) { return false }
  32. let i = 0
  33. while (i < s.length) {
  34. let c = s.charCodeAt(i)
  35. if (!((c >= 48 && c <= 57) || (c >= 65 && c <= 90) || (c >= 97 && c <= 122) || c == 45 || c == 95)) { return false }
  36. i = i + 1
  37. }
  38. return true
  39. }
  40. // the page's subscription ({ endpoint, keys = { p256dh, auth } }) and its zone → stored for the user (one row per endpoint:
  41. // a device that signs in as someone else takes it over). Answers { ok } or { error }.
  42. static savePush = (userId, sub, zone) => {
  43. if (sub == null || hlTypeName(sub) != 'Hybrid' || sub.keys == null || hlTypeName(sub.keys) != 'Hybrid') { return { error = 'no push subscription' } }
  44. e = sub.endpoint
  45. 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' } }
  46. if (!(allowHttp && e.startsWith('http://')) && !publicPushHost(e)) { return { error = 'the push endpoint is not a public push service address' } }
  47. if (!isB64Url(sub.keys.p256dh, 80, 100) || !isB64Url(sub.keys.auth, 16, 40)) { return { error = 'the push keys are not base64url' } }
  48. if (zone == null || hlTypeName(zone) != 'String' || !knownZone(zone)) { return { error = 'the time zone is missing' } }
  49. old = firstOf(pushTable.find('endpoint', e))
  50. if (old != null) {
  51. if (old.owner == userId && old.p256dh == sub.keys.p256dh && old.auth == sub.keys.auth && old.zone == zone) { return { ok = true } }
  52. 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 })
  53. return { ok = true }
  54. }
  55. if (countOfList(pushTable.find('owner', userId)) >= maxPerUser) { return { error = 'too many devices with reminders' } }
  56. 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() } }
  57. return { ok = true }
  58. }
  59. // this device stops getting pushes
  60. static dropPush = (userId, endpoint) => {
  61. old = endpoint != null && hlTypeName(endpoint) == 'String' ? firstOf(pushTable.find('endpoint', endpoint)) : null
  62. if (old != null && old.owner == userId) { pushTable.delete(old.id) }
  63. return { ok = true }
  64. }
  65. // "Send a test notification" (the button on the phone): the device's own row is marked to get ONE test push `testDelayMs` from now
  66. // (long enough to leave the app: it must arrive like a reminder, with the calendar closed). Only the owner's own device.
  67. static testDelayMs = toNumber(envOr('CALENDAR_PUSH_TEST_DELAY', '10')) * 1000
  68. static testPush = (userId, endpoint) => {
  69. old = endpoint != null && hlTypeName(endpoint) == 'String' ? firstOf(pushTable.find('endpoint', endpoint)) : null
  70. if (old == null || old.owner != userId) { return { error = 'this device is not subscribed: turn the notifications on first' } }
  71. // rate limit: one test per device per 30 s (a test still waiting counts: testAt is set when it is asked for)
  72. if (old.testAt != null && old.testAt > now() - 30000) { return { error = 'a test was just sent: wait 30 seconds' } }
  73. 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() })
  74. return { ok = true }
  75. }
  76. static hasPush = (userId, endpoint) => {
  77. old = endpoint != null && hlTypeName(endpoint) == 'String' ? firstOf(pushTable.find('endpoint', endpoint)) : null
  78. return old != null && old.owner == userId
  79. }
  80. // P1: up to when the server has already handled this device's reminders (sent them as pushes): the page must not show those a
  81. // second time as "missed" (the push was shown, tapped or swiped away, then the page opened and showed it again). 0 = unknown:
  82. // 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).
  83. static pushedUntil = (userId, endpoint) => {
  84. old = endpoint != null && hlTypeName(endpoint) == 'String' ? firstOf(pushTable.find('endpoint', endpoint)) : null
  85. if (old == null || old.owner != userId || old.since == null || old.since < now() - lateMs) { return { since = 0 } }
  86. return { since = old.since }
  87. }
  88. // the date of an instant in a zone, 'YYYY-MM-DD'
  89. static dateIn = (ms, zone) => {
  90. l = local(ms, zone)
  91. return l.year + '-' + pad(l.month) + '-' + pad(l.day)
  92. }
  93. // the words of a reminder at the time it is sent: on time → "Starts in 1 hour", else "Starts at 14:00"
  94. static wordsOf = (q, nowMs) => { return nowMs - q.at < 300000 ? q.body : q.late }
  95. // one subscription's round: send what is due. Answers the new `since`, or null when it was deleted.
  96. static roundOf = (s, nowMs, byOwner) => {
  97. if (byOwner[s.owner] == null) {
  98. t = dateIn(nowMs, 'UTC')
  99. byOwner[s.owner] = upcoming(s.owner, shift(t, -2), shift(t, 35))
  100. }
  101. events = []
  102. let i = 0
  103. while (i < byOwner[s.owner].length) {
  104. let v = byOwner[s.owner][i]
  105. 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 })
  106. i = i + 1
  107. }
  108. sinceMs = s.since < nowMs - lateMs ? nowMs - lateMs : s.since
  109. due = missed(events, sinceMs, nowMs, dateIn(nowMs, s.zone), s.zone)
  110. sub = { endpoint = s.endpoint keys = { p256dh = s.p256dh auth = s.auth } }
  111. let allSent = true
  112. i = 0
  113. while (i < due.length) {
  114. let q = due[i]
  115. let ttl = (q.start - nowMs - (q.start - nowMs) % 1000) / 1000
  116. if (ttl > 86400) { ttl = 86400 }
  117. if (ttl < 60) { ttl = 60 }
  118. 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' })
  119. if (r.gone) {
  120. pushTable.delete(s.id)
  121. return null
  122. }
  123. if (!r.ok) { allSent = false console.log('push not sent (' + r.status + '): ' + r.error) }
  124. else { console.log('push sent (' + r.status + ') for ' + q.key) }
  125. i = i + 1
  126. }
  127. return allSent ? nowMs : s.since
  128. }
  129. // CALENDAR_JOBS=0 (the standby container, compose profile standby): the clock does nothing, so only the main container sends reminders
  130. static jobsOn = envOr('CALENDAR_JOBS', '1') != '0'
  131. static round = () => {
  132. if (!jobsOn) { return null }
  133. nowMs = now()
  134. subs = pushTable.find(null, null)
  135. byOwner = {}
  136. let i = 0
  137. while (i < subs.length) {
  138. let s = subs[i]
  139. let next = roundOf(s, nowMs, byOwner)
  140. if (next != null && next != s.since) {
  141. 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 })
  142. }
  143. i = i + 1
  144. }
  145. }
  146. // the test pushes that came due: what the phone will show is the title "Calendar test" and the body "Push works on this device"
  147. static testRound = () => {
  148. if (!jobsOn) { return null }
  149. nowMs = now()
  150. subs = pushTable.find(null, null)
  151. let i = 0
  152. while (i < subs.length) {
  153. let s = subs[i]
  154. if (s.test != null && s.test > 0 && s.test <= nowMs) {
  155. 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 })
  156. 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' })
  157. if (r.gone) { pushTable.delete(s.id) console.log('push test: the subscription is gone (' + r.status + ')') }
  158. else if (!r.ok) { console.log('push test not sent (' + r.status + '): ' + r.error) }
  159. else { console.log('push test sent (' + r.status + ')') }
  160. }
  161. i = i + 1
  162. }
  163. }
  164. // THE CLOCK: project.hl constructs this file once (`push = new Push()`)
  165. static ticker = every(toNumber(envOr('CALENDAR_PUSH_EVERY', '30')))
  166. on ticker.tick(t) { round() }
  167. static testTicker = every(2)
  168. 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