diff --git a/public/push-sw.js b/public/push-sw.js new file mode 100644 index 0000000..838211c --- /dev/null +++ b/public/push-sw.js @@ -0,0 +1,72 @@ +/* AzuuCine — notifications push (chargé dans le service worker généré par Workbox via importScripts). + * Affiche la notification reçue, et au clic ouvre (ou ramène au premier plan) l'app sur le bon écran. */ +/* eslint-env serviceworker */ + +// Écrans que le serveur peut demander d'ouvrir (tout le reste ouvre l'accueil) +var OPEN_RE = /^(notifications|item:[A-Za-z0-9_-]{1,64}|u:[a-z0-9_]{3,20})$/ + +function clip(v, max) { + if (typeof v !== 'string') return '' + v = v.replace(/[\u0000-\u001f\u007f]/g, ' ').trim() + return v.length > max ? v.slice(0, max - 1) + '…' : v +} + +/** Adresse à ouvrir : uniquement « /?open=<écran> » sur ce site. */ +function safeUrl(raw) { + try { + var u = new URL(typeof raw === 'string' ? raw : '/', self.location.origin) + var open = u.searchParams.get('open') || '' + if (u.origin === self.location.origin && u.pathname === '/' && OPEN_RE.test(open)) return '/?open=' + encodeURIComponent(open) + } catch (e) { + /* adresse invalide */ + } + return '/' +} + +self.addEventListener('push', function (event) { + var data = {} + try { + data = event.data ? event.data.json() : {} + } catch (e) { + data = {} + } + var title = clip(data.title, 120) || 'AzuuCine' + var options = { + body: clip(data.body, 300), + tag: clip(data.tag, 64) || undefined, + icon: '/icons/icon-192.png', + data: { url: safeUrl(data.url) }, + } + event.waitUntil( + Promise.all([ + self.registration.showNotification(title, options), + // App ouverte : on lui signale qu'il y a du nouveau (compteur de la cloche) + self.clients.matchAll({ type: 'window', includeUncontrolled: true }).then(function (list) { + list.forEach(function (c) { + c.postMessage({ type: 'azuu:push' }) + }) + }), + ]), + ) +}) + +self.addEventListener('notificationclick', function (event) { + event.notification.close() + var url = safeUrl(event.notification.data && event.notification.data.url) + var open = new URL(url, self.location.origin).searchParams.get('open') || '' + event.waitUntil( + self.clients.matchAll({ type: 'window', includeUncontrolled: true }).then(function (list) { + // Une fenêtre de l'app est déjà ouverte : on la ramène et on lui dit quoi afficher + for (var i = 0; i < list.length; i++) { + var c = list[i] + var cu = new URL(c.url) + // (les pages légales, /privacy et /legal, ne sont pas l'app) + if (cu.origin === self.location.origin && cu.pathname === '/' && 'focus' in c) { + c.postMessage({ type: 'azuu:open', open: open }) + return c.focus() + } + } + return self.clients.openWindow ? self.clients.openWindow(url) : undefined + }), + ) +}) diff --git a/scripts/gen-vapid.mjs b/scripts/gen-vapid.mjs new file mode 100644 index 0000000..5b49d8a --- /dev/null +++ b/scripts/gen-vapid.mjs @@ -0,0 +1,24 @@ +#!/usr/bin/env node +// Génère une paire de clés VAPID (P-256) pour les notifications push, et un secret de webhook. +// À lancer UNE fois sur ton PC : node scripts/gen-vapid.mjs +// Les valeurs affichées vont dans les secrets Supabase (jamais dans le dépôt, jamais dans .env / VITE_). +// Ne pas exécuter en CI. Voir supabase/PUSH_SETUP.md. +import { webcrypto as crypto } from 'node:crypto' + +const b64url = (buf) => Buffer.from(buf).toString('base64url') + +const pair = await crypto.subtle.generateKey({ name: 'ECDSA', namedCurve: 'P-256' }, true, ['sign', 'verify']) +const publicKey = b64url(await crypto.subtle.exportKey('raw', pair.publicKey)) +const { d: privateKey } = await crypto.subtle.exportKey('jwk', pair.privateKey) +const webhookSecret = b64url(crypto.getRandomValues(new Uint8Array(32))) + +console.log(`# Clés VAPID et secret du webhook — à garder secrètes (sauf VAPID_PUBLIC_KEY) +# 1) Secrets des fonctions Supabase (Dashboard → Edge Functions → Secrets, ou en ligne de commande) : +supabase secrets set VAPID_PUBLIC_KEY=${publicKey} +supabase secrets set VAPID_PRIVATE_KEY=${privateKey} +supabase secrets set VAPID_SUBJECT=mailto:ton-adresse@example.com +supabase secrets set PUSH_WEBHOOK_SECRET=${webhookSecret} + +# 2) Le même PUSH_WEBHOOK_SECRET dans Supabase Vault (SQL Editor) : +select vault.create_secret('${webhookSecret}', 'azuu_push_secret'); +`) diff --git a/src/App.tsx b/src/App.tsx index 6c9bb88..e3713e0 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -14,6 +14,8 @@ import StatsPage from './pages/StatsPage' import SettingsPage from './pages/SettingsPage' import AdminPage from './pages/AdminPage' import NotFoundPage from './pages/NotFoundPage' +import PushBridge from './components/PushBridge' +import SyncIndicator from './components/SyncIndicator' import { useMedia } from './store' import type { SearchResult } from './lib/catalogApi' import type { MediaItem } from './types' @@ -83,6 +85,8 @@ export default function App() { + + {roulette && setRoulette(false)} onOpen={openItem} />} {calendar && setCalendar(false)} onOpen={openItem} />} diff --git a/src/components/PushBridge.tsx b/src/components/PushBridge.tsx new file mode 100644 index 0000000..894c8e7 --- /dev/null +++ b/src/components/PushBridge.tsx @@ -0,0 +1,75 @@ +import { useEffect, useRef, useState } from 'react' +import { keepPushFresh } from '../lib/push' +import { useMedia } from '../store' +import { useSocial } from './social/SocialProvider' + +/** Écrans qu'une notification push peut ouvrir (« /?open=… », voir public/push-sw.js). */ +const OPEN_RE = /^(notifications|item:[A-Za-z0-9_-]{1,64}|u:[a-z0-9_]{3,20})$/ + +/** Lit (et retire de l'adresse) l'écran demandé par une notification au lancement de l'app. */ +function takeOpenParam(): string | null { + try { + const params = new URLSearchParams(location.search) + const open = params.get('open') + if (open === null) return null + params.delete('open') + const q = params.toString() + history.replaceState(history.state, '', `${location.pathname}${q ? `?${q}` : ''}${location.hash}`) + return OPEN_RE.test(open) ? open : null + } catch { + return null + } +} + +/** + * Lien entre les notifications push et l'app : ouvre le bon écran au clic sur une notification + * (app lancée, ou déjà ouverte : message du service worker), met à jour la cloche quand + * une notification arrive, et garde l'abonnement de l'appareil à jour côté serveur. + */ +export default function PushBridge() { + const { account, items, loading } = useMedia() + const social = useSocial() + const [target, setTarget] = useState(takeOpenParam) + const socialRef = useRef(social) + socialRef.current = social + + // Messages du service worker + useEffect(() => { + if (!('serviceWorker' in navigator)) return + const onMessage = (e: MessageEvent) => { + const data = e.data as { type?: unknown; open?: unknown } | null + if (!data || typeof data !== 'object') return + if (data.type === 'azuu:open' && typeof data.open === 'string' && OPEN_RE.test(data.open)) setTarget(data.open) + else if (data.type === 'azuu:push') void socialRef.current.refresh() + } + navigator.serviceWorker.addEventListener('message', onMessage) + return () => navigator.serviceWorker.removeEventListener('message', onMessage) + }, []) + + // Ouvre l'écran demandé une fois le compte et la bibliothèque chargés + useEffect(() => { + if (!target) return + if (!account) { + // Pas (ou plus) connecté : rien à ouvrir + if (!loading) setTarget(null) + return + } + if (!social.enabled || loading) return + setTarget(null) + if (target === 'notifications') social.openNotifications() + else if (target.startsWith('u:')) social.openProfile(target.slice(2)) + else { + const item = items.find((i) => i.id === target.slice(5)) + if (item) social.openItem(item) + else social.openNotifications() + } + }, [target, account, social, loading, items]) + + // Abonnement push renouvelé par le navigateur, langue changée… : on le signale au serveur + const accountOn = !!account + useEffect(() => { + if (accountOn) void keepPushFresh() + }, [accountOn]) + + return null +} diff --git a/src/components/PushToggle.tsx b/src/components/PushToggle.tsx new file mode 100644 index 0000000..b3e20ab --- /dev/null +++ b/src/components/PushToggle.tsx @@ -0,0 +1,85 @@ +import { BellRing, Loader2 } from 'lucide-react' +import { useEffect, useState } from 'react' +import { t } from '../i18n' +import { enablePush, disablePush, getPushState, PushError, type PushState } from '../lib/push' +import { cx } from '../lib/utils' + +/** Réglages → Notifications : « Notifications sur cet appareil » (Web Push, même app fermée). */ +export default function PushToggle() { + const [state, setState] = useState(null) + const [busy, setBusy] = useState(false) + const [error, setError] = useState(null) + + useEffect(() => { + let alive = true + void getPushState().then((s) => alive && setState(s)) + return () => { + alive = false + } + }, []) + + if (state === null) return null + const on = state === 'on' + const available = state === 'on' || state === 'off' + + const toggle = async () => { + if (busy || !available) return + setBusy(true) + setError(null) + try { + if (on) { + await disablePush() + setState('off') + } else { + // La permission n'est demandée qu'ici, au clic + setState(await enablePush()) + } + } catch (e) { + const code = e instanceof PushError ? e.code : 'failed' + if (code === 'denied') setState('denied') + else setError(code === 'not-ready' ? t('push.notReady') : t('push.error')) + } finally { + setBusy(false) + } + } + + const hint = + state === 'needs-install' + ? t('push.iosInstall') + : state === 'unsupported' + ? t('push.unsupported') + : state === 'denied' + ? t('push.denied') + : t('push.deviceHint') + + return ( +
+ + {error && ( +

+ {error} +

+ )} +
+ ) +} diff --git a/src/components/SyncIndicator.tsx b/src/components/SyncIndicator.tsx new file mode 100644 index 0000000..757838b --- /dev/null +++ b/src/components/SyncIndicator.tsx @@ -0,0 +1,138 @@ +import { Check, CloudOff, RefreshCw, X } from 'lucide-react' +import { useEffect, useRef, useState } from 'react' +import { t } from '../i18n' +import { cx } from '../lib/utils' +import { useMedia } from '../store' + +function useOnline(): boolean { + const [online, setOnline] = useState(() => navigator.onLine) + useEffect(() => { + const up = () => setOnline(true) + const down = () => setOnline(false) + window.addEventListener('online', up) + window.addEventListener('offline', down) + return () => { + window.removeEventListener('online', up) + window.removeEventListener('offline', down) + } + }, []) + return online +} + +type Kind = 'offline' | 'offline-local' | 'pending' | 'synced' + +/** + * Petite pastille discrète : hors-ligne, ou modifications pas encore envoyées au compte. + * Mobile : juste au-dessus de la barre de navigation ; ordinateur : en bas de la barre latérale. + * Elle disparaît une fois tout synchronisé (après un bref « Synchronisé »). + * L'état vient du moteur de synchro (useMedia().account.sync) : rien n'est recalculé ici. + */ +export default function SyncIndicator() { + const { account } = useMedia() + const online = useOnline() + const pending = account?.sync.pending ?? 0 + const syncing = account?.sync.state === 'syncing' + const failed = account?.sync.state === 'error' + + // Une modification part normalement en 1-2 s : on ne signale l'attente que si elle dure + const [slow, setSlow] = useState(false) + useEffect(() => { + if (pending === 0) { + setSlow(false) + return + } + const timer = setTimeout(() => setSlow(true), failed ? 0 : 4000) + return () => clearTimeout(timer) + }, [pending > 0, failed]) + + // Sans compte, l'app marche hors-ligne : message rassurant, que l'on peut masquer + const [dismissed, setDismissed] = useState(false) + useEffect(() => { + if (online) setDismissed(false) + }, [online]) + + const base: Kind | null = !online + ? account + ? 'offline' + : dismissed + ? null + : 'offline-local' + : account && pending > 0 && slow + ? 'pending' + : null + + // Bref « Synchronisé » quand la pastille d'attente disparaît + const [flash, setFlash] = useState(false) + const shown = useRef(null) + useEffect(() => { + const was = shown.current + shown.current = base + if (base) { + setFlash(false) + return + } + if (account && was === 'pending' && pending === 0 && online) setFlash(true) + }, [base, account, pending, online]) + useEffect(() => { + if (!flash) return + const timer = setTimeout(() => setFlash(false), 2200) + return () => clearTimeout(timer) + }, [flash]) + const kind: Kind | null = base ?? (flash ? 'synced' : null) + if (!kind) return null + + const text = + kind === 'offline' + ? pending > 0 + ? `${t('sync.offline')} · ${t('sync.pending', { count: pending })}` + : t('netPill.offlineSync') + : kind === 'offline-local' + ? t('netPill.offlineLocal') + : kind === 'pending' + ? syncing + ? `${t('sync.syncing')} · ${t('sync.pending', { count: pending })}` + : t('sync.pending', { count: pending }) + : t('netPill.synced') + + const icon = + kind === 'synced' ? ( + + ) : kind === 'pending' ? ( + + ) : ( + + ) + + const pill = 'pointer-events-auto inline-flex max-w-full items-center gap-2 rounded-full border border-line bg-surface px-3.5 py-1.5 text-xs font-medium text-ink-2 shadow-lg lg:w-full lg:rounded-xl lg:px-3 lg:py-2 lg:text-start' + + return ( +
+ {kind === 'pending' ? ( + // Envoi en attente : un appui relance la synchro + + ) : kind === 'offline-local' ? ( + + {icon} + {text} + + + ) : ( + + {icon} + {text} + + )} +
+ ) +} diff --git a/src/i18n/locales/ar.ts b/src/i18n/locales/ar.ts index 69a5109..bead2e5 100644 --- a/src/i18n/locales/ar.ts +++ b/src/i18n/locales/ar.ts @@ -1288,6 +1288,18 @@ const dict: Translations = { 'challenges.more_few': "+ {count} تحديات أخرى", 'challenges.more_many': "+ {count} تحديًا آخر", 'challenges.more_other': "+ {count} تحدٍّ آخر", + // — Notifications push & indicateur hors-ligne — + 'push.device': "الإشعارات على هذا الجهاز", + 'push.deviceHint': "حتى عندما يكون التطبيق مغلقًا. تنطبق الخيارات أدناه أيضًا.", + 'push.iosInstall': "على iPhone وiPad، أضف AzuuCine أولًا إلى الشاشة الرئيسية (iOS 16.4 أو أحدث)، ثم افتح التطبيق من أيقونته لتفعيل الإشعارات.", + 'push.unsupported': "هذا المتصفح لا يدعم الإشعارات الفورية.", + 'push.denied': "الإشعارات محظورة لهذا الموقع. اسمح بها من إعدادات المتصفح ثم حاول مجددًا.", + 'push.notReady': "الإشعارات الفورية غير متاحة على الخادم بعد.", + 'push.error': "تعذّر تفعيل الإشعارات. تحقق من اتصالك وحاول مجددًا.", + 'netPill.offlineSync': "غير متصل — ستتم مزامنة تعديلاتك", + 'netPill.offlineLocal': "غير متصل — كل شيء محفوظ على هذا الجهاز", + 'netPill.synced': "تمت المزامنة", + 'netPill.hide': "إخفاء", } export default dict diff --git a/src/i18n/locales/de.ts b/src/i18n/locales/de.ts index eb6569b..56cd009 100644 --- a/src/i18n/locales/de.ts +++ b/src/i18n/locales/de.ts @@ -1073,6 +1073,18 @@ const dict: Translations = { 'challenges.startsIn_other': "Beginnt in {count} Tagen", 'challenges.more_one': "+ {count} weitere Challenge", 'challenges.more_other': "+ {count} weitere Challenges", + // — Notifications push & indicateur hors-ligne — + 'push.device': "Benachrichtigungen auf diesem Gerät", + 'push.deviceHint': "Auch wenn die App geschlossen ist. Die Auswahl unten gilt ebenfalls.", + 'push.iosInstall': "Auf iPhone und iPad füge AzuuCine zuerst zum Home-Bildschirm hinzu (iOS 16.4 oder neuer) und öffne die App dann über ihr Symbol, um Benachrichtigungen zu aktivieren.", + 'push.unsupported': "Dieser Browser unterstützt keine Push-Benachrichtigungen.", + 'push.denied': "Benachrichtigungen sind für diese Seite blockiert. Erlaube sie in den Browser-Einstellungen und versuche es erneut.", + 'push.notReady': "Push-Benachrichtigungen sind auf dem Server noch nicht verfügbar.", + 'push.error': "Benachrichtigungen konnten nicht aktiviert werden. Prüfe deine Verbindung und versuche es erneut.", + 'netPill.offlineSync': "Offline — deine Änderungen werden synchronisiert", + 'netPill.offlineLocal': "Offline — alles bleibt auf diesem Gerät gespeichert", + 'netPill.synced': "Synchronisiert", + 'netPill.hide': "Ausblenden", } export default dict diff --git a/src/i18n/locales/en.ts b/src/i18n/locales/en.ts index dbe6e55..a878198 100644 --- a/src/i18n/locales/en.ts +++ b/src/i18n/locales/en.ts @@ -1073,6 +1073,18 @@ const dict: Translations = { 'challenges.startsIn_other': "Starts in {count} days", 'challenges.more_one': "+ {count} more challenge", 'challenges.more_other': "+ {count} more challenges", + // — Notifications push & indicateur hors-ligne — + 'push.device': "Notifications on this device", + 'push.deviceHint': "Even when the app is closed. The choices below apply too.", + 'push.iosInstall': "On iPhone and iPad, first add AzuuCine to your Home Screen (iOS 16.4 or later), then open the app from its icon to turn on notifications.", + 'push.unsupported': "This browser doesn’t support push notifications.", + 'push.denied': "Notifications are blocked for this site. Allow them in your browser settings, then try again.", + 'push.notReady': "Push notifications aren’t available on the server yet.", + 'push.error': "Couldn’t turn on notifications. Check your connection and try again.", + 'netPill.offlineSync': "Offline — your changes will sync", + 'netPill.offlineLocal': "Offline — everything stays saved on this device", + 'netPill.synced': "Synced", + 'netPill.hide': "Hide", } export default dict diff --git a/src/i18n/locales/es.ts b/src/i18n/locales/es.ts index 040c40c..1ef0fd2 100644 --- a/src/i18n/locales/es.ts +++ b/src/i18n/locales/es.ts @@ -1073,6 +1073,18 @@ const dict: Translations = { 'challenges.startsIn_other': "Empieza en {count} días", 'challenges.more_one': "+ {count} reto más", 'challenges.more_other': "+ {count} retos más", + // — Notifications push & indicateur hors-ligne — + 'push.device': "Notificaciones en este dispositivo", + 'push.deviceHint': "Incluso con la app cerrada. Las opciones de abajo también se aplican.", + 'push.iosInstall': "En iPhone y iPad, primero añade AzuuCine a la pantalla de inicio (iOS 16.4 o posterior) y abre la app desde su icono para activar las notificaciones.", + 'push.unsupported': "Este navegador no admite notificaciones push.", + 'push.denied': "Las notificaciones están bloqueadas para este sitio. Permítelas en los ajustes del navegador y vuelve a intentarlo.", + 'push.notReady': "Las notificaciones push aún no están disponibles en el servidor.", + 'push.error': "No se pudieron activar las notificaciones. Comprueba tu conexión e inténtalo de nuevo.", + 'netPill.offlineSync': "Sin conexión — tus cambios se sincronizarán", + 'netPill.offlineLocal': "Sin conexión — todo queda guardado en este dispositivo", + 'netPill.synced': "Sincronizado", + 'netPill.hide': "Ocultar", } export default dict diff --git a/src/i18n/locales/fr.ts b/src/i18n/locales/fr.ts index 0fe58fc..5f2101e 100644 --- a/src/i18n/locales/fr.ts +++ b/src/i18n/locales/fr.ts @@ -1075,6 +1075,18 @@ const dict = { 'challenges.startsIn_other': "Commence dans {count} jours", 'challenges.more_one': "+ {count} autre défi", 'challenges.more_other': "+ {count} autres défis", + // — Notifications push & indicateur hors-ligne — + 'push.device': "Notifications sur cet appareil", + 'push.deviceHint': "Même quand l’app est fermée. Les choix ci-dessous s’appliquent aussi.", + 'push.iosInstall': "Sur iPhone et iPad, ajoute d’abord AzuuCine à l’écran d’accueil (iOS 16.4 ou plus récent), puis ouvre l’app depuis son icône pour activer les notifications.", + 'push.unsupported': "Ce navigateur ne gère pas les notifications push.", + 'push.denied': "Notifications bloquées pour ce site. Autorise-les dans les réglages du navigateur, puis réessaie.", + 'push.notReady': "Les notifications push ne sont pas encore disponibles sur le serveur.", + 'push.error': "Impossible d’activer les notifications. Vérifie ta connexion et réessaie.", + 'netPill.offlineSync': "Hors ligne — tes modifs seront synchronisées", + 'netPill.offlineLocal': "Hors ligne — tout reste enregistré sur cet appareil", + 'netPill.synced': "Synchronisé", + 'netPill.hide': "Masquer", } export default dict diff --git a/src/i18n/locales/hi.ts b/src/i18n/locales/hi.ts index 0ee1809..ba42f51 100644 --- a/src/i18n/locales/hi.ts +++ b/src/i18n/locales/hi.ts @@ -1073,6 +1073,18 @@ const dict: Translations = { 'challenges.startsIn_other': "{count} दिन में शुरू", 'challenges.more_one': "+ {count} और चुनौती", 'challenges.more_other': "+ {count} और चुनौतियाँ", + // — Notifications push & indicateur hors-ligne — + 'push.device': "इस डिवाइस पर सूचनाएँ", + 'push.deviceHint': "ऐप बंद होने पर भी। नीचे दिए विकल्प भी लागू होते हैं।", + 'push.iosInstall': "iPhone और iPad पर पहले AzuuCine को होम स्क्रीन पर जोड़ें (iOS 16.4 या नया), फिर सूचनाएँ चालू करने के लिए ऐप को उसके आइकन से खोलें।", + 'push.unsupported': "यह ब्राउज़र पुश सूचनाएँ सपोर्ट नहीं करता।", + 'push.denied': "इस साइट के लिए सूचनाएँ ब्लॉक हैं। ब्राउज़र सेटिंग्स में अनुमति दें, फिर दोबारा कोशिश करें।", + 'push.notReady': "पुश सूचनाएँ अभी सर्वर पर उपलब्ध नहीं हैं।", + 'push.error': "सूचनाएँ चालू नहीं हो सकीं। अपना कनेक्शन जाँचें और दोबारा कोशिश करें।", + 'netPill.offlineSync': "ऑफ़लाइन — आपके बदलाव सिंक हो जाएँगे", + 'netPill.offlineLocal': "ऑफ़लाइन — सब कुछ इस डिवाइस पर सहेजा रहता है", + 'netPill.synced': "सिंक हो गया", + 'netPill.hide': "छिपाएँ", } export default dict diff --git a/src/i18n/locales/id.ts b/src/i18n/locales/id.ts index 5c347f5..00fd9ae 100644 --- a/src/i18n/locales/id.ts +++ b/src/i18n/locales/id.ts @@ -1073,6 +1073,18 @@ const dict: Translations = { 'challenges.startsIn_other': "Mulai dalam {count} hari", 'challenges.more_one': "+ {count} tantangan lain", 'challenges.more_other': "+ {count} tantangan lain", + // — Notifications push & indicateur hors-ligne — + 'push.device': "Notifikasi di perangkat ini", + 'push.deviceHint': "Bahkan saat aplikasi ditutup. Pilihan di bawah juga berlaku.", + 'push.iosInstall': "Di iPhone dan iPad, tambahkan dulu AzuuCine ke Layar Utama (iOS 16.4 atau lebih baru), lalu buka aplikasi dari ikonnya untuk mengaktifkan notifikasi.", + 'push.unsupported': "Browser ini tidak mendukung notifikasi push.", + 'push.denied': "Notifikasi diblokir untuk situs ini. Izinkan di pengaturan browser, lalu coba lagi.", + 'push.notReady': "Notifikasi push belum tersedia di server.", + 'push.error': "Tidak dapat mengaktifkan notifikasi. Periksa koneksimu dan coba lagi.", + 'netPill.offlineSync': "Offline — perubahanmu akan disinkronkan", + 'netPill.offlineLocal': "Offline — semuanya tetap tersimpan di perangkat ini", + 'netPill.synced': "Tersinkron", + 'netPill.hide': "Sembunyikan", } export default dict diff --git a/src/i18n/locales/it.ts b/src/i18n/locales/it.ts index b27422f..919afbc 100644 --- a/src/i18n/locales/it.ts +++ b/src/i18n/locales/it.ts @@ -1073,6 +1073,18 @@ const dict: Translations = { 'challenges.startsIn_other': "Inizia tra {count} giorni", 'challenges.more_one': "+ {count} altra sfida", 'challenges.more_other': "+ {count} altre sfide", + // — Notifications push & indicateur hors-ligne — + 'push.device': "Notifiche su questo dispositivo", + 'push.deviceHint': "Anche con l’app chiusa. Valgono anche le scelte qui sotto.", + 'push.iosInstall': "Su iPhone e iPad, aggiungi prima AzuuCine alla schermata Home (iOS 16.4 o successivo), poi apri l’app dalla sua icona per attivare le notifiche.", + 'push.unsupported': "Questo browser non supporta le notifiche push.", + 'push.denied': "Le notifiche sono bloccate per questo sito. Consentile nelle impostazioni del browser, poi riprova.", + 'push.notReady': "Le notifiche push non sono ancora disponibili sul server.", + 'push.error': "Impossibile attivare le notifiche. Controlla la connessione e riprova.", + 'netPill.offlineSync': "Offline — le modifiche verranno sincronizzate", + 'netPill.offlineLocal': "Offline — tutto resta salvato su questo dispositivo", + 'netPill.synced': "Sincronizzato", + 'netPill.hide': "Nascondi", } export default dict diff --git a/src/i18n/locales/ja.ts b/src/i18n/locales/ja.ts index 5f898f4..79c9634 100644 --- a/src/i18n/locales/ja.ts +++ b/src/i18n/locales/ja.ts @@ -1073,6 +1073,18 @@ const dict: Translations = { 'challenges.startsIn_other': "{count}日後に開始", 'challenges.more_one': "ほか{count}件のチャレンジ", 'challenges.more_other': "ほか{count}件のチャレンジ", + // — Notifications push & indicateur hors-ligne — + 'push.device': "このデバイスの通知", + 'push.deviceHint': "アプリを閉じていても届きます。下の設定も適用されます。", + 'push.iosInstall': "iPhone・iPad では、まず AzuuCine をホーム画面に追加し(iOS 16.4 以降)、アイコンからアプリを開いて通知をオンにしてください。", + 'push.unsupported': "このブラウザはプッシュ通知に対応していません。", + 'push.denied': "このサイトの通知はブロックされています。ブラウザの設定で許可してから、もう一度お試しください。", + 'push.notReady': "プッシュ通知はまだサーバーで利用できません。", + 'push.error': "通知をオンにできませんでした。接続を確認して、もう一度お試しください。", + 'netPill.offlineSync': "オフライン — 変更は後で同期されます", + 'netPill.offlineLocal': "オフライン — すべてこのデバイスに保存されています", + 'netPill.synced': "同期済み", + 'netPill.hide': "閉じる", } export default dict diff --git a/src/i18n/locales/ko.ts b/src/i18n/locales/ko.ts index 42c444d..944d9bc 100644 --- a/src/i18n/locales/ko.ts +++ b/src/i18n/locales/ko.ts @@ -1073,6 +1073,18 @@ const dict: Translations = { 'challenges.startsIn_other': "{count}일 후 시작", 'challenges.more_one': "+ 챌린지 {count}개 더", 'challenges.more_other': "+ 챌린지 {count}개 더", + // — Notifications push & indicateur hors-ligne — + 'push.device': "이 기기의 알림", + 'push.deviceHint': "앱이 닫혀 있어도 받아요. 아래 선택 사항도 적용돼요.", + 'push.iosInstall': "iPhone과 iPad에서는 먼저 AzuuCine을 홈 화면에 추가한 뒤(iOS 16.4 이상) 아이콘으로 앱을 열어 알림을 켜 주세요.", + 'push.unsupported': "이 브라우저는 푸시 알림을 지원하지 않아요.", + 'push.denied': "이 사이트의 알림이 차단되어 있어요. 브라우저 설정에서 허용한 뒤 다시 시도해 주세요.", + 'push.notReady': "서버에서 아직 푸시 알림을 사용할 수 없어요.", + 'push.error': "알림을 켜지 못했어요. 연결을 확인하고 다시 시도해 주세요.", + 'netPill.offlineSync': "오프라인 — 변경 사항은 나중에 동기화돼요", + 'netPill.offlineLocal': "오프라인 — 모든 내용이 이 기기에 저장돼 있어요", + 'netPill.synced': "동기화됨", + 'netPill.hide': "숨기기", } export default dict diff --git a/src/i18n/locales/nl.ts b/src/i18n/locales/nl.ts index b966af8..192f81a 100644 --- a/src/i18n/locales/nl.ts +++ b/src/i18n/locales/nl.ts @@ -1073,6 +1073,18 @@ const dict: Translations = { 'challenges.startsIn_other': "Begint over {count} dagen", 'challenges.more_one': "+ {count} andere uitdaging", 'challenges.more_other': "+ {count} andere uitdagingen", + // — Notifications push & indicateur hors-ligne — + 'push.device': "Meldingen op dit apparaat", + 'push.deviceHint': "Ook als de app gesloten is. De keuzes hieronder gelden ook.", + 'push.iosInstall': "Voeg op iPhone en iPad AzuuCine eerst toe aan je beginscherm (iOS 16.4 of nieuwer) en open de app via het pictogram om meldingen aan te zetten.", + 'push.unsupported': "Deze browser ondersteunt geen pushmeldingen.", + 'push.denied': "Meldingen zijn geblokkeerd voor deze site. Sta ze toe in je browserinstellingen en probeer het opnieuw.", + 'push.notReady': "Pushmeldingen zijn nog niet beschikbaar op de server.", + 'push.error': "Kon meldingen niet aanzetten. Controleer je verbinding en probeer het opnieuw.", + 'netPill.offlineSync': "Offline — je wijzigingen worden gesynchroniseerd", + 'netPill.offlineLocal': "Offline — alles blijft op dit apparaat bewaard", + 'netPill.synced': "Gesynchroniseerd", + 'netPill.hide': "Verbergen", } export default dict diff --git a/src/i18n/locales/pl.ts b/src/i18n/locales/pl.ts index aee0fe4..7fa2ddc 100644 --- a/src/i18n/locales/pl.ts +++ b/src/i18n/locales/pl.ts @@ -1209,6 +1209,18 @@ const dict: Translations = { 'challenges.more_few': "+ {count} inne wyzwania", 'challenges.more_many': "+ {count} innych wyzwań", 'challenges.more_other': "+ {count} innego wyzwania", + // — Notifications push & indicateur hors-ligne — + 'push.device': "Powiadomienia na tym urządzeniu", + 'push.deviceHint': "Nawet gdy aplikacja jest zamknięta. Poniższe ustawienia też obowiązują.", + 'push.iosInstall': "Na iPhonie i iPadzie najpierw dodaj AzuuCine do ekranu początkowego (iOS 16.4 lub nowszy), a potem otwórz aplikację z jej ikony, aby włączyć powiadomienia.", + 'push.unsupported': "Ta przeglądarka nie obsługuje powiadomień push.", + 'push.denied': "Powiadomienia są zablokowane dla tej witryny. Zezwól na nie w ustawieniach przeglądarki i spróbuj ponownie.", + 'push.notReady': "Powiadomienia push nie są jeszcze dostępne na serwerze.", + 'push.error': "Nie udało się włączyć powiadomień. Sprawdź połączenie i spróbuj ponownie.", + 'netPill.offlineSync': "Offline — zmiany zostaną zsynchronizowane", + 'netPill.offlineLocal': "Offline — wszystko zostaje zapisane na tym urządzeniu", + 'netPill.synced': "Zsynchronizowano", + 'netPill.hide': "Ukryj", } export default dict diff --git a/src/i18n/locales/pt.ts b/src/i18n/locales/pt.ts index 974058c..91d53f4 100644 --- a/src/i18n/locales/pt.ts +++ b/src/i18n/locales/pt.ts @@ -1073,6 +1073,18 @@ const dict: Translations = { 'challenges.startsIn_other': "Começa em {count} dias", 'challenges.more_one': "+ {count} outro desafio", 'challenges.more_other': "+ {count} outros desafios", + // — Notifications push & indicateur hors-ligne — + 'push.device': "Notificações neste dispositivo", + 'push.deviceHint': "Mesmo com o app fechado. As opções abaixo também valem.", + 'push.iosInstall': "No iPhone e iPad, primeiro adicione o AzuuCine à Tela de Início (iOS 16.4 ou mais recente) e abra o app pelo ícone para ativar as notificações.", + 'push.unsupported': "Este navegador não suporta notificações push.", + 'push.denied': "As notificações estão bloqueadas para este site. Permita-as nas configurações do navegador e tente de novo.", + 'push.notReady': "As notificações push ainda não estão disponíveis no servidor.", + 'push.error': "Não foi possível ativar as notificações. Verifique sua conexão e tente de novo.", + 'netPill.offlineSync': "Offline — suas alterações serão sincronizadas", + 'netPill.offlineLocal': "Offline — tudo fica salvo neste dispositivo", + 'netPill.synced': "Sincronizado", + 'netPill.hide': "Ocultar", } export default dict diff --git a/src/i18n/locales/ru.ts b/src/i18n/locales/ru.ts index 5641dd9..7283a2c 100644 --- a/src/i18n/locales/ru.ts +++ b/src/i18n/locales/ru.ts @@ -1209,6 +1209,18 @@ const dict: Translations = { 'challenges.more_few': "+ ещё {count} челленджа", 'challenges.more_many': "+ ещё {count} челленджей", 'challenges.more_other': "+ ещё {count} челленджа", + // — Notifications push & indicateur hors-ligne — + 'push.device': "Уведомления на этом устройстве", + 'push.deviceHint': "Даже когда приложение закрыто. Настройки ниже тоже действуют.", + 'push.iosInstall': "На iPhone и iPad сначала добавьте AzuuCine на экран «Домой» (iOS 16.4 или новее), затем откройте приложение с его значка, чтобы включить уведомления.", + 'push.unsupported': "Этот браузер не поддерживает push-уведомления.", + 'push.denied': "Уведомления для этого сайта заблокированы. Разрешите их в настройках браузера и повторите попытку.", + 'push.notReady': "Push-уведомления пока недоступны на сервере.", + 'push.error': "Не удалось включить уведомления. Проверьте подключение и повторите попытку.", + 'netPill.offlineSync': "Нет сети — изменения будут синхронизированы", + 'netPill.offlineLocal': "Нет сети — всё сохранено на этом устройстве", + 'netPill.synced': "Синхронизировано", + 'netPill.hide': "Скрыть", } export default dict diff --git a/src/i18n/locales/th.ts b/src/i18n/locales/th.ts index 5b61721..eb8016b 100644 --- a/src/i18n/locales/th.ts +++ b/src/i18n/locales/th.ts @@ -1073,6 +1073,18 @@ const dict: Translations = { 'challenges.startsIn_other': "เริ่มในอีก {count} วัน", 'challenges.more_one': "+ อีก {count} ชาเลนจ์", 'challenges.more_other': "+ อีก {count} ชาเลนจ์", + // — Notifications push & indicateur hors-ligne — + 'push.device': "การแจ้งเตือนบนอุปกรณ์นี้", + 'push.deviceHint': "แม้ปิดแอปอยู่ ตัวเลือกด้านล่างก็มีผลด้วย", + 'push.iosInstall': "บน iPhone และ iPad ให้เพิ่ม AzuuCine ไปยังหน้าจอโฮมก่อน (iOS 16.4 ขึ้นไป) แล้วเปิดแอปจากไอคอนเพื่อเปิดการแจ้งเตือน", + 'push.unsupported': "เบราว์เซอร์นี้ไม่รองรับการแจ้งเตือนแบบพุช", + 'push.denied': "การแจ้งเตือนถูกบล็อกสำหรับเว็บไซต์นี้ อนุญาตในการตั้งค่าเบราว์เซอร์แล้วลองอีกครั้ง", + 'push.notReady': "เซิร์ฟเวอร์ยังไม่พร้อมสำหรับการแจ้งเตือนแบบพุช", + 'push.error': "เปิดการแจ้งเตือนไม่สำเร็จ ตรวจสอบการเชื่อมต่อแล้วลองอีกครั้ง", + 'netPill.offlineSync': "ออฟไลน์ — การเปลี่ยนแปลงจะซิงค์ภายหลัง", + 'netPill.offlineLocal': "ออฟไลน์ — ทุกอย่างยังบันทึกอยู่ในอุปกรณ์นี้", + 'netPill.synced': "ซิงค์แล้ว", + 'netPill.hide': "ซ่อน", } export default dict diff --git a/src/i18n/locales/tr.ts b/src/i18n/locales/tr.ts index d6e0d87..76fd47f 100644 --- a/src/i18n/locales/tr.ts +++ b/src/i18n/locales/tr.ts @@ -1073,6 +1073,18 @@ const dict: Translations = { 'challenges.startsIn_other': "{count} gün sonra başlıyor", 'challenges.more_one': "+ {count} hedef daha", 'challenges.more_other': "+ {count} hedef daha", + // — Notifications push & indicateur hors-ligne — + 'push.device': "Bu cihazda bildirimler", + 'push.deviceHint': "Uygulama kapalıyken bile. Aşağıdaki seçimler de geçerlidir.", + 'push.iosInstall': "iPhone ve iPad’de önce AzuuCine’i Ana Ekran’a ekle (iOS 16.4 veya üstü), ardından bildirimleri açmak için uygulamayı simgesinden aç.", + 'push.unsupported': "Bu tarayıcı anlık bildirimleri desteklemiyor.", + 'push.denied': "Bu site için bildirimler engellendi. Tarayıcı ayarlarından izin ver ve tekrar dene.", + 'push.notReady': "Anlık bildirimler sunucuda henüz kullanılamıyor.", + 'push.error': "Bildirimler açılamadı. Bağlantını kontrol edip tekrar dene.", + 'netPill.offlineSync': "Çevrimdışı — değişikliklerin eşitlenecek", + 'netPill.offlineLocal': "Çevrimdışı — her şey bu cihazda kayıtlı kalır", + 'netPill.synced': "Eşitlendi", + 'netPill.hide': "Gizle", } export default dict diff --git a/src/i18n/locales/vi.ts b/src/i18n/locales/vi.ts index 3950cdf..ad7ec27 100644 --- a/src/i18n/locales/vi.ts +++ b/src/i18n/locales/vi.ts @@ -1073,6 +1073,18 @@ const dict: Translations = { 'challenges.startsIn_other': "Bắt đầu sau {count} ngày", 'challenges.more_one': "+ {count} thử thách khác", 'challenges.more_other': "+ {count} thử thách khác", + // — Notifications push & indicateur hors-ligne — + 'push.device': "Thông báo trên thiết bị này", + 'push.deviceHint': "Ngay cả khi ứng dụng đã đóng. Các lựa chọn bên dưới cũng được áp dụng.", + 'push.iosInstall': "Trên iPhone và iPad, trước tiên hãy thêm AzuuCine vào Màn hình chính (iOS 16.4 trở lên), sau đó mở ứng dụng từ biểu tượng để bật thông báo.", + 'push.unsupported': "Trình duyệt này không hỗ trợ thông báo đẩy.", + 'push.denied': "Thông báo đã bị chặn cho trang này. Hãy cho phép trong cài đặt trình duyệt rồi thử lại.", + 'push.notReady': "Máy chủ chưa hỗ trợ thông báo đẩy.", + 'push.error': "Không thể bật thông báo. Kiểm tra kết nối rồi thử lại.", + 'netPill.offlineSync': "Ngoại tuyến — thay đổi của bạn sẽ được đồng bộ", + 'netPill.offlineLocal': "Ngoại tuyến — mọi thứ vẫn được lưu trên thiết bị này", + 'netPill.synced': "Đã đồng bộ", + 'netPill.hide': "Ẩn", } export default dict diff --git a/src/i18n/locales/zh.ts b/src/i18n/locales/zh.ts index 6acfe60..8db866c 100644 --- a/src/i18n/locales/zh.ts +++ b/src/i18n/locales/zh.ts @@ -1073,6 +1073,18 @@ const dict: Translations = { 'challenges.startsIn_other': "{count} 天后开始", 'challenges.more_one': "+ 另外 {count} 个挑战", 'challenges.more_other': "+ 另外 {count} 个挑战", + // — Notifications push & indicateur hors-ligne — + 'push.device': "此设备上的通知", + 'push.deviceHint': "即使应用已关闭也会提醒。下方的选项同样适用。", + 'push.iosInstall': "在 iPhone 和 iPad 上,请先将 AzuuCine 添加到主屏幕(iOS 16.4 或更高版本),再从图标打开应用以开启通知。", + 'push.unsupported': "此浏览器不支持推送通知。", + 'push.denied': "此网站的通知已被阻止。请在浏览器设置中允许后重试。", + 'push.notReady': "服务器暂未开放推送通知。", + 'push.error': "无法开启通知。请检查网络连接后重试。", + 'netPill.offlineSync': "离线 — 你的修改将稍后同步", + 'netPill.offlineLocal': "离线 — 所有内容都保存在此设备上", + 'netPill.synced': "已同步", + 'netPill.hide': "隐藏", } export default dict diff --git a/src/lib/push.ts b/src/lib/push.ts new file mode 100644 index 0000000..f7733f7 --- /dev/null +++ b/src/lib/push.ts @@ -0,0 +1,210 @@ +import { getLang } from '../i18n' +import { cloudFetch } from './cloud/api' +import { cloudEnabled } from './cloud/config' +import { detectPlatform } from './pwa' +import { scopedKey } from './scope' +import { isPlainObject, storageGet, storageSet } from './security' + +/** + * Notifications push (Web Push) sur cet appareil : + * - la permission n'est demandée qu'au clic sur l'interrupteur (jamais au chargement) ; + * - l'abonnement du navigateur est enregistré sur le serveur (register_push_subscription) ; + * - le serveur envoie ensuite les notifications de la cloche, même app fermée. + */ + +export type PushSupport = 'ok' | 'unsupported' | 'needs-install' +export type PushState = 'unsupported' | 'needs-install' | 'denied' | 'off' | 'on' + +export class PushError extends Error { + constructor(public code: 'denied' | 'not-ready' | 'failed') { + super(code) + } +} + +/** Dernier enregistrement réussi (par compte) */ +const storeKey = () => scopedKey('push') +const REFRESH_MS = 7 * 24 * 3600 * 1000 + +function isStandalone(): boolean { + return window.matchMedia?.('(display-mode: standalone)').matches || (navigator as { standalone?: boolean }).standalone === true +} + +/** Ce navigateur sait-il recevoir des notifications push ? (iPhone : seulement l'app installée, iOS 16.4+) */ +export function pushSupport(): PushSupport { + if (!cloudEnabled || typeof window === 'undefined') return 'unsupported' + const api = 'serviceWorker' in navigator && 'PushManager' in window && 'Notification' in window + if (detectPlatform() === 'ios' && (!isStandalone() || !api)) return 'needs-install' + return api ? 'ok' : 'unsupported' +} + +function withTimeout(p: Promise, ms: number): Promise { + return new Promise((resolve, reject) => { + const timer = setTimeout(() => reject(new PushError('failed')), ms) + p.then( + (v) => { + clearTimeout(timer) + resolve(v) + }, + (e) => { + clearTimeout(timer) + reject(e) + }, + ) + }) +} + +/** Service worker actif (absent en mode développement : on n'attend pas indéfiniment). */ +const registration = () => withTimeout(navigator.serviceWorker.ready, 8000) + +async function currentSubscription(): Promise { + const reg = await navigator.serviceWorker.getRegistration() + return (await reg?.pushManager.getSubscription()) ?? null +} + +export async function getPushState(): Promise { + const support = pushSupport() + if (support !== 'ok') return support + if (Notification.permission === 'denied') return 'denied' + if (Notification.permission !== 'granted') return 'off' + try { + return (await currentSubscription()) ? 'on' : 'off' + } catch { + return 'off' + } +} + +function b64urlToBytes(s: string): Uint8Array { + const b64 = s.replace(/-/g, '+').replace(/_/g, '/') + const bin = atob(b64 + '='.repeat((4 - (b64.length % 4)) % 4)) + const out = new Uint8Array(new ArrayBuffer(bin.length)) + for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i) + return out +} + +function bytesToB64url(buf: ArrayBuffer | null): string { + if (!buf) return '' + let s = '' + for (const b of new Uint8Array(buf)) s += String.fromCharCode(b) + return btoa(s).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '') +} + +/** Clé publique VAPID du serveur (la clé privée ne quitte jamais Supabase). */ +async function serverKey(): Promise { + let res: Response + try { + res = await cloudFetch('/functions/v1/send-push') + } catch { + throw new PushError('failed') + } + if (res.status === 404 || res.status === 503) throw new PushError('not-ready') + if (!res.ok) throw new PushError('failed') + const body = (await res.json().catch(() => null)) as unknown + const key = isPlainObject(body) && typeof body.publicKey === 'string' ? body.publicKey : '' + if (!/^B[A-Za-z0-9_-]{86}$/.test(key)) throw new PushError('not-ready') + return key +} + +/** Petit libellé de l'appareil (« Chrome · Android ») pour s'y retrouver côté serveur. */ +function deviceLabel(): string { + const ua = navigator.userAgent + const browser = /Edg\//.test(ua) ? 'Edge' : /Firefox\//.test(ua) ? 'Firefox' : /Chrome\//.test(ua) ? 'Chrome' : /Safari\//.test(ua) ? 'Safari' : 'Web' + const p = detectPlatform() + const os = p === 'ios' ? 'iOS' : p === 'android' ? 'Android' : /Windows/.test(ua) ? 'Windows' : /Mac/.test(ua) ? 'macOS' : /Linux|CrOS/.test(ua) ? 'Linux' : '' + return os ? `${browser} · ${os}` : browser +} + +async function register(sub: PushSubscription): Promise { + const lang = getLang() + const res = await cloudFetch('/rest/v1/rpc/register_push_subscription', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + p_endpoint: sub.endpoint, + p_p256dh: bytesToB64url(sub.getKey('p256dh')), + p_auth: bytesToB64url(sub.getKey('auth')), + p_lang: lang, + p_ua: deviceLabel(), + }), + }) + if (res.status === 404) throw new PushError('not-ready') + if (!res.ok) throw new PushError('failed') + storageSet(storeKey(), JSON.stringify({ endpoint: sub.endpoint, lang, at: Date.now() })) +} + +/** Active les notifications push sur cet appareil. À appeler uniquement depuis un clic. */ +export async function enablePush(): Promise { + const support = pushSupport() + if (support !== 'ok') return support + const permission = await Notification.requestPermission() + if (permission === 'denied') throw new PushError('denied') + if (permission !== 'granted') return 'off' + + const key = await serverKey() + const reg = await registration() + let sub = await reg.pushManager.getSubscription() + // Abonnement créé avec une autre clé serveur (clés VAPID changées) : on le refait + if (sub && sub.options.applicationServerKey && bytesToB64url(sub.options.applicationServerKey) !== key) { + await sub.unsubscribe().catch(() => false) + sub = null + } + if (!sub) { + try { + sub = await reg.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: b64urlToBytes(key) }) + } catch { + throw new PushError(Notification.permission === 'denied' ? 'denied' : 'failed') + } + } + try { + await register(sub) + } catch (e) { + await sub.unsubscribe().catch(() => false) + throw e instanceof PushError ? e : new PushError('failed') + } + return 'on' +} + +/** Coupe les notifications push sur cet appareil (et retire l'appareil du serveur). */ +export async function disablePush(): Promise { + if (pushSupport() !== 'ok') return + const sub = await currentSubscription().catch(() => null) + storageSet(storeKey(), null) + if (!sub) return + try { + await cloudFetch('/rest/v1/rpc/unregister_push_subscription', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ p_endpoint: sub.endpoint }), + }) + } catch { + /* hors-ligne : le serveur oubliera l'abonnement au premier envoi refusé (410) */ + } + await sub.unsubscribe().catch(() => false) +} + +/** Désabonne seulement le navigateur (compte supprimé : le serveur a déjà tout effacé). */ +export async function forgetPushLocally(): Promise { + storageSet(storeKey(), null) + if (pushSupport() !== 'ok') return + const sub = await currentSubscription().catch(() => null) + await sub?.unsubscribe().catch(() => false) +} + +/** + * Au lancement : réenregistre l'abonnement si le navigateur l'a renouvelé, si la langue a changé, + * ou une fois par semaine (le serveur garde ainsi les appareils réellement utilisés). + */ +export async function keepPushFresh(): Promise { + if (pushSupport() !== 'ok' || Notification.permission !== 'granted' || !navigator.onLine) return + const sub = await currentSubscription().catch(() => null) + if (!sub) return + let saved: unknown = null + try { + saved = JSON.parse(storageGet(storeKey()) ?? 'null') + } catch { + /* ignore */ + } + // Pas d'enregistrement connu : l'abonnement n'a pas été créé par ce compte, on n'y touche pas + if (!isPlainObject(saved)) return + const fresh = saved.endpoint === sub.endpoint && saved.lang === getLang() && typeof saved.at === 'number' && Date.now() - saved.at < REFRESH_MS + if (!fresh) await register(sub).catch(() => {}) +} diff --git a/src/pages/SettingsPage.tsx b/src/pages/SettingsPage.tsx index ddad8de..8dfa76f 100644 --- a/src/pages/SettingsPage.tsx +++ b/src/pages/SettingsPage.tsx @@ -3,6 +3,7 @@ import { LanguageSelect } from '../i18n/react' import { Check, Download, ExternalLink, Eye, EyeOff, HardDrive, Import, ShieldCheck, Smartphone, Trash2, Upload, UserX } from 'lucide-react' import { useEffect, useRef, useState, type ReactNode } from 'react' import AccountSection from '../components/AccountSection' +import PushToggle from '../components/PushToggle' import ConfirmDialog from '../components/ConfirmDialog' import ImportWizard from '../components/ImportWizard' import { PageHeader, SectionTitle } from '../components/ui' @@ -311,6 +312,7 @@ export default function SettingsPage({ onOpenAdmin }: { onOpenAdmin: () => void <> {t('settings.notifs')}

{t('settings.notifsHint')}

+
{NOTIF_PREFS.map(({ key, label }) => { const on = settings.notifPrefs?.[key] !== false diff --git a/src/store.tsx b/src/store.tsx index 57b1ef7..c82335e 100644 --- a/src/store.tsx +++ b/src/store.tsx @@ -9,6 +9,7 @@ import { createSync, type SyncEngine, type SyncStatus } from './lib/cloud/sync' import { deleteDatabase, readOtherDatabase } from './lib/db' import { cloudFetch } from './lib/cloud/api' import { signOut } from './lib/cloud/auth' +import { disablePush, forgetPushLocally } from './lib/push' import { dbNameFor, scopedKey } from './lib/scope' import { isPlainObject, LIMITS, readStorage, storageGet, storageSet } from './lib/security' import { mediaDB, requestPersistentStorage } from './lib/db' @@ -461,6 +462,8 @@ export function MediaProvider({ children, cloudUser }: { children: ReactNode; cl if (engine && navigator.onLine) await engine.syncNow() if (!force && engine && engine.status().pending > 0) return 'pending' engine?.stop() + // Cet appareil ne doit plus recevoir les notifications push de ce compte + await disablePush().catch(() => {}) await wipeAccountFromDevice(userId) await signOut() return 'done' @@ -473,6 +476,7 @@ export function MediaProvider({ children, cloudUser }: { children: ReactNode; cl }) if (!res.ok) throw new Error(res.status === 429 ? t('account.err.deleteRate') : t('account.err.delete')) syncRef.current?.stop() + await forgetPushLocally().catch(() => {}) await wipeAccountFromDevice(userId) await signOut() }, diff --git a/supabase/PUSH_SETUP.md b/supabase/PUSH_SETUP.md new file mode 100644 index 0000000..37afe87 --- /dev/null +++ b/supabase/PUSH_SETUP.md @@ -0,0 +1,109 @@ +# Notifications push (Web Push) — mise en service + +Les notifications de la cloche (nouveaux abonnés, demandes acceptées, réactions, nouveaux épisodes…) +peuvent aussi arriver **sur le téléphone / l'ordinateur, même app fermée**. + +``` +nouvelle ligne dans public.notifications + └─ déclencheur notifications_push (SQL) ── pg_net ──► fonction « send-push » (en-tête x-push-secret) + ├─ push_claim() : notifications non envoyées + appareils + ├─ préférences (notifPrefs) appliquées, textes traduits, regroupés + ├─ chiffrement aes128gcm + jeton VAPID ──► FCM / Mozilla / Apple / Windows + └─ push_done() : appareils expirés (404/410) supprimés +``` + +Rien ne casse tant que ce n'est pas configuré : sans secrets ni Vault, le déclencheur ne fait rien, +la cloche fonctionne comme avant et l'interrupteur des Réglages affiche « pas encore disponible ». + +--- + +## 1. Base de données (SQL Editor) + +Prérequis déjà appliqués : `20261007120000_social_notifications.sql` et `20261008140000_episode_notifications_fix.sql`. + +1. Supabase → **SQL Editor** → coller `supabase/migrations/20261009150000_web_push.sql` → **Run**. + - Elle active l'extension **pg_net** (`create extension if not exists pg_net`). Si l'éditeur refuse, + l'activer à la main : **Database → Extensions → pg_net → Enable**, puis relancer le fichier. + - Le fichier est idempotent : on peut le relancer sans risque. + +## 2. Clés VAPID et secret partagé (sur ton PC) + +```bash +node scripts/gen-vapid.mjs +``` + +Le script affiche les commandes à copier. **Ne jamais committer ces valeurs** (ni dans `.env`, ni en `VITE_…`). +La clé publique n'est pas secrète (l'app la lit via la fonction), la clé privée et le secret du webhook le sont. + +## 3. Secrets des fonctions + +Supabase → **Edge Functions → Secrets** (ou `supabase secrets set …`) : + +| Nom | Valeur | +| --- | --- | +| `VAPID_PUBLIC_KEY` | clé publique affichée par le script (87 caractères, commence par `B`) | +| `VAPID_PRIVATE_KEY` | clé privée affichée par le script (43 caractères) | +| `VAPID_SUBJECT` | `mailto:ton-adresse@…` (contact pour les services push) | +| `PUSH_WEBHOOK_SECRET` | secret aléatoire affiché par le script (≥ 32 caractères) | + +`SUPABASE_URL` et `SUPABASE_SERVICE_ROLE_KEY` sont fournis automatiquement. `ALLOWED_ORIGINS` +(déjà en place pour `tmdb`) sert aussi ici pour la lecture de la clé publique depuis le site. + +## 4. Déployer la fonction + +```bash +supabase functions deploy send-push --project-ref qfgnxonqwldcfdjqhhjz +``` + +`supabase/config.toml` contient `verify_jwt = false` pour `send-push` : la base l'appelle sans jeton +utilisateur, l'accès est protégé par l'en-tête `x-push-secret` (comparé en temps constant). +Vérification : ouvrir `https://qfgnxonqwldcfdjqhhjz.supabase.co/functions/v1/send-push` → `{"publicKey":"B…"}`. + +## 5. Adresse et secret dans Supabase Vault (SQL Editor) + +Le déclencheur lit ces deux valeurs dans Vault (elles ne sont jamais écrites dans une migration) : + +```sql +select vault.create_secret('https://qfgnxonqwldcfdjqhhjz.supabase.co/functions/v1/send-push', 'azuu_push_url'); +select vault.create_secret('', 'azuu_push_secret'); +``` + +Pour changer une valeur plus tard : + +```sql +select vault.update_secret((select id from vault.secrets where name = 'azuu_push_secret'), ''); +``` + +(et mettre la même dans le secret `PUSH_WEBHOOK_SECRET` de la fonction). + +## 6. Publier l'app + +`git push` (Gitea Actions construit et publie). Le service worker se met à jour tout seul ; +il charge `push-sw.js` (servi en `Cache-Control: no-cache`, en-tête généré depuis `vite.config.ts`). + +## 7. Tester + +1. Sur l'app : **Réglages → Notifications → Notifications sur cet appareil** (la permission n'est demandée qu'à ce moment-là). + - iPhone / iPad : uniquement depuis l'app **installée sur l'écran d'accueil**, iOS 16.4 ou plus récent. +2. Depuis un autre compte, s'abonner à ce compte → une notification doit arriver (même app fermée). +3. En cas de souci : + ```sql + select count(*) from public.push_subscriptions; -- l'appareil est-il inscrit ? + select id, status_code, content, created from net._http_response order by created desc limit 10; -- appels de la base + ``` + et **Edge Functions → send-push → Logs**. Un `401` = `PUSH_WEBHOOK_SECRET` et `azuu_push_secret` différents ; + un `503 not-configured` = secrets VAPID manquants ou mal copiés. + +## Sécurité (résumé) + +- `push_subscriptions` : RLS activé et forcé ; chacun ne voit / supprime que ses appareils ; ajout uniquement via + `register_push_subscription` (security definer) qui n'accepte que des adresses **https** vers les services push + connus (`fcm.googleapis.com`, `updates.push.services.mozilla.com`, `*.push.apple.com`, `web.push.apple.com`, + `*.notify.windows.com`) : pas de SSRF possible. La fonction d'envoi revérifie la liste. +- 10 appareils max par compte (les plus anciens sont retirés), 10 nouvelles inscriptions max par 10 minutes. +- Un abonnement déjà lié à un autre compte n'est repris que si l'on fournit les mêmes clés (même navigateur). +- À la déconnexion, l'appareil est désinscrit ; à la suppression du compte, tout part en cascade. +- `push_claim` / `push_done` : réservées au rôle `service_role`. Les préférences `notifPrefs` sont appliquées + à la création **et** à l'envoi. +- Changer les clés VAPID invalide les abonnements existants : après une rotation, vider la table + (`delete from public.push_subscriptions;`) ; chacun réactive l'interrupteur. diff --git a/supabase/config.toml b/supabase/config.toml index 80f128a..43fe8a7 100644 --- a/supabase/config.toml +++ b/supabase/config.toml @@ -9,3 +9,6 @@ verify_jwt = false [functions.delete-account] verify_jwt = false + +[functions.send-push] +verify_jwt = false diff --git a/supabase/functions/_shared/webpush.ts b/supabase/functions/_shared/webpush.ts new file mode 100644 index 0000000..6b8c21c --- /dev/null +++ b/supabase/functions/_shared/webpush.ts @@ -0,0 +1,201 @@ +// Web Push sans dépendance : chiffrement « aes128gcm » (RFC 8188 + RFC 8291) et +// authentification VAPID (RFC 8292, jeton JWT ES256), uniquement avec WebCrypto. +// Aucune API propre à Deno ici : le module est aussi testé avec Node (vecteurs de la RFC 8291). + +const enc = new TextEncoder() +/** Octets adossés à un ArrayBuffer (exigé par les types WebCrypto / fetch récents) */ +export type Bytes = Uint8Array + +export function b64urlEncode(bytes: Bytes): string { + let s = '' + for (const b of bytes) s += String.fromCharCode(b) + return btoa(s).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '') +} + +export function b64urlDecode(str: string): Bytes { + if (!/^[A-Za-z0-9_-]*={0,2}$/.test(str)) throw new Error('base64url invalide') + const b64 = str.replace(/=+$/, '').replace(/-/g, '+').replace(/_/g, '/') + const bin = atob(b64 + '='.repeat((4 - (b64.length % 4)) % 4)) + const out = new Uint8Array(bin.length) + for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i) + return out +} + +function concat(...parts: Uint8Array[]): Bytes { + const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0)) + let o = 0 + for (const p of parts) { + out.set(p, o) + o += p.length + } + return out +} + +async function hmac(key: Bytes, data: Bytes): Promise { + const k = await crypto.subtle.importKey('raw', key, { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']) + return new Uint8Array(await crypto.subtle.sign('HMAC', k, data)) +} + +/** Clé publique P-256 brute (65 octets, 0x04 || X || Y) → JWK. */ +function rawToJwk(raw: Bytes, d?: Bytes): JsonWebKey { + if (raw.length !== 65 || raw[0] !== 4) throw new Error('clé publique P-256 invalide') + return { + kty: 'EC', + crv: 'P-256', + x: b64urlEncode(raw.slice(1, 33)), + y: b64urlEncode(raw.slice(33, 65)), + ...(d ? { d: b64urlEncode(d) } : {}), + ext: true, + } +} + +export interface EncryptOptions { + /** Pour les tests uniquement : paire éphémère et sel imposés (vecteurs RFC 8291). */ + asPrivate?: Bytes + asPublic?: Bytes + salt?: Bytes + /** Taille d'enregistrement annoncée (4096 par défaut) */ + rs?: number +} + +/** + * Chiffre un message pour un abonnement push (Content-Encoding: aes128gcm). + * @param uaPublic clé « p256dh » de l'abonnement (65 octets) + * @param authSecret clé « auth » de l'abonnement (16 octets) + */ +export async function encryptPayload( + plaintext: Bytes, + uaPublic: Bytes, + authSecret: Bytes, + opts: EncryptOptions = {}, +): Promise { + if (uaPublic.length !== 65 || uaPublic[0] !== 4) throw new Error('p256dh invalide') + if (authSecret.length < 16) throw new Error('auth invalide') + const rs = opts.rs ?? 4096 + // Un seul enregistrement : le message (+ 1 octet de délimitation + 16 octets de tag) doit tenir dedans + if (plaintext.length + 1 + 16 > rs) throw new Error('message trop long') + + // Paire de clés éphémère du serveur d'application + let asPriv: CryptoKey + let asPublic: Bytes + if (opts.asPrivate && opts.asPublic) { + asPriv = await crypto.subtle.importKey('jwk', rawToJwk(opts.asPublic, opts.asPrivate), { name: 'ECDH', namedCurve: 'P-256' }, false, ['deriveBits']) + asPublic = opts.asPublic + } else { + const pair = (await crypto.subtle.generateKey({ name: 'ECDH', namedCurve: 'P-256' }, true, ['deriveBits'])) as CryptoKeyPair + asPriv = pair.privateKey + asPublic = new Uint8Array(await crypto.subtle.exportKey('raw', pair.publicKey)) + } + const uaKey = await crypto.subtle.importKey('raw', uaPublic, { name: 'ECDH', namedCurve: 'P-256' }, false, []) + const ecdhSecret = new Uint8Array(await crypto.subtle.deriveBits({ name: 'ECDH', public: uaKey }, asPriv, 256)) + + // RFC 8291 §3.3-3.4 (HKDF écrit avec HMAC, une seule itération suffit pour ≤ 32 octets) + const prkKey = await hmac(authSecret, ecdhSecret) + const keyInfo = concat(enc.encode('WebPush: info\0'), uaPublic, asPublic) + const ikm = await hmac(prkKey, concat(keyInfo, new Uint8Array([1]))) + + const salt = opts.salt ?? crypto.getRandomValues(new Uint8Array(16)) + if (salt.length !== 16) throw new Error('sel invalide') + const prk = await hmac(salt, ikm) + const cek = (await hmac(prk, enc.encode('Content-Encoding: aes128gcm\0\x01'))).slice(0, 16) + const nonce = (await hmac(prk, enc.encode('Content-Encoding: nonce\0\x01'))).slice(0, 12) + + // Dernier (et seul) enregistrement : délimiteur 0x02, sans remplissage + const record = concat(plaintext, new Uint8Array([2])) + const aes = await crypto.subtle.importKey('raw', cek, { name: 'AES-GCM' }, false, ['encrypt']) + const cipher = new Uint8Array(await crypto.subtle.encrypt({ name: 'AES-GCM', iv: nonce, tagLength: 128 }, aes, record)) + + // En-tête RFC 8188 : sel (16) || rs (4, gros-boutiste) || idlen (1) || keyid (clé publique éphémère) + const header = new Uint8Array(16 + 4 + 1 + asPublic.length) + header.set(salt, 0) + new DataView(header.buffer).setUint32(16, rs, false) + header[20] = asPublic.length + header.set(asPublic, 21) + return concat(header, cipher) +} + +export interface VapidKeys { + /** Clé publique brute en base64url (65 octets) */ + publicKey: string + /** Clé privée (scalaire « d », 32 octets) en base64url */ + privateKey: string + /** « mailto:… » ou « https://… » */ + subject: string +} + +const signingKeys = new Map>() + +function vapidSigningKey(v: VapidKeys): Promise { + const cacheKey = v.publicKey + let p = signingKeys.get(cacheKey) + if (!p) { + p = crypto.subtle.importKey('jwk', rawToJwk(b64urlDecode(v.publicKey), b64urlDecode(v.privateKey)), { name: 'ECDSA', namedCurve: 'P-256' }, false, ['sign']) + signingKeys.set(cacheKey, p) + } + return p +} + +/** En-tête Authorization VAPID pour un point d'envoi donné (jeton valable 12 h). */ +export async function vapidAuthorization(endpoint: string, v: VapidKeys, nowSec = Math.floor(Date.now() / 1000)): Promise { + const aud = new URL(endpoint).origin + const header = b64urlEncode(enc.encode(JSON.stringify({ typ: 'JWT', alg: 'ES256' }))) + const claims = b64urlEncode(enc.encode(JSON.stringify({ aud, exp: nowSec + 12 * 3600, sub: v.subject }))) + const unsigned = `${header}.${claims}` + // WebCrypto renvoie la signature au format r || s (64 octets), celui attendu par JWS + const sig = new Uint8Array(await crypto.subtle.sign({ name: 'ECDSA', hash: 'SHA-256' }, await vapidSigningKey(v), enc.encode(unsigned))) + return `vapid t=${unsigned}.${b64urlEncode(sig)}, k=${v.publicKey}` +} + +export interface PushTarget { + endpoint: string + p256dh: string + auth: string +} + +export type PushResult = 'ok' | 'gone' | 'error' + +/** Envoie un message chiffré à un abonnement. « gone » = abonnement expiré (à supprimer). */ +export async function sendWebPush(target: PushTarget, payload: string, v: VapidKeys, ttl = 24 * 3600, topic?: string): Promise { + const body = await encryptPayload(enc.encode(payload), b64urlDecode(target.p256dh), b64urlDecode(target.auth)) + const headers: Record = { + Authorization: await vapidAuthorization(target.endpoint, v), + 'Content-Encoding': 'aes128gcm', + 'Content-Type': 'application/octet-stream', + TTL: String(ttl), + Urgency: 'normal', + } + // « Topic » : un message plus récent du même sujet remplace celui encore en attente + if (topic && /^[A-Za-z0-9_-]{1,32}$/.test(topic)) headers.Topic = topic + const ctrl = new AbortController() + const timer = setTimeout(() => ctrl.abort(), 10_000) + try { + const res = await fetch(target.endpoint, { method: 'POST', headers, body, signal: ctrl.signal, redirect: 'error' }) + await res.body?.cancel() + if (res.status === 404 || res.status === 410) return 'gone' + return res.ok ? 'ok' : 'error' + } catch { + return 'error' + } finally { + clearTimeout(timer) + } +} + +/** Mêmes hôtes que la vérification côté base (anti-SSRF, double contrôle). */ +export function isAllowedPushEndpoint(endpoint: string): boolean { + if (endpoint.length > 1024) return false + let u: URL + try { + u = new URL(endpoint) + } catch { + return false + } + if (u.protocol !== 'https:' || u.username || u.password || (u.port && u.port !== '443')) return false + const h = u.hostname.toLowerCase() + return ( + h === 'fcm.googleapis.com' || + h === 'updates.push.services.mozilla.com' || + h === 'web.push.apple.com' || + /^[a-z0-9-]{1,63}(\.[a-z0-9-]{1,63})*\.push\.apple\.com$/.test(h) || + /^[a-z0-9-]{1,63}(\.[a-z0-9-]{1,63})*\.notify\.windows\.com$/.test(h) + ) +} diff --git a/supabase/functions/send-push/compose.ts b/supabase/functions/send-push/compose.ts new file mode 100644 index 0000000..8701c78 --- /dev/null +++ b/supabase/functions/send-push/compose.ts @@ -0,0 +1,97 @@ +// Transforme les notifications d'un compte en messages push courts (regroupés si besoin). +// Module sans API Deno : testé aussi avec Node. + +import { fill, MESSAGES } from './messages.ts' + +export interface ClaimedItem { + id: number + kind: string + emoji: string | null + item_id: string | null + episode: number | null + ep_count: number | null + actor: { username: string; display_name: string } | null + title: string | null +} + +export interface PushMessage { + title: string + body: string + /** Écran à ouvrir au clic (paramètre « open » de l'app) */ + open: string + /** Une notification du même « tag » remplace la précédente sur l'appareil */ + tag: string +} + +const EMOJIS = new Set(['👍', '❤️', '🔥', '😂', '😮', '😢']) + +/** Texte venu de la base : sans caractères de contrôle ni de direction, longueur bornée. */ +export function clean(v: unknown, max: number): string { + if (typeof v !== 'string') return '' + const s = v.replace(/[\u0000-\u001f\u007f-\u009f​-‏‪-‮⁦-⁩]/g, '').replace(/\s+/g, ' ').trim() + return s.length > max ? s.slice(0, max - 1).trimEnd() + '…' : s +} + +const SAFE_ID = /^[A-Za-z0-9_-]{1,64}$/ +const SAFE_USER = /^[a-z0-9_]{3,20}$/ + +export function compose(items: ClaimedItem[], lang: string): PushMessage[] { + const tx = MESSAGES[lang] ?? MESSAGES.fr + const out: PushMessage[] = [] + const eps = items.filter((i) => i.kind === 'new_episode' || i.kind === 'new_season') + const social = items.filter((i) => i.kind !== 'new_episode' && i.kind !== 'new_season') + + // Épisodes : un message par série, ou un seul résumé s'il y en a plusieurs + if (eps.length === 1) { + const e = eps[0] + const n = Number.isInteger(e.episode) && (e.episode as number) > 0 ? (e.episode as number) : null + out.push({ + title: clean(e.title, 80) || 'AzuuCine', + body: e.kind === 'new_season' || n === null ? tx.season : fill(tx.episode, { n }), + open: e.item_id && SAFE_ID.test(e.item_id) ? `item:${e.item_id}` : 'notifications', + tag: e.item_id && SAFE_ID.test(e.item_id) ? `ep-${e.item_id}`.slice(0, 64) : 'episodes', + }) + } else if (eps.length > 1) { + const titles = [...new Set(eps.map((e) => clean(e.title, 40)).filter(Boolean))] + out.push({ + title: `${tx.episodesTitle} (${eps.length})`, + body: clean(titles.join(' · '), 160) || fill(tx.many, { count: eps.length }), + open: 'notifications', + tag: 'episodes', + }) + } + + // Abonnements / réactions : un message chacun (3 au plus), sinon un résumé + if (social.length > 3) { + out.push({ title: 'AzuuCine', body: fill(tx.many, { count: social.length }), open: 'notifications', tag: 'social' }) + } else { + for (const s of social) { + const name = clean(s.actor?.display_name, 40) || clean(s.actor?.username, 20) || 'AzuuCine' + const user = s.actor && SAFE_USER.test(s.actor.username) ? s.actor.username : null + let body: string + let open = 'notifications' + let title = 'AzuuCine' + switch (s.kind) { + case 'follow_request': + body = fill(tx.followRequest, { name }) + break + case 'new_follower': + body = fill(tx.newFollower, { name }) + if (user) open = `u:${user}` + break + case 'follow_accepted': + body = fill(tx.followAccepted, { name }) + if (user) open = `u:${user}` + break + case 'reaction': + body = fill(tx.reaction, { name, emoji: s.emoji && EMOJIS.has(s.emoji) ? s.emoji : '' }).replace(/\s+/g, ' ') + title = clean(s.title, 80) || 'AzuuCine' + break + default: + continue + } + out.push({ title, body, open, tag: `n-${s.id}` }) + } + } + return out +} diff --git a/supabase/functions/send-push/index.ts b/supabase/functions/send-push/index.ts new file mode 100644 index 0000000..397682c --- /dev/null +++ b/supabase/functions/send-push/index.ts @@ -0,0 +1,119 @@ +// Notifications push (Web Push). +// - GET : renvoie la clé publique VAPID (pour que l'app puisse s'abonner). +// - POST : appelé par la base à chaque nouvelle notification (déclencheur + pg_net), +// avec l'en-tête « x-push-secret ». Prend les notifications non envoyées du compte, +// applique ses préférences, les regroupe et les envoie à tous ses appareils. +// Secrets (supabase secrets set …) : VAPID_PUBLIC_KEY, VAPID_PRIVATE_KEY, VAPID_SUBJECT, PUSH_WEBHOOK_SECRET. +// Voir supabase/PUSH_SETUP.md. + +import { corsHeaders, json } from '../_shared/auth.ts' +import { isAllowedPushEndpoint, sendWebPush, type VapidKeys } from '../_shared/webpush.ts' +import { compose, type ClaimedItem } from './compose.ts' + +const SUPABASE_URL = Deno.env.get('SUPABASE_URL') ?? '' +const SERVICE_KEY = Deno.env.get('SUPABASE_SERVICE_ROLE_KEY') ?? '' +const WEBHOOK_SECRET = Deno.env.get('PUSH_WEBHOOK_SECRET') ?? '' +const VAPID: VapidKeys = { + publicKey: (Deno.env.get('VAPID_PUBLIC_KEY') ?? '').trim(), + privateKey: (Deno.env.get('VAPID_PRIVATE_KEY') ?? '').trim(), + subject: (Deno.env.get('VAPID_SUBJECT') ?? '').trim(), +} +const vapidReady = /^B[A-Za-z0-9_-]{86}$/.test(VAPID.publicKey) && /^[A-Za-z0-9_-]{43}$/.test(VAPID.privateKey) && /^(mailto:|https:\/\/)/.test(VAPID.subject) + +const enc = new TextEncoder() + +/** Comparaison en temps constant (le secret ne peut pas être deviné caractère par caractère). */ +async function sameSecret(given: string, expected: string): Promise { + if (!given || expected.length < 32 || given.length > 512) return false + const key = await crypto.subtle.importKey('raw', crypto.getRandomValues(new Uint8Array(32)), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']) + const [a, b] = await Promise.all([crypto.subtle.sign('HMAC', key, enc.encode(given)), crypto.subtle.sign('HMAC', key, enc.encode(expected))]) + const x = new Uint8Array(a) + const y = new Uint8Array(b) + let diff = 0 + for (let i = 0; i < x.length; i++) diff |= x[i] ^ y[i] + return diff === 0 +} + +async function rpc(name: string, args: Record): Promise { + const res = await fetch(`${SUPABASE_URL}/rest/v1/rpc/${name}`, { + method: 'POST', + headers: { apikey: SERVICE_KEY, Authorization: `Bearer ${SERVICE_KEY}`, 'Content-Type': 'application/json' }, + body: JSON.stringify(args), + }) + if (!res.ok) throw new Error(`${name}: ${res.status}`) + const text = await res.text() + return (text ? JSON.parse(text) : null) as T +} + +interface Sub { + endpoint: string + p256dh: string + auth: string + lang: string +} + +const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i + +Deno.serve(async (req) => { + if (req.method === 'OPTIONS') return new Response(null, { status: 204, headers: corsHeaders(req) }) + + // Clé publique : elle n'a rien de secret (elle est envoyée au service push du navigateur) + if (req.method === 'GET') { + if (!vapidReady) return json(req, 503, { error: 'not-configured' }) + return json(req, 200, { publicKey: VAPID.publicKey }, { 'Cache-Control': 'public, max-age=3600' }) + } + if (req.method !== 'POST') return json(req, 405, { error: 'method' }) + + // Appel réservé à la base de données + if (!WEBHOOK_SECRET || !(await sameSecret(req.headers.get('x-push-secret') ?? '', WEBHOOK_SECRET))) { + return json(req, 401, { error: 'auth' }) + } + if (!vapidReady || !SERVICE_KEY || !SUPABASE_URL) return json(req, 503, { error: 'not-configured' }) + + let userId = '' + try { + const body = (await req.json()) as { user_id?: unknown } + if (typeof body.user_id === 'string' && UUID.test(body.user_id)) userId = body.user_id + } catch { + /* corps invalide */ + } + if (!userId) return json(req, 400, { error: 'user' }) + + let claim: { subs?: Sub[]; items?: ClaimedItem[] } + try { + claim = (await rpc('push_claim', { p_user: userId })) ?? {} + } catch { + return json(req, 502, { error: 'claim' }) + } + const subs = (claim.subs ?? []).filter((s) => isAllowedPushEndpoint(s.endpoint)).slice(0, 10) + const items = (claim.items ?? []).slice(0, 100) + if (!subs.length || !items.length) return json(req, 200, { sent: 0 }) + + const gone: string[] = [] + const ok: string[] = [] + let sent = 0 + await Promise.all( + subs.map(async (s) => { + const messages = compose(items, s.lang).slice(0, 4) + let alive = true + for (const m of messages) { + if (!alive) break + const payload = JSON.stringify({ title: m.title, body: m.body, tag: m.tag, url: `/?open=${encodeURIComponent(m.open)}` }) + const r = await sendWebPush(s, payload, VAPID, 24 * 3600, m.tag.replace(/[^A-Za-z0-9_-]/g, '').slice(0, 32)) + if (r === 'gone') { + gone.push(s.endpoint) + alive = false + } else if (r === 'ok') { + sent++ + if (!ok.includes(s.endpoint)) ok.push(s.endpoint) + } + } + }), + ) + try { + await rpc('push_done', { p_user: userId, p_gone: gone, p_ok: ok }) + } catch { + /* le ménage se fera au prochain envoi */ + } + return json(req, 200, { sent, gone: gone.length }) +}) diff --git a/supabase/functions/send-push/messages.ts b/supabase/functions/send-push/messages.ts new file mode 100644 index 0000000..2628f6a --- /dev/null +++ b/supabase/functions/send-push/messages.ts @@ -0,0 +1,200 @@ +// Textes courts des notifications push, dans la langue choisie sur l'appareil à l'inscription. +// Variables : {name} (auteur), {emoji}, {n} (numéro d'épisode), {count}. + +export interface PushTexts { + followRequest: string + newFollower: string + followAccepted: string + reaction: string + episode: string + season: string + episodesTitle: string + many: string +} + +export const MESSAGES: Record = { + fr: { + followRequest: '{name} veut s’abonner à toi', + newFollower: '{name} te suit désormais', + followAccepted: '{name} a accepté ta demande d’abonnement', + reaction: '{name} a réagi {emoji} à ton avis', + episode: 'Épisode {n} disponible', + season: 'Nouvelle saison disponible', + episodesTitle: 'Nouveaux épisodes', + many: 'Nouvelles notifications : {count}', + }, + en: { + followRequest: '{name} wants to follow you', + newFollower: '{name} is now following you', + followAccepted: '{name} accepted your follow request', + reaction: '{name} reacted {emoji} to your review', + episode: 'Episode {n} is out', + season: 'New season is out', + episodesTitle: 'New episodes', + many: 'New notifications: {count}', + }, + es: { + followRequest: '{name} quiere seguirte', + newFollower: '{name} ahora te sigue', + followAccepted: '{name} aceptó tu solicitud de seguimiento', + reaction: '{name} reaccionó {emoji} a tu reseña', + episode: 'Episodio {n} disponible', + season: 'Nueva temporada disponible', + episodesTitle: 'Nuevos episodios', + many: 'Notificaciones nuevas: {count}', + }, + it: { + followRequest: '{name} vuole seguirti', + newFollower: '{name} ora ti segue', + followAccepted: '{name} ha accettato la tua richiesta', + reaction: '{name} ha reagito {emoji} alla tua recensione', + episode: 'Episodio {n} disponibile', + season: 'Nuova stagione disponibile', + episodesTitle: 'Nuovi episodi', + many: 'Nuove notifiche: {count}', + }, + de: { + followRequest: '{name} möchte dir folgen', + newFollower: '{name} folgt dir jetzt', + followAccepted: '{name} hat deine Anfrage angenommen', + reaction: '{name} hat mit {emoji} auf deine Bewertung reagiert', + episode: 'Folge {n} ist verfügbar', + season: 'Neue Staffel verfügbar', + episodesTitle: 'Neue Folgen', + many: 'Neue Benachrichtigungen: {count}', + }, + pt: { + followRequest: '{name} quer seguir você', + newFollower: '{name} agora segue você', + followAccepted: '{name} aceitou seu pedido para seguir', + reaction: '{name} reagiu {emoji} à sua avaliação', + episode: 'Episódio {n} disponível', + season: 'Nova temporada disponível', + episodesTitle: 'Novos episódios', + many: 'Novas notificações: {count}', + }, + nl: { + followRequest: '{name} wil je volgen', + newFollower: '{name} volgt je nu', + followAccepted: '{name} heeft je volgverzoek geaccepteerd', + reaction: '{name} reageerde {emoji} op je recensie', + episode: 'Aflevering {n} is uit', + season: 'Nieuw seizoen beschikbaar', + episodesTitle: 'Nieuwe afleveringen', + many: 'Nieuwe meldingen: {count}', + }, + pl: { + followRequest: '{name} chce cię obserwować', + newFollower: '{name} obserwuje cię', + followAccepted: '{name} zaakceptował(a) twoją prośbę', + reaction: '{name} zareagował(a) {emoji} na twoją recenzję', + episode: 'Odcinek {n} jest dostępny', + season: 'Nowy sezon jest dostępny', + episodesTitle: 'Nowe odcinki', + many: 'Nowe powiadomienia: {count}', + }, + ru: { + followRequest: '{name} хочет подписаться на вас', + newFollower: '{name} теперь подписан(а) на вас', + followAccepted: '{name} принял(а) ваш запрос на подписку', + reaction: '{name} отреагировал(а) {emoji} на ваш отзыв', + episode: 'Вышла серия {n}', + season: 'Вышел новый сезон', + episodesTitle: 'Новые серии', + many: 'Новые уведомления: {count}', + }, + tr: { + followRequest: '{name} seni takip etmek istiyor', + newFollower: '{name} artık seni takip ediyor', + followAccepted: '{name} takip isteğini kabul etti', + reaction: '{name} incelemene {emoji} tepkisi verdi', + episode: '{n}. bölüm yayında', + season: 'Yeni sezon yayında', + episodesTitle: 'Yeni bölümler', + many: 'Yeni bildirimler: {count}', + }, + ar: { + followRequest: '{name} يريد متابعتك', + newFollower: '{name} يتابعك الآن', + followAccepted: '{name} قبل طلب المتابعة', + reaction: '{name} تفاعل {emoji} مع مراجعتك', + episode: 'الحلقة {n} متاحة', + season: 'موسم جديد متاح', + episodesTitle: 'حلقات جديدة', + many: 'إشعارات جديدة: {count}', + }, + hi: { + followRequest: '{name} आपको फ़ॉलो करना चाहते हैं', + newFollower: '{name} अब आपको फ़ॉलो करते हैं', + followAccepted: '{name} ने आपका फ़ॉलो अनुरोध स्वीकार किया', + reaction: '{name} ने आपकी समीक्षा पर {emoji} प्रतिक्रिया दी', + episode: 'एपिसोड {n} उपलब्ध है', + season: 'नया सीज़न उपलब्ध है', + episodesTitle: 'नए एपिसोड', + many: 'नई सूचनाएँ: {count}', + }, + id: { + followRequest: '{name} ingin mengikutimu', + newFollower: '{name} sekarang mengikutimu', + followAccepted: '{name} menerima permintaan mengikutimu', + reaction: '{name} bereaksi {emoji} pada ulasanmu', + episode: 'Episode {n} sudah tersedia', + season: 'Musim baru sudah tersedia', + episodesTitle: 'Episode baru', + many: 'Notifikasi baru: {count}', + }, + th: { + followRequest: '{name} ต้องการติดตามคุณ', + newFollower: '{name} ติดตามคุณแล้ว', + followAccepted: '{name} ยอมรับคำขอติดตามของคุณแล้ว', + reaction: '{name} แสดงความรู้สึก {emoji} ต่อรีวิวของคุณ', + episode: 'ตอนที่ {n} มาแล้ว', + season: 'ซีซันใหม่มาแล้ว', + episodesTitle: 'ตอนใหม่', + many: 'การแจ้งเตือนใหม่: {count}', + }, + vi: { + followRequest: '{name} muốn theo dõi bạn', + newFollower: '{name} đã theo dõi bạn', + followAccepted: '{name} đã chấp nhận yêu cầu theo dõi', + reaction: '{name} đã bày tỏ {emoji} với đánh giá của bạn', + episode: 'Tập {n} đã ra mắt', + season: 'Mùa mới đã ra mắt', + episodesTitle: 'Tập mới', + many: 'Thông báo mới: {count}', + }, + zh: { + followRequest: '{name} 想要关注你', + newFollower: '{name} 关注了你', + followAccepted: '{name} 接受了你的关注请求', + reaction: '{name} 对你的评论回应了 {emoji}', + episode: '第 {n} 集已上线', + season: '新一季已上线', + episodesTitle: '新剧集', + many: '新通知:{count}', + }, + ja: { + followRequest: '{name}さんがあなたをフォローしたいと言っています', + newFollower: '{name}さんがあなたをフォローしました', + followAccepted: '{name}さんがフォローリクエストを承認しました', + reaction: '{name}さんがあなたのレビューに{emoji}でリアクションしました', + episode: '第{n}話が配信されました', + season: '新シーズンが配信されました', + episodesTitle: '新しいエピソード', + many: '新しい通知:{count}', + }, + ko: { + followRequest: '{name}님이 팔로우를 요청했어요', + newFollower: '{name}님이 회원님을 팔로우해요', + followAccepted: '{name}님이 팔로우 요청을 수락했어요', + reaction: '{name}님이 리뷰에 {emoji} 반응을 남겼어요', + episode: '{n}화가 공개됐어요', + season: '새 시즌이 공개됐어요', + episodesTitle: '새 에피소드', + many: '새 알림: {count}', + }, +} + +export function fill(text: string, vars: Record): string { + return text.replace(/\{(\w+)\}/g, (m, k: string) => (k in vars ? String(vars[k]) : m)) +} diff --git a/supabase/migrations/20261009150000_web_push.sql b/supabase/migrations/20261009150000_web_push.sql new file mode 100644 index 0000000..a4ee450 --- /dev/null +++ b/supabase/migrations/20261009150000_web_push.sql @@ -0,0 +1,213 @@ +-- ════════════════════════════════════════════════════════════════════════════ +-- AzuuCine — Notifications push (Web Push), même app fermée (9 octobre 2026) +-- 1. push_subscriptions : les appareils où chacun a activé les notifications. +-- 2. Inscription / désinscription sûres (hôtes des services push connus uniquement : anti-SSRF). +-- 3. À chaque nouvelle notification (cloche), la base appelle la fonction serveur « send-push » +-- (extension pg_net), avec un secret partagé lu dans Supabase Vault (jamais écrit ici). +-- +-- Prérequis : 20261007120000_social_notifications.sql appliqué. +-- À coller dans Supabase → SQL Editor → Run. Idempotent (réexécutable sans risque). +-- Étapes manuelles (secrets, Vault, déploiement) : voir supabase/PUSH_SETUP.md +-- ════════════════════════════════════════════════════════════════════════════ + +-- pg_net : appels HTTP asynchrones depuis la base (envoyés après la validation de la transaction) +create extension if not exists pg_net; + +-- ── Abonnements push (un par appareil / navigateur) ── +create table if not exists public.push_subscriptions ( + id bigint generated always as identity primary key, + user_id uuid not null default auth.uid() references auth.users(id) on delete cascade, + endpoint text not null unique check (char_length(endpoint) between 20 and 1024), + p256dh text not null check (p256dh ~ '^B[A-Za-z0-9_-]{86}=?$'), + auth text not null check (auth ~ '^[A-Za-z0-9_-]{22}(==)?$'), + -- Langue des messages envoyés à cet appareil + lang text not null default 'fr' check (lang in ('fr','en','es','it','de','pt','nl','pl','ru','tr','ar','hi','id','th','vi','zh','ja','ko')), + -- Petit libellé de l'appareil (« Chrome · Android »), pour s'y retrouver + user_agent text check (user_agent is null or char_length(user_agent) <= 60), + created_at timestamptz not null default now(), + last_used_at timestamptz +); +create index if not exists push_subscriptions_user_idx on public.push_subscriptions (user_id); +alter table public.push_subscriptions enable row level security; +alter table public.push_subscriptions force row level security; +revoke all on public.push_subscriptions from anon, authenticated; +grant select, delete on public.push_subscriptions to authenticated; + +-- Chacun ne voit / supprime que ses propres appareils (l'ajout passe par la fonction ci-dessous) +drop policy if exists push_subscriptions_select_own on public.push_subscriptions; +create policy push_subscriptions_select_own on public.push_subscriptions + for select to authenticated using (user_id = (select auth.uid())); +drop policy if exists push_subscriptions_delete_own on public.push_subscriptions; +create policy push_subscriptions_delete_own on public.push_subscriptions + for delete to authenticated using (user_id = (select auth.uid())); + +-- ── Notifications : marque « déjà envoyée en push » ── +alter table public.notifications add column if not exists pushed_at timestamptz; +create index if not exists notifications_unpushed_idx on public.notifications (user_id, created_at) where pushed_at is null; +-- L'historique existant n'est jamais envoyé en push +update public.notifications set pushed_at = created_at +where pushed_at is null and created_at < now() - interval '15 minutes'; + +-- ── Inscription d'un appareil ── +create or replace function public.register_push_subscription( + p_endpoint text, p_p256dh text, p_auth text, p_lang text default 'fr', p_ua text default null +) +returns jsonb language plpgsql security definer set search_path = '' as $$ +declare + me uuid := auth.uid(); + v_host text; + v_lang text; + v_ua text; +begin + if me is null then raise exception 'auth'; end if; + + -- Adresse d'envoi : https uniquement, vers un service push connu (sinon le serveur pourrait + -- être utilisé pour contacter n'importe quelle adresse : SSRF) + if p_endpoint is null or char_length(p_endpoint) > 1024 + or p_endpoint !~ '^https://[A-Za-z0-9.-]+(:443)?/[^[:space:]]*$' then + raise exception 'bad endpoint'; + end if; + v_host := lower(substring(p_endpoint from '^https://([A-Za-z0-9.-]+)')); + if not ( + v_host in ('fcm.googleapis.com', 'updates.push.services.mozilla.com', 'web.push.apple.com') + or v_host ~ '^([a-z0-9-]{1,63}\.)+push\.apple\.com$' + or v_host ~ '^([a-z0-9-]{1,63}\.)+notify\.windows\.com$' + ) then + raise exception 'push service not allowed'; + end if; + if p_p256dh is null or p_p256dh !~ '^B[A-Za-z0-9_-]{86}=?$' then raise exception 'bad key'; end if; + if p_auth is null or p_auth !~ '^[A-Za-z0-9_-]{22}(==)?$' then raise exception 'bad auth'; end if; + + v_lang := case when p_lang in ('fr','en','es','it','de','pt','nl','pl','ru','tr','ar','hi','id','th','vi','zh','ja','ko') then p_lang else 'fr' end; + v_ua := nullif(left(regexp_replace(coalesce(p_ua, ''), '[^A-Za-z0-9 ._()/·-]', '', 'g'), 60), ''); + + -- Anti-abus : 10 nouveaux appareils max en 10 minutes + if (select count(*) from public.push_subscriptions s + where s.user_id = me and s.created_at > now() - interval '10 minutes') >= 10 then + raise exception 'rate'; + end if; + + -- Même navigateur réinscrit (ou changement de compte sur l'appareil) : on met à jour. + -- Un abonnement d'un autre compte n'est repris que si l'on prouve le posséder (mêmes clés). + insert into public.push_subscriptions as s (user_id, endpoint, p256dh, auth, lang, user_agent, last_used_at) + values (me, p_endpoint, p_p256dh, p_auth, v_lang, v_ua, now()) + on conflict (endpoint) do update + set user_id = me, p256dh = excluded.p256dh, auth = excluded.auth, lang = excluded.lang, + user_agent = excluded.user_agent, last_used_at = now() + where s.user_id = me or (s.p256dh = excluded.p256dh and s.auth = excluded.auth); + if not found then raise exception 'endpoint taken'; end if; + + -- 10 appareils max par compte : les plus anciens sont retirés + delete from public.push_subscriptions + where user_id = me and id not in ( + select id from public.push_subscriptions where user_id = me + order by coalesce(last_used_at, created_at) desc limit 10 + ); + return jsonb_build_object('ok', true); +end; +$$; + +-- ── Désinscription d'un appareil ── +create or replace function public.unregister_push_subscription(p_endpoint text) +returns jsonb language plpgsql security definer set search_path = '' as $$ +begin + if auth.uid() is null then raise exception 'auth'; end if; + delete from public.push_subscriptions where user_id = auth.uid() and endpoint = p_endpoint; + return jsonb_build_object('ok', true); +end; +$$; + +-- ── Fonction serveur (service_role) : prend les notifications à envoyer d'un compte ── +-- Les notifications arrivées ensemble (plusieurs épisodes) sont prises d'un coup, ce qui permet +-- de les regrouper ; une notification n'est prise qu'une seule fois (pushed_at). +create or replace function public.push_claim(p_user uuid) +returns jsonb language plpgsql security definer set search_path = '' as $$ +declare res jsonb; +begin + if coalesce(auth.jwt()->>'role', '') <> 'service_role' then raise exception 'forbidden'; end if; + with claimed as ( + update public.notifications n set pushed_at = now() + where n.user_id = p_user and n.pushed_at is null and n.read_at is null + and n.created_at > now() - interval '15 minutes' + returning n.id, n.user_id, n.kind, n.actor_id, n.item_id, n.emoji, n.episode, n.ep_count, n.created_at + ) + select jsonb_build_object( + 'subs', coalesce(( + select jsonb_agg(jsonb_build_object('endpoint', s.endpoint, 'p256dh', s.p256dh, 'auth', s.auth, 'lang', s.lang)) + from public.push_subscriptions s where s.user_id = p_user), '[]'::jsonb), + 'items', coalesce(( + select jsonb_agg(jsonb_build_object( + 'id', c.id, 'kind', c.kind, 'emoji', c.emoji, 'item_id', c.item_id, + 'episode', c.episode, 'ep_count', c.ep_count, + 'actor', case when p.id is null then null + else jsonb_build_object('username', p.username, 'display_name', p.display_name) end, + 'title', (select it.data->>'title' from public.items it where it.user_id = c.user_id and it.id = c.item_id) + ) order by c.created_at) + from claimed c left join public.profiles p on p.id = c.actor_id + where public.azuu_wants(c.user_id, c.kind)), '[]'::jsonb) + ) into res; + return res; +end; +$$; + +-- ── Fonction serveur (service_role) : bilan d'un envoi ── +create or replace function public.push_done(p_user uuid, p_gone text[], p_ok text[]) +returns void language plpgsql security definer set search_path = '' as $$ +begin + if coalesce(auth.jwt()->>'role', '') <> 'service_role' then raise exception 'forbidden'; end if; + -- Abonnements expirés (404 / 410) : supprimés + delete from public.push_subscriptions where user_id = p_user and endpoint = any(coalesce(p_gone, '{}')); + update public.push_subscriptions set last_used_at = now() + where user_id = p_user and endpoint = any(coalesce(p_ok, '{}')); +end; +$$; + +-- ── Déclencheur : nouvelle notification → appel de « send-push » ── +-- Adresse et secret dans Vault (voir PUSH_SETUP.md) : +-- azuu_push_url = https://.supabase.co/functions/v1/send-push +-- azuu_push_secret = la même valeur que le secret PUSH_WEBHOOK_SECRET de la fonction +-- Un seul appel par compte et par transaction (plusieurs épisodes d'un coup = 1 appel, regroupé). +-- Toute erreur (pg_net absent, Vault vide…) est ignorée : la notification reste dans la cloche. +create or replace function public.azuu_push_dispatch() +returns trigger language plpgsql security definer set search_path = '' as $$ +declare + v_url text; + v_secret text; + v_flag text := 'azuu.push_' || replace(new.user_id::text, '-', ''); +begin + if not exists (select 1 from public.push_subscriptions s where s.user_id = new.user_id) then return null; end if; + if current_setting(v_flag, true) = '1' then return null; end if; + begin + select ds.decrypted_secret into v_url from vault.decrypted_secrets ds where ds.name = 'azuu_push_url' limit 1; + select ds.decrypted_secret into v_secret from vault.decrypted_secrets ds where ds.name = 'azuu_push_secret' limit 1; + if v_url is null or v_secret is null or char_length(v_secret) < 32 + or v_url !~ '^https://[A-Za-z0-9.-]+/functions/v1/send-push$' then + return null; + end if; + perform net.http_post( + url := v_url, + body := jsonb_build_object('user_id', new.user_id), + headers := jsonb_build_object('Content-Type', 'application/json', 'x-push-secret', v_secret), + timeout_milliseconds := 10000 + ); + perform set_config(v_flag, '1', true); + exception when others then + null; + end; + return null; +end; +$$; +drop trigger if exists notifications_push on public.notifications; +create trigger notifications_push after insert on public.notifications + for each row execute function public.azuu_push_dispatch(); + +-- ── Droits ── +revoke all on function public.register_push_subscription(text, text, text, text, text) from public, anon; +revoke all on function public.unregister_push_subscription(text) from public, anon; +revoke all on function public.push_claim(uuid) from public, anon, authenticated; +revoke all on function public.push_done(uuid, text[], text[]) from public, anon, authenticated; +revoke all on function public.azuu_push_dispatch() from public, anon, authenticated; +grant execute on function public.register_push_subscription(text, text, text, text, text) to authenticated; +grant execute on function public.unregister_push_subscription(text) to authenticated; +grant execute on function public.push_claim(uuid) to service_role; +grant execute on function public.push_done(uuid, text[], text[]) to service_role; diff --git a/vite.config.ts b/vite.config.ts index 36cb950..10bb443 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -3,6 +3,10 @@ import react from '@vitejs/plugin-react' import tailwindcss from '@tailwindcss/vite' import { VitePWA } from 'vite-plugin-pwa' +// Gestion des notifications push (public/push-sw.js), ajoutée au service worker généré. +// La date de build dans l'adresse fait changer sw.js à chaque version : push-sw.js est toujours rechargé. +const pushSwVersion = Date.now().toString(36) + /** * Politique de sécurité du contenu (CSP) : le navigateur n'exécute que les scripts de l'app, * et ne contacte que TMDB / AniList. Même si une donnée piégée arrivait à s'afficher, @@ -55,6 +59,8 @@ function contentSecurityPolicy(supabaseUrl: string): Plugin { '# Le service worker doit toujours être revérifié pour que les mises à jour arrivent', '/sw.js', ' Cache-Control: no-cache', + '/push-sw.js', + ' Cache-Control: no-cache', '', ].join('\n'), }) @@ -105,6 +111,7 @@ export default defineConfig(({ mode }) => { ], }, workbox: { + importScripts: [`push-sw.js?v=${pushSwVersion}`], globPatterns: ['**/*.{js,css,html,svg,png,ico,webmanifest,woff2}'], // L'app vit entièrement sur « / » (routes après le #) : toute autre adresse reçoit la page 404 du serveur navigateFallbackAllowlist: [/^\/(?:index\.html)?(?:\?.*)?$/],