Sprint: pbi-55 (#156)

* ST-cmovs79lt: Schema + migratie PushSubscription model

Voeg PushSubscription model toe aan prisma/schema.prisma met
snake_case-conventie, relation field op User, en bijbehorende
migratie (push_subscriptions tabel, FK + index op user_id).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* ST-cmovs7e3o: web-push dependency + VAPID env vars feature-gated

Voeg web-push + @types/web-push toe aan package.json.
Registreer NEXT_PUBLIC_VAPID_PUBLIC_KEY, VAPID_PRIVATE_KEY,
VAPID_SUBJECT en INTERNAL_PUSH_SECRET als .optional() in lib/env.ts.
Documenteer alle vier in .env.example en README.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* ST-cmovs7jgr: lib/push-server.ts met sendPushToUser + stale-cleanup

Server-only push-lib met VAPID feature-gate, send naar alle
subscriptions van een user, en automatische cleanup bij 404/410.
Unit tests: success-pad, 410 verwijdert sub, 404 verwijdert sub,
andere errors loggen zonder delete.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* ST-cmovs7ouz: lib/push-client.ts client-side push helpers + stub actions/push.ts

Client-side helpers: isPushSupported, isIOSSafari, isStandalonePWA,
urlBase64ToUint8Array, subscribeToPush, unsubscribeFromPush.
Stub actions/push.ts zodat imports resolven (implementatie volgt
in volgende taak). Unit tests voor urlBase64ToUint8Array.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* ST-cmovs7ut4: actions/push.ts subscribeToPushAction + unsubscribeFromPushAction

Vervangt stub met volledige implementatie: requireUser via getSession,
demo-block, Zod-validatie, upsert met user_id-scoping en user-scoped
deleteMany. Tests (8): idempotentie, demo-block, unauthenticated, invalid input.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* ST-cmovs80c1: POST /api/internal/push/send met constant-time Bearer check

Route: 503 als INTERNAL_PUSH_SECRET uitstaat, 401 bij verkeerd secret
(timingSafeEqual), 400 bij invalid JSON, 422 bij Zod-fout, 204 bij succes.
push-server.ts: env-import vervangen door process.env om SESSION_SECRET
validatie tijdens build te omzeilen. Tests aangepast.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* ST-cmovs862j: Admin test-send route + public/sw.js service worker

POST /api/internal/push/test-send: requireAdmin check (redirect bij
niet-admin), optioneel body met defaults, roept sendPushToUser aan, 204.
public/sw.js: push-handler met showNotification, notificationclick met
same-origin guard, focus bestaand venster of openWindow.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* ST-cmovs8jvq: PushToggle component met 3 states + iOS-banner

Client component met states loading/unsupported/ios-needs-install/
denied/subscribed/unsubscribed. useEffect detecteert initial status,
permission-prompt alleen via user-click. iOS-banner NL, denied-uitleg,
subscribe/unsubscribe knoppen met sonner-toasts.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* ST-cmovs8psg: notifications-sheet + iOS meta-tags in layout

notifications-sheet.tsx: PushToggle onderin met sectie
'Notificatie-instellingen' en visuele scheidslijn.
app/layout.tsx: appleWebApp.capable, statusBarStyle en
mobile-web-app-capable meta-tags toegevoegd via Next.js Metadata API.
manifest.json had al display: standalone.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* ST-cmovs8vxj: docs/patterns/web-push.md pattern-documentatie

Architectuur-diagram, payload-shape, foutcodes, VAPID-config,
iOS-quirks, demo-users blokkade, trigger-voorbeelden (server +
HTTP) en admin-testroute curl-voorbeeld.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
Janpeter Visser 2026-05-07 21:46:01 +02:00 committed by GitHub
parent 25bd59c0b9
commit 7ae8a24372
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
22 changed files with 984 additions and 167 deletions

View file

@ -80,6 +80,7 @@ Auto-generated on 2026-05-07 from front-matter and headings.
| [Server Action](./patterns/server-action.md) | active | 2026-05-03 |
| [Float sort_order (drag-and-drop volgorde)](./patterns/sort-order.md) | active | 2026-05-03 |
| [Story met UI-component](./patterns/story-with-ui-component.md) | active | 2026-05-03 |
| [Web Push](./patterns/web-push.md) | active | 2026-05-07 |
| [Zustand optimistische update + rollback](./patterns/zustand-optimistic.md) | active | 2026-05-03 |
## Other Docs

111
docs/patterns/web-push.md Normal file
View file

@ -0,0 +1,111 @@
---
title: "Web Push"
status: active
audience: [ai-agent, contributor]
language: nl
last_updated: 2026-05-07
when_to_read: "When sending push notifications from the server or MCP layer, or when troubleshooting PWA push on iOS."
---
# Patroon: Web Push
## Wat & wanneer
Gebruik Web Push voor OS-niveau notificaties die ook verschijnen wanneer de browser-tab gesloten is (b.v. Claude-vragen, sprint-completion). Gebruik het **niet** voor in-app realtime feedback — daarvoor dient de SSE/realtime/notifications-stack (`stores/notifications-store`).
## Architectuur
```
MCP / cron
POST /api/internal/push/send ← Bearer: INTERNAL_PUSH_SECRET
lib/push-server.ts → sendPushToUser(userId, payload)
│ • VAPID-check (disabled = warn + return)
│ • prisma.pushSubscription.findMany
│ • Promise.allSettled(sendOne[])
│ • 404/410 → auto-delete stale subscription
Web Push Service (FCM / APNS)
public/sw.js → showNotification + notificationclick
```
## Payload-shape
```ts
type PushPayload = {
title: string // max 80 tekens
body: string // max 300 tekens
url: string // absoluut pad ('/dashboard') of volledige URL
tag?: string // dedupliceert notificaties met dezelfde tag
}
```
## Foutcodes
| Code | Betekenis | Actie |
|------|-----------|-------|
| 404 / 410 | Stale endpoint (browser heeft sub verwijderd) | Auto-delete in `sendOne` |
| 5xx | Tijdelijke fout push-service | Geen automatische retry in v1 — log + swallow |
| 401 (send-route) | Verkeerd of ontbrekend Bearer-secret | Check `INTERNAL_PUSH_SECRET` |
| 422 (send-route) | Ongeldige body | Zie payload-shape hierboven |
| 503 (send-route) | `INTERNAL_PUSH_SECRET` niet geconfigureerd | Zet env-var |
## VAPID-configuratie
Genereer sleutels eenmalig:
```bash
npx web-push generate-vapid-keys
```
Zet in `.env.local`:
```bash
NEXT_PUBLIC_VAPID_PUBLIC_KEY="<public key>"
VAPID_PRIVATE_KEY="<private key>"
VAPID_SUBJECT="mailto:admin@example.com"
INTERNAL_PUSH_SECRET="<min 32 chars, openssl rand -base64 32>"
```
Als de VAPID-envs ontbreken, returnt `sendPushToUser` vroeg met een `console.warn`; de app crasht **niet**.
## iOS-quirks
- Vereist iOS 16.4+ (Safari 16.4).
- De gebruiker moet de app eerst via **Zet op beginscherm** als PWA installeren. Push werkt niet vanuit een normale Safari-tab.
- In de EU (iOS 17.4+ na DMA) worden meldingen door Apple beperkt voor alternatieve browser-engines; test op Safari specifiek.
- `isIOSSafari()` + `!isStandalonePWA()``PushToggle` toont de installatie-banner in plaats van een toggle.
## Demo-users
`subscribeToPushAction` controleert `session.isDemo` en returnt zonder schrijven. Demo-gebruikers kunnen zich dus niet aanmelden voor push.
## Triggeren vanuit MCP of server-code
```ts
// Directe server-aanroep (binnen Next.js):
import { sendPushToUser } from '@/lib/push-server'
await sendPushToUser(userId, { title: 'Vraag van Claude', body: question, url: `/products/${productId}` })
// Vanuit MCP / externe service (HTTP):
await fetch(`${BASE_URL}/api/internal/push/send`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${INTERNAL_PUSH_SECRET}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({ userId, payload: { title, body, url } }),
})
// 204 = verzonden, 503 = VAPID niet geconfigureerd
```
## Admin testroute
```bash
curl -X POST https://<host>/api/internal/push/test-send \
-H "Cookie: <admin session cookie>"
# Vereist ingelogde admin-sessie; stuurt push naar eigen account.
```