Suppression du système de notifications

- Plus de cloche sur l'accueil ni de panneau de notifications.
- Plus de notifications push : réglage retiré, service worker sans push-sw.js,
  fonction send-push et script VAPID supprimés du dépôt.
- Réglages « Notifications » retirés (et notifPrefs des réglages synchronisés).
- Plus d'envoi des nouveaux épisodes au serveur pour les notifications.
- Au lancement, l'appli résilie l'ancien abonnement push de l'appareil s'il en reste un.
- Textes retirés des 18 langues ; politique de confidentialité mise à jour.
- Serveur : migration 20261122120000_remove_notifications.sql (déjà appliquée en ligne) :
  plus aucune notification créée ni envoyée, données vidées.
- Les demandes d'abonnement et invitations aux listes restent accessibles
  depuis le profil et les listes partagées.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YVo1qxKoBQCaMd7Ue8PGbe
This commit is contained in:
Claude committed 2026-11-22 17:04:40 +00:00
1 parent 3eb8d4651c
commit dba91678bd
43 files changed
+62 -2298

No files matched your search

-111
View File
@@ -1,111 +0,0 @@
# 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/A_COLLER_2026-10-09.sql` (contient `20261009150000_web_push.sql` et l'adresse `azuu_push_url` dans Vault) → **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
> ✅ Déjà fait le 9 oct. 2026 (version 1 déployée par Claude). À refaire seulement si `functions/send-push` change.
```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('<la même valeur que PUSH_WEBHOOK_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'), '<nouvelle valeur>');
```
(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.
-2
View File
@@ -10,5 +10,3 @@ verify_jwt = false
[functions.delete-account]
verify_jwt = false
[functions.send-push]
verify_jwt = false
-201
View File
@@ -1,201 +0,0 @@
// 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<ArrayBuffer>
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<Bytes> {
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<Bytes> {
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<string, Promise<CryptoKey>>()
function vapidSigningKey(v: VapidKeys): Promise<CryptoKey> {
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<string> {
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<PushResult> {
const body = await encryptPayload(enc.encode(payload), b64urlDecode(target.p256dh), b64urlDecode(target.auth))
const headers: Record<string, string> = {
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)
)
}
-104
View File
@@ -1,104 +0,0 @@
// 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\u200b-\u200f\u202a-\u202e\u2066-\u2069]/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) || 'Kino',
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: 'Kino', 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) || 'Kino'
const user = s.actor && SAFE_USER.test(s.actor.username) ? s.actor.username : null
let body: string
let open = 'notifications'
let title = 'Kino'
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) || 'Kino'
break
case 'review_comment':
body = fill(tx.comment, { name })
title = clean(s.title, 80) || 'Kino'
break
case 'shared_list_invite':
body = fill(tx.listInvite, { name, list: clean(s.title, 60) })
break
default:
continue
}
out.push({ title, body, open, tag: `n-${s.id}` })
}
}
return out
}
-119
View File
@@ -1,119 +0,0 @@
// 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<boolean> {
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<T>(name: string, args: Record<string, unknown>): Promise<T> {
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<typeof claim>('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 })
})
-238
View File
@@ -1,238 +0,0 @@
// Textes courts des notifications push, dans la langue choisie sur l'appareil à l'inscription.
// Variables : {name} (auteur), {emoji}, {n} (numéro d'épisode), {count}, {list} (nom de liste).
export interface PushTexts {
followRequest: string
newFollower: string
followAccepted: string
reaction: string
episode: string
season: string
episodesTitle: string
many: string
comment: string
listInvite: string
}
export const MESSAGES: Record<string, PushTexts> = {
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}',
comment: '{name} a commenté ton avis',
listInvite: "{name} t'invite dans la liste « {list} »",
},
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}',
comment: '{name} commented on your review',
listInvite: '{name} invited you to the list “{list}”',
},
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}',
comment: '{name} comentó tu reseña',
listInvite: '{name} te invitó a la lista «{list}»',
},
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}',
comment: '{name} ha commentato la tua recensione',
listInvite: '{name} ti ha invitato nella lista «{list}»',
},
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}',
comment: '{name} hat deine Bewertung kommentiert',
listInvite: '{name} hat dich zur Liste „{list}“ eingeladen',
},
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}',
comment: '{name} comentou sua avaliação',
listInvite: '{name} convidou você para a lista “{list}”',
},
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}',
comment: '{name} reageerde op je recensie',
listInvite: '{name} nodigde je uit voor de lijst ‘{list}’',
},
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}',
comment: '{name} skomentował(a) twoją recenzję',
listInvite: '{name} zaprasza cię do listy „{list}”',
},
ru: {
followRequest: '{name} хочет подписаться на вас',
newFollower: '{name} теперь подписан(а) на вас',
followAccepted: '{name} принял(а) ваш запрос на подписку',
reaction: '{name} отреагировал(а) {emoji} на ваш отзыв',
episode: 'Вышла серия {n}',
season: 'Вышел новый сезон',
episodesTitle: 'Новые серии',
many: 'Новые уведомления: {count}',
comment: '{name} прокомментировал(а) ваш отзыв',
listInvite: '{name} приглашает вас в список «{list}»',
},
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}',
comment: '{name} incelemene yorum yaptı',
listInvite: '{name} seni “{list}” listesine davet etti',
},
ar: {
followRequest: '{name} يريد متابعتك',
newFollower: '{name} يتابعك الآن',
followAccepted: '{name} قبل طلب المتابعة',
reaction: '{name} تفاعل {emoji} مع مراجعتك',
episode: 'الحلقة {n} متاحة',
season: 'موسم جديد متاح',
episodesTitle: 'حلقات جديدة',
many: 'إشعارات جديدة: {count}',
comment: '{name} علّق على مراجعتك',
listInvite: '{name} يدعوك إلى القائمة «{list}»',
},
hi: {
followRequest: '{name} आपको फ़ॉलो करना चाहते हैं',
newFollower: '{name} अब आपको फ़ॉलो करते हैं',
followAccepted: '{name} ने आपका फ़ॉलो अनुरोध स्वीकार किया',
reaction: '{name} ने आपकी समीक्षा पर {emoji} प्रतिक्रिया दी',
episode: 'एपिसोड {n} उपलब्ध है',
season: 'नया सीज़न उपलब्ध है',
episodesTitle: 'नए एपिसोड',
many: 'नई सूचनाएँ: {count}',
comment: '{name} ने आपकी समीक्षा पर टिप्पणी की',
listInvite: '{name} ने आपको सूची “{list}” में आमंत्रित किया',
},
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}',
comment: '{name} mengomentari ulasanmu',
listInvite: '{name} mengundangmu ke daftar “{list}”',
},
th: {
followRequest: '{name} ต้องการติดตามคุณ',
newFollower: '{name} ติดตามคุณแล้ว',
followAccepted: '{name} ยอมรับคำขอติดตามของคุณแล้ว',
reaction: '{name} แสดงความรู้สึก {emoji} ต่อรีวิวของคุณ',
episode: 'ตอนที่ {n} มาแล้ว',
season: 'ซีซันใหม่มาแล้ว',
episodesTitle: 'ตอนใหม่',
many: 'การแจ้งเตือนใหม่: {count}',
comment: '{name} แสดงความคิดเห็นในรีวิวของคุณ',
listInvite: '{name} เชิญคุณเข้าร่วมรายการ “{list}”',
},
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}',
comment: '{name} đã bình luận về đánh giá của bạn',
listInvite: '{name} mời bạn vào danh sách “{list}”',
},
zh: {
followRequest: '{name} 想要关注你',
newFollower: '{name} 关注了你',
followAccepted: '{name} 接受了你的关注请求',
reaction: '{name} 对你的评论回应了 {emoji}',
episode: '第 {n} 集已上线',
season: '新一季已上线',
episodesTitle: '新剧集',
many: '新通知:{count}',
comment: '{name} 评论了你的影评',
listInvite: '{name} 邀请你加入列表「{list}」',
},
ja: {
followRequest: '{name}さんがあなたをフォローしたいと言っています',
newFollower: '{name}さんがあなたをフォローしました',
followAccepted: '{name}さんがフォローリクエストを承認しました',
reaction: '{name}さんがあなたのレビューに{emoji}でリアクションしました',
episode: '第{n}話が配信されました',
season: '新シーズンが配信されました',
episodesTitle: '新しいエピソード',
many: '新しい通知:{count}',
comment: '{name}さんがあなたのレビューにコメントしました',
listInvite: '{name}さんがリスト「{list}」にあなたを招待しました',
},
ko: {
followRequest: '{name}님이 팔로우를 요청했어요',
newFollower: '{name}님이 회원님을 팔로우해요',
followAccepted: '{name}님이 팔로우 요청을 수락했어요',
reaction: '{name}님이 리뷰에 {emoji} 반응을 남겼어요',
episode: '{n}화가 공개됐어요',
season: '새 시즌이 공개됐어요',
episodesTitle: '새 에피소드',
many: '새 알림: {count}',
comment: '{name}님이 리뷰에 댓글을 남겼어요',
listInvite: "{name}님이 '{list}' 리스트에 초대했어요",
},
}
export function fill(text: string, vars: Record<string, string | number>): string {
return text.replace(/\{(\w+)\}/g, (m, k: string) => (k in vars ? String(vars[k]) : m))
}
@@ -0,0 +1,29 @@
-- Kino — suppression du système de notifications (22 novembre 2026). Idempotent.
-- Plus aucune notification n'est créée ni envoyée (cloche et push). Les tables restent en place,
-- vides, car d'autres fonctions y font encore référence (listes partagées…).
-- Envoi push à chaque notification, et notifications automatiques (abonnements, réactions)
drop trigger if exists notifications_push on public.notifications;
drop trigger if exists follows_notify on public.follows;
drop trigger if exists reactions_notify on public.review_reactions;
-- Commentaires, invitations… appelaient azuu_notify : elle ne fait plus rien
create or replace function public.azuu_notify(p_user uuid, p_kind text, p_actor uuid, p_item text default null, p_emoji text default null)
returns void language plpgsql security definer set search_path = '' as $$
begin
return;
end $$;
-- Nouveaux épisodes : plus de notification
create or replace function public.add_episode_notifications(p_list jsonb)
returns integer language plpgsql security definer set search_path = '' as $$
begin
return 0;
end $$;
-- Plus aucun appareil ne peut s'inscrire aux notifications push
revoke execute on function public.register_push_subscription(text, text, text, text, text) from public, anon, authenticated;
-- Données devenues inutiles : appareils inscrits et notifications déjà reçues
delete from public.push_subscriptions;
delete from public.notifications;