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:
Claude committed 2026-10-09 15:21:17 +00:00
1 parent c246b16e7e
commit 6f7064f53f
35 files changed
+1779

No files matched your search

+97
View File
@@ -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
}
+119
View File
@@ -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 })
})
+200
View File
@@ -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))
}