Audit : corrections de bugs, sécurité et performances (sans changement de fonctionnement)
Données et synchro - Import « remplacer » atomique (plus de bibliothèque vidée si l'écriture échoue). - Deux onglets sur le même compte : mise à jour croisée, file d'envoi partagée sans perte. - Réception : une modification locale faite pendant la synchro n'est plus écrasée ; une seule transaction. - Envoi : file vidée paquet par paquet, fiche invalide isolée (quota : gardée en attente), taille en octets réels, délai proportionnel à la taille ; grandes affiches décodées sans fetch (bloqué par la CSP). - Plus d'écriture dans la base d'un autre compte après déconnexion ; base fermée proprement (iOS). - Revisionnages journalisés à part (rewatchLog) : les défis ne sous-estiment plus le 1er visionnage ; décocher des épisodes un autre jour ne gonfle plus les défis. Comptes et social - Renouvellement de session : plus de déconnexion de tous les onglets avec un jeton déjà utilisé, plus de rafale de renouvellements, déconnexion qui révoque bien la session serveur. - Délais maximum sur les appels réseau, écran blanc évité au retour de Google. - Abonnés/abonnements au-delà de 50, pagination du fil et des profils, fil hors-ligne, listes bloquées. - Code mort retiré (CommentsSheet et options jamais utilisées). Interface et logique - Toast qui ne disparaissait plus, focus sur « Annuler » dans les confirmations, Échap pendant la saisie IME. - Demi-étoile en arabe, flèches RTL, fonds d'overlay en jeton de thème, couleur du thème étoilé. - Séries en cours sans total connu : les nouveaux épisodes se cochent à nouveau ; épisodes spéciaux ignorés. - Catalogue, accueil et calendrier plus rapides sur les grosses bibliothèques. Sources externes - Proxy TMDB : les 18 langues acceptées (9 étaient refusées), 429 transmis, délais, paramètres durcis. - Contenus adultes AniList filtrés des recommandations, cache d'import borné, imports plus sûrs. Serveur (migration 20261122140000_audit_hardening.sql, déjà appliquée en ligne) - Fonctions admin et « comptes suspendus » versionnées ; blocage effectif ; avis robustes ; fiches supprimées vidées ; comptes suspendus sans abonnement ni réaction ; objets morts supprimés. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01YVo1qxKoBQCaMd7Ue8PGbe
This commit is contained in:
73 files changed
+2074
-2162
No files matched your search
File diff suppressed because it is too large.
Load diff
@@ -28,8 +28,22 @@ export function json(req: Request, status: number, body: unknown, extra: Record<
|
||||
})
|
||||
}
|
||||
|
||||
// Petit cache jeton → utilisateur (évite de revérifier le même jeton à chaque requête)
|
||||
const verified = new Map<string, { id: string; until: number }>()
|
||||
// Petit cache jeton → utilisateur (évite de revérifier le même jeton à chaque requête).
|
||||
// Les jetons refusés sont aussi gardés 30 s (id null) : un jeton invalide répété ne sollicite pas Supabase Auth à chaque fois.
|
||||
const verified = new Map<string, { id: string | null; until: number }>()
|
||||
|
||||
function remember(token: string, id: string | null, ttlMs: number) {
|
||||
// Trop d'entrées : on retire les plus anciennes (ordre d'insertion de la Map) au lieu de tout vider
|
||||
if (verified.size >= 5000) {
|
||||
let n = verified.size - 4000
|
||||
for (const k of verified.keys()) {
|
||||
if (n-- <= 0) break
|
||||
verified.delete(k)
|
||||
}
|
||||
}
|
||||
verified.delete(token)
|
||||
verified.set(token, { id, until: Date.now() + ttlMs })
|
||||
}
|
||||
|
||||
/** Vérifie le jeton de connexion auprès de Supabase Auth. Renvoie l'id de l'utilisateur, ou null. */
|
||||
export async function getUserId(req: Request): Promise<string | null> {
|
||||
@@ -38,12 +52,24 @@ export async function getUserId(req: Request): Promise<string | null> {
|
||||
if (!token || token.length > 4096 || token === ANON_KEY) return null
|
||||
const cached = verified.get(token)
|
||||
if (cached && cached.until > Date.now()) return cached.id
|
||||
const res = await fetch(`${SUPABASE_URL}/auth/v1/user`, { headers: { apikey: ANON_KEY, Authorization: `Bearer ${token}` } })
|
||||
if (!res.ok) return null
|
||||
const user = (await res.json()) as { id?: string }
|
||||
let res: Response
|
||||
try {
|
||||
res = await fetch(`${SUPABASE_URL}/auth/v1/user`, {
|
||||
headers: { apikey: ANON_KEY, Authorization: `Bearer ${token}` },
|
||||
signal: AbortSignal.timeout(8000),
|
||||
})
|
||||
} catch {
|
||||
return null // Auth injoignable : on ne met rien en cache
|
||||
}
|
||||
if (!res.ok) {
|
||||
await res.body?.cancel()
|
||||
// Jeton refusé (401/403) : mémorisé brièvement ; erreur passagère (5xx…) : pas de cache
|
||||
if (res.status === 401 || res.status === 403) remember(token, null, 30_000)
|
||||
return null
|
||||
}
|
||||
const user = (await res.json().catch(() => ({}))) as { id?: string }
|
||||
if (typeof user.id !== 'string') return null
|
||||
if (verified.size > 5000) verified.clear()
|
||||
verified.set(token, { id: user.id, until: Date.now() + 60_000 })
|
||||
remember(token, user.id, 60_000)
|
||||
return user.id
|
||||
}
|
||||
|
||||
@@ -53,7 +79,16 @@ export function rateLimited(userId: string, max: number, windowMs: number): bool
|
||||
const now = Date.now()
|
||||
const list = (hits.get(userId) ?? []).filter((t) => now - t < windowMs)
|
||||
list.push(now)
|
||||
// Réinsertion : la clé passe en fin de Map (ordre = dernière activité)
|
||||
hits.delete(userId)
|
||||
hits.set(userId, list)
|
||||
if (hits.size > 10000) hits.clear()
|
||||
// Trop de clés : on retire les moins récemment actives au lieu de tout vider (sinon tout le monde repart à zéro)
|
||||
if (hits.size > 10000) {
|
||||
let n = hits.size - 8000
|
||||
for (const k of hits.keys()) {
|
||||
if (n-- <= 0) break
|
||||
hits.delete(k)
|
||||
}
|
||||
}
|
||||
return list.length > max
|
||||
}
|
||||
@@ -11,7 +11,8 @@ const PATHS = /^\/(search\/(multi|person)|configuration|discover\/(movie|tv)|(mo
|
||||
|
||||
// Paramètres autorisés et forme de leur valeur
|
||||
const PARAMS: Record<string, RegExp> = {
|
||||
language: /^(fr-FR|en-US|es-ES|it-IT|de-DE|pt-BR|zh-CN|ja-JP|ko-KR)$/,
|
||||
// Forme « xx » ou « xx-YY » : couvre toutes les langues de l'app (src/i18n/index.ts) sans liste à tenir à jour
|
||||
language: /^[a-z]{2}(-[A-Z]{2})?$/,
|
||||
query: /^[^\u0000-\u001f]{1,100}$/,
|
||||
include_adult: /^false$/,
|
||||
page: /^[1-9]\d?$/,
|
||||
@@ -35,15 +36,7 @@ Deno.serve(async (req) => {
|
||||
if (req.method !== 'GET') return json(req, 405, { error: 'method' })
|
||||
if (!TMDB_KEY) return json(req, 500, { error: 'TMDB_API_KEY manquante' })
|
||||
|
||||
// Compte connecté : 600 requêtes / 10 min. Visiteur sans compte (mode découverte) : 200 / 10 min par adresse IP.
|
||||
const userId = await getUserId(req)
|
||||
if (userId) {
|
||||
if (rateLimited(userId, 600, 10 * 60_000)) return json(req, 429, { error: 'rate' })
|
||||
} else {
|
||||
const ip = (req.headers.get('x-forwarded-for') ?? '').split(',')[0].trim() || req.headers.get('cf-connecting-ip') || 'inconnu'
|
||||
if (rateLimited(`ip:${ip.slice(0, 64)}`, 200, 10 * 60_000)) return json(req, 429, { error: 'rate' })
|
||||
}
|
||||
|
||||
// On vérifie l'adresse et les paramètres AVANT d'appeler Supabase Auth (une requête invalide ne coûte rien)
|
||||
const url = new URL(req.url)
|
||||
const path = url.searchParams.get('path') ?? ''
|
||||
if (!PATHS.test(path)) return json(req, 400, { error: 'path' })
|
||||
@@ -51,17 +44,50 @@ Deno.serve(async (req) => {
|
||||
const target = new URL('https://api.themoviedb.org/3' + path)
|
||||
for (const [k, v] of url.searchParams) {
|
||||
if (k === 'path') continue
|
||||
const rule = PARAMS[k]
|
||||
// Object.hasOwn : « ?constructor=x » ne doit pas remonter jusqu'au prototype
|
||||
const rule = Object.hasOwn(PARAMS, k) ? PARAMS[k] : undefined
|
||||
if (!rule || !rule.test(v)) return json(req, 400, { error: 'param', name: k.slice(0, 40) })
|
||||
target.searchParams.set(k, v)
|
||||
}
|
||||
|
||||
// Compte connecté : 600 requêtes / 10 min. Visiteur sans compte (mode découverte) : 200 / 10 min par adresse IP.
|
||||
const userId = await getUserId(req)
|
||||
if (userId) {
|
||||
if (rateLimited(userId, 600, 10 * 60_000)) return json(req, 429, { error: 'rate' })
|
||||
} else {
|
||||
// NB : la 1re entrée de x-forwarded-for peut être fournie par le client. Faute de garantie documentée
|
||||
// sur un en-tête posé par la plateforme Supabase (non falsifiable), on garde ce comportement.
|
||||
const ip = (req.headers.get('x-forwarded-for') ?? '').split(',')[0].trim() || req.headers.get('cf-connecting-ip') || 'inconnu'
|
||||
if (rateLimited(`ip:${ip.slice(0, 64)}`, 200, 10 * 60_000)) return json(req, 429, { error: 'rate' })
|
||||
}
|
||||
|
||||
// Clé v3 (32 caractères) en paramètre, jeton v4 en en-tête
|
||||
const isBearer = TMDB_KEY.length > 40
|
||||
if (!isBearer) target.searchParams.set('api_key', TMDB_KEY)
|
||||
|
||||
const res = await fetch(target, { headers: isBearer ? { Authorization: `Bearer ${TMDB_KEY}` } : {} })
|
||||
if (!res.ok) return json(req, res.status === 404 ? 404 : 502, { error: 'tmdb', status: res.status })
|
||||
const body = await res.text()
|
||||
let res: Response
|
||||
let body: string
|
||||
try {
|
||||
res = await fetch(target, {
|
||||
headers: isBearer ? { Authorization: `Bearer ${TMDB_KEY}` } : {},
|
||||
signal: AbortSignal.timeout(8000),
|
||||
})
|
||||
if (res.status === 429) {
|
||||
// TMDB nous limite : on transmet le 429 (et le délai conseillé) plutôt qu'une erreur générique
|
||||
const retry = res.headers.get('Retry-After')
|
||||
await res.body?.cancel()
|
||||
return json(req, 429, { error: 'tmdb', status: 429 }, retry && /^\d{1,5}$/.test(retry) ? { 'Retry-After': retry } : {})
|
||||
}
|
||||
if (!res.ok) {
|
||||
await res.body?.cancel()
|
||||
return json(req, res.status === 404 ? 404 : 502, { error: 'tmdb', status: res.status })
|
||||
}
|
||||
body = await res.text()
|
||||
} catch (e) {
|
||||
// TMDB injoignable ou trop lent (délai dépassé)
|
||||
const timeout = e instanceof DOMException && (e.name === 'TimeoutError' || e.name === 'AbortError')
|
||||
return json(req, timeout ? 504 : 502, { error: timeout ? 'timeout' : 'upstream' })
|
||||
}
|
||||
if (body.length > 2_000_000) return json(req, 502, { error: 'size' })
|
||||
return new Response(body, {
|
||||
status: 200,
|
||||
|
||||
@@ -23,7 +23,10 @@ revoke all on function public.is_admin() from public, anon;
|
||||
grant execute on function public.is_admin() to authenticated;
|
||||
|
||||
-- Romain est administrateur.
|
||||
insert into public.admins (user_id) values ('4529202d-618c-4b40-ab13-228eef3f71ad') on conflict do nothing;
|
||||
-- (seulement si ce compte existe : une base neuve ou une copie de test n'a pas cet utilisateur)
|
||||
insert into public.admins (user_id)
|
||||
select id from auth.users where id = '4529202d-618c-4b40-ab13-228eef3f71ad'
|
||||
on conflict do nothing;
|
||||
|
||||
-- ── Intégration de la suspension dans les fonctions sociales ──
|
||||
-- (can_view, search_profiles, get_feed, get_follow_list, get_follow_requests, get_profile
|
||||
|
||||
@@ -22,14 +22,24 @@ begin
|
||||
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;
|
||||
do $$ begin
|
||||
if to_regprocedure('public.register_push_subscription(text,text,text,text,text)') is not null then
|
||||
execute 'revoke execute on function public.register_push_subscription(text,text,text,text,text) from public, anon, authenticated';
|
||||
end if;
|
||||
end $$;
|
||||
|
||||
-- Données devenues inutiles : appareils inscrits et notifications déjà reçues
|
||||
delete from public.push_subscriptions;
|
||||
do $$ begin
|
||||
if to_regclass('public.push_subscriptions') is not null then delete from public.push_subscriptions; end if;
|
||||
end $$;
|
||||
delete from public.notifications;
|
||||
|
||||
-- Ménage : fonctions et secrets qui ne servaient qu'à l'envoi push
|
||||
drop function if exists public.azuu_push_dispatch();
|
||||
drop function if exists public.push_claim(uuid);
|
||||
drop function if exists public.push_done(uuid, text[], text[]);
|
||||
delete from vault.secrets where name in ('azuu_push_secret', 'azuu_push_url');
|
||||
do $$ begin
|
||||
if to_regclass('vault.secrets') is not null then
|
||||
delete from vault.secrets where name in ('azuu_push_secret', 'azuu_push_url');
|
||||
end if;
|
||||
end $$;
|
||||
@@ -0,0 +1,495 @@
|
||||
-- ============================================================================
|
||||
-- Kino — audit du 22 novembre 2026 : corrections serveur. Idempotent (rejouable).
|
||||
-- 1. Fonctions présentes en ligne mais absentes du dépôt (admin, versions « comptes suspendus ») :
|
||||
-- elles sont maintenant versionnées ici, telles qu'en ligne (+ corrections ci-dessous).
|
||||
-- 2. Blocage : un compte qui m'a bloqué ne m'est plus visible (profil, bibliothèque, avis, recherche).
|
||||
-- 3. Avis par titre : une note mal formée ne casse plus la page ; tri avant pagination.
|
||||
-- 4. Fiches supprimées : leur contenu est effacé (empêchait de dépasser le quota de stockage).
|
||||
-- 5. Comptes suspendus : ne peuvent plus s'abonner ni réagir.
|
||||
-- 6. Ménage : objets inutilisés depuis la suppression des notifications, fonctions de test.
|
||||
-- ============================================================================
|
||||
|
||||
-- ── 1. Lecture : visibilité d'un compte (suspendu ou m'ayant bloqué = invisible) ──
|
||||
create or replace function public.can_view(owner uuid)
|
||||
returns boolean language sql stable security definer set search_path = '' as $$
|
||||
select auth.uid() is not null and (
|
||||
owner = auth.uid()
|
||||
or (
|
||||
not exists (select 1 from public.profiles p where p.id = owner and p.suspended)
|
||||
and not exists (select 1 from public.blocks b where b.blocker_id = owner and b.blocked_id = auth.uid())
|
||||
and (
|
||||
exists (select 1 from public.profiles p where p.id = owner and not p.is_private)
|
||||
or exists (select 1 from public.follows f where f.follower_id = auth.uid() and f.following_id = owner and f.status = 'accepted')
|
||||
)
|
||||
)
|
||||
)
|
||||
$$;
|
||||
revoke all on function public.can_view(uuid) from public, anon, authenticated;
|
||||
|
||||
create or replace function public.get_profile(p_username text)
|
||||
returns jsonb language plpgsql stable security definer set search_path = '' as $$
|
||||
declare
|
||||
p public.profiles;
|
||||
me uuid := auth.uid();
|
||||
res jsonb;
|
||||
begin
|
||||
if me is null then
|
||||
return null;
|
||||
end if;
|
||||
select * into p from public.profiles where username = lower(trim(p_username));
|
||||
if not found then
|
||||
return null;
|
||||
end if;
|
||||
-- Compte suspendu : invisible pour les autres (l'admin et le compte lui-même y accèdent)
|
||||
if p.suspended and p.id <> me and not public.is_admin() then
|
||||
return null;
|
||||
end if;
|
||||
-- Compte qui m'a bloqué : invisible
|
||||
if p.id <> me and exists (select 1 from public.blocks b where b.blocker_id = p.id and b.blocked_id = me) then
|
||||
return null;
|
||||
end if;
|
||||
res := public.profile_card(p) || jsonb_build_object(
|
||||
'bio', p.bio,
|
||||
'banner_url', p.banner_url,
|
||||
'is_me', p.id = me,
|
||||
'follows_me', exists (select 1 from public.follows where follower_id = p.id and following_id = me and status = 'accepted'),
|
||||
'followers', (select count(*) from public.follows where following_id = p.id and status = 'accepted'),
|
||||
'following', (select count(*) from public.follows where follower_id = p.id and status = 'accepted'),
|
||||
'visible', public.can_view(p.id)
|
||||
);
|
||||
if public.can_view(p.id) then
|
||||
res := res || jsonb_build_object(
|
||||
'stats', (
|
||||
select jsonb_build_object(
|
||||
'total', count(*),
|
||||
'finished', count(*) filter (where data->>'status' = 'termine'),
|
||||
'finished_year', count(*) filter (where data->>'status' = 'termine' and left(data->>'endDate', 4) = to_char(now(), 'YYYY')),
|
||||
'films', count(*) filter (where data->>'status' = 'termine' and data->>'type' = 'film'),
|
||||
'series', count(*) filter (where data->>'status' = 'termine' and data->>'type' <> 'film'),
|
||||
'episodes', coalesce(sum(case when data->>'episodesWatched' ~ '^\d{1,6}$' then (data->>'episodesWatched')::int else 0 end), 0),
|
||||
'rated', count(*) filter (where data ? 'rating')
|
||||
)
|
||||
from public.items where user_id = p.id and not deleted
|
||||
),
|
||||
'top', (
|
||||
select coalesce(jsonb_agg(public.public_item(data) order by data->'top'->>'category', (data->'top'->>'rank')), '[]'::jsonb)
|
||||
from public.items i
|
||||
where i.user_id = p.id and not i.deleted and jsonb_typeof(i.data->'top') = 'object'
|
||||
and coalesce(
|
||||
(select s.data->'topCategories' ? (i.data->'top'->>'category')
|
||||
from public.settings s where s.user_id = p.id and jsonb_typeof(s.data->'topCategories') = 'array'),
|
||||
true)
|
||||
),
|
||||
'recent', (
|
||||
select coalesce(jsonb_agg(public.public_item(s.data) order by s.k desc nulls last), '[]'::jsonb)
|
||||
from (
|
||||
select data, coalesce(data->>'endDate', data->>'startDate') as k
|
||||
from public.items
|
||||
where user_id = p.id and not deleted and data->>'status' = 'termine'
|
||||
order by k desc nulls last limit 12
|
||||
) s
|
||||
),
|
||||
'watching', (
|
||||
select coalesce(jsonb_agg(public.public_item(s.data) order by s.k desc nulls last), '[]'::jsonb)
|
||||
from (
|
||||
select data, coalesce(data->>'startDate', left(data->>'updatedAt', 10)) as k
|
||||
from public.items
|
||||
where user_id = p.id and not deleted and data->>'status' = 'en_cours'
|
||||
order by k desc nulls last limit 8
|
||||
) s
|
||||
),
|
||||
'watchlist', (
|
||||
select coalesce(jsonb_agg(public.public_item(s.data) order by s.k desc nulls last), '[]'::jsonb)
|
||||
from (
|
||||
select data, data->>'createdAt' as k
|
||||
from public.items
|
||||
where user_id = p.id and not deleted and data->>'status' = 'a_voir'
|
||||
order by k desc nulls last limit 8
|
||||
) s
|
||||
)
|
||||
);
|
||||
end if;
|
||||
return res;
|
||||
end;
|
||||
$$;
|
||||
revoke all on function public.get_profile(text) from public, anon;
|
||||
grant execute on function public.get_profile(text) to authenticated;
|
||||
|
||||
create or replace function public.search_profiles(q text)
|
||||
returns jsonb language plpgsql stable security definer set search_path = '' as $$
|
||||
declare
|
||||
term text := lower(trim(coalesce(q, '')));
|
||||
pattern text;
|
||||
begin
|
||||
if auth.uid() is null or char_length(term) < 2 or char_length(term) > 40 then
|
||||
return '[]'::jsonb;
|
||||
end if;
|
||||
pattern := replace(replace(replace(ltrim(term, '@'), '\', '\\'), '%', '\%'), '_', '\_');
|
||||
return (
|
||||
select coalesce(jsonb_agg(public.profile_card(p) order by (p.username = ltrim(term, '@')) desc, p.username), '[]'::jsonb)
|
||||
from (
|
||||
select * from public.profiles pr
|
||||
where pr.id <> auth.uid() and not pr.suspended
|
||||
and not exists (select 1 from public.blocks b where b.blocker_id = pr.id and b.blocked_id = auth.uid())
|
||||
and (pr.username like pattern || '%' or lower(pr.display_name) like '%' || pattern || '%')
|
||||
order by pr.username
|
||||
limit 20
|
||||
) p
|
||||
);
|
||||
end;
|
||||
$$;
|
||||
revoke all on function public.search_profiles(text) from public, anon;
|
||||
grant execute on function public.search_profiles(text) to authenticated;
|
||||
|
||||
-- Versions en ligne (comptes suspendus filtrés), désormais dans le dépôt
|
||||
create or replace function public.get_follow_requests()
|
||||
returns jsonb language sql stable security definer set search_path = '' as $$
|
||||
select coalesce(jsonb_agg(public.profile_card(p) order by f.created_at desc), '[]'::jsonb)
|
||||
from public.follows f
|
||||
join public.profiles p on p.id = f.follower_id and not p.suspended
|
||||
where f.following_id = auth.uid() and f.status = 'pending'
|
||||
$$;
|
||||
revoke all on function public.get_follow_requests() from public, anon;
|
||||
grant execute on function public.get_follow_requests() to authenticated;
|
||||
|
||||
create or replace function public.get_follow_list(p_user uuid, p_kind text, p_offset integer default 0)
|
||||
returns jsonb language plpgsql stable security definer set search_path = '' as $$
|
||||
begin
|
||||
if not public.can_view(p_user) or p_kind not in ('followers', 'following') then
|
||||
return '[]'::jsonb;
|
||||
end if;
|
||||
return (
|
||||
select coalesce(jsonb_agg(public.profile_card(p) order by s.created_at desc), '[]'::jsonb)
|
||||
from (
|
||||
select case when p_kind = 'followers' then f.follower_id else f.following_id end as uid, f.created_at
|
||||
from public.follows f
|
||||
where f.status = 'accepted' and (case when p_kind = 'followers' then f.following_id else f.follower_id end) = p_user
|
||||
order by f.created_at desc
|
||||
offset greatest(p_offset, 0)
|
||||
limit 50
|
||||
) s
|
||||
join public.profiles p on p.id = s.uid and not p.suspended
|
||||
);
|
||||
end;
|
||||
$$;
|
||||
revoke all on function public.get_follow_list(uuid, text, integer) from public, anon;
|
||||
grant execute on function public.get_follow_list(uuid, text, integer) to authenticated;
|
||||
|
||||
create or replace function public.get_feed(p_before timestamptz default null, p_limit integer default 30)
|
||||
returns jsonb language sql stable security definer set search_path = '' as $$
|
||||
select coalesce(jsonb_agg(entry order by created_at desc), '[]'::jsonb)
|
||||
from (
|
||||
select a.created_at,
|
||||
jsonb_build_object(
|
||||
'id', a.id, 'kind', a.kind, 'created_at', a.created_at,
|
||||
'user', jsonb_build_object('username', p.username, 'display_name', p.display_name, 'avatar_url', p.avatar_url),
|
||||
'item', public.public_item(i.data)
|
||||
) as entry
|
||||
from public.activity a
|
||||
join public.follows f on f.following_id = a.user_id and f.follower_id = auth.uid() and f.status = 'accepted'
|
||||
join public.profiles p on p.id = a.user_id and not p.suspended
|
||||
join public.items i on i.user_id = a.user_id and i.id = a.item_id and not i.deleted
|
||||
where p_before is null or a.created_at < p_before
|
||||
order by a.created_at desc
|
||||
limit least(greatest(p_limit, 1), 50)
|
||||
) s
|
||||
$$;
|
||||
revoke all on function public.get_feed(timestamptz, integer) from public, anon;
|
||||
grant execute on function public.get_feed(timestamptz, integer) to authenticated;
|
||||
|
||||
-- ── 1 bis. Administration (fonctions en ligne, versionnées ici) ──
|
||||
create or replace function public.admin_overview()
|
||||
returns jsonb language plpgsql stable security definer set search_path = '' as $$
|
||||
declare res jsonb;
|
||||
begin
|
||||
if not public.is_admin() then raise exception 'forbidden'; end if;
|
||||
select jsonb_build_object(
|
||||
'users', (select count(*) from auth.users),
|
||||
'profiles', (select count(*) from public.profiles),
|
||||
'public_profiles', (select count(*) from public.profiles where not is_private and not suspended),
|
||||
'private_profiles', (select count(*) from public.profiles where is_private and not suspended),
|
||||
'suspended', (select count(*) from public.profiles where suspended),
|
||||
'items', (select count(*) from public.items where not deleted),
|
||||
'reviews', (select count(*) from public.items where not deleted and coalesce(data->>'notes','') <> ''),
|
||||
'films', (select count(*) from public.items where not deleted and data->>'type' = 'film'),
|
||||
'series', (select count(*) from public.items where not deleted and data->>'type' <> 'film'),
|
||||
'follows', (select count(*) from public.follows where status = 'accepted'),
|
||||
'pending_follows', (select count(*) from public.follows where status = 'pending'),
|
||||
'media_files', (select count(*) from storage.objects where bucket_id = 'profile-media'),
|
||||
'signups_7d', (select count(*) from auth.users where created_at > now() - interval '7 days'),
|
||||
'signups_30d', (select count(*) from auth.users where created_at > now() - interval '30 days'),
|
||||
'active_7d', (select count(distinct user_id) from public.activity where created_at > now() - interval '7 days'),
|
||||
'new_items_7d', (select count(*) from public.items where not deleted and updated_at > now() - interval '7 days'),
|
||||
'signups_by_day', (
|
||||
select coalesce(jsonb_agg(jsonb_build_object('day', to_char(d.day, 'YYYY-MM-DD'), 'n', coalesce(c.n, 0)) order by d.day), '[]'::jsonb)
|
||||
from generate_series((current_date - 13), current_date, interval '1 day') as d(day)
|
||||
left join (
|
||||
select date_trunc('day', created_at)::date as day, count(*) as n
|
||||
from auth.users where created_at > now() - interval '14 days' group by 1
|
||||
) c on c.day = d.day::date
|
||||
)
|
||||
) into res;
|
||||
return res;
|
||||
end;
|
||||
$$;
|
||||
|
||||
create or replace function public.admin_users(q text default null, p_offset integer default 0)
|
||||
returns jsonb language plpgsql stable security definer set search_path = '' as $$
|
||||
declare term text := lower(trim(coalesce(q, '')));
|
||||
begin
|
||||
if not public.is_admin() then raise exception 'forbidden'; end if;
|
||||
return (
|
||||
select coalesce(jsonb_agg(row_to_json(x) order by x.created_at desc), '[]'::jsonb)
|
||||
from (
|
||||
select u.id, u.email, u.created_at, u.last_sign_in_at,
|
||||
p.username, p.display_name, p.is_private, coalesce(p.suspended, false) as suspended,
|
||||
(select count(*) from public.items i where i.user_id = u.id and not i.deleted) as items,
|
||||
(select count(*) from public.items i where i.user_id = u.id and not i.deleted and coalesce(i.data->>'notes','') <> '') as reviews,
|
||||
(select count(*) from public.follows f where f.following_id = u.id and f.status = 'accepted') as followers
|
||||
from auth.users u
|
||||
left join public.profiles p on p.id = u.id
|
||||
where term = '' or lower(u.email) like '%' || term || '%'
|
||||
or lower(coalesce(p.username, '')) like '%' || term || '%'
|
||||
or lower(coalesce(p.display_name, '')) like '%' || term || '%'
|
||||
order by u.created_at desc
|
||||
offset greatest(p_offset, 0) limit 50
|
||||
) x
|
||||
);
|
||||
end;
|
||||
$$;
|
||||
|
||||
create or replace function public.admin_recent_reviews(p_offset integer default 0)
|
||||
returns jsonb language plpgsql stable security definer set search_path = '' as $$
|
||||
begin
|
||||
if not public.is_admin() then raise exception 'forbidden'; end if;
|
||||
return (
|
||||
select coalesce(jsonb_agg(row_to_json(x) order by x.updated_at desc), '[]'::jsonb)
|
||||
from (
|
||||
select i.id as item_id, i.user_id, i.updated_at,
|
||||
p.username, p.display_name, coalesce(p.suspended, false) as suspended,
|
||||
i.data->>'title' as title, i.data->>'type' as type,
|
||||
i.data->>'notes' as notes,
|
||||
-- Note mal formée dans une fiche : ignorée au lieu de faire échouer la liste
|
||||
case when i.data->>'rating' ~ '^[0-9]{1,2}(\.[0-9]{1,3})?$' then (i.data->>'rating')::numeric end as rating
|
||||
from public.items i
|
||||
left join public.profiles p on p.id = i.user_id
|
||||
where not i.deleted and coalesce(i.data->>'notes','') <> ''
|
||||
order by i.updated_at desc
|
||||
offset greatest(p_offset, 0) limit 30
|
||||
) x
|
||||
);
|
||||
end;
|
||||
$$;
|
||||
|
||||
create or replace function public.admin_set_suspended(p_user uuid, p_value boolean)
|
||||
returns jsonb language plpgsql security definer set search_path = '' as $$
|
||||
begin
|
||||
if not public.is_admin() then raise exception 'forbidden'; end if;
|
||||
if p_user = auth.uid() then raise exception 'cannot suspend yourself'; end if;
|
||||
update public.profiles set suspended = coalesce(p_value, false), updated_at = now() where id = p_user;
|
||||
return jsonb_build_object('ok', found, 'suspended', p_value);
|
||||
end;
|
||||
$$;
|
||||
|
||||
create or replace function public.admin_clear_review(p_user uuid, p_item text)
|
||||
returns jsonb language plpgsql security definer set search_path = '' as $$
|
||||
declare now_iso text := to_char(now() at time zone 'utc', 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"');
|
||||
begin
|
||||
if not public.is_admin() then raise exception 'forbidden'; end if;
|
||||
update public.items
|
||||
set data = jsonb_set((data - 'notes'), '{updatedAt}', to_jsonb(now_iso)),
|
||||
updated_at = now()
|
||||
where user_id = p_user and id = p_item and not deleted and coalesce(data->>'notes','') <> '';
|
||||
return jsonb_build_object('ok', found);
|
||||
end;
|
||||
$$;
|
||||
|
||||
revoke all on function public.admin_overview() from public, anon;
|
||||
revoke all on function public.admin_users(text, integer) from public, anon;
|
||||
revoke all on function public.admin_recent_reviews(integer) from public, anon;
|
||||
revoke all on function public.admin_set_suspended(uuid, boolean) from public, anon;
|
||||
revoke all on function public.admin_clear_review(uuid, text) from public, anon;
|
||||
grant execute on function public.admin_overview() to authenticated;
|
||||
grant execute on function public.admin_users(text, integer) to authenticated;
|
||||
grant execute on function public.admin_recent_reviews(integer) to authenticated;
|
||||
grant execute on function public.admin_set_suspended(uuid, boolean) to authenticated;
|
||||
grant execute on function public.admin_clear_review(uuid, text) to authenticated;
|
||||
|
||||
-- ── 3. Avis d'un titre : note mal formée tolérée, comptes qui m'ont bloqué exclus, tri avant pagination ──
|
||||
create or replace function public.title_reviews(p_external_id text, p_offset integer default 0)
|
||||
returns jsonb language plpgsql stable security definer set search_path = '' as $$
|
||||
declare me uuid := auth.uid(); res jsonb;
|
||||
begin
|
||||
if me is null or p_external_id !~ '^(tmdb:(movie|tv):[0-9]{1,10}|anilist:[0-9]{1,10})$' then
|
||||
return jsonb_build_object('friends', '[]'::jsonb, 'others', '[]'::jsonb);
|
||||
end if;
|
||||
with revs as (
|
||||
select i.user_id, i.id as item_id, i.updated_at,
|
||||
case when i.data->>'rating' ~ '^[0-9]{1,2}(\.[0-9]{1,3})?$' then (i.data->>'rating')::numeric end as rating,
|
||||
i.data->>'notes' as notes,
|
||||
coalesce(i.data->>'notesSpoiler', '') = 'true' as spoiler,
|
||||
pr,
|
||||
exists(select 1 from public.follows f where f.follower_id = me and f.following_id = i.user_id and f.status = 'accepted') as friend
|
||||
from public.items i
|
||||
join public.profiles pr on pr.id = i.user_id
|
||||
where i.data->>'externalId' = p_external_id
|
||||
and not i.deleted and coalesce(i.data->>'notes','') <> ''
|
||||
and i.user_id <> me and not pr.suspended
|
||||
and not exists (select 1 from public.blocks b where b.blocker_id = i.user_id and b.blocked_id = me)
|
||||
and (not pr.is_private
|
||||
or exists(select 1 from public.follows f where f.follower_id = me and f.following_id = i.user_id and f.status = 'accepted'))
|
||||
),
|
||||
enriched as (
|
||||
select r.*,
|
||||
(select coalesce(jsonb_object_agg(e.emoji, e.c), '{}'::jsonb)
|
||||
from (select emoji, count(*) c from public.review_reactions rr
|
||||
where rr.author_id = r.user_id and rr.item_id = r.item_id group by emoji) e) as reactions,
|
||||
(select count(*) from public.review_reactions rr where rr.author_id = r.user_id and rr.item_id = r.item_id) as total,
|
||||
(select emoji from public.review_reactions rr where rr.author_id = r.user_id and rr.item_id = r.item_id and rr.user_id = me) as mine,
|
||||
(select count(*) from public.review_comments rc join public.profiles cp on cp.id = rc.user_id
|
||||
where rc.author_id = r.user_id and rc.item_id = r.item_id and (not cp.suspended or rc.user_id = me)) as comments
|
||||
from revs r
|
||||
)
|
||||
select jsonb_build_object(
|
||||
'friends', coalesce((select jsonb_agg(entry order by total desc, updated_at desc) from (
|
||||
select jsonb_build_object('user', public.profile_card(pr), 'user_id', user_id, 'item_id', item_id,
|
||||
'updated_at', updated_at, 'rating', rating, 'notes', notes, 'spoiler', spoiler,
|
||||
'reactions', reactions, 'total', total, 'mine', mine, 'comments', comments) entry, total, updated_at
|
||||
from enriched where friend order by total desc, updated_at desc offset greatest(p_offset, 0) limit 40) f), '[]'::jsonb),
|
||||
'others', coalesce((select jsonb_agg(entry order by total desc, updated_at desc) from (
|
||||
select jsonb_build_object('user', public.profile_card(pr), 'user_id', user_id, 'item_id', item_id,
|
||||
'updated_at', updated_at, 'rating', rating, 'notes', notes, 'spoiler', spoiler,
|
||||
'reactions', reactions, 'total', total, 'mine', mine, 'comments', comments) entry, total, updated_at
|
||||
from enriched where not friend order by total desc, updated_at desc offset greatest(p_offset, 0) limit 40) o), '[]'::jsonb)
|
||||
) into res;
|
||||
return res;
|
||||
end;
|
||||
$$;
|
||||
revoke all on function public.title_reviews(text, integer) from public, anon;
|
||||
grant execute on function public.title_reviews(text, integer) to authenticated;
|
||||
|
||||
-- Les avis d'un titre sont cherchés par externalId : index (au lieu de parcourir toutes les fiches)
|
||||
create index if not exists items_review_external_idx on public.items ((data->>'externalId'))
|
||||
where not deleted and coalesce(data->>'notes', '') <> '';
|
||||
|
||||
-- ── Profils : chacun ne lit directement que le sien (les autres passent par les fonctions ci-dessus) ──
|
||||
drop policy if exists "profiles readable" on public.profiles;
|
||||
drop policy if exists "own profile read" on public.profiles;
|
||||
create policy "own profile read" on public.profiles for select to authenticated using ((select auth.uid()) = id);
|
||||
|
||||
-- ── 4. Fiche ou liste supprimée : on n'en garde que la trace (contenu effacé) ──
|
||||
create or replace function public.azuu_tombstone()
|
||||
returns trigger language plpgsql set search_path = '' as $$
|
||||
begin
|
||||
if new.deleted then new.data := null; end if;
|
||||
return new;
|
||||
end $$;
|
||||
revoke all on function public.azuu_tombstone() from public, anon, authenticated;
|
||||
drop trigger if exists items_atombstone on public.items;
|
||||
create trigger items_atombstone before insert or update on public.items for each row execute function public.azuu_tombstone();
|
||||
drop trigger if exists lists_atombstone on public.lists;
|
||||
create trigger lists_atombstone before insert or update on public.lists for each row execute function public.azuu_tombstone();
|
||||
update public.items set data = null where deleted and data is not null;
|
||||
update public.lists set data = null where deleted and data is not null;
|
||||
|
||||
-- Fiche effacée pour de bon : ses commentaires et réactions partent aussi
|
||||
create or replace function public.azuu_review_cleanup()
|
||||
returns trigger language plpgsql security definer set search_path = '' as $$
|
||||
declare r record;
|
||||
begin
|
||||
if tg_op = 'DELETE' then r := old; else r := new; end if;
|
||||
delete from public.review_comments where author_id = r.user_id and item_id = r.id;
|
||||
if tg_op = 'DELETE' then
|
||||
delete from public.review_reactions where author_id = r.user_id and item_id = r.id;
|
||||
end if;
|
||||
return null;
|
||||
end $$;
|
||||
revoke all on function public.azuu_review_cleanup() from public, anon, authenticated;
|
||||
drop trigger if exists items_review_cleanup_del on public.items;
|
||||
create trigger items_review_cleanup_del after delete on public.items for each row execute function public.azuu_review_cleanup();
|
||||
|
||||
-- ── 5. Compte suspendu : ne peut plus s'abonner ni réagir ──
|
||||
create or replace function public.azuu_actor_active_guard()
|
||||
returns trigger language plpgsql security definer set search_path = '' as $$
|
||||
begin
|
||||
if auth.uid() is not null and not public.azuu_me_active() then
|
||||
raise exception 'forbidden';
|
||||
end if;
|
||||
return new;
|
||||
end $$;
|
||||
revoke all on function public.azuu_actor_active_guard() from public, anon, authenticated;
|
||||
drop trigger if exists follows_zsuspended_guard on public.follows;
|
||||
create trigger follows_zsuspended_guard before insert on public.follows for each row execute function public.azuu_actor_active_guard();
|
||||
drop trigger if exists review_reactions_zsuspended_guard on public.review_reactions;
|
||||
create trigger review_reactions_zsuspended_guard before insert or update on public.review_reactions for each row execute function public.azuu_actor_active_guard();
|
||||
|
||||
-- Blocage : on quitte aussi les listes partagées l'un de l'autre
|
||||
create or replace function public.block_user(p_user uuid)
|
||||
returns jsonb language plpgsql security definer set search_path = '' as $$
|
||||
declare me uuid := auth.uid();
|
||||
begin
|
||||
if me is null then raise exception 'auth'; end if;
|
||||
if p_user is null or p_user = me then raise exception 'bad target'; end if;
|
||||
if not exists (select 1 from public.profiles p where p.id = p_user) then raise exception 'not found'; end if;
|
||||
if (select count(*) from public.blocks b where b.blocker_id = me) >= 1000 then raise exception 'too many blocks'; end if;
|
||||
insert into public.blocks (blocker_id, blocked_id) values (me, p_user) on conflict do nothing;
|
||||
delete from public.follows f
|
||||
where (f.follower_id = me and f.following_id = p_user) or (f.follower_id = p_user and f.following_id = me);
|
||||
delete from public.shared_list_members m using public.shared_lists l
|
||||
where m.list_id = l.id and m.user_id <> l.owner_id
|
||||
and ((l.owner_id = me and m.user_id = p_user) or (l.owner_id = p_user and m.user_id = me));
|
||||
return jsonb_build_object('ok', true);
|
||||
end;
|
||||
$$;
|
||||
revoke all on function public.block_user(uuid) from public, anon;
|
||||
grant execute on function public.block_user(uuid) to authenticated;
|
||||
|
||||
-- Fil d'activité : basculer un statut en boucle ne fait plus remonter la fiche en tête du fil des abonnés
|
||||
create or replace function public.azuu_log(p_user uuid, p_item text, p_kind text)
|
||||
returns void language plpgsql security definer set search_path = '' as $$
|
||||
begin
|
||||
-- Pas de doublon pour la même fiche dans la journée : la première activité est gardée telle quelle
|
||||
if exists (select 1 from public.activity
|
||||
where user_id = p_user and item_id = p_item and kind = p_kind and created_at > now() - interval '1 day') then
|
||||
return;
|
||||
end if;
|
||||
insert into public.activity (user_id, item_id, kind) values (p_user, p_item, p_kind);
|
||||
-- On garde les 500 dernières activités par compte
|
||||
delete from public.activity
|
||||
where user_id = p_user and id in (
|
||||
select id from public.activity where user_id = p_user order by created_at desc offset 500
|
||||
);
|
||||
end;
|
||||
$$;
|
||||
revoke all on function public.azuu_log(uuid, text, text) from public, anon, authenticated;
|
||||
|
||||
-- Profils publics : on ne sort pas non plus le journal des revisionnages (privé, comme episodeLog)
|
||||
create or replace function public.public_item(d jsonb)
|
||||
returns jsonb language sql immutable set search_path = '' as $$
|
||||
select case when length(coalesce(x->>'poster', '')) > 150000 then x - 'poster' else x end
|
||||
from (select d - 'listIds' - 'notesPublic' - 'tags' - 'episodeLog' - 'rewatchLog' as x) s
|
||||
$$;
|
||||
revoke all on function public.public_item(jsonb) from public, anon, authenticated;
|
||||
|
||||
-- ── Index (clés étrangères utilisées à la suppression d'un compte, filtres admin) ──
|
||||
create index if not exists reports_target_user_idx on public.reports (target_user_id);
|
||||
create index if not exists review_reactions_user_idx on public.review_reactions (user_id);
|
||||
create index if not exists moderation_log_admin_idx on public.moderation_log (admin_id);
|
||||
drop index if exists public.review_reactions_target_idx;
|
||||
|
||||
-- ── 6. Ménage : ce qui ne servait qu'aux notifications (la table notifications reste : des fonctions de listes partagées y font encore référence) ──
|
||||
drop function if exists public.get_notifications(integer);
|
||||
drop function if exists public.notifications_unread();
|
||||
drop function if exists public.mark_notifications_read();
|
||||
drop function if exists public.add_episode_notifications(jsonb);
|
||||
drop function if exists public.register_push_subscription(text, text, text, text, text);
|
||||
drop function if exists public.unregister_push_subscription(text);
|
||||
drop function if exists public.azuu_follow_notify();
|
||||
drop function if exists public.azuu_reaction_notify();
|
||||
drop function if exists public.azuu_wants(uuid, text);
|
||||
drop table if exists public.episode_seen;
|
||||
drop table if exists public.push_subscriptions;
|
||||
|
||||
-- Fonctions de test oubliées
|
||||
drop function if exists public._tmp_ping2();
|
||||
drop function if exists public._tmp_sd2();
|
||||
Reference in new issue
Block a user