gitoria

notes

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commitd860dc2dd860dc2dnotes#12: the markup names its own rules instead of hand-written class strings: the selected row is `aria-current="page"` (the list-first theme rule styles it, no class), the delete question is `Style.pAsk` and follows its own `open` attribute (bound to `asking`), the error line is `Style.pMessage` (body once in lib/looks.hl, rule in notes.hl, main.hl and loginfailed.hl). The CSS declarations are the same, only selectors changed (.ask -> p.ask, .ask.open -> p.ask[open], .message -> p.message); the pages look the same (AE 0 at 4 sizes). main.hl's selectorClass in/out stays (login.js reads it).mred860dc2d/plugins/web/push.hl

6.9 KB

  1. // WEB PUSH, THE SERVER'S HALF (ticket #173): `sendPush(subscription, payload, opts)` sends one message to a
  2. // browser's push service — VAPID (RFC 8292: an ES256 JWT in `Authorization: vapid t=…, k=…`) and the payload
  3. // encrypted for the browser (RFC 8291 / RFC 8188 aes128gcm), posted with hl:fetch.
  4. //
  5. // import { sendPush } from 'hl:web' (server.hl names it; this file is the work)
  6. // let r = sendPush(sub, JSON.stringify({ title = 'Dentist', body = 'in 1 h', url = '/' }), { ttl = 3600 })
  7. // // r = { ok, status, gone, error }: `gone` is true on 404/410 — drop that subscription
  8. //
  9. // The keys are the app's settings: `pushKey` (public), `pushPrivateKey`, `pushSubject` (WebFramework.hl).
  10. import { base64urlEncode, base64urlDecode, p256Generate, p256PublicKey, es256Sign, ecdhSharedSecret, hkdfExtract, hkdfExpand, aes128gcmEncrypt } from 'hl:crypto'
  11. import { fetch } from 'hl:fetch'
  12. import { now } from 'hl:time'
  13. static vapid = { key = null; priv = null; subject = null; }
  14. // WebFramework hands the three settings over when it boots (and checks they belong together)
  15. static configure = (key, priv, subject) => {
  16. vapid.key = key
  17. vapid.priv = priv
  18. vapid.subject = subject
  19. }
  20. // THE BODY, RFC 8291 §3.4 + RFC 8188: header (salt 16, rs 4096, idlen 65, the server's ECDH public key)
  21. // then ONE record, plaintext + 0x02, sealed with AES-128-GCM. `uaPublic` (65 B) and `authSecret` (16 B) are
  22. // the subscription's keys.p256dh and keys.auth. `asKeys` ({ privateKey, publicKey }) and `salt` (16 B) are
  23. // made fresh for every message; they are parameters ONLY so the RFC 8291 §5 vector can be reproduced
  24. // byte for byte (the test's hook — sendPush never passes them, and no setting reaches them).
  25. static encrypt = (uaPublic, authSecret, plaintext, asKeys, salt) => {
  26. let keys = asKeys != null ? asKeys : p256Generate()
  27. let s = salt != null ? salt : p256Generate().privateKey.slice(0, 16)
  28. let secret = ecdhSharedSecret(keys.privateKey, uaPublic)
  29. if (secret == null) { return null }
  30. let keyInfo = toBytes('WebPush: info')
  31. keyInfo.append(0)
  32. keyInfo.append(uaPublic)
  33. keyInfo.append(keys.publicKey)
  34. let ikm = hkdfExpand(hkdfExtract(authSecret, secret), keyInfo, 32)
  35. let prk = hkdfExtract(s, ikm)
  36. let cekInfo = toBytes('Content-Encoding: aes128gcm')
  37. cekInfo.append(0)
  38. let nonceInfo = toBytes('Content-Encoding: nonce')
  39. nonceInfo.append(0)
  40. let padded = toBytes(plaintext)
  41. padded.append(2)
  42. let sealed = aes128gcmEncrypt(hkdfExpand(prk, cekInfo, 16), hkdfExpand(prk, nonceInfo, 12), padded, null)
  43. let body = toBytes(s)
  44. body.append(0)
  45. body.append(0)
  46. body.append(16)
  47. body.append(0)
  48. body.append(keys.publicKey.length)
  49. body.append(keys.publicKey)
  50. return body.concat(sealed)
  51. }
  52. // the VAPID JWT for one push service: aud is the endpoint's origin, exp 12 h out (the limit is 24 h)
  53. static jwt = (endpoint, priv, subject) => {
  54. let rest = endpoint.slice(endpoint.indexOf('://') + 3)
  55. let slash = rest.indexOf('/')
  56. let aud = endpoint.slice(0, endpoint.indexOf('://') + 3 + (slash < 0 ? rest.length : slash))
  57. let ms = now()
  58. let exp = (ms - ms % 1000) / 1000 + 43200
  59. let head = base64urlEncode('{"typ":"JWT","alg":"ES256"}')
  60. let claims = base64urlEncode('{"aud":' + JSON.stringify(aud) + ',"exp":' + exp + ',"sub":' + JSON.stringify(subject) + '}')
  61. return head + '.' + claims + '.' + base64urlEncode(es256Sign(priv, toBytes(head + '.' + claims)))
  62. }
  63. static urlSafe = (text) => {
  64. let i = 0
  65. while (i < text.length) {
  66. if (!'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'.includes(text[i])) { return false }
  67. i = i + 1
  68. }
  69. return true
  70. }
  71. // SEND ONE PUSH. `subscription` is what subscribePush() gave the page: { endpoint, keys = { p256dh, auth } }
  72. // (as the app stored it). `payload`: a String (its UTF-8) or Bytes, up to 3993 bytes — the worker shows
  73. // JSON text { title, body, url, tag, icon }. `opts`: ttl (seconds the service may hold it, default 86400),
  74. // urgency ('very-low' | 'low' | 'normal' | 'high'), topic (replaces an undelivered push of the same topic;
  75. // up to 32 characters of the URL-safe base64 alphabet). Answers { ok, status, gone, error }: ok is a 2xx
  76. // (201 = accepted), `gone` a 404/410 (the subscription is dead: forget it), status 0 and `error` a push
  77. // service that could not be reached (only where the caller has an `on Error(e)` handler — hl:fetch routes a
  78. // connection failure there, and without one the failure faults the call, as hl:fetch does) or a subscription
  79. // that is malformed. A missing setting is an error.
  80. static sendPush = (subscription, payload, opts) => {
  81. if (vapid.priv == null) { hlError("hl:web: sendPush needs the app's settings pushKey, pushPrivateKey and pushSubject") }
  82. let o = opts != null ? opts : {}
  83. if (o.urgency != null && !['very-low', 'low', 'normal', 'high'].includes(o.urgency)) { hlError("hl:web: sendPush urgency is 'very-low', 'low', 'normal' or 'high', and this one is " + o.urgency) }
  84. if (o.topic != null && (hlTypeName(o.topic) != 'String' || o.topic.length > 32 || o.topic.length == 0 || !urlSafe(o.topic))) { hlError('hl:web: sendPush topic is up to 32 characters of the URL-safe base64 alphabet') }
  85. let data = hlTypeName(payload) == 'Bytes' ? payload : toBytes(payload == null ? '' : payload)
  86. if (data == null || data.length > 3993) { hlError('hl:web: sendPush payload is a String or Bytes of at most 3993 bytes') }
  87. let sub = subscription
  88. if (sub == null || hlTypeName(sub.endpoint) != 'String' || !sub.endpoint.startsWith('https://') && !sub.endpoint.startsWith('http://') || sub.keys == null) {
  89. return { ok = false; status = 0; gone = false; error = 'the subscription has no endpoint or keys'; }
  90. }
  91. let ua = hlTypeName(sub.keys.p256dh) == 'String' ? base64urlDecode(sub.keys.p256dh) : null
  92. let auth = hlTypeName(sub.keys.auth) == 'String' ? base64urlDecode(sub.keys.auth) : null
  93. if (ua == null || ua.length != 65 || auth == null || auth.length != 16) {
  94. return { ok = false; status = 0; gone = false; error = 'the subscription keys are not a 65-byte p256dh and a 16-byte auth'; }
  95. }
  96. let body = encrypt(ua, auth, data, null, null)
  97. if (body == null) { return { ok = false; status = 0; gone = false; error = 'the subscription p256dh is not a point on P-256'; } }
  98. let headers = {
  99. 'authorization' = 'vapid t=' + jwt(sub.endpoint, vapid.priv, vapid.subject) + ', k=' + vapid.key
  100. 'content-encoding' = 'aes128gcm'
  101. 'content-type' = 'application/octet-stream'
  102. 'ttl' = '' + (o.ttl != null ? o.ttl : 86400)
  103. }
  104. if (o.urgency != null) { headers['urgency'] = o.urgency }
  105. if (o.topic != null) { headers['topic'] = o.topic }
  106. // hl:fetch sends a String body byte for byte, and the encrypted body is no UTF-8: the raw String of the bytes
  107. let raw = __native('crypto.base64url_decode', base64urlEncode(body))
  108. let r = fetch(sub.endpoint, { method = 'POST'; headers = headers; body = raw; timeoutMs = 15000; maxRedirects = 0; })
  109. if (r == null) { return { ok = false; status = 0; gone = false; error = 'the push service could not be reached'; } }
  110. let err = r.status == 0 ? 'the push service did not answer' : null
  111. return { ok = r.ok; status = r.status; gone = r.status == 404 || r.status == 410; error = err; }
  112. }

Branches

Latest commits

  • d860dc2dnotes#12: the markup names its own rules instead of hand-written class strings: the selected row is `aria-current="page"` (the list-first theme rule styles it, no class), the delete question is `Style.pAsk` and follows its own `open` attribute (bound to `asking`), the error line is `Style.pMessage` (body once in lib/looks.hl, rule in notes.hl, main.hl and loginfailed.hl). The CSS declarations are the same, only selectors changed (.ask -> p.ask, .ask.open -> p.ask[open], .message -> p.message); the pages look the same (AE 0 at 4 sizes). main.hl's selectorClass in/out stays (login.js reads it).mre
  • 2e7f8664notes#13: the list and back links pass the note key from the loop (emit pick(e, r.key)) instead of writing data-note into the View and reading it back with getAttribute; the two window.history.replaceState calls and the identcode e.target.value read stay (hl:web has no replace-navigation, a bound hidden input is not adopted on a script's change event), see NO13 reportmre
  • 4dc98282notes#15: a deleted note made in this tab leaves the list at once (the delete now removes this tab's edit under every key the row has: local id, server id); gate: browser.mjs notes#15 section, red on the old codemre
  • e4e7402fnotes#11: plain declarations instead of let for variables never reassigned (components/notes.hl 3, lib/jsoncheck.hl 5, lib/util.hl 2, tools/migrate-short-ids.hl 8)mre
  • 27b6a09enotes#8: Style blocks in the nested form (note-list, note-editor, .ask with their children nested, :empty as a nested pseudo-class); the same CSS rules, the pages look the samemre
  • 71a9538bnotes: B27W report, log linemre
  • 78ba0073notes: an ident access key (Authorization: Bearer idt_…) reads and writes its identity's notes through /api/me and /api/notes; gate tests/ident-access-notes.mjs (ident#27)mre
  • 3de46dacnotes: the sign-in callback keeps the session it finds and signs it in (same cookie, nothing signed out; ident#28); security gate 73+5 failing → 78 passedmre
  • 5909d458notes: MdEditor from components 59704ce (text on the clipboard always pastes, a file manager copy still attaches; pipe rows without a delimiter row; tickets#49, notes#5)mre
  • 98bd6a98N5b: pipe rows without a delimiter row are a table (MdEditor ad4e929, plain copy); gate tests/dashboard-table.mjs; reportmre
  • dbf93319N5 report: components gate rerun 613 passed, 0 failedmre
  • 3a8bc0d2N5: empty Table-button table is written as a real pipe table (MdEditor 4bd1112, plain copy); gate tests/table-button.mjs; reportmre
  • c16bd443N5: step 1 report (tables pass locally; his DASHBOARD note has no delimiter row)mre
  • 6091320anotes: MdEditor 7437e32 (surface drawn at once when the page is claimed); gate measures claim-to-text on 5 note loads at 1280 and 390mre
  • 0aa9277enotes: move each component's styles into its own Style block (shell and header selector in main.hl, list, editor frame and delete question in notes.hl); styles.hl keeps the theme inherit, the accent and the message colour; .gitignore ignores a bin symlink too; tests/shots.mjs for the pixel comparemre
  • 9ba01de3notes: write the standby service out in full so the boot gate can read the main servicemre
  • 98cab40anotes: standby service on its port plus 10 and a deploy that hands over through it without a gapmre
  • 1fadb473notes gate: the editor table now has 1 px cell lines from the notes thememre
  • 8762115cnotes: take the components e54f83a (paste as Markdown, text typed before the editor is built is kept, Table button); table lines come from the notes thememre
  • ac23e194ident#31: the selector's sign-in returns to the page the user started on (return attribute = the login callback with next), gate checkmre