R9 Web Push in decePub: one subscription per persona, each with its own token and registration
Build / Build (push) Successful in 56s

Settings gets "Notifications on this device" (PushEditor): personas, alerts in four groups, policy, a test
notification, after a one-time notice of what the push service learns. Each persona ticked gets its own service
worker registration (push-worker.js at push/{slot}/), so its own endpoint and keys, subscribed with its own token
(IHttpService's *As); nothing PrivaPub stores ties two personas together and the worker never reads the payload's
token. PushService follows the tokens (re-subscribing after a renewal), reconciles at every session start, turns
off before sign-out and drops deleted or suspended personas. A click opens that persona's notifications; the app
badge counts the unread ones. Exchanges now ask for the push scope.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WpVCoDeM1qUTRp4fXQdfof
This commit is contained in:
thepraandClaude Opus 5.5 committed 2026-10-18 09:50:46 +02:00
1 parent d33697e3fc
commit ab17959ed4
29 files changed
+2047 -67

No files matched your search

+175
View File
@@ -0,0 +1,175 @@
// Web Push in this browser (Services/PushService.cs, imported on demand like js/feed.js). Each persona the reader turns
// notifications on for gets a service worker registration of its own: wwwroot/push-worker.js at the scope push/{slot}/,
// where the slot is a random name this device keeps. Its push subscription is that persona's alone, with its own
// endpoint and keys, so nothing PrivaPub stores ties two personas of one login together, and the worker knows the
// persona from its scope without ever reading the payload's token.
//
// What fails as browsers fail (no permission, a push service that refused) comes back as { error }; what fails
// unexpectedly is also reported through window.logFromJs.
const workerUrl = new URL("../push-worker.js", import.meta.url).href
const scopesRoot = new URL("../push/", import.meta.url).href
const scopeOf = slot => `${scopesRoot}${slot}/`
function report(e, where) {
console.error(e)
window.logFromJs?.(e?.message ?? String(e), `push.${where}`)
}
function ios() {
return /iPad|iPhone|iPod/.test(navigator.userAgent) || (navigator.platform === "MacIntel" && navigator.maxTouchPoints > 1)
}
function installed() {
return window.matchMedia("(display-mode: standalone)").matches || navigator.standalone === true
}
// Whether this browser can be pushed to at all, why not, and what the reader allowed: default, granted or denied. On an
// iPhone or iPad, Safari offers Web Push only to the app added to the Home Screen and opened from there.
export function support() {
try {
const permission = typeof Notification == "undefined" ? "default" : Notification.permission
if (!window.isSecureContext)
return { supported: false, reason: "insecure", permission }
if (!("serviceWorker" in navigator) || !("PushManager" in window) || typeof Notification == "undefined" || !("showNotification" in ServiceWorkerRegistration.prototype))
return { supported: false, reason: ios() && !installed() ? "ios-install" : "unsupported", permission }
return { supported: true, reason: null, permission }
} catch (e) {
report(e, "support")
return { supported: false, reason: "unsupported", permission: "default" }
}
}
// Asks the reader once (the browser's own prompt, after a click); what the browser already knows is answered at once.
export async function requestPermission() {
try {
if (Notification.permission !== "default")
return Notification.permission
return await Notification.requestPermission()
} catch (e) {
report(e, "requestPermission")
return typeof Notification == "undefined" ? "default" : Notification.permission
}
}
async function registrationOf(slot, create) {
const scope = scopeOf(slot)
// (getRegistration(url) answers the registration that controls the URL: the app's own one when this one is missing)
let registration = (await navigator.serviceWorker.getRegistrations()).find(r => r.scope === scope)
if (!registration && create)
registration = await navigator.serviceWorker.register(workerUrl, { scope, updateViaCache: "none" })
if (registration)
await activated(registration)
return registration
}
// a push subscription needs an active worker
function activated(registration) {
return new Promise(resolve => {
const worker = registration.installing ?? registration.waiting
if (registration.active || !worker)
return resolve()
const settle = () => {
if (worker.state === "activated" || worker.state === "redundant")
resolve()
}
worker.addEventListener("statechange", settle)
setTimeout(resolve, 10000)
})
}
function fromBase64Url(text) {
const normal = text.replace(/=+$/, "").replace(/-/g, "+").replace(/_/g, "/")
const raw = atob(normal + "===".slice((normal.length + 3) % 4))
return Uint8Array.from(raw, c => c.charCodeAt(0))
}
function sameKey(buffer, bytes) {
// a browser that doesn't say which key it subscribed with is taken at its word
if (!buffer)
return true
const held = new Uint8Array(buffer)
return held.length === bytes.length && held.every((value, i) => value === bytes[i])
}
function describe(subscription) {
const keys = subscription.toJSON().keys ?? {}
const encodings = PushManager.supportedContentEncodings
return {
endpoint: subscription.endpoint,
p256dh: keys.p256dh ?? null,
auth: keys.auth ?? null,
// RFC 8291's aes128gcm, which every browser that pushes decrypts; the aesgcm draft only where it is all there is
standard: !Array.isArray(encodings) || encodings.includes("aes128gcm"),
error: null
}
}
// The persona's subscription in this browser, made (with its registration) when there is none, and made again when it
// was made with another server key. Its endpoint and its keys as URL-safe base64.
export async function subscribe(slot, serverKey) {
try {
if (Notification.permission !== "granted")
return { error: `permission ${Notification.permission}` }
const key = fromBase64Url(serverKey)
const registration = await registrationOf(slot, true)
let subscription = await registration.pushManager.getSubscription()
if (subscription && !sameKey(subscription.options?.applicationServerKey, key)) {
await subscription.unsubscribe()
subscription = null
}
subscription ??= await registration.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: key })
return describe(subscription)
} catch (e) {
console.error(e)
return { error: e?.message ?? String(e) }
}
}
// The persona's subscription and its registration go: the push service forgets the endpoint, and refuses PrivaPub what it
// would still send there.
export async function unsubscribe(slot) {
try {
const registration = await registrationOf(slot, false)
if (!registration)
return true
const subscription = await registration.pushManager.getSubscription()
await subscription?.unsubscribe()
return await registration.unregister()
} catch (e) {
report(e, "unsubscribe")
return false
}
}
// The slots this browser holds registrations for, so the app drops those it no longer knows (a device whose storage was
// cleared would otherwise keep showing what PrivaPub pushes).
export async function slots() {
try {
if (!("serviceWorker" in navigator))
return []
return (await navigator.serviceWorker.getRegistrations())
.map(r => r.scope)
.filter(scope => scope.startsWith(scopesRoot))
.map(scope => scope.slice(scopesRoot.length).replace(/\/$/, ""))
.filter(name => name.length > 0)
} catch (e) {
report(e, "slots")
return []
}
}
// A notification shown by the persona's registration alone, nothing sent anywhere: it shows how they will look, and its
// click goes where theirs would.
export async function test(slot, title, body) {
try {
const registration = await registrationOf(slot, false)
if (!registration || Notification.permission !== "granted")
return false
await registration.showNotification(title, { body, tag: "decepub-test", icon: new URL("../imgs/icon-192.png", import.meta.url).href, data: {} })
return true
} catch (e) {
report(e, "test")
return false
}
}
+28 -2
View File
@@ -49,9 +49,13 @@ window.isOnline = async () => {
window.logFromJs(e.message, "isOnline")
}
}
// The installed app's badge: the current persona's unread notifications (Index.razor). Browsers without the Badging API
// (Firefox, or a tab that isn't installed) show none, and say nothing about it.
window.setAppBadge = (counter) => {
try {
navigator.setAppBadge(counter)
if (typeof navigator.setAppBadge != "function")
return
navigator.setAppBadge(counter)?.catch?.(e => console.debug(e))
} catch (e) {
console.error(e)
window.logFromJs(e.message, "setAppBadge")
@@ -59,12 +63,34 @@ window.setAppBadge = (counter) => {
}
window.clearAppBadge = () => {
try {
navigator.clearAppBadge()
if (typeof navigator.clearAppBadge != "function")
return
navigator.clearAppBadge()?.catch?.(e => console.debug(e))
} catch (e) {
console.error(e)
window.logFromJs(e.message, "clearAppBadge")
}
}
// A click on a Web Push notification while decePub is open: the persona's worker (push-worker.js) focuses this tab and
// says which of its registrations showed it, and the app opens that persona's notifications (CascadingState.PushOpened).
// Only this origin's workers can post here.
try {
if ("serviceWorker" in navigator) {
navigator.serviceWorker.addEventListener("message", event => {
try {
if (event.data?.type !== "decepub-push-open" || typeof event.data.slot != "string")
return
window.cascadingStateInstance?.invokeMethodAsync("PushOpened", event.data.slot)
} catch (e) {
console.error(e)
window.logFromJs(e.message, "pushOpened")
}
})
navigator.serviceWorker.startMessages()
}
} catch (e) {
console.error(e)
}
// On a touch screen a tap on a post (not on its links, controls or menus, and not ending a text selection) opens its
// thread, through the card's own thread link (Content.razor, data-thread-link), which Blazor's router takes.
document.addEventListener("click", event => {
+101
View File
@@ -0,0 +1,101 @@
// The service worker of one persona's Web Push subscription. wwwroot/js/push.js registers this script once per persona
// the reader turns notifications on for, at the scope push/{slot}/ (a random name this device keeps in localStorage's
// PushDevice, Services/PushService.cs), so each persona has a push subscription of its own: its own endpoint and keys,
// which PrivaPub stores with that persona's token alone. The same file serves development and published builds; the
// app's own workers (service-worker.js, service-worker.published.js) receive no pushes. It controls no page, so it has no
// fetch handler.
//
// A push shows the payload's title, body and icon, tagged with its notification id so a repeat replaces it. The payload
// is Mastodon's, so it also carries the subscription's access token: that is never read, kept, shown or passed on here.
// A click opens decePub on the notifications of the persona this registration is for: an open decePub tab is focused and
// told which (main.js, CascadingState.PushOpened), else a new one opens at ?notifications=1&push={slot}.
const appRoot = new URL("./", self.location).href
const slot = new URL(self.registration.scope).pathname.split("/").filter(part => part.length > 0).pop()
self.addEventListener("install", () => self.skipWaiting())
self.addEventListener("push", event => event.waitUntil(show(event.data)))
self.addEventListener("notificationclick", event => {
event.notification.close()
event.waitUntil(open())
})
// the push service changed the subscription: the same key subscribes again here, and the app tells PrivaPub the new
// endpoint the next time it starts (PushService.Reconcile), since this worker holds no token to tell it with
self.addEventListener("pushsubscriptionchange", event => event.waitUntil(renew(event)))
async function show(data) {
let title = "decePub"
const options = { icon: appRoot + "imgs/icon-192.png", timestamp: Date.now(), data: {} }
try {
const payload = data ? data.json() : null
if (payload && typeof payload == "object") {
if (typeof payload.title == "string" && payload.title.length > 0)
title = payload.title
if (typeof payload.body == "string")
options.body = payload.body
if (isWebAddress(payload.icon))
options.icon = payload.icon
if (payload.notification_id != null)
options.tag = String(payload.notification_id)
if (typeof payload.preferred_locale == "string")
options.lang = payload.preferred_locale
options.data = { notificationId: options.tag ?? null, type: typeof payload.notification_type == "string" ? payload.notification_type : null }
}
} catch (e) {
console.error(e)
}
// a push always shows something (userVisibleOnly): one that can't be read shows decePub's name alone
await self.registration.showNotification(title, options)
try {
// the count is the app's to say (Index.razor); until it opens, a dot says something waits
await self.navigator.setAppBadge?.()
} catch (e) {
console.debug(e)
}
}
function isWebAddress(value) {
if (typeof value != "string")
return false
try {
const url = new URL(value)
return url.protocol === "https:" || url.protocol === "http:"
} catch {
return false
}
}
async function open() {
const windows = await self.clients.matchAll({ type: "window", includeUncontrolled: true })
const app = windows.filter(client => client.url.startsWith(appRoot))
const target = app.find(client => client.focused) ?? app.find(client => client.visibilityState === "visible") ?? app[0]
if (target) {
try {
await target.focus()
} catch (e) {
console.error(e)
}
// (navigate() is only for the worker that controls the tab: the app's own one does)
target.postMessage({ type: "decepub-push-open", slot })
return
}
const url = new URL(appRoot)
url.searchParams.set("notifications", "1")
url.searchParams.set("push", slot)
await self.clients.openWindow(url.href)
}
async function renew(event) {
try {
const key = event.oldSubscription?.options?.applicationServerKey
if (!key || event.newSubscription)
return
await self.registration.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: key })
} catch (e) {
console.error(e)
}
}
+2
View File
@@ -1,4 +1,6 @@
// In development, always fetch from the network and do not enable offline support.
// This is because caching would make development more difficult (changes would not
// be reflected on the first load after each change).
// Web Push has workers of its own, one registration per persona at push/{slot}/ (push-worker.js, the same file in
// development and published builds): this worker receives no pushes.
self.addEventListener('fetch', () => { });
+4 -2
View File
@@ -9,8 +9,10 @@ self.addEventListener('fetch', event => event.respondWith(onFetch(event)));
const cacheNamePrefix = 'offline-cache-';
const cacheName = `${cacheNamePrefix}${self.assetsManifest.version}`;
const offlineAssetsInclude = [ /\.dll$/, /\.pdb$/, /\.wasm/, /\.html/, /\.js$/, /\.json$/, /\.css$/, /\.woff$/, /\.png$/, /\.jpe?g$/, /\.gif$/, /\.ico$/, /\.blat$/, /\.dat$/ ];
// The globe (4 MB of script and textures) is fetched when the feed first shows it, never precached.
const offlineAssetsExclude = [ /^service-worker\.js$/, /^vendor\/globe\// ];
// The globe (4 MB of script and textures) is fetched when the feed first shows it, never precached. The personas' Web Push
// worker (push-worker.js, its own registrations at push/{slot}/) is fetched by the browser as a worker script, which no
// service worker serves, so it isn't precached either; this worker receives no pushes.
const offlineAssetsExclude = [ /^service-worker\.js$/, /^push-worker\.js$/, /^vendor\/globe\// ];
async function onInstall(event) {
console.info('Service worker: Install');