Notifications push (Web Push) et indicateur hors-ligne / synchro en attente
- Réglages → Notifications : interrupteur « Notifications sur cet appareil » (permission demandée au clic uniquement, iOS : explication « installe l'app », permission refusée, navigateur non compatible). Désinscription à la déconnexion. - Service worker : push-sw.js chargé via workbox.importScripts (affichage + clic qui ouvre/focalise l'app sur le bon écran via « /?open=… »). - Serveur : table push_subscriptions (RLS, anti-SSRF, 10 appareils max), déclencheur pg_net + secret dans Vault, fonction send-push (aes128gcm + VAPID ES256 en WebCrypto, testée sur le vecteur RFC 8291), regroupement des épisodes, préférences notifPrefs, ménage des abonnements expirés. - scripts/gen-vapid.mjs et supabase/PUSH_SETUP.md (étapes manuelles). - Pastille discrète hors-ligne / « N modifications en attente » (mobile au-dessus de la barre de nav, ordinateur dans la barre latérale), basée sur l'état du moteur de synchro existant. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01YVo1qxKoBQCaMd7Ue8PGbe
This commit is contained in:
35 files changed
+1779
No files matched your search
@@ -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('<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.
|
||||
@@ -9,3 +9,6 @@ verify_jwt = false
|
||||
|
||||
[functions.delete-account]
|
||||
verify_jwt = false
|
||||
|
||||
[functions.send-push]
|
||||
verify_jwt = false
|
||||
@@ -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<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)
|
||||
)
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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<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 })
|
||||
})
|
||||
@@ -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<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}',
|
||||
},
|
||||
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, string | number>): string {
|
||||
return text.replace(/\{(\w+)\}/g, (m, k: string) => (k in vars ? String(vars[k]) : m))
|
||||
}
|
||||
@@ -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://<ref>.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;
|
||||
Reference in new issue
Block a user