ident
All repositories: gitoria
6.9 KB
// WEB PUSH, THE SERVER'S HALF (ticket #173): `sendPush(subscription, payload, opts)` sends one message to a// browser's push service — VAPID (RFC 8292: an ES256 JWT in `Authorization: vapid t=…, k=…`) and the payload// encrypted for the browser (RFC 8291 / RFC 8188 aes128gcm), posted with hl:fetch.//// import { sendPush } from 'hl:web' (server.hl names it; this file is the work)// let r = sendPush(sub, JSON.stringify({ title = 'Dentist', body = 'in 1 h', url = '/' }), { ttl = 3600 })// // r = { ok, status, gone, error }: `gone` is true on 404/410 — drop that subscription//// The keys are the app's settings: `pushKey` (public), `pushPrivateKey`, `pushSubject` (WebFramework.hl).import { base64urlEncode, base64urlDecode, p256Generate, p256PublicKey, es256Sign, ecdhSharedSecret, hkdfExtract, hkdfExpand, aes128gcmEncrypt } from 'hl:crypto'import { fetch } from 'hl:fetch'import { now } from 'hl:time'static vapid = { key = null; priv = null; subject = null; }// WebFramework hands the three settings over when it boots (and checks they belong together)static configure = (key, priv, subject) => {vapid.key = keyvapid.priv = privvapid.subject = subject}// THE BODY, RFC 8291 §3.4 + RFC 8188: header (salt 16, rs 4096, idlen 65, the server's ECDH public key)// then ONE record, plaintext + 0x02, sealed with AES-128-GCM. `uaPublic` (65 B) and `authSecret` (16 B) are// the subscription's keys.p256dh and keys.auth. `asKeys` ({ privateKey, publicKey }) and `salt` (16 B) are// made fresh for every message; they are parameters ONLY so the RFC 8291 §5 vector can be reproduced// byte for byte (the test's hook — sendPush never passes them, and no setting reaches them).static encrypt = (uaPublic, authSecret, plaintext, asKeys, salt) => {let keys = asKeys != null ? asKeys : p256Generate()let s = salt != null ? salt : p256Generate().privateKey.slice(0, 16)let secret = ecdhSharedSecret(keys.privateKey, uaPublic)if (secret == null) { return null }let keyInfo = toBytes('WebPush: info')keyInfo.append(0)keyInfo.append(uaPublic)keyInfo.append(keys.publicKey)let ikm = hkdfExpand(hkdfExtract(authSecret, secret), keyInfo, 32)let prk = hkdfExtract(s, ikm)let cekInfo = toBytes('Content-Encoding: aes128gcm')cekInfo.append(0)let nonceInfo = toBytes('Content-Encoding: nonce')nonceInfo.append(0)let padded = toBytes(plaintext)padded.append(2)let sealed = aes128gcmEncrypt(hkdfExpand(prk, cekInfo, 16), hkdfExpand(prk, nonceInfo, 12), padded, null)let body = toBytes(s)body.append(0)body.append(0)body.append(16)body.append(0)body.append(keys.publicKey.length)body.append(keys.publicKey)return body.concat(sealed)}// the VAPID JWT for one push service: aud is the endpoint's origin, exp 12 h out (the limit is 24 h)static jwt = (endpoint, priv, subject) => {let rest = endpoint.slice(endpoint.indexOf('://') + 3)let slash = rest.indexOf('/')let aud = endpoint.slice(0, endpoint.indexOf('://') + 3 + (slash < 0 ? rest.length : slash))let ms = now()let exp = (ms - ms % 1000) / 1000 + 43200let head = base64urlEncode('{"typ":"JWT","alg":"ES256"}')let claims = base64urlEncode('{"aud":' + JSON.stringify(aud) + ',"exp":' + exp + ',"sub":' + JSON.stringify(subject) + '}')return head + '.' + claims + '.' + base64urlEncode(es256Sign(priv, toBytes(head + '.' + claims)))}static urlSafe = (text) => {let i = 0while (i < text.length) {if (!'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'.includes(text[i])) { return false }i = i + 1}return true}// SEND ONE PUSH. `subscription` is what subscribePush() gave the page: { endpoint, keys = { p256dh, auth } }// (as the app stored it). `payload`: a String (its UTF-8) or Bytes, up to 3993 bytes — the worker shows// JSON text { title, body, url, tag, icon }. `opts`: ttl (seconds the service may hold it, default 86400),// urgency ('very-low' | 'low' | 'normal' | 'high'), topic (replaces an undelivered push of the same topic;// up to 32 characters of the URL-safe base64 alphabet). Answers { ok, status, gone, error }: ok is a 2xx// (201 = accepted), `gone` a 404/410 (the subscription is dead: forget it), status 0 and `error` a push// service that could not be reached (only where the caller has an `on Error(e)` handler — hl:fetch routes a// connection failure there, and without one the failure faults the call, as hl:fetch does) or a subscription// that is malformed. A missing setting is an error.static sendPush = (subscription, payload, opts) => {if (vapid.priv == null) { hlError("hl:web: sendPush needs the app's settings pushKey, pushPrivateKey and pushSubject") }let o = opts != null ? opts : {}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) }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') }let data = hlTypeName(payload) == 'Bytes' ? payload : toBytes(payload == null ? '' : payload)if (data == null || data.length > 3993) { hlError('hl:web: sendPush payload is a String or Bytes of at most 3993 bytes') }let sub = subscriptionif (sub == null || hlTypeName(sub.endpoint) != 'String' || !sub.endpoint.startsWith('https://') && !sub.endpoint.startsWith('http://') || sub.keys == null) {return { ok = false; status = 0; gone = false; error = 'the subscription has no endpoint or keys'; }}let ua = hlTypeName(sub.keys.p256dh) == 'String' ? base64urlDecode(sub.keys.p256dh) : nulllet auth = hlTypeName(sub.keys.auth) == 'String' ? base64urlDecode(sub.keys.auth) : nullif (ua == null || ua.length != 65 || auth == null || auth.length != 16) {return { ok = false; status = 0; gone = false; error = 'the subscription keys are not a 65-byte p256dh and a 16-byte auth'; }}let body = encrypt(ua, auth, data, null, null)if (body == null) { return { ok = false; status = 0; gone = false; error = 'the subscription p256dh is not a point on P-256'; } }let headers = {'authorization' = 'vapid t=' + jwt(sub.endpoint, vapid.priv, vapid.subject) + ', k=' + vapid.key'content-encoding' = 'aes128gcm''content-type' = 'application/octet-stream''ttl' = '' + (o.ttl != null ? o.ttl : 86400)}if (o.urgency != null) { headers['urgency'] = o.urgency }if (o.topic != null) { headers['topic'] = o.topic }// hl:fetch sends a String body byte for byte, and the encrypted body is no UTF-8: the raw String of the byteslet raw = __native('crypto.base64url_decode', base64urlEncode(body))let r = fetch(sub.endpoint, { method = 'POST'; headers = headers; body = raw; timeoutMs = 15000; maxRedirects = 0; })if (r == null) { return { ok = false; status = 0; gone = false; error = 'the push service could not be reached'; } }let err = r.status == 0 ? 'the push service did not answer' : nullreturn { ok = r.ok; status = r.status; gone = r.status == 404 || r.status == 410; error = err; }}
Branches
Latest commits
- e24b59a6ident#40.3: the time zone is one component (components/timezone.hl); its face changeTimeZone moves with itmre
- 8cbc5717ident#40.3: the email step is one component (components/emailstep.hl) placed by home.hl and embed.hlmre
- 6fad3bd2Merge branch 'f3-codestep' into mainIdent
- 51e387f2|||PR ident#40 the code step is one component (components/codestep.hl) placed by home.hl and embed.hl; its verify face, setCode, browserZone and verify call exist once (#40.2)mre
- c28bddeeMerge branch 'f2-shell' into mainIdent
- c3a40ff6|||PR ident#40 one shell for the app and /start (account part off on /start, #40.1); startshell.hl removed; unused signOut faces gone (#40.4)mre
- 060f3870ident#40.4: use the shell sign-out faces in regression gatesmre
- 9b94aa6aMerge branch 'f1b-cleanup' into mainIdent
- edcfce3f|||PR ident#41 ident#43 ident#44 login error page as a component (same status codes and text, pixel-identical), declarations and route wiring cleaned upmre
- 3ac85995ident#43 ident#44: plain declarations for never-reassigned lets, one envString helper, named route functions and audience rule out of project.hlmre
- c7eef14aMerge branch 'nv1-navigate' into mainIdent
- 644f9775|||PR ident#36 navigate() instead of window.location in the shell, start shell and homemre
- 4ca2f921deploy.sh: tar --hard-dereference so backups hold no hard linksmre
- 23971fb7ident#49: media queries in the language's @media formmre
- 73f4f97dident: re-vendor to hybriel day38b (mpackdb store-open fix)mre
- aa056c03ident: a startup error prints its message before exit 1 (hybriel#247)mre
- ee37a861ident#G48: gitoria's registration gets the wildcard origin of its repo addresses at load (gate tests/gitoria-origin.mjs)mre
- dc6d486fident#27: the docs gate expects the new Access entry in the main menumre
- d277633cident#27: README: identity access and the introspect endpointmre
- e999b0d3ident#27: the Access tab — one key per identity for all its apps: give access in three steps, the overview matrix, a cell's sheet (since, last use, level, rotate, revoke), the app's check POST /api/introspect, agent identities hidden from the login picker, an inbox icon in the header's icon style (gate: tests/access.mjs)mre