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

@ -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))
})
})

View file

@ -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()
})
})