diff --git a/.env.example b/.env.example index d981a5b..291c7b0 100644 --- a/.env.example +++ b/.env.example @@ -15,6 +15,16 @@ NODE_ENV="development" # Generate with: openssl rand -base64 32 CRON_SECRET="" +# PBI-55 — Web Push (VAPID). All optional; app starts without these. +# Generate keys with: npx web-push generate-vapid-keys +NEXT_PUBLIC_VAPID_PUBLIC_KEY="" +VAPID_PRIVATE_KEY="" +# Must start with mailto: e.g. mailto:admin@example.com +VAPID_SUBJECT="mailto:admin@example.com" +# Shared secret for POST /api/internal/push/send — min 32 chars +# Generate with: openssl rand -base64 32 +INTERNAL_PUSH_SECRET="" + # v1-readiness item 2 — Sentry error monitoring. # Optional. Without DSN, the SDK is a no-op (no network, no overhead). # Get a DSN at https://sentry.io → Project → Settings → Client Keys (DSN). diff --git a/README.md b/README.md index 4de7224..2f154e8 100644 --- a/README.md +++ b/README.md @@ -202,6 +202,10 @@ Zie [.env.example](.env.example). | `DIRECT_URL` | Nee | Directe Neon connection string voor migraties (Prisma `directUrl`) | | `SESSION_SECRET` | Ja | Minimaal 32 tekens; gebruikt door iron-session | | `CRON_SECRET` | Productie | Bearer-secret voor `/api/cron/*` routes — required als crons aan staan | +| `NEXT_PUBLIC_VAPID_PUBLIC_KEY` | Nee | VAPID public key voor Web Push — genereer met `npx web-push generate-vapid-keys` | +| `VAPID_PRIVATE_KEY` | Nee | VAPID private key voor Web Push | +| `VAPID_SUBJECT` | Nee | Contact URI voor Web Push (bijv. `mailto:admin@example.com`) | +| `INTERNAL_PUSH_SECRET` | Nee | Bearer-secret voor `/api/internal/push/*` routes (min 32 tekens) | | `NEXT_PUBLIC_SENTRY_DSN` | Nee | Sentry DSN — zonder is de SDK een no-op | | `SENTRY_ORG` / `SENTRY_PROJECT` / `SENTRY_AUTH_TOKEN` | Nee | Source-map upload tijdens build | | `NODE_ENV` | Nee | Wordt door Node/Vercel gezet | diff --git a/__tests__/actions/push.test.ts b/__tests__/actions/push.test.ts new file mode 100644 index 0000000..1e74a22 --- /dev/null +++ b/__tests__/actions/push.test.ts @@ -0,0 +1,102 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest' + +const { mockGetSession } = vi.hoisted(() => ({ + mockGetSession: vi.fn(), +})) + +vi.mock('@/lib/auth', () => ({ + getSession: mockGetSession, +})) + +const { mockUpsert, mockDeleteMany } = vi.hoisted(() => ({ + mockUpsert: vi.fn(), + mockDeleteMany: vi.fn(), +})) + +vi.mock('@/lib/prisma', () => ({ + prisma: { + pushSubscription: { + upsert: mockUpsert, + deleteMany: mockDeleteMany, + }, + }, +})) + +import { subscribeToPushAction, unsubscribeFromPushAction } from '@/actions/push' + +const VALID_INPUT = { + endpoint: 'https://push.example.com/subscription/abc123', + keys: { p256dh: 'aBcDeFgH', auth: 'xYzAbC' }, +} + +const SESSION_USER = { userId: 'user-1', isDemo: false } +const SESSION_DEMO = { userId: 'demo-1', isDemo: true } + +beforeEach(() => { + vi.clearAllMocks() + mockUpsert.mockResolvedValue({}) + mockDeleteMany.mockResolvedValue({ count: 1 }) +}) + +describe('subscribeToPushAction', () => { + it('upserts subscription for authenticated user', async () => { + mockGetSession.mockResolvedValue(SESSION_USER) + await subscribeToPushAction(VALID_INPUT) + expect(mockUpsert).toHaveBeenCalledWith( + expect.objectContaining({ + where: { endpoint: VALID_INPUT.endpoint }, + create: expect.objectContaining({ user_id: 'user-1', endpoint: VALID_INPUT.endpoint }), + }) + ) + }) + + it('is idempotent — calling twice upserts twice without error', async () => { + mockGetSession.mockResolvedValue(SESSION_USER) + await subscribeToPushAction(VALID_INPUT) + await subscribeToPushAction(VALID_INPUT) + expect(mockUpsert).toHaveBeenCalledTimes(2) + }) + + it('returns without writing for demo user', async () => { + mockGetSession.mockResolvedValue(SESSION_DEMO) + await subscribeToPushAction(VALID_INPUT) + expect(mockUpsert).not.toHaveBeenCalled() + }) + + it('returns without writing when not authenticated', async () => { + mockGetSession.mockResolvedValue({}) + await subscribeToPushAction(VALID_INPUT) + expect(mockUpsert).not.toHaveBeenCalled() + }) + + it('returns without writing for invalid input', async () => { + mockGetSession.mockResolvedValue(SESSION_USER) + // @ts-expect-error intentionally invalid + await subscribeToPushAction({ endpoint: 'not-a-url', keys: {} }) + expect(mockUpsert).not.toHaveBeenCalled() + }) +}) + +describe('unsubscribeFromPushAction', () => { + it('deletes subscription scoped to user_id', async () => { + mockGetSession.mockResolvedValue(SESSION_USER) + await unsubscribeFromPushAction({ endpoint: VALID_INPUT.endpoint }) + expect(mockDeleteMany).toHaveBeenCalledWith({ + where: { endpoint: VALID_INPUT.endpoint, user_id: 'user-1' }, + }) + }) + + it('does not touch subscriptions of other users', async () => { + mockGetSession.mockResolvedValue({ userId: 'other-user', isDemo: false }) + await unsubscribeFromPushAction({ endpoint: VALID_INPUT.endpoint }) + expect(mockDeleteMany).toHaveBeenCalledWith( + expect.objectContaining({ where: expect.objectContaining({ user_id: 'other-user' }) }) + ) + }) + + it('returns without writing when not authenticated', async () => { + mockGetSession.mockResolvedValue({}) + await unsubscribeFromPushAction({ endpoint: VALID_INPUT.endpoint }) + expect(mockDeleteMany).not.toHaveBeenCalled() + }) +}) diff --git a/__tests__/api/push-send.test.ts b/__tests__/api/push-send.test.ts new file mode 100644 index 0000000..44bc616 --- /dev/null +++ b/__tests__/api/push-send.test.ts @@ -0,0 +1,75 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest' + +vi.mock('server-only', () => ({})) + +const { mockSendPushToUser } = vi.hoisted(() => ({ + mockSendPushToUser: vi.fn(), +})) + +vi.mock('@/lib/push-server', () => ({ + sendPushToUser: mockSendPushToUser, + enabled: true, +})) + +vi.hoisted(() => { + process.env.INTERNAL_PUSH_SECRET = 'a-valid-secret-that-is-at-least-32-chars' +}) + +import { POST } from '@/app/api/internal/push/send/route' + +const VALID_BODY = { + userId: 'user-1', + payload: { title: 'Hello', body: 'World', url: '/dashboard' }, +} +const SECRET = 'a-valid-secret-that-is-at-least-32-chars' + +function makeRequest(body: unknown, bearer?: string) { + return new Request('http://localhost/api/internal/push/send', { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + ...(bearer !== undefined ? { Authorization: bearer } : {}), + }, + body: JSON.stringify(body), + }) +} + +beforeEach(() => { + vi.clearAllMocks() + mockSendPushToUser.mockResolvedValue(undefined) +}) + +describe('POST /api/internal/push/send', () => { + it('returns 401 without authorization header', async () => { + const res = await POST(makeRequest(VALID_BODY)) + expect(res.status).toBe(401) + expect(mockSendPushToUser).not.toHaveBeenCalled() + }) + + it('returns 401 with wrong bearer secret', async () => { + const res = await POST(makeRequest(VALID_BODY, 'Bearer wrong-secret')) + expect(res.status).toBe(401) + }) + + it('returns 422 with invalid body', async () => { + const res = await POST(makeRequest({ userId: '', payload: {} }, `Bearer ${SECRET}`)) + expect(res.status).toBe(422) + expect(mockSendPushToUser).not.toHaveBeenCalled() + }) + + it('returns 204 and calls sendPushToUser on success', async () => { + const res = await POST(makeRequest(VALID_BODY, `Bearer ${SECRET}`)) + expect(res.status).toBe(204) + expect(mockSendPushToUser).toHaveBeenCalledWith('user-1', VALID_BODY.payload) + }) + + it('returns 400 for invalid JSON', async () => { + const req = new Request('http://localhost/api/internal/push/send', { + method: 'POST', + headers: { Authorization: `Bearer ${SECRET}`, 'Content-Type': 'application/json' }, + body: 'not-json', + }) + const res = await POST(req) + expect(res.status).toBe(400) + }) +}) diff --git a/__tests__/lib/push-client.test.ts b/__tests__/lib/push-client.test.ts new file mode 100644 index 0000000..761b6e1 --- /dev/null +++ b/__tests__/lib/push-client.test.ts @@ -0,0 +1,35 @@ +import { describe, it, expect, vi } from 'vitest' + +vi.mock('@/actions/push', () => ({ + subscribeToPushAction: vi.fn(), + unsubscribeFromPushAction: vi.fn(), +})) + +import { urlBase64ToUint8Array } from '@/lib/push-client' + +describe('urlBase64ToUint8Array', () => { + it('converts a base64url-encoded VAPID public key to Uint8Array', () => { + // 65-byte uncompressed EC public key encoded as base64url (no padding) + const base64url = 'BNMxB-LJm6XvGGiJSsYLdumcYiM7q9s_1aM9i5lI8lVzZ7GYJw1QkQFmrknwFsI4dI-e1iyvUhYHjNpHJKJD3oc' + const result = urlBase64ToUint8Array(base64url) + expect(result).toBeInstanceOf(Uint8Array) + expect(result.length).toBe(65) + expect(result[0]).toBe(0x04) // uncompressed EC point prefix + }) + + it('handles base64url with padding', () => { + // simple known vector: "hello" = aGVsbG8= in base64 + const result = urlBase64ToUint8Array('aGVsbG8') + expect(result).toBeInstanceOf(Uint8Array) + expect(Array.from(result)).toEqual([104, 101, 108, 108, 111]) // "hello" + }) + + it('converts - and _ characters correctly', () => { + // base64url uses - and _ instead of + and / + const base64standard = 'AB+/AA==' + const base64url = 'AB-_AA' + const fromStd = urlBase64ToUint8Array(base64standard) + const fromUrl = urlBase64ToUint8Array(base64url) + expect(Array.from(fromStd)).toEqual(Array.from(fromUrl)) + }) +}) diff --git a/__tests__/lib/push-server.test.ts b/__tests__/lib/push-server.test.ts new file mode 100644 index 0000000..87af039 --- /dev/null +++ b/__tests__/lib/push-server.test.ts @@ -0,0 +1,77 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest' + +vi.mock('server-only', () => ({})) + +const { mockSendNotification } = vi.hoisted(() => ({ + mockSendNotification: vi.fn(), +})) + +vi.mock('web-push', () => ({ + default: { + setVapidDetails: vi.fn(), + sendNotification: mockSendNotification, + }, +})) + +vi.hoisted(() => { + process.env.NEXT_PUBLIC_VAPID_PUBLIC_KEY = 'pk' + process.env.VAPID_PRIVATE_KEY = 'sk' + process.env.VAPID_SUBJECT = 'mailto:test@example.com' +}) + +const { mockPushSubscription } = vi.hoisted(() => ({ + mockPushSubscription: { + findMany: vi.fn(), + update: vi.fn(), + delete: vi.fn(), + }, +})) +vi.mock('@/lib/prisma', () => ({ + prisma: { pushSubscription: mockPushSubscription }, +})) + +import { sendPushToUser } from '@/lib/push-server' + +const SUB = { id: 'sub-1', endpoint: 'https://push.example.com/1', p256dh: 'p256dh', auth: 'auth' } +const PAYLOAD = { title: 'Test', body: 'Body', url: '/test' } + +beforeEach(() => { + vi.clearAllMocks() + mockPushSubscription.findMany.mockResolvedValue([SUB]) + mockPushSubscription.update.mockResolvedValue(SUB) + mockPushSubscription.delete.mockResolvedValue(SUB) +}) + +describe('sendPushToUser', () => { + it('sends notification and updates last_used_at on success', async () => { + mockSendNotification.mockResolvedValue({ statusCode: 201 }) + await sendPushToUser('user-1', PAYLOAD) + expect(mockSendNotification).toHaveBeenCalledOnce() + expect(mockPushSubscription.update).toHaveBeenCalledWith({ + where: { id: SUB.id }, + data: { last_used_at: expect.any(Date) }, + }) + }) + + it('deletes subscription on 410 (expired)', async () => { + mockSendNotification.mockRejectedValue({ statusCode: 410 }) + await sendPushToUser('user-1', PAYLOAD) + expect(mockPushSubscription.delete).toHaveBeenCalledWith({ where: { id: SUB.id } }) + expect(mockPushSubscription.update).not.toHaveBeenCalled() + }) + + it('deletes subscription on 404 (not found)', async () => { + mockSendNotification.mockRejectedValue({ statusCode: 404 }) + await sendPushToUser('user-1', PAYLOAD) + expect(mockPushSubscription.delete).toHaveBeenCalledWith({ where: { id: SUB.id } }) + }) + + it('logs error but does not delete on other error status', async () => { + const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {}) + mockSendNotification.mockRejectedValue({ statusCode: 500 }) + await sendPushToUser('user-1', PAYLOAD) + expect(mockPushSubscription.delete).not.toHaveBeenCalled() + expect(consoleSpy).toHaveBeenCalled() + consoleSpy.mockRestore() + }) +}) diff --git a/actions/push.ts b/actions/push.ts new file mode 100644 index 0000000..ec9a216 --- /dev/null +++ b/actions/push.ts @@ -0,0 +1,52 @@ +'use server' + +import { z } from 'zod' +import { prisma } from '@/lib/prisma' +import { getSession } from '@/lib/auth' + +const subscribeSchema = z.object({ + endpoint: z.string().url(), + keys: z.object({ + p256dh: z.string().min(1), + auth: z.string().min(1), + }), + userAgent: z.string().optional(), +}) + +export type SubscribeToPushInput = z.infer + +export async function subscribeToPushAction(input: SubscribeToPushInput): Promise { + const session = await getSession() + if (!session.userId) return + if (session.isDemo) return + + const parsed = subscribeSchema.safeParse(input) + if (!parsed.success) return + + const { endpoint, keys, userAgent } = parsed.data + await prisma.pushSubscription.upsert({ + where: { endpoint }, + create: { + user_id: session.userId, + endpoint, + p256dh: keys.p256dh, + auth: keys.auth, + user_agent: userAgent ?? null, + }, + update: { + user_id: session.userId, + p256dh: keys.p256dh, + auth: keys.auth, + last_used_at: new Date(), + }, + }) +} + +export async function unsubscribeFromPushAction(args: { endpoint: string }): Promise { + const session = await getSession() + if (!session.userId) return + + await prisma.pushSubscription.deleteMany({ + where: { endpoint: args.endpoint, user_id: session.userId }, + }) +} diff --git a/app/api/internal/push/send/route.ts b/app/api/internal/push/send/route.ts new file mode 100644 index 0000000..4891e59 --- /dev/null +++ b/app/api/internal/push/send/route.ts @@ -0,0 +1,48 @@ +import { timingSafeEqual } from 'crypto' +import { z } from 'zod' +import { sendPushToUser } from '@/lib/push-server' + +const schema = z.object({ + userId: z.string().min(1), + payload: z.object({ + title: z.string().max(80), + body: z.string().max(300), + url: z.string().startsWith('/').or(z.string().url()), + tag: z.string().optional(), + }), +}) + +export async function POST(req: Request) { + if (!process.env.INTERNAL_PUSH_SECRET) { + return new Response(null, { status: 503 }) + } + + const authHeader = req.headers.get('authorization') ?? '' + const expected = `Bearer ${process.env.INTERNAL_PUSH_SECRET}` + let authorized = false + try { + authorized = + authHeader.length === expected.length && + timingSafeEqual(Buffer.from(authHeader), Buffer.from(expected)) + } catch { + authorized = false + } + if (!authorized) { + return new Response(null, { status: 401 }) + } + + let body: unknown + try { + body = await req.json() + } catch { + return new Response(null, { status: 400 }) + } + + const parsed = schema.safeParse(body) + if (!parsed.success) { + return Response.json({ errors: parsed.error.flatten().fieldErrors }, { status: 422 }) + } + + await sendPushToUser(parsed.data.userId, parsed.data.payload) + return new Response(null, { status: 204 }) +} diff --git a/app/api/internal/push/test-send/route.ts b/app/api/internal/push/test-send/route.ts new file mode 100644 index 0000000..7359f46 --- /dev/null +++ b/app/api/internal/push/test-send/route.ts @@ -0,0 +1,30 @@ +import { z } from 'zod' +import { requireAdmin } from '@/lib/auth-guard' +import { sendPushToUser } from '@/lib/push-server' + +const schema = z.object({ + title: z.string().max(80).optional(), + body: z.string().max(300).optional(), + url: z.string().optional(), +}) + +export async function POST(req: Request) { + const session = await requireAdmin() + + let input: z.infer = {} + try { + const raw = await req.json() + const parsed = schema.safeParse(raw) + if (parsed.success) input = parsed.data + } catch { + // body is optional — use defaults + } + + await sendPushToUser(session.userId, { + title: input.title ?? 'Test push', + body: input.body ?? 'Admin test notification', + url: input.url ?? '/', + }) + + return new Response(null, { status: 204 }) +} diff --git a/app/layout.tsx b/app/layout.tsx index 78b08fe..5cc59ad 100644 --- a/app/layout.tsx +++ b/app/layout.tsx @@ -1,4 +1,4 @@ -import type { Metadata } from "next"; +import type { Metadata, Viewport } from "next"; import { Geist, Geist_Mono } from "next/font/google"; import { Analytics } from "@vercel/analytics/next"; import { Toaster } from "sonner"; @@ -30,6 +30,17 @@ export const metadata: Metadata = { ], }, manifest: "/manifest.json", + appleWebApp: { + capable: true, + statusBarStyle: 'default', + }, + other: { + 'mobile-web-app-capable': 'yes', + }, +}; + +export const viewport: Viewport = { + themeColor: '#ffffff', }; export default function RootLayout({ diff --git a/components/notifications/notifications-sheet.tsx b/components/notifications/notifications-sheet.tsx index 44aeaf6..a161eb2 100644 --- a/components/notifications/notifications-sheet.tsx +++ b/components/notifications/notifications-sheet.tsx @@ -17,6 +17,7 @@ import { } from '@/components/ui/sheet' import { useNotificationsStore } from '@/stores/notifications-store' import { AnswerModal } from './answer-modal' +import { PushToggle } from './push-toggle' import { cn } from '@/lib/utils' import type { NotificationQuestion } from '@/stores/notifications-store' @@ -94,6 +95,12 @@ export function NotificationsSheet({ })} )} +
+

+ Notificatie-instellingen +

+ +
diff --git a/components/notifications/push-toggle.tsx b/components/notifications/push-toggle.tsx new file mode 100644 index 0000000..0351335 --- /dev/null +++ b/components/notifications/push-toggle.tsx @@ -0,0 +1,116 @@ +'use client' + +import { useEffect, useState } from 'react' +import { toast } from 'sonner' +import { Button } from '@/components/ui/button' +import { + isPushSupported, + isIOSSafari, + isStandalonePWA, + subscribeToPush, + unsubscribeFromPush, +} from '@/lib/push-client' + +type PushStatus = + | 'loading' + | 'unsupported' + | 'ios-needs-install' + | 'denied' + | 'subscribed' + | 'unsubscribed' + +interface PushToggleProps { + vapidPublicKey?: string +} + +export function PushToggle({ vapidPublicKey }: PushToggleProps) { + const [status, setStatus] = useState('loading') + + useEffect(() => { + async function detectStatus() { + if (!isPushSupported()) { + if (isIOSSafari() && !isStandalonePWA()) { + setStatus('ios-needs-install') + } else { + setStatus('unsupported') + } + return + } + + if (Notification.permission === 'denied') { + setStatus('denied') + return + } + + try { + const reg = await navigator.serviceWorker.getRegistration() + const sub = await reg?.pushManager.getSubscription() + setStatus(sub ? 'subscribed' : 'unsubscribed') + } catch { + setStatus('unsubscribed') + } + } + + detectStatus() + }, []) + + async function handleSubscribe() { + if (!vapidPublicKey) { + toast.error('Push niet beschikbaar — VAPID-sleutel ontbreekt') + return + } + try { + await subscribeToPush(vapidPublicKey) + setStatus('subscribed') + toast.success('Push-notificaties geactiveerd') + } catch { + if (Notification.permission === 'denied') { + setStatus('denied') + } + toast.error('Kon push niet activeren. Controleer je browserinstellingen.') + } + } + + async function handleUnsubscribe() { + try { + await unsubscribeFromPush() + setStatus('unsubscribed') + toast.success('Push-notificaties uitgeschakeld') + } catch { + toast.error('Kon push niet uitschakelen') + } + } + + if (status === 'loading' || status === 'unsupported') return null + + if (status === 'ios-needs-install') { + return ( +
+ Op iPhone/iPad: tik op het delen-icoon en kies{' '} + Zet op beginscherm. Daarna kun je notificaties activeren. +
+ ) + } + + if (status === 'denied') { + return ( +

+ Notificaties zijn geblokkeerd. Schakel ze in via je browser-instellingen. +

+ ) + } + + if (status === 'unsubscribed') { + return ( + + ) + } + + return ( + + ) +} diff --git a/docs/INDEX.md b/docs/INDEX.md index 3c7670c..d391d49 100644 --- a/docs/INDEX.md +++ b/docs/INDEX.md @@ -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 diff --git a/docs/patterns/web-push.md b/docs/patterns/web-push.md new file mode 100644 index 0000000..24c83ff --- /dev/null +++ b/docs/patterns/web-push.md @@ -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="" +VAPID_PRIVATE_KEY="" +VAPID_SUBJECT="mailto:admin@example.com" +INTERNAL_PUSH_SECRET="" +``` + +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:///api/internal/push/test-send \ + -H "Cookie: " +# Vereist ingelogde admin-sessie; stuurt push naar eigen account. +``` diff --git a/lib/env.ts b/lib/env.ts index 40d0676..482cef5 100644 --- a/lib/env.ts +++ b/lib/env.ts @@ -9,6 +9,17 @@ const envSchema = z.object({ // /api/cron/expire-questions. In productie verplicht; lokaal dev mag missen // (de cron-route geeft 401 als de header niet matcht). CRON_SECRET: z.string().optional(), + // PBI-55 Web Push — alle vier .optional() zodat de app ook start zonder VAPID + NEXT_PUBLIC_VAPID_PUBLIC_KEY: z.string().optional(), + VAPID_PRIVATE_KEY: z.string().optional(), + VAPID_SUBJECT: z + .string() + .refine( + (v) => v.startsWith('mailto:') || z.string().email().safeParse(v).success, + { message: 'VAPID_SUBJECT must start with mailto: or be a valid email' } + ) + .optional(), + INTERNAL_PUSH_SECRET: z.string().min(32).optional(), }) const parsed = envSchema.safeParse(process.env) diff --git a/lib/push-client.ts b/lib/push-client.ts new file mode 100644 index 0000000..2889c7d --- /dev/null +++ b/lib/push-client.ts @@ -0,0 +1,50 @@ +import { subscribeToPushAction, unsubscribeFromPushAction } from '@/actions/push' + +export function isPushSupported(): boolean { + return typeof window !== 'undefined' && + 'serviceWorker' in navigator && + 'PushManager' in window +} + +export function isIOSSafari(): boolean { + if (typeof window === 'undefined') return false + const ua = navigator.userAgent + return /iPhone|iPad/.test(ua) && !/CriOS|FxiOS/.test(ua) +} + +export function isStandalonePWA(): boolean { + if (typeof window === 'undefined') return false + return ( + window.matchMedia('(display-mode: standalone)').matches || + !!(navigator as Navigator & { standalone?: boolean }).standalone + ) +} + +export function urlBase64ToUint8Array(base64: string): Uint8Array { + const padding = '='.repeat((4 - (base64.length % 4)) % 4) + const base64Std = (base64 + padding).replace(/-/g, '+').replace(/_/g, '/') + const rawData = atob(base64Std) + const buf = new Uint8Array(rawData.length) + for (let i = 0; i < rawData.length; i++) buf[i] = rawData.charCodeAt(i) + return buf +} + +export async function subscribeToPush(publicKey: string): Promise { + const reg = await navigator.serviceWorker.register('/sw.js', { updateViaCache: 'none' }) + await navigator.serviceWorker.ready + const sub = await reg.pushManager.subscribe({ + userVisibleOnly: true, + applicationServerKey: urlBase64ToUint8Array(publicKey), + }) + await subscribeToPushAction(sub.toJSON() as Parameters[0]) + return sub +} + +export async function unsubscribeFromPush(): Promise { + const reg = await navigator.serviceWorker.getRegistration() + const sub = await reg?.pushManager.getSubscription() + if (sub) { + await sub.unsubscribe() + await unsubscribeFromPushAction({ endpoint: sub.endpoint }) + } +} diff --git a/lib/push-server.ts b/lib/push-server.ts new file mode 100644 index 0000000..5774253 --- /dev/null +++ b/lib/push-server.ts @@ -0,0 +1,63 @@ +import 'server-only' + +import webpush from 'web-push' +import { prisma } from '@/lib/prisma' + +export type PushPayload = { + title: string + body: string + url: string + tag?: string +} + +const vapidReady = + !!process.env.NEXT_PUBLIC_VAPID_PUBLIC_KEY && + !!process.env.VAPID_PRIVATE_KEY && + !!process.env.VAPID_SUBJECT + +if (vapidReady) { + webpush.setVapidDetails( + process.env.VAPID_SUBJECT!, + process.env.NEXT_PUBLIC_VAPID_PUBLIC_KEY!, + process.env.VAPID_PRIVATE_KEY!, + ) +} + +export const enabled = vapidReady + +export async function sendPushToUser(userId: string, payload: PushPayload): Promise { + if (!enabled) { + console.warn('[push-server] VAPID not configured — skipping push for user', userId) + return + } + + const subs = await prisma.pushSubscription.findMany({ where: { user_id: userId } }) + await Promise.allSettled(subs.map((sub) => sendOne(sub, payload))) +} + +async function sendOne( + sub: { id: string; endpoint: string; p256dh: string; auth: string }, + payload: PushPayload, +): Promise { + try { + await webpush.sendNotification( + { endpoint: sub.endpoint, keys: { p256dh: sub.p256dh, auth: sub.auth } }, + JSON.stringify(payload), + ) + await prisma.pushSubscription.update({ + where: { id: sub.id }, + data: { last_used_at: new Date() }, + }) + } catch (err: unknown) { + const status = (err as { statusCode?: number }).statusCode + if (status === 404 || status === 410) { + try { + await prisma.pushSubscription.delete({ where: { id: sub.id } }) + } catch { + // already deleted by a concurrent request — ignore + } + } else { + console.error('[push-server] sendNotification error for endpoint', sub.endpoint, err) + } + } +} diff --git a/package-lock.json b/package-lock.json index cfcb587..76a8d6a 100644 --- a/package-lock.json +++ b/package-lock.json @@ -45,6 +45,7 @@ "sonner": "^1.7.4", "tailwind-merge": "^3.5.0", "tw-animate-css": "^1.4.0", + "web-push": "^3.6.7", "yaml": "^2.8.4", "zod": "^3.25.76", "zustand": "^5.0.12" @@ -60,6 +61,7 @@ "@types/pg": "^8.20.0", "@types/react": "^19", "@types/react-dom": "^19", + "@types/web-push": "^3.6.4", "@vitest/coverage-v8": "^4.1.5", "chokidar-cli": "^3.0.0", "concurrently": "^9.2.1", @@ -2159,9 +2161,6 @@ "cpu": [ "arm" ], - "libc": [ - "glibc" - ], "license": "LGPL-3.0-or-later", "optional": true, "os": [ @@ -2178,9 +2177,6 @@ "cpu": [ "arm64" ], - "libc": [ - "glibc" - ], "license": "LGPL-3.0-or-later", "optional": true, "os": [ @@ -2197,9 +2193,6 @@ "cpu": [ "ppc64" ], - "libc": [ - "glibc" - ], "license": "LGPL-3.0-or-later", "optional": true, "os": [ @@ -2216,9 +2209,6 @@ "cpu": [ "riscv64" ], - "libc": [ - "glibc" - ], "license": "LGPL-3.0-or-later", "optional": true, "os": [ @@ -2235,9 +2225,6 @@ "cpu": [ "s390x" ], - "libc": [ - "glibc" - ], "license": "LGPL-3.0-or-later", "optional": true, "os": [ @@ -2254,9 +2241,6 @@ "cpu": [ "x64" ], - "libc": [ - "glibc" - ], "license": "LGPL-3.0-or-later", "optional": true, "os": [ @@ -2273,9 +2257,6 @@ "cpu": [ "arm64" ], - "libc": [ - "musl" - ], "license": "LGPL-3.0-or-later", "optional": true, "os": [ @@ -2292,9 +2273,6 @@ "cpu": [ "x64" ], - "libc": [ - "musl" - ], "license": "LGPL-3.0-or-later", "optional": true, "os": [ @@ -2311,9 +2289,6 @@ "cpu": [ "arm" ], - "libc": [ - "glibc" - ], "license": "Apache-2.0", "optional": true, "os": [ @@ -2336,9 +2311,6 @@ "cpu": [ "arm64" ], - "libc": [ - "glibc" - ], "license": "Apache-2.0", "optional": true, "os": [ @@ -2361,9 +2333,6 @@ "cpu": [ "ppc64" ], - "libc": [ - "glibc" - ], "license": "Apache-2.0", "optional": true, "os": [ @@ -2386,9 +2355,6 @@ "cpu": [ "riscv64" ], - "libc": [ - "glibc" - ], "license": "Apache-2.0", "optional": true, "os": [ @@ -2411,9 +2377,6 @@ "cpu": [ "s390x" ], - "libc": [ - "glibc" - ], "license": "Apache-2.0", "optional": true, "os": [ @@ -2436,9 +2399,6 @@ "cpu": [ "x64" ], - "libc": [ - "glibc" - ], "license": "Apache-2.0", "optional": true, "os": [ @@ -2461,9 +2421,6 @@ "cpu": [ "arm64" ], - "libc": [ - "musl" - ], "license": "Apache-2.0", "optional": true, "os": [ @@ -2486,9 +2443,6 @@ "cpu": [ "x64" ], - "libc": [ - "musl" - ], "license": "Apache-2.0", "optional": true, "os": [ @@ -2965,9 +2919,6 @@ "cpu": [ "arm64" ], - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -2984,9 +2935,6 @@ "cpu": [ "arm64" ], - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -3003,9 +2951,6 @@ "cpu": [ "x64" ], - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -3022,9 +2967,6 @@ "cpu": [ "x64" ], - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -4306,9 +4248,6 @@ "arm64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -4326,9 +4265,6 @@ "arm64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -4346,9 +4282,6 @@ "ppc64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -4366,9 +4299,6 @@ "s390x" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -4386,9 +4316,6 @@ "x64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -4406,9 +4333,6 @@ "x64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -4700,9 +4624,6 @@ "cpu": [ "arm" ], - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -4716,9 +4637,6 @@ "cpu": [ "arm" ], - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -4732,9 +4650,6 @@ "cpu": [ "arm64" ], - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -4748,9 +4663,6 @@ "cpu": [ "arm64" ], - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -4764,9 +4676,6 @@ "cpu": [ "loong64" ], - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -4780,9 +4689,6 @@ "cpu": [ "loong64" ], - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -4796,9 +4702,6 @@ "cpu": [ "ppc64" ], - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -4812,9 +4715,6 @@ "cpu": [ "ppc64" ], - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -4828,9 +4728,6 @@ "cpu": [ "riscv64" ], - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -4844,9 +4741,6 @@ "cpu": [ "riscv64" ], - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -4860,9 +4754,6 @@ "cpu": [ "s390x" ], - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -4876,9 +4767,6 @@ "cpu": [ "x64" ], - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -4892,9 +4780,6 @@ "cpu": [ "x64" ], - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -5678,9 +5563,6 @@ "arm64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -5698,9 +5580,6 @@ "arm64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -5718,9 +5597,6 @@ "x64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -5738,9 +5614,6 @@ "x64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -6652,6 +6525,16 @@ "integrity": "sha512-lrpDziQipxCEeK5kWxvljWYhUvOiB2A9izZd9B2AFarYAkqZshb4lPbRs7zKEic6eGtH8V/2qJW+dPp9OtF6bw==", "license": "MIT" }, + "node_modules/@types/web-push": { + "version": "3.6.4", + "resolved": "https://registry.npmjs.org/@types/web-push/-/web-push-3.6.4.tgz", + "integrity": "sha512-GnJmSr40H3RAnj0s34FNTcJi1hmWFV5KXugE0mYWnYhgTAHLJ/dJKAwDmvPJYMke0RplY2XE9LnM4hqSqKIjhQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, "node_modules/@types/yauzl": { "version": "2.10.3", "resolved": "https://registry.npmjs.org/@types/yauzl/-/yauzl-2.10.3.tgz", @@ -7071,9 +6954,6 @@ "arm64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -7088,9 +6968,6 @@ "arm64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -7105,9 +6982,6 @@ "ppc64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -7122,9 +6996,6 @@ "riscv64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -7139,9 +7010,6 @@ "riscv64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -7156,9 +7024,6 @@ "s390x" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -7173,9 +7038,6 @@ "x64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -7190,9 +7052,6 @@ "x64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -8238,6 +8097,18 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/asn1.js": { + "version": "5.4.1", + "resolved": "https://registry.npmjs.org/asn1.js/-/asn1.js-5.4.1.tgz", + "integrity": "sha512-+I//4cYPccV8LdmBLiX8CYvf9Sp3vQsrqu2QNXRcrbiWvcx/UdlFiqUJJzxRQxgsZmvhXhn4cSKeSmoFjVdupA==", + "license": "MIT", + "dependencies": { + "bn.js": "^4.0.0", + "inherits": "^2.0.1", + "minimalistic-assert": "^1.0.0", + "safer-buffer": "^2.1.0" + } + }, "node_modules/assertion-error": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz", @@ -8566,6 +8437,12 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/bn.js": { + "version": "4.12.3", + "resolved": "https://registry.npmjs.org/bn.js/-/bn.js-4.12.3.tgz", + "integrity": "sha512-fGTi3gxV/23FTYdAoUtLYp6qySe2KE3teyZitipKNRuVYcBkoP/bB3guXN/XVKUe9mxCHXnc9C4ocyz8OmgN0g==", + "license": "MIT" + }, "node_modules/body-parser": { "version": "2.2.2", "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.2.2.tgz", @@ -8682,6 +8559,12 @@ "node": "*" } }, + "node_modules/buffer-equal-constant-time": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/buffer-equal-constant-time/-/buffer-equal-constant-time-1.0.1.tgz", + "integrity": "sha512-zRpUiDwd/xk6ADqPMATG8vc9VPrkck7T07OIx0gnjmJAnHnTVXNQG3vfvWNuiZIkwu9KrKdA1iJKfsfTVxE6NA==", + "license": "BSD-3-Clause" + }, "node_modules/buffer-from": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz", @@ -10707,6 +10590,15 @@ "node": ">= 0.4" } }, + "node_modules/ecdsa-sig-formatter": { + "version": "1.0.11", + "resolved": "https://registry.npmjs.org/ecdsa-sig-formatter/-/ecdsa-sig-formatter-1.0.11.tgz", + "integrity": "sha512-nagl3RYrbNv6kQkeJIpt6NJZy8twLB/2vtz6yN9Z4vRKHN4/QZJIEbqohALSgwKdnksuY3k5Addp5lg8sVoVcQ==", + "license": "Apache-2.0", + "dependencies": { + "safe-buffer": "^5.0.1" + } + }, "node_modules/eciesjs": { "version": "0.4.18", "resolved": "https://registry.npmjs.org/eciesjs/-/eciesjs-0.4.18.tgz", @@ -12783,6 +12675,15 @@ "url": "https://opencollective.com/unified" } }, + "node_modules/http_ece": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/http_ece/-/http_ece-1.2.0.tgz", + "integrity": "sha512-JrF8SSLVmcvc5NducxgyOrKXe3EsyHMgBFgSaIUGmArKe+rwr0uphRkRXvwiom3I+fpIfoItveHrfudL8/rxuA==", + "license": "MIT", + "engines": { + "node": ">=16" + } + }, "node_modules/http-errors": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz", @@ -14011,6 +13912,27 @@ "node": ">=4.0" } }, + "node_modules/jwa": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/jwa/-/jwa-2.0.1.tgz", + "integrity": "sha512-hRF04fqJIP8Abbkq5NKGN0Bbr3JxlQ+qhZufXVr0DvujKy93ZCbXZMHDL4EOtodSbCWxOqR8MS1tXA5hwqCXDg==", + "license": "MIT", + "dependencies": { + "buffer-equal-constant-time": "^1.0.1", + "ecdsa-sig-formatter": "1.0.11", + "safe-buffer": "^5.0.1" + } + }, + "node_modules/jws": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/jws/-/jws-4.0.1.tgz", + "integrity": "sha512-EKI/M/yqPncGUUh44xz0PxSidXFr/+r0pA70+gIYhjv+et7yxM+s29Y+VGDkovRofQem0fs7Uvf4+YmAdyRduA==", + "license": "MIT", + "dependencies": { + "jwa": "^2.0.1", + "safe-buffer": "^5.0.1" + } + }, "node_modules/katex": { "version": "0.16.45", "resolved": "https://registry.npmjs.org/katex/-/katex-0.16.45.tgz", @@ -14261,9 +14183,6 @@ "arm64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MPL-2.0", "optional": true, "os": [ @@ -14285,9 +14204,6 @@ "arm64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MPL-2.0", "optional": true, "os": [ @@ -14309,9 +14225,6 @@ "x64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MPL-2.0", "optional": true, "os": [ @@ -14333,9 +14246,6 @@ "x64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MPL-2.0", "optional": true, "os": [ @@ -15836,6 +15746,12 @@ "node": ">=4" } }, + "node_modules/minimalistic-assert": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/minimalistic-assert/-/minimalistic-assert-1.0.1.tgz", + "integrity": "sha512-UtJcAD4yEaGtjPezWuO9wC4nwUnVH/8/Im3yEHQP4b67cXlD/Qr9hdITCU1xDbSEXg2XKNaP8jsReV7vQd00/A==", + "license": "ISC" + }, "node_modules/minimatch": { "version": "3.1.5", "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz", @@ -18542,7 +18458,6 @@ "version": "5.2.1", "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", - "dev": true, "funding": [ { "type": "github", @@ -21089,6 +21004,25 @@ "node": ">=10.13.0" } }, + "node_modules/web-push": { + "version": "3.6.7", + "resolved": "https://registry.npmjs.org/web-push/-/web-push-3.6.7.tgz", + "integrity": "sha512-OpiIUe8cuGjrj3mMBFWY+e4MMIkW3SVT+7vEIjvD9kejGUypv8GPDf84JdPWskK8zMRIJ6xYGm+Kxr8YkPyA0A==", + "license": "MPL-2.0", + "dependencies": { + "asn1.js": "^5.3.0", + "http_ece": "1.2.0", + "https-proxy-agent": "^7.0.0", + "jws": "^4.0.0", + "minimist": "^1.2.5" + }, + "bin": { + "web-push": "src/cli.js" + }, + "engines": { + "node": ">= 16" + } + }, "node_modules/web-streams-polyfill": { "version": "3.3.3", "resolved": "https://registry.npmjs.org/web-streams-polyfill/-/web-streams-polyfill-3.3.3.tgz", diff --git a/package.json b/package.json index 0f6d444..2c6252e 100644 --- a/package.json +++ b/package.json @@ -63,6 +63,7 @@ "sonner": "^1.7.4", "tailwind-merge": "^3.5.0", "tw-animate-css": "^1.4.0", + "web-push": "^3.6.7", "yaml": "^2.8.4", "zod": "^3.25.76", "zustand": "^5.0.12" @@ -84,6 +85,7 @@ "@types/pg": "^8.20.0", "@types/react": "^19", "@types/react-dom": "^19", + "@types/web-push": "^3.6.4", "@vitest/coverage-v8": "^4.1.5", "chokidar-cli": "^3.0.0", "concurrently": "^9.2.1", diff --git a/prisma/migrations/20260507200000_add_push_subscriptions/migration.sql b/prisma/migrations/20260507200000_add_push_subscriptions/migration.sql new file mode 100644 index 0000000..2abe20f --- /dev/null +++ b/prisma/migrations/20260507200000_add_push_subscriptions/migration.sql @@ -0,0 +1,20 @@ +-- PushSubscription model for Web Push notifications (PBI-55) + +CREATE TABLE "push_subscriptions" ( + "id" TEXT NOT NULL, + "user_id" TEXT NOT NULL, + "endpoint" TEXT NOT NULL, + "p256dh" TEXT NOT NULL, + "auth" TEXT NOT NULL, + "user_agent" TEXT, + "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "last_used_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT "push_subscriptions_pkey" PRIMARY KEY ("id") +); + +CREATE UNIQUE INDEX "push_subscriptions_endpoint_key" ON "push_subscriptions"("endpoint"); + +CREATE INDEX "push_subscriptions_user_id_idx" ON "push_subscriptions"("user_id"); + +ALTER TABLE "push_subscriptions" ADD CONSTRAINT "push_subscriptions_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE; diff --git a/prisma/schema.prisma b/prisma/schema.prisma index 548f8fc..52da4a6 100644 --- a/prisma/schema.prisma +++ b/prisma/schema.prisma @@ -164,6 +164,7 @@ model User { claude_jobs ClaudeJob[] claude_workers ClaudeWorker[] started_sprint_runs SprintRun[] @relation("SprintRunStartedBy") + push_subscriptions PushSubscription[] @@index([active_product_id]) @@map("users") @@ -624,3 +625,18 @@ model ClaudeQuestion { @@index([status, expires_at]) @@map("claude_questions") } + +model PushSubscription { + id String @id @default(cuid()) + user User @relation(fields: [user_id], references: [id], onDelete: Cascade) + user_id String + endpoint String @unique + p256dh String + auth String + user_agent String? + created_at DateTime @default(now()) + last_used_at DateTime @default(now()) + + @@index([user_id]) + @@map("push_subscriptions") +} diff --git a/public/sw.js b/public/sw.js new file mode 100644 index 0000000..f4ebb07 --- /dev/null +++ b/public/sw.js @@ -0,0 +1,42 @@ +// Service Worker for Web Push notifications (PBI-55) + +self.addEventListener('push', (event) => { + let payload = { title: 'Scrum4Me', body: '', url: '/', tag: undefined } + try { + if (event.data) payload = { ...payload, ...event.data.json() } + } catch (_) {} + + event.waitUntil( + self.registration.showNotification(payload.title, { + body: payload.body, + icon: '/icon-192.png', + badge: '/icon-192.png', + tag: payload.tag, + data: { url: payload.url }, + }) + ) +}) + +self.addEventListener('notificationclick', (event) => { + event.notification.close() + + const rawUrl = event.notification.data?.url || '/' + const targetUrl = new URL(rawUrl, self.location.origin) + + // Same-origin guard + if (targetUrl.origin !== self.location.origin) return + + event.waitUntil( + self.clients + .matchAll({ type: 'window', includeUncontrolled: true }) + .then((clients) => { + for (const client of clients) { + if (client.url.startsWith(self.location.origin) && 'focus' in client) { + client.navigate(targetUrl.href) + return client.focus() + } + } + return self.clients.openWindow(targetUrl.href) + }) + ) +})