feat: web push notifications, mobile-ready (PRD §5.6)
ADR 0003: VAPID self-hosted today, DeviceToken model agnostic to
platform so iOS/Android (Expo/APNs/FCM) plug in as new senders later.
Backend (apps/api/src/modules/notifications)
- sender.ts: NotificationSender interface, WebPushSender via VAPID
- notifications.routes.ts: GET /me/notifications/config, POST/DELETE
/me/device-tokens, PATCH /me/notifications/settings, POST /me/notifications/test
- scheduler.ts: node-cron Mon 09:00 Europe/Rome for weekly weigh-in
reminder; auto-cleanup of expired tokens on 404/410
- env: VAPID_PUBLIC_KEY/PRIVATE_KEY/SUBJECT (all optional → push gracefully off)
Frontend
- public/sw.js minimal (push + notificationclick)
- lib/notifications/push-client.ts: subscribe / unsubscribe / getCurrentSubscription
- profile/notifications-{actions,panel}.tsx: editorial panel with toggles,
device list, "send test", per-device removal
- pushReady requires both permission AND active subscription (covers the
case where the user revoked the SW but kept the browser permission)
Schema
- DeviceToken { userId, platform, endpoint, p256dh, auth, token, userAgent,
createdAt, lastSeenAt } with unique(userId, endpoint)
- ExtendedPrismaClient type exported from @ketopath/db
- NotificationSettings zod schema in @ketopath/shared
Tooling
- lint-staged: split .js out of eslint glob so service worker is only
formatted (it lives outside the TS project)
i18n
- Notifications namespace (it) with typed error keys
Smoke tested: POST /me/device-tokens 201, POST /me/notifications/test 200,
real push delivered to a macOS Chrome device.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
1 parent
cdfc685855
commit
bb48357179
26 files changed
+1144
-2
No files matched your search
@@ -0,0 +1,77 @@
|
||||
// PRD §5.6 — invio push agnostico rispetto alla piattaforma.
|
||||
// Per ora c'è solo l'implementazione web (VAPID). Aggiungere mobile = un nuovo
|
||||
// `Sender` (Expo / APNs / FCM) senza toccare i call site. Vedi ADR 0003.
|
||||
|
||||
import type { DeviceToken } from '@ketopath/db';
|
||||
// `web-push` espone CommonJS: il default import è ciò che funziona a runtime,
|
||||
// ma il plugin `import` di ESLint non lo riconosce — disabilitiamo solo qui.
|
||||
// eslint-disable-next-line import/default
|
||||
import webpush from 'web-push';
|
||||
import type { PushSubscription } from 'web-push';
|
||||
|
||||
import { env } from '../../config/env.js';
|
||||
|
||||
export interface NotificationPayload {
|
||||
title: string;
|
||||
body: string;
|
||||
url?: string;
|
||||
// Niente dati sanitari nel payload (CLAUDE.md "Privacy first").
|
||||
}
|
||||
|
||||
export interface SendResult {
|
||||
ok: boolean;
|
||||
/** true ↔ il token è scaduto/revocato e va cancellato dal DB. */
|
||||
expired: boolean;
|
||||
errorCode?: number;
|
||||
}
|
||||
|
||||
let webPushConfigured = false;
|
||||
function configureWebPush(): boolean {
|
||||
if (webPushConfigured) return true;
|
||||
if (!env.VAPID_PUBLIC_KEY || !env.VAPID_PRIVATE_KEY || !env.VAPID_SUBJECT) {
|
||||
return false;
|
||||
}
|
||||
// eslint-disable-next-line import/no-named-as-default-member
|
||||
webpush.setVapidDetails(env.VAPID_SUBJECT, env.VAPID_PUBLIC_KEY, env.VAPID_PRIVATE_KEY);
|
||||
webPushConfigured = true;
|
||||
return true;
|
||||
}
|
||||
|
||||
export function pushIsEnabled(): boolean {
|
||||
return configureWebPush();
|
||||
}
|
||||
|
||||
export async function sendToDevice(
|
||||
device: DeviceToken,
|
||||
payload: NotificationPayload,
|
||||
): Promise<SendResult> {
|
||||
if (device.platform === 'web') {
|
||||
return sendWebPush(device, payload);
|
||||
}
|
||||
// Placeholder per iOS/Android — vedi ADR 0003.
|
||||
return { ok: false, expired: false, errorCode: 501 };
|
||||
}
|
||||
|
||||
async function sendWebPush(device: DeviceToken, payload: NotificationPayload): Promise<SendResult> {
|
||||
if (!configureWebPush()) {
|
||||
return { ok: false, expired: false };
|
||||
}
|
||||
if (!device.endpoint || !device.p256dh || !device.auth) {
|
||||
return { ok: false, expired: true }; // record incompleto: trattalo come scaduto
|
||||
}
|
||||
const subscription: PushSubscription = {
|
||||
endpoint: device.endpoint,
|
||||
keys: { p256dh: device.p256dh, auth: device.auth },
|
||||
};
|
||||
try {
|
||||
// eslint-disable-next-line import/no-named-as-default-member
|
||||
await webpush.sendNotification(subscription, JSON.stringify(payload), {
|
||||
TTL: 60 * 60, // 1 ora
|
||||
});
|
||||
return { ok: true, expired: false };
|
||||
} catch (err) {
|
||||
const e = err as { statusCode?: number };
|
||||
const status = e.statusCode ?? 0;
|
||||
return { ok: false, expired: status === 404 || status === 410, errorCode: status };
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user