nmor/the-claude-council/web-push-notifications

Claude Code and agent skill by nmor/the-claude-council

Trust tier 2
  • community
LLM review pending
Source check pending

Checking that the SKILL.md file is still in the repository.

VAPID-signed Web Push (RFC 8030, 8291, 8292) — subscribe lifecycle, endpoint hashing, payload size cap, pushsubscriptionchange routing, and how to wire alarms / notifications across browser + service worker.

Install

npx vskill@latest install nmor/the-claude-council/web-push-notifications

SKILL.md

The same SKILL.md was published earlier as nmor/the-claude-council/web-push-notifications.

Web Push + VAPID

Size budget: 18 KB — token-budget.mjs --check.

Companion skill to provider-research (RFC 8030, 8291, 8292 are the canonical sources). Activates whenever Web Push code is touched — backend send, service worker subscribe / push event, frontend register composable.

Required reading

  • RFC 8030 — Generic Event Delivery (HTTP push semantics, TTL,

prefer, urgency).

  • RFC 8291 — Message Encryption for Web Push (aes128gcm content

encoding).

  • RFC 8292 — VAPID (server identification).
  • W3C Push API — subscription lifecycle, pushsubscriptionchange.
  • Provider-specific endpoint domains: FCM (fcm.googleapis.com),

Mozilla autopush (updates.push.services.mozilla.com), Apple (web.push.apple.com), WNS (*.notify.windows.com).

For a fresh integration: refresh docs/provider-research/web-push-vapid.md before any change.

Hard rules

1. Backend store hashes the endpoint, not the URL

The endpoint URL is sensitive (it's a push capability the server side can revoke OR replay). Store endpoint_hash = sha256(endpoint) as the SK on the subscriptions table. The full endpoint is encrypted via piiEncryption.ts if you ever need to read it back. The hash is what you compare on subscribe / unsubscribe.

ts
const endpointHash = Buffer.from(
await crypto.subtle.digest("SHA-256", new TextEncoder().encode(endpoint)),
).toString("hex");
2. Payload size cap pre-encryption

RFC 8030 + the FCM-class providers cap the encrypted body at roughly 4 KiB. The aes128gcm wrapping adds ~100 bytes. Cap the plaintext at 3 KiB BEFORE handing to web-push.sendNotification to leave headroom; reject larger payloads with a typed error so the caller can shorten the message rather than silently failing.

ts
const MAX_PUSH_PAYLOAD_BYTES = 3 * 1024;
if (Buffer.byteLength(JSON.stringify(payload), "utf8") > MAX_PUSH_PAYLOAD_BYTES) {
return { ok: false, reason: "payload_too_large" };
}
3. Endpoint-allowlist on subscribe

Only accept subscriptions whose endpoint host is in the known list:

ts
const ALLOWED_PUSH_HOSTS = [
"fcm.googleapis.com",
"updates.push.services.mozilla.com",
"web.push.apple.com",
];

This blocks endpoint = http://internal-host SSRF attempts. WNS hosts are wildcarded — match by .endsWith(".notify.windows.com").

4. 410 Gone → purge

web-push.sendNotification throws WebPushError with statusCode === 410 when the endpoint is permanently dead (user disabled notifications, removed app, etc.). The send path MUST delete the row from the subscriptions table on 410 — keeping dead endpoints in the table burns send-quota every alarm fire and never recovers.

statusCode === 404 (FCM-specific) gets the same treatment.

5. pushsubscriptionchange routing

When the browser rotates the endpoint (push server migration, key rotation, user logged out then back in), the SW receives a pushsubscriptionchange event. The SW cannot directly talk to the backend with auth — it posts a message to the page, which calls the authenticated /api/push/subscribe endpoint with the new subscription.

ts
// sw.js
self.addEventListener("pushsubscriptionchange", (event) => {
event.waitUntil((async () => {
const sub = await self.registration.pushManager.getSubscription();
if (!sub) return;
const clients = await self.clients.matchAll({ includeUncontrolled: true });
for (const client of clients) {
client.postMessage({ type: "app:push-resubscribe", subscription: sub.toJSON() });
}
})());
});
// useWebPushRegister.ts — page handler
navigator.serviceWorker.addEventListener("message", async (event) => {
if (event.data?.type !== "app:push-resubscribe") return;
await apiPost("/api/push/subscribe", { subscription: event.data.subscription });
});

Without the page-side handler the SW posts into a void and Web Push silently stops working after the next endpoint rotation.

6. notificationclick routing

Same shape — the SW's notificationclick handler can't navigate the SPA directly (HTML5-history routes don't survive a SW-driven URL change). The SW focuses an existing client (or opens a new one) and posts the click target as a message; the page calls router.push(target) on receipt.

ts
// sw.js
self.addEventListener("notificationclick", (event) => {
event.notification.close();
const target = event.notification.data?.deepLink;
event.waitUntil((async () => {
const clients = await self.clients.matchAll({ type: "window", includeUncontrolled: true });
if (clients.length > 0) {
await clients[0].focus();
clients[0].postMessage({ type: "app:notification-click", target });
return;
}
await self.clients.openWindow(target ?? "/");
})());
});
// useWebPushRegister.ts — page handler with router
navigator.serviceWorker.addEventListener("message", (event) => {
if (event.data?.type !== "app:notification-click") return;
if (event.data.target) router.push(event.data.target).catch(handleNavError);
});

location.hash = … does NOT navigate in HTML5-history mode — must go through the router.

7. Unsubscribe = backend FIRST, then browser
ts
// useWebPushRegister.ts — canonical unsubscribe
async function unsubscribe(): Promise<void> {
const sub = await registration.pushManager.getSubscription();
if (!sub) return;
const endpointHash = await hashEndpoint(sub.endpoint);
await apiDelete(`/api/push/subscribe/${endpointHash}`).catch((err) =>
log.warn("push unsubscribe API call failed; continuing browser-side", { error: stringifyError(err) }),
);
await sub.unsubscribe();
}

Browser-side unsubscribe-only leaves the backend sending to a dead endpoint until 410 cleanup kicks in. Backend-first means the row is purged immediately.

8. AudioContext unlock for in-page alarms

WS-delivered alarms in an open tab play through an AudioContext that the browser keeps suspended until the first user gesture. If the alarm fires while the context is suspended, the audio is silent. The composable must:

  1. Try to play.
  2. If AudioContext.state === "suspended", surface a "Tap to

enable alarm sounds" toast that resumes on click.

  1. Persist audioContextUnlocked: true in localStorage once

unlocked so subsequent alarms play without prompting.

9. VAPID key rotation

The VAPID keypair lives in Secrets Manager. Rotation:

  1. Generate new keypair.
  2. Update Secrets Manager.
  3. New subscribes immediately use the new key.
  4. Existing subscribes work for their TTL window.
  5. After 30 days, force re-subscribe of any subscription older than

the rotation date.

Document the rotation procedure in the project runbook.

Test contract

  • Subscribe: payload validated, endpoint host allowlisted, hash

computed, row written.

  • Send happy-path: payload under cap, send returns 201.
  • Send oversized: typed error returned, no provider call.
  • 410 Gone: row purged, next alarm doesn't try the dead endpoint.
  • 404 Not Found: same treatment.
  • pushsubscriptionchange: SW message reaches page, page re-subs

via authenticated POST.

  • notificationclick: SW message reaches page, router navigates.
  • Unsubscribe: backend DELETE called before browser unsubscribe.

Cross-references

  • ~/.claude/rules/common/official-docs-first.md — RFC + W3C

citations.

  • provider-research skill — the workflow.
  • fire-and-forget skill — the canonical shape for the

send-side-effect that doesn't block alarm dispatch.

  • ~/.claude/rules-library/common/no-discards.md — pushSubscription errors

must surface via typed error / log, never silently swallowed.

Purpose

Principal-level browser + mobile push: W3C Push API + Service Worker registration, VAPID identity (RFC 8292), aes128gcm payload encryption (RFC 8291), push protocol contract (RFC 8030), per- endpoint subscription lifecycle (subscribe → 410 Gone → cleanup), FCM (Android + web), APNs (iOS), urgency + TTL semantics, focus state detection (don't alert what the user is reading), unsubscribe discipline + privacy notice, payload size limits (~4 KB), and the fire-and-forget dispatch shape that decouples send from acknowledgement.

Negative scope (NOT what this skill covers):

  • In-app banner / toast UI rendering — out
  • Email / SMS notifications — separate channels
  • Real-time WebSocket / SSE push — different protocol
  • Native iOS / Android push outside web context — see platform-

specific skills (APNs / FCM native)

  • Marketing campaign orchestration — out (consent + frequency mgmt

belongs to a separate skill)

When NOT to use

  • Server-to-server fan-out — use SNS / Pub/Sub directly
  • Real-time in-app updates while the user has the tab focused

(WebSocket / SSE are lower-latency)

  • One-off transactional emails — use email channel
  • Users who haven't granted permission — never auto-prompt; ask in

context of explicit user intent

Standards Cited

  • RFC 8030 (Web Push Protocol) — generic delivery contract
  • RFC 8291 (Web Push Encryption — aes128gcm) — payload encryption
  • RFC 8292 (VAPID — Voluntary Application Server Identification) —

identity + sender authentication

  • W3C Push API (w3.org/TR/push-api/) — browser-side subscription

API

  • W3C Service Workers (w3.org/TR/service-workers/) — receive +

display side

  • W3C Notifications API (w3.org/TR/notifications/) — display

semantics

  • Firebase Cloud Messaging (FCM) v1 API — Android + web
  • Apple Push Notification service (APNs) HTTP/2 API — iOS
  • OWASP ASVS 4.0.3 §3.5 (Token-based Session Management) —

VAPID key rotation

  • OWASP ASVS 4.0.3 §13.1 (Generic Web Service Security) —

endpoint validation

  • GDPR Article 7 (Consent) — opt-in record + revocation

Anti-Patterns

PatternWhy badCorrect alternative
Auto-prompt for permission on first visitBrowsers downrank pushy sites; users deny permanentlyPrompt only after a clear user-intent moment (signup complete, opt-in toggle, etc.)
Treating 410 Gone as a transient errorEndpoint already revoked; keep retrying = wasted requestsMark subscription invalid + remove from DB
Storing the entire PushSubscription JSON without normalisationCross-field updates are painfulNormalise: endpoint, p256dh, auth per record
Sending unencrypted payloadBrowser drops the message; not all push services allow plaintextAlways encrypt per RFC 8291 (aes128gcm)
No urgency headerDevices may delay / batch; battery saving hides urgent alertsSet Urgency: high only for genuinely time-sensitive; normal default
No TTL headerPush service holds undeliverable messages indefinitelySet realistic TTL (e.g., 24h for chat, 4h for ride status)
Notifying while the user has the tab focusedAnnoyance + UX violationCheck Window.focus / visibilityState before notifying
Reusing VAPID keys across environmentsKey rotation in prod requires re-subscribing all usersSeparate keys per environment + scheduled rotation plan
Marketing pushes without unsubscribe pathGDPR / CAN-SPAM violationEvery push has user-visible opt-out + consent record
Treating push delivery as guaranteedBest-effort by design; user may be offline 7 daysPair with email / in-app inbox for durability
Service worker scope mismatchSubscription tied to wrong scope; pushes lost on URL changeRegister SW at root scope (or document scope strategy)

Verification Checklist

This is the start of the file. Read the full SKILL.md on GitHub.

Security

  • Security scanPassed, 100 of 100Pattern checks on the skill's files.
  • Model reviewNot runA model review is scheduled for the next rescan.

Quality evaluation

  • Task evaluationNot runNo evaluation yet. Run one in Skill Studio.

Source

Popularity

Repository stars
12
Repository forks
2
7-day trend score
18

Stars and forks are for the whole GitHub repository, not this skill alone. Not refreshed yet.

Works with

Any agent vskill installs to: 56 targets in all. These 39 have a page on this site.

  • Claude Code
  • Cursor
  • GitHub Copilot
  • Windsurf
  • Codex
  • Gemini CLI
  • Cline
  • Amp
  • Roo Code
  • Goose
  • Continue
  • Kilo Code
  • Junie
  • Trae
  • OpenHands
  • Qwen Code
  • AI Agent
  • Tabnine Chat
  • Sourcegraph Cody
  • Amazon Q
  • Firebase Genkit
  • Sweep
  • Devin
  • Phind
  • Mentat
  • Claude Desktop
  • Aider
  • GPT Pilot
  • Plandex
  • bolt.new
  • v0
  • Replit Agent
  • Anse
  • TypingMind
  • BetterChatGPT
  • LibreChat
  • Warp AI
  • Pieces
  • Fig AI
Embed badge
vskill VERIFIED badge
[![vskill VERIFIED](https://verified-skill.com/api/v1/skills/nmor/the-claude-council/web-push-notifications/badge)](https://verified-skill.com/skills/nmor/the-claude-council/web-push-notifications)

Something wrong with this skill or its page? Tell us.