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
+36
-8
@@ -1,19 +1,37 @@
|
||||
import { t } from '../../i18n'
|
||||
import { AuthError, getAccessToken } from './auth'
|
||||
import { SUPABASE_ANON_KEY, SUPABASE_URL } from './config'
|
||||
import { AuthError, getAccessToken, getSession } from './auth'
|
||||
import { SUPABASE_ANON_KEY, SUPABASE_URL, TimeoutError, withTimeout } from './config'
|
||||
|
||||
/** fetch avec un délai maximal (le serveur qui ne répond pas ne bloque jamais l'app). */
|
||||
async function timedFetch(url: string, init: RequestInit = {}): Promise<Response> {
|
||||
try {
|
||||
// Délai proportionnel à la taille de l'envoi (photo, grosse synchro sur une connexion lente : ~5 Ko/s minimum),
|
||||
// et long pour la suppression de compte (le serveur efface tout avant de répondre)
|
||||
const bytes = init.body instanceof Blob ? init.body.size : typeof init.body === 'string' ? init.body.length : 0
|
||||
const ms = url.includes('/functions/v1/delete-account') ? 120_000 : Math.max(20_000, 20_000 + bytes / 5)
|
||||
return await withTimeout((signal) => fetch(url, { ...init, signal }), init.signal, ms)
|
||||
} catch (e) {
|
||||
if (e instanceof TimeoutError) throw new Error(t('common.offline'))
|
||||
throw e
|
||||
}
|
||||
}
|
||||
|
||||
/** Appel authentifié à Supabase (base de données ou fonctions serveur). Réessaie une fois si le jeton a expiré. */
|
||||
export async function cloudFetch(path: string, init: RequestInit = {}): Promise<Response> {
|
||||
let failed: string | undefined
|
||||
for (let attempt = 0; attempt < 2; attempt++) {
|
||||
const token = await getAccessToken(attempt > 0)
|
||||
// Après un refus : on ne force le renouvellement que si le jeton refusé est toujours le jeton courant
|
||||
// (plusieurs appels refusés en même temps ne déclenchent qu'un renouvellement, les autres reprennent le nouveau)
|
||||
const token = await getAccessToken(failed !== undefined && getSession()?.accessToken === failed)
|
||||
if (!token) throw new AuthError(t('auth.err.session'))
|
||||
const res = await fetch(SUPABASE_URL + path, {
|
||||
const res = await timedFetch(SUPABASE_URL + path, {
|
||||
...init,
|
||||
headers: { apikey: SUPABASE_ANON_KEY, Authorization: `Bearer ${token}`, ...(init.headers ?? {}) },
|
||||
credentials: 'omit',
|
||||
referrerPolicy: 'no-referrer',
|
||||
})
|
||||
if (res.status !== 401) return res
|
||||
failed = token
|
||||
}
|
||||
throw new AuthError(t('auth.err.session'))
|
||||
}
|
||||
@@ -24,7 +42,7 @@ export async function tmdbViaCloud<T>(path: string, params: Record<string, strin
|
||||
// Sans compte (mode découverte) : appel anonyme, limité côté serveur par adresse IP
|
||||
const res = (await getAccessToken())
|
||||
? await cloudFetch(`/functions/v1/tmdb?${q}`)
|
||||
: await fetch(`${SUPABASE_URL}/functions/v1/tmdb?${q}`, { headers: { apikey: SUPABASE_ANON_KEY }, credentials: 'omit', referrerPolicy: 'no-referrer' })
|
||||
: await timedFetch(`${SUPABASE_URL}/functions/v1/tmdb?${q}`, { headers: { apikey: SUPABASE_ANON_KEY }, credentials: 'omit', referrerPolicy: 'no-referrer' })
|
||||
if (res.status === 429) throw new Error(t('err.searchRate'))
|
||||
if (!res.ok) throw new Error(t('err.tmdbStatus', { status: res.status }))
|
||||
return res.json() as Promise<T>
|
||||
@@ -36,14 +54,24 @@ export type ProxyState = 'ok' | 'missing-key' | 'not-deployed' | 'offline' | 'er
|
||||
export async function checkTmdbProxy(): Promise<ProxyState> {
|
||||
if (!navigator.onLine) return 'offline'
|
||||
try {
|
||||
const res = await cloudFetch(`/functions/v1/tmdb?${new URLSearchParams({ path: '/configuration' })}`)
|
||||
const path = `/functions/v1/tmdb?${new URLSearchParams({ path: '/configuration' })}`
|
||||
let res: Response
|
||||
try {
|
||||
res = await cloudFetch(path)
|
||||
} catch (e) {
|
||||
// Pas de session valable : ce n'est pas le proxy qui manque, on le teste sans compte (comme la recherche)
|
||||
if (!(e instanceof AuthError)) throw e
|
||||
res = await timedFetch(SUPABASE_URL + path, { headers: { apikey: SUPABASE_ANON_KEY }, credentials: 'omit', referrerPolicy: 'no-referrer' })
|
||||
}
|
||||
if (res.ok) return 'ok'
|
||||
if (res.status === 404) return 'not-deployed'
|
||||
const body = (await res.json().catch(() => ({}))) as { error?: string; status?: number }
|
||||
if (res.status === 500 && body.error?.includes('TMDB_API_KEY')) return 'missing-key'
|
||||
if (res.status === 502 && body.status === 401) return 'missing-key'
|
||||
return 'error'
|
||||
} catch {
|
||||
return navigator.onLine ? 'not-deployed' : 'offline'
|
||||
} catch (e) {
|
||||
if (!navigator.onLine) return 'offline'
|
||||
// Échec réseau (fonction absente) ; un serveur qui ne répond pas à temps n'est pas « non déployé »
|
||||
return e instanceof TypeError ? 'not-deployed' : 'error'
|
||||
}
|
||||
}
|
||||
+98
-28
@@ -1,5 +1,5 @@
|
||||
import { t, type TKey } from '../../i18n'
|
||||
import { SUPABASE_ANON_KEY, SUPABASE_URL } from './config'
|
||||
import { SUPABASE_ANON_KEY, SUPABASE_URL, withTimeout } from './config'
|
||||
import { isPwnedPassword } from '../pwned'
|
||||
|
||||
/**
|
||||
@@ -108,17 +108,21 @@ const msg = (code: string) => (CODE_KEYS[code] ? t(CODE_KEYS[code], { n: PASSWOR
|
||||
async function gotrue(path: string, init: { method?: string; body?: unknown; token?: string } = {}): Promise<Record<string, unknown>> {
|
||||
let res: Response
|
||||
try {
|
||||
res = await fetch(`${SUPABASE_URL}/auth/v1${path}`, {
|
||||
method: init.method ?? 'POST',
|
||||
headers: {
|
||||
apikey: SUPABASE_ANON_KEY,
|
||||
'Content-Type': 'application/json',
|
||||
...(init.token ? { Authorization: `Bearer ${init.token}` } : {}),
|
||||
},
|
||||
body: init.body ? JSON.stringify(init.body) : undefined,
|
||||
credentials: 'omit',
|
||||
referrerPolicy: 'no-referrer',
|
||||
})
|
||||
// Délai maximal : sans réponse, on fait comme hors-ligne plutôt que d'attendre indéfiniment
|
||||
res = await withTimeout((signal) =>
|
||||
fetch(`${SUPABASE_URL}/auth/v1${path}`, {
|
||||
method: init.method ?? 'POST',
|
||||
headers: {
|
||||
apikey: SUPABASE_ANON_KEY,
|
||||
'Content-Type': 'application/json',
|
||||
...(init.token ? { Authorization: `Bearer ${init.token}` } : {}),
|
||||
},
|
||||
body: init.body ? JSON.stringify(init.body) : undefined,
|
||||
credentials: 'omit',
|
||||
referrerPolicy: 'no-referrer',
|
||||
signal,
|
||||
}),
|
||||
)
|
||||
} catch {
|
||||
throw new Error(t('common.offline'))
|
||||
}
|
||||
@@ -131,8 +135,7 @@ async function gotrue(path: string, init: { method?: string; body?: unknown; tok
|
||||
if (!res.ok) {
|
||||
const code = String(data.error_code ?? data.code ?? data.error ?? '')
|
||||
const err = new AuthError(msg(code) ?? (res.status === 429 ? t('auth.err.rate') : t('auth.err.status', { status: res.status })))
|
||||
;(err as AuthError & { status: number; code: string }).status = res.status
|
||||
;(err as AuthError & { status: number; code: string }).code = code
|
||||
;(err as AuthError & { status: number }).status = res.status
|
||||
throw err
|
||||
}
|
||||
return data
|
||||
@@ -160,8 +163,9 @@ export async function signIn(email: string, password: string): Promise<void> {
|
||||
setSession(s)
|
||||
}
|
||||
|
||||
/** Crée un compte. Renvoie true si un email de confirmation a été envoyé (pas encore connecté). */
|
||||
/** Inscription. Le pseudo choisi est repris par la base à la création du profil (s'il est libre). */
|
||||
/**
|
||||
* Inscription. Renvoie true si un email de confirmation a été envoyé (pas encore connecté). Le pseudo choisi est repris par la base à la création du profil (s'il est libre).
|
||||
*/
|
||||
export async function signUp(email: string, password: string, username?: string): Promise<boolean> {
|
||||
if (password.length < PASSWORD_MIN) throw new AuthError(t('auth.err.weak', { n: PASSWORD_MIN }))
|
||||
if (await isPwnedPassword(password)) throw new AuthError(t('auth.err.pwned'))
|
||||
@@ -190,7 +194,17 @@ export async function updatePassword(password: string): Promise<void> {
|
||||
|
||||
/** Déconnexion : invalide la session côté serveur (si possible) et l'efface de l'appareil. */
|
||||
export async function signOut(): Promise<void> {
|
||||
const s = current
|
||||
let s = current
|
||||
// Jeton d'accès expiré (ou presque) : on tente d'abord de le renouveler, sinon le serveur refuserait
|
||||
// la déconnexion et la session resterait ouverte côté serveur. Effacée sur l'appareil quoi qu'il arrive.
|
||||
if (s && navigator.onLine && s.expiresAt - 60_000 <= Date.now()) {
|
||||
try {
|
||||
const next = await refresh()
|
||||
if (next && next.user.id === s.user.id) s = next
|
||||
} catch {
|
||||
/* au mieux */
|
||||
}
|
||||
}
|
||||
setSession(null)
|
||||
if (s && navigator.onLine) {
|
||||
try {
|
||||
@@ -226,17 +240,34 @@ export async function signInWithGoogle(): Promise<void> {
|
||||
location.assign(`${SUPABASE_URL}/auth/v1/authorize?${params}`)
|
||||
}
|
||||
|
||||
/** Retour de Google : adresse avec ?code=… (ou ?error=…). */
|
||||
export const hasOAuthRedirect = () => /[?&](code|error)=/.test(location.search)
|
||||
/** Vérificateur gardé pendant l'aller-retour vers Google (null s'il n'y en a pas). */
|
||||
function readVerifier(): { verifier?: unknown; at?: unknown } | null {
|
||||
try {
|
||||
const raw = localStorage.getItem(VERIFIER_KEY)
|
||||
const parsed: unknown = raw ? JSON.parse(raw) : null
|
||||
return parsed && typeof parsed === 'object' ? (parsed as { verifier?: unknown; at?: unknown }) : null
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Retour de Google : adresse avec ?code=… (ou ?error=…), seulement si une connexion Google a été lancée
|
||||
* depuis cet appareil (vérificateur présent) — une autre adresse avec ?code= n'est pas un retour de Google.
|
||||
*/
|
||||
export const hasOAuthRedirect = () => /[?&](code|error)=/.test(location.search) && readVerifier() !== null
|
||||
|
||||
async function consumeOAuthRedirect(): Promise<{ error?: string }> {
|
||||
const params = new URLSearchParams(location.search)
|
||||
const code = params.get('code') ?? ''
|
||||
const oauthError = params.get('error_description') ?? params.get('error')
|
||||
history.replaceState(null, '', `${location.pathname}#/`)
|
||||
let saved: { verifier?: string; at?: number } = {}
|
||||
const stored = readVerifier()
|
||||
const saved = {
|
||||
verifier: typeof stored?.verifier === 'string' ? stored.verifier : undefined,
|
||||
at: typeof stored?.at === 'number' ? stored.at : undefined,
|
||||
}
|
||||
try {
|
||||
saved = JSON.parse(localStorage.getItem(VERIFIER_KEY) ?? '{}')
|
||||
localStorage.removeItem(VERIFIER_KEY)
|
||||
} catch {
|
||||
/* ignore */
|
||||
@@ -260,26 +291,65 @@ async function consumeOAuthRedirect(): Promise<{ error?: string }> {
|
||||
|
||||
let refreshing: Promise<Session | null> | null = null
|
||||
|
||||
/**
|
||||
* Session plus récente laissée par un autre onglet (même compte, jeton de renouvellement différent,
|
||||
* ou nouveau jeton d'accès encore valable) : à reprendre plutôt que de renouveler avec un jeton périmé.
|
||||
*/
|
||||
function newerStored(s: Session): Session | null {
|
||||
const stored = load()
|
||||
if (!stored || stored.user.id !== s.user.id) return null
|
||||
// Seulement une session plus récente que la nôtre (si notre propre écriture avait échoué, le stockage est en retard)
|
||||
if (stored.expiresAt <= s.expiresAt) return null
|
||||
if (stored.refreshToken !== s.refreshToken) return stored
|
||||
if (stored.accessToken !== s.accessToken && stored.expiresAt - 60_000 > Date.now()) return stored
|
||||
return null
|
||||
}
|
||||
|
||||
async function refresh(): Promise<Session | null> {
|
||||
const s = current
|
||||
if (!s) return null
|
||||
if (!current) return null
|
||||
refreshing ??= (async () => {
|
||||
const s = current
|
||||
if (!s) return null
|
||||
// Un autre onglet a peut-être déjà renouvelé la session (le jeton de renouvellement ne sert qu'une fois)
|
||||
const adopted = newerStored(s)
|
||||
if (adopted) {
|
||||
setSession(adopted)
|
||||
return adopted
|
||||
}
|
||||
const sent = s.refreshToken
|
||||
try {
|
||||
const data = await gotrue('/token?grant_type=refresh_token', { body: { refresh_token: s.refreshToken } })
|
||||
const data = await gotrue('/token?grant_type=refresh_token', { body: { refresh_token: sent } })
|
||||
const next = toSession(data)
|
||||
// Déconnexion (ou autre compte) pendant le renouvellement : on ne ressuscite pas l'ancienne session
|
||||
if (!next || next.user.id !== s.user.id || current?.user.id !== s.user.id) return null
|
||||
// Session plus récente entre-temps (nouvelle connexion, autre onglet) : on ne l'écrase pas
|
||||
if (current.refreshToken !== sent) return current
|
||||
setSession(next)
|
||||
return next
|
||||
} catch (e) {
|
||||
// Un autre onglet a renouvelé pendant ce temps : notre jeton était simplement périmé
|
||||
if (current?.user.id === s.user.id && current.refreshToken !== sent) return current
|
||||
const adoptedLate = newerStored(s)
|
||||
if (adoptedLate && current?.user.id === s.user.id) {
|
||||
setSession(adoptedLate)
|
||||
return adoptedLate
|
||||
}
|
||||
// Jeton de renouvellement refusé (révoqué, compte supprimé…) : on déconnecte
|
||||
const status = (e as { status?: number }).status
|
||||
if ((status === 400 || status === 401 || status === 403) && current?.user.id === s.user.id) setSession(null)
|
||||
const stored = load()
|
||||
if (
|
||||
(status === 400 || status === 401 || status === 403) &&
|
||||
current?.user.id === s.user.id &&
|
||||
current.refreshToken === sent &&
|
||||
(!stored || stored.refreshToken === sent)
|
||||
) {
|
||||
setSession(null)
|
||||
}
|
||||
return null
|
||||
} finally {
|
||||
refreshing = null
|
||||
}
|
||||
})()
|
||||
})().finally(() => {
|
||||
refreshing = null
|
||||
})
|
||||
return refreshing
|
||||
}
|
||||
|
||||
|
||||
@@ -17,3 +17,35 @@ export const cloudEnabled = !!(SUPABASE_URL && SUPABASE_ANON_KEY)
|
||||
if (!cloudEnabled && (rawUrl || rawKey)) {
|
||||
console.warn('[Kino] .env incomplet ou invalide : les comptes sont désactivés (mode local). Vérifie VITE_SUPABASE_URL et VITE_SUPABASE_ANON_KEY.')
|
||||
}
|
||||
|
||||
/** Délai maximal d'attente d'une réponse du serveur (la déconnexion ou la synchro ne doivent jamais rester bloquées). */
|
||||
export const CLOUD_TIMEOUT_MS = 20_000
|
||||
|
||||
/**
|
||||
* Lance `run` avec un signal qui s'interrompt au bout de `ms` (ou si `signal`, celui de l'appelant, s'interrompt).
|
||||
* Le délai ne court que jusqu'à l'arrivée des en-têtes : la lecture d'une longue réponse n'est pas coupée.
|
||||
* `timedOut()` indique si c'est le délai (et non l'appelant) qui a interrompu l'appel.
|
||||
*/
|
||||
export async function withTimeout<T>(run: (signal: AbortSignal) => Promise<T>, signal?: AbortSignal | null, ms = CLOUD_TIMEOUT_MS): Promise<T> {
|
||||
const ctrl = new AbortController()
|
||||
let expired = false
|
||||
const onAbort = () => ctrl.abort(signal?.reason)
|
||||
if (signal?.aborted) ctrl.abort(signal.reason)
|
||||
else signal?.addEventListener('abort', onAbort, { once: true })
|
||||
const timer = setTimeout(() => {
|
||||
expired = true
|
||||
ctrl.abort()
|
||||
}, ms)
|
||||
try {
|
||||
return await run(ctrl.signal)
|
||||
} catch (e) {
|
||||
if (expired) throw new TimeoutError()
|
||||
throw e
|
||||
} finally {
|
||||
clearTimeout(timer)
|
||||
signal?.removeEventListener('abort', onAbort)
|
||||
}
|
||||
}
|
||||
|
||||
/** Le serveur n'a pas répondu à temps. */
|
||||
export class TimeoutError extends Error {}
|
||||
+15
-15
@@ -28,15 +28,8 @@ export const REPORT_DETAILS_MAX = 500
|
||||
export const BUG_DESCRIPTION_MIN = 10
|
||||
export const BUG_DESCRIPTION_MAX = 2000
|
||||
|
||||
/** Erreur renvoyée par le serveur, avec son code court (« rate limited », « not found »…). */
|
||||
export class ModerationError extends Error {
|
||||
constructor(
|
||||
message: string,
|
||||
readonly code: string,
|
||||
) {
|
||||
super(message)
|
||||
}
|
||||
}
|
||||
/** Erreur renvoyée par le serveur (message déjà traduit). */
|
||||
export class ModerationError extends Error {}
|
||||
|
||||
async function rpc<T>(name: string, args: Record<string, unknown> = {}): Promise<T> {
|
||||
const res = await cloudFetch(`/rest/v1/rpc/${name}`, {
|
||||
@@ -49,7 +42,7 @@ async function rpc<T>(name: string, args: Record<string, unknown> = {}): Promise
|
||||
const code = typeof body.message === 'string' ? body.message.slice(0, 40) : `http ${res.status}`
|
||||
const msg =
|
||||
code === 'rate limited' ? t('report.errRate') : code === 'not found' ? t('report.errNotFound') : res.status === 404 ? t('report.errUnavailable') : t('social.err.server', { status: res.status })
|
||||
throw new ModerationError(msg, code)
|
||||
throw new ModerationError(msg)
|
||||
}
|
||||
const text = await res.text()
|
||||
return (text ? JSON.parse(text) : null) as T
|
||||
@@ -88,13 +81,18 @@ const listeners = new Set<() => void>()
|
||||
const emit = () => listeners.forEach((fn) => fn())
|
||||
|
||||
/** Charge (une fois par session) la liste des comptes que j'ai bloqués. Silencieux si le serveur n'est pas à jour. */
|
||||
export function loadBlocks(force = false): Promise<void> {
|
||||
export function loadBlocks(): Promise<void> {
|
||||
const uid = getSession()?.user.id
|
||||
if (loaded && !force && loadedFor === uid) return loaded
|
||||
if (loaded && loadedFor === uid) return loaded
|
||||
if (loadedFor !== uid) blocked = []
|
||||
loadedFor = uid
|
||||
loaded = rpc<unknown>('my_blocks')
|
||||
const p: Promise<void> = rpc<unknown>('my_blocks')
|
||||
.then((rows) => {
|
||||
// Réponse arrivée après un changement de compte : elle ne concerne plus le compte ouvert
|
||||
if (loadedFor !== uid || getSession()?.user.id !== uid) {
|
||||
if (loaded === p) loaded = null
|
||||
return
|
||||
}
|
||||
blocked = (Array.isArray(rows) ? rows : []).flatMap((r) => {
|
||||
if (!isPlainObject(r) || typeof r.id !== 'string' || !UUID.test(r.id)) return []
|
||||
const username = cleanText(r.username, 20) ?? ''
|
||||
@@ -103,9 +101,11 @@ export function loadBlocks(force = false): Promise<void> {
|
||||
emit()
|
||||
})
|
||||
.catch(() => {
|
||||
/* fonction pas encore déployée / hors-ligne : rien n'est masqué */
|
||||
/* fonction pas encore déployée / hors-ligne : rien n'est masqué, on réessaiera au prochain affichage */
|
||||
if (loaded === p) loaded = null
|
||||
})
|
||||
return loaded
|
||||
loaded = p
|
||||
return p
|
||||
}
|
||||
|
||||
export const isBlocked = (userId: string | undefined | null) => !!userId && loadedFor === getSession()?.user.id && blocked.some((b) => b.id === userId)
|
||||
|
||||
+31
-9
@@ -162,16 +162,32 @@ export async function getMyProfile(): Promise<Profile | null> {
|
||||
return row?.username ? getProfile(row.username) : null
|
||||
}
|
||||
|
||||
export async function getProfileItems(userId: string, status: string | null, offset: number): Promise<MediaItem[]> {
|
||||
if (!UUID.test(userId)) return []
|
||||
return toItems(await rpc('get_profile_items', { p_user: userId, p_status: status, p_offset: offset, p_limit: 48 }))
|
||||
/** Nombre de lignes renvoyées par le serveur (avant le tri des lignes invalides) : sert au décalage de la page suivante. */
|
||||
const rawCount = (v: unknown) => (Array.isArray(v) ? v.length : 0)
|
||||
|
||||
export const PROFILE_ITEMS_PAGE = 48
|
||||
|
||||
/** Une page de la bibliothèque d'un profil. `received` : lignes reçues du serveur (pour la page suivante). */
|
||||
export async function getProfileItems(userId: string, status: string | null, offset: number): Promise<{ items: MediaItem[]; received: number }> {
|
||||
if (!UUID.test(userId)) return { items: [], received: 0 }
|
||||
const raw = await rpc('get_profile_items', { p_user: userId, p_status: status, p_offset: offset, p_limit: PROFILE_ITEMS_PAGE })
|
||||
return { items: toItems(raw), received: rawCount(raw) }
|
||||
}
|
||||
|
||||
export async function getFeed(before?: string): Promise<FeedEntry[]> {
|
||||
const raw = await rpc('get_feed', { p_before: before ?? null, p_limit: 30 })
|
||||
if (!Array.isArray(raw)) return []
|
||||
export const FEED_PAGE = 30
|
||||
|
||||
/**
|
||||
* Une page du fil. `received` : lignes reçues du serveur ; `cursor` : date de la dernière ligne reçue
|
||||
* (même invalide), d'où repartir pour la page suivante.
|
||||
*/
|
||||
export async function getFeed(before?: string): Promise<{ entries: FeedEntry[]; received: number; cursor?: string }> {
|
||||
const raw = await rpc('get_feed', { p_before: before ?? null, p_limit: FEED_PAGE })
|
||||
if (!Array.isArray(raw)) return { entries: [], received: 0 }
|
||||
const out: FeedEntry[] = []
|
||||
let cursor: string | undefined
|
||||
for (const r of raw.slice(0, 50)) {
|
||||
// Date brute du serveur (précision à la microseconde) : rien n'est sauté ni répété d'une page à l'autre
|
||||
if (isPlainObject(r) && safeIso(r.created_at)) cursor = r.created_at as string
|
||||
if (!isPlainObject(r) || !isPlainObject(r.user)) continue
|
||||
const item = othersItem(r.item)
|
||||
const name = username(r.user.username)
|
||||
@@ -186,14 +202,20 @@ export async function getFeed(before?: string): Promise<FeedEntry[]> {
|
||||
item,
|
||||
})
|
||||
}
|
||||
return out
|
||||
return { entries: out, received: raw.length, cursor }
|
||||
}
|
||||
|
||||
const toCards = (raw: unknown) => (Array.isArray(raw) ? raw.slice(0, 100).map(toCard).filter((c): c is ProfileCard => c !== null) : [])
|
||||
|
||||
export const searchProfiles = async (q: string) => (q.trim().length < 2 ? [] : toCards(await rpc('search_profiles', { q: q.trim().slice(0, 40) })))
|
||||
export const getFollowList = async (userId: string, kind: 'followers' | 'following', offset = 0) =>
|
||||
UUID.test(userId) ? toCards(await rpc('get_follow_list', { p_user: userId, p_kind: kind, p_offset: offset })) : []
|
||||
/** Le serveur renvoie au plus 50 comptes à la fois */
|
||||
export const FOLLOW_PAGE = 50
|
||||
/** Une page d'abonnés / d'abonnements. `received` : lignes reçues du serveur (pour la page suivante). */
|
||||
export async function getFollowList(userId: string, kind: 'followers' | 'following', offset = 0): Promise<{ cards: ProfileCard[]; received: number }> {
|
||||
if (!UUID.test(userId)) return { cards: [], received: 0 }
|
||||
const raw = await rpc('get_follow_list', { p_user: userId, p_kind: kind, p_offset: offset })
|
||||
return { cards: toCards(raw), received: rawCount(raw) }
|
||||
}
|
||||
export const getFollowRequests = async () => toCards(await rpc('get_follow_requests'))
|
||||
|
||||
// ─── Abonnements ───
|
||||
|
||||
+176
-46
@@ -1,10 +1,10 @@
|
||||
import { t } from '../../i18n'
|
||||
import type { CustomList, MediaItem, Settings } from '../../types'
|
||||
import { normalizeItem, normalizeLists, normalizeSettings } from '../backup'
|
||||
import { mediaDB, onMediaChange } from '../db'
|
||||
import { mediaDB, onMediaChange, type RemoteDecision } from '../db'
|
||||
import { blobToPosterDataURL } from '../image'
|
||||
import { isPlainObject, isSafeId, safeIso } from '../security'
|
||||
import { scopedKey } from '../scope'
|
||||
import { getScope, scopedKey } from '../scope'
|
||||
import { cloudFetch } from './api'
|
||||
|
||||
/**
|
||||
@@ -42,12 +42,48 @@ interface SyncMeta {
|
||||
}
|
||||
|
||||
const PAGE = 500
|
||||
/** Limite d'une fiche côté serveur : 400 000 octets (texte jsonb, un peu plus long que JSON.stringify) → marge. */
|
||||
const MAX_ROW_BYTES = 380_000
|
||||
const MAX_BATCH_BYTES = 1_500_000
|
||||
const OVERLAP_MS = 60_000
|
||||
|
||||
const jsonHeaders = { 'Content-Type': 'application/json' }
|
||||
|
||||
/** Taille réelle en octets (UTF-8 : un accent ou un emoji compte pour plusieurs). */
|
||||
const encoder = new TextEncoder()
|
||||
const byteSize = (v: unknown) => encoder.encode(JSON.stringify(v)).length
|
||||
|
||||
/** Data URL → Blob sans fetch (la CSP n'autorise pas `data:` en connect-src). */
|
||||
function dataURLToBlob(url: string): Blob {
|
||||
const comma = url.indexOf(',')
|
||||
const head = url.slice(0, comma)
|
||||
const body = url.slice(comma + 1)
|
||||
const type = head.slice(5).split(';')[0] || 'application/octet-stream'
|
||||
if (!/;base64$/i.test(head)) return new Blob([decodeURIComponent(body)], { type })
|
||||
const bin = atob(body)
|
||||
const bytes = new Uint8Array(bin.length)
|
||||
for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i)
|
||||
return new Blob([bytes], { type })
|
||||
}
|
||||
|
||||
/** Refus du serveur propre à une ligne (et non session expirée, limite de débit…) : inutile de la renvoyer. */
|
||||
const isRowRejected = (e: PushError) =>
|
||||
e.status >= 400 && e.status < 500 && ![401, 403, 404, 408, 429].includes(e.status) &&
|
||||
// Quota du compte atteint : ce n'est pas la fiche qui pose problème, on la garde en attente (elle partira plus tard)
|
||||
!/quota/i.test(e.detail)
|
||||
|
||||
/** Erreur d'envoi, avec le code HTTP. */
|
||||
class PushError extends Error {
|
||||
constructor(
|
||||
readonly status: number,
|
||||
readonly detail = '',
|
||||
) {
|
||||
super(t('sync.err.push', { status }))
|
||||
}
|
||||
}
|
||||
|
||||
const maxIso = (a?: string, b?: string) => (a && b ? (a > b ? a : b) : (a ?? b))
|
||||
|
||||
export interface SyncEngine {
|
||||
start: () => void
|
||||
stop: () => void
|
||||
@@ -84,14 +120,51 @@ export function createSync(userId: string, hooks: SyncHooks): SyncEngine {
|
||||
}
|
||||
|
||||
let meta = loadMeta()
|
||||
const saveMeta = () => {
|
||||
/** Entrées de la boîte d'envoi envoyées par cet onglet (clé → horodatage envoyé). */
|
||||
const sent = new Map<string, string>()
|
||||
|
||||
/** Toujours le même compte, pas déconnecté : sinon on n'écrit plus rien sur l'appareil. */
|
||||
const alive = () => !stopped && getScope() === userId
|
||||
|
||||
/**
|
||||
* Un autre onglet du même compte partage cette boîte d'envoi : on relit ce qui est enregistré et on
|
||||
* fusionne (sans écraser ses entrées en attente, sans ressusciter celles que cet onglet a envoyées).
|
||||
*/
|
||||
const mergeStored = () => {
|
||||
const stored = loadMeta()
|
||||
for (const [k, v] of Object.entries(stored.outbox)) {
|
||||
if (sent.get(k) === v) continue
|
||||
if (!meta.outbox[k] || meta.outbox[k] < v) meta.outbox[k] = v
|
||||
}
|
||||
meta.itemsCursor = maxIso(meta.itemsCursor, stored.itemsCursor)
|
||||
meta.listsCursor = maxIso(meta.listsCursor, stored.listsCursor)
|
||||
meta.settingsAt = maxIso(meta.settingsAt, stored.settingsAt)
|
||||
meta.lastSyncAt = maxIso(meta.lastSyncAt, stored.lastSyncAt)
|
||||
}
|
||||
|
||||
const saveMeta = (cursors?: Pick<SyncMeta, 'itemsCursor' | 'listsCursor'>) => {
|
||||
if (!alive()) return
|
||||
try {
|
||||
mergeStored()
|
||||
// Curseur volontairement reculé (fiches à relire) : il ne doit pas être ré-avancé par la fusion
|
||||
if (cursors) Object.assign(meta, cursors)
|
||||
localStorage.setItem(META_KEY, JSON.stringify(meta))
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
}
|
||||
|
||||
/** Retire de la boîte d'envoi ce qui vient de partir (sauf si re-modifié entre-temps). */
|
||||
const done = (keys: string[], snapshot: Record<string, string>) => {
|
||||
for (const k of keys) {
|
||||
if (meta.outbox[k] !== snapshot[k]) continue
|
||||
delete meta.outbox[k]
|
||||
sent.set(k, snapshot[k])
|
||||
}
|
||||
saveMeta()
|
||||
setStatus({})
|
||||
}
|
||||
|
||||
let status: SyncStatus = { state: 'idle', lastSyncAt: meta.lastSyncAt, pending: Object.keys(meta.outbox).length }
|
||||
const listeners = new Set<(s: SyncStatus) => void>()
|
||||
const setStatus = (patch: Partial<SyncStatus>) => {
|
||||
@@ -110,38 +183,68 @@ export function createSync(userId: string, hooks: SyncHooks): SyncEngine {
|
||||
|
||||
/** Réduit une fiche trop lourde (affiche importée en très haute qualité) avant envoi. */
|
||||
async function fitForUpload(item: MediaItem): Promise<MediaItem> {
|
||||
if (JSON.stringify(item).length <= MAX_ROW_BYTES) return item
|
||||
if (byteSize(item) <= MAX_ROW_BYTES) return item
|
||||
if (item.poster?.startsWith('data:image')) {
|
||||
try {
|
||||
const blob = await (await fetch(item.poster)).blob()
|
||||
const blob = dataURLToBlob(item.poster)
|
||||
const smaller = { ...item, poster: await blobToPosterDataURL(blob, 360, 0.75) }
|
||||
if (JSON.stringify(smaller).length <= MAX_ROW_BYTES) return smaller
|
||||
if (byteSize(smaller) <= MAX_ROW_BYTES) return smaller
|
||||
} catch {
|
||||
/* image illisible */
|
||||
}
|
||||
}
|
||||
const { poster: _poster, ...rest } = item
|
||||
const stripped = rest as MediaItem
|
||||
return JSON.stringify(stripped).length <= MAX_ROW_BYTES ? stripped : { ...stripped, notes: stripped.notes?.slice(0, 5000), overview: undefined }
|
||||
return byteSize(stripped) <= MAX_ROW_BYTES ? stripped : { ...stripped, notes: stripped.notes?.slice(0, 5000), overview: undefined }
|
||||
}
|
||||
|
||||
async function upsert(table: 'items' | 'lists', rows: { id: string; data: unknown; deleted: boolean; updated_at: string }[]) {
|
||||
type UpRow = { id: string; data: unknown; deleted: boolean; updated_at: string }
|
||||
|
||||
async function send(table: 'items' | 'lists', rows: UpRow[]) {
|
||||
const res = await cloudFetch(`/rest/v1/${table}?on_conflict=user_id,id`, {
|
||||
method: 'POST',
|
||||
headers: { ...jsonHeaders, Prefer: 'resolution=merge-duplicates,return=minimal' },
|
||||
body: JSON.stringify(rows.map((r) => ({ ...r, user_id: userId }))),
|
||||
})
|
||||
if (!res.ok) throw new PushError(res.status, (await res.text().catch(() => '')).slice(0, 500))
|
||||
}
|
||||
|
||||
/** Envoi par paquets ; chaque paquet accepté est aussitôt retiré de la boîte d'envoi (`sentRows`). */
|
||||
async function upsert(table: 'items' | 'lists', rows: UpRow[], sentRows: (rows: UpRow[]) => void) {
|
||||
// Envoi par paquets de taille raisonnable
|
||||
let batch: typeof rows = []
|
||||
let batch: UpRow[] = []
|
||||
let size = 0
|
||||
const flush = async () => {
|
||||
if (!batch.length) return
|
||||
const res = await cloudFetch(`/rest/v1/${table}?on_conflict=user_id,id`, {
|
||||
method: 'POST',
|
||||
headers: { ...jsonHeaders, Prefer: 'resolution=merge-duplicates,return=minimal' },
|
||||
body: JSON.stringify(batch.map((r) => ({ ...r, user_id: userId }))),
|
||||
})
|
||||
if (!res.ok) throw new Error(t('sync.err.push', { status: res.status }))
|
||||
const current = batch
|
||||
batch = []
|
||||
size = 0
|
||||
try {
|
||||
await send(table, current)
|
||||
} catch (e) {
|
||||
if (!(e instanceof PushError) || !isRowRejected(e)) throw e
|
||||
// Paquet refusé : on renvoie ligne par ligne, une fiche invalide ne bloque pas les autres
|
||||
for (const r of current) {
|
||||
let status = e.status
|
||||
try {
|
||||
if (current.length > 1) {
|
||||
await send(table, [r])
|
||||
sentRows([r])
|
||||
continue
|
||||
}
|
||||
} catch (err) {
|
||||
if (!(err instanceof PushError) || !isRowRejected(err)) throw err
|
||||
status = err.status
|
||||
}
|
||||
console.warn(`[sync] ${table}/${r.id} refusé par le serveur (${status}), ignoré`)
|
||||
sentRows([r])
|
||||
}
|
||||
return
|
||||
}
|
||||
sentRows(current)
|
||||
}
|
||||
for (const r of rows) {
|
||||
const bytes = JSON.stringify(r).length
|
||||
const bytes = byteSize(r)
|
||||
if (size + bytes > MAX_BATCH_BYTES || batch.length >= 200) await flush()
|
||||
batch.push(r)
|
||||
size += bytes
|
||||
@@ -150,13 +253,15 @@ export function createSync(userId: string, hooks: SyncHooks): SyncEngine {
|
||||
}
|
||||
|
||||
async function push() {
|
||||
// Entrées ajoutées par un autre onglet du même compte : envoyées aussi
|
||||
if (alive()) mergeStored()
|
||||
const snapshot = { ...meta.outbox }
|
||||
const keys = Object.keys(snapshot)
|
||||
if (!keys.length) return
|
||||
|
||||
const itemIds = keys.filter((k) => k.startsWith('i:')).map((k) => k.slice(2))
|
||||
if (itemIds.length) {
|
||||
const rows = []
|
||||
const rows: UpRow[] = []
|
||||
for (const id of itemIds) {
|
||||
const item = await mediaDB.get(id)
|
||||
if (item) {
|
||||
@@ -166,7 +271,7 @@ export function createSync(userId: string, hooks: SyncHooks): SyncEngine {
|
||||
rows.push({ id, data: null, deleted: true, updated_at: snapshot[`i:${id}`] })
|
||||
}
|
||||
}
|
||||
await upsert('items', rows)
|
||||
await upsert('items', rows, (sentRows) => done(sentRows.map((r) => `i:${r.id}`), snapshot))
|
||||
}
|
||||
|
||||
const listIds = keys.filter((k) => k.startsWith('l:')).map((k) => k.slice(2))
|
||||
@@ -178,6 +283,7 @@ export function createSync(userId: string, hooks: SyncHooks): SyncEngine {
|
||||
const l = current.get(id)
|
||||
return { id, data: l ?? null, deleted: !l, updated_at: snapshot[`l:${id}`] }
|
||||
}),
|
||||
(sentRows) => done(sentRows.map((r) => `l:${r.id}`), snapshot),
|
||||
)
|
||||
}
|
||||
|
||||
@@ -187,13 +293,11 @@ export function createSync(userId: string, hooks: SyncHooks): SyncEngine {
|
||||
headers: { ...jsonHeaders, Prefer: 'resolution=merge-duplicates,return=minimal' },
|
||||
body: JSON.stringify({ user_id: userId, data: hooks.getSettings(), updated_at: snapshot.s }),
|
||||
})
|
||||
if (!res.ok) throw new Error(t('sync.err.push', { status: res.status }))
|
||||
meta.settingsAt = snapshot.s
|
||||
if (!res.ok) throw new PushError(res.status)
|
||||
meta.settingsAt = maxIso(meta.settingsAt, snapshot.s)
|
||||
// On ne retire que ce qui n'a pas été re-modifié pendant l'envoi
|
||||
done(['s'], snapshot)
|
||||
}
|
||||
|
||||
// On ne retire que ce qui n'a pas été re-modifié pendant l'envoi
|
||||
for (const k of keys) if (meta.outbox[k] === snapshot[k]) delete meta.outbox[k]
|
||||
saveMeta()
|
||||
}
|
||||
|
||||
// ─── Réception ───
|
||||
@@ -222,39 +326,61 @@ export function createSync(userId: string, hooks: SyncHooks): SyncEngine {
|
||||
return { rows, cursor: last }
|
||||
}
|
||||
|
||||
/**
|
||||
* Curseur après une réception : les lignes ignorées car une modification locale était en attente sont
|
||||
* relues la prochaine fois (si l'envoi local est refusé par le serveur — version distante plus récente —,
|
||||
* c'est elle qu'il faudra récupérer).
|
||||
*/
|
||||
const heldCursor = (cursor: string | undefined, held: string[]) => {
|
||||
const first = held.length ? held.reduce((a, b) => (a < b ? a : b)) : undefined
|
||||
return first && (!cursor || first < cursor) ? first : undefined
|
||||
}
|
||||
|
||||
async function pullItems() {
|
||||
const { rows, cursor } = await fetchChanges('items', meta.itemsCursor)
|
||||
const toPut: MediaItem[] = []
|
||||
const toRemove: string[] = []
|
||||
for (const r of rows) {
|
||||
if (meta.outbox[`i:${r.id}`]) continue // modification locale en attente : elle passera en priorité
|
||||
const local = await mediaDB.get(r.id)
|
||||
if (r.deleted) {
|
||||
if (local) toRemove.push(r.id)
|
||||
continue
|
||||
if (!alive()) return
|
||||
const remote = new Map<string, Row>()
|
||||
for (const r of rows) remote.set(r.id, r) // la plus récente (ordre du serveur) l'emporte
|
||||
const held: string[] = []
|
||||
// Décision prise dans la transaction d'écriture (une seule pour toutes les fiches) : la boîte d'envoi
|
||||
// et la version locale sont relues au dernier moment, une modification faite pendant la réception gagne.
|
||||
const decide = (id: string, local: MediaItem | undefined): RemoteDecision => {
|
||||
const r = remote.get(id)!
|
||||
if (!alive()) return null
|
||||
if (meta.outbox[`i:${id}`]) {
|
||||
held.push(r.server_updated_at) // modification locale en attente : elle passera en priorité
|
||||
return null
|
||||
}
|
||||
if (r.deleted) return local ? 'remove' : null
|
||||
const item = normalizeItem(r.data)
|
||||
if (!item || item.id !== r.id) continue
|
||||
if (local && local.updatedAt > item.updatedAt) continue
|
||||
if (!item || item.id !== id) return null
|
||||
if (local && local.updatedAt > item.updatedAt) return null
|
||||
// Même version : on garde l'affiche locale si le serveur ne l'a pas (fiche allégée à l'envoi)
|
||||
if (local && local.updatedAt === item.updatedAt && !item.poster && local.poster) item.poster = local.poster
|
||||
if (local && JSON.stringify(local) === JSON.stringify(item)) continue
|
||||
toPut.push(item)
|
||||
if (local && JSON.stringify(local) === JSON.stringify(item)) return null
|
||||
return { put: item }
|
||||
}
|
||||
await mediaDB.putMany(toPut, { silent: true })
|
||||
await mediaDB.removeMany(toRemove, { silent: true })
|
||||
const change = await mediaDB.mergeRemote([...remote.keys()], decide)
|
||||
if (!alive()) return
|
||||
meta.itemsCursor = safeIso(cursor)
|
||||
saveMeta()
|
||||
if (toPut.length || toRemove.length) hooks.itemsChanged()
|
||||
const back = heldCursor(meta.itemsCursor, held)
|
||||
if (back) meta.itemsCursor = back
|
||||
saveMeta(back ? { itemsCursor: back } : undefined)
|
||||
if (change.put.length || change.removed.length) hooks.itemsChanged()
|
||||
}
|
||||
|
||||
async function pullLists() {
|
||||
const { rows, cursor } = await fetchChanges('lists', meta.listsCursor)
|
||||
if (!alive()) return
|
||||
const held: string[] = []
|
||||
if (rows.length) {
|
||||
const map = new Map(hooks.getLists().map((l) => [l.id, l]))
|
||||
let changed = false
|
||||
for (const r of rows) {
|
||||
if (meta.outbox[`l:${r.id}`]) continue
|
||||
if (meta.outbox[`l:${r.id}`]) {
|
||||
held.push(r.server_updated_at)
|
||||
continue
|
||||
}
|
||||
if (r.deleted) {
|
||||
changed = map.delete(r.id) || changed
|
||||
continue
|
||||
@@ -268,7 +394,9 @@ export function createSync(userId: string, hooks: SyncHooks): SyncEngine {
|
||||
if (changed) hooks.applyLists([...map.values()].sort((a, b) => a.createdAt.localeCompare(b.createdAt)))
|
||||
}
|
||||
meta.listsCursor = safeIso(cursor)
|
||||
saveMeta()
|
||||
const back = heldCursor(meta.listsCursor, held)
|
||||
if (back) meta.listsCursor = back
|
||||
saveMeta(back ? { listsCursor: back } : undefined)
|
||||
}
|
||||
|
||||
async function pullSettings() {
|
||||
@@ -279,6 +407,8 @@ export function createSync(userId: string, hooks: SyncHooks): SyncEngine {
|
||||
const at = safeIso(row?.updated_at)
|
||||
if (!row || !at || (meta.settingsAt && at <= meta.settingsAt)) return
|
||||
const s = normalizeSettings(row.data)
|
||||
if (!alive()) return
|
||||
// Les appareils à jour envoient toujours la liste des mois masqués ([] = aucun) ; absente = ancienne version, on n'y touche pas
|
||||
if (s) hooks.applySettings(s)
|
||||
meta.settingsAt = at
|
||||
saveMeta()
|
||||
@@ -306,12 +436,12 @@ export function createSync(userId: string, hooks: SyncHooks): SyncEngine {
|
||||
} catch (e) {
|
||||
pushError = e
|
||||
}
|
||||
// Déconnexion pendant la synchro : on n'écrit plus rien dans la base de cet utilisateur
|
||||
if (stopped) return
|
||||
// Déconnexion (ou changement de compte) pendant la synchro : on n'écrit plus rien sur l'appareil
|
||||
if (!alive()) return
|
||||
await pullItems()
|
||||
if (stopped) return
|
||||
if (!alive()) return
|
||||
await pullLists()
|
||||
if (stopped) return
|
||||
if (!alive()) return
|
||||
await pullSettings()
|
||||
if (pushError) throw pushError
|
||||
meta.lastSyncAt = new Date().toISOString()
|
||||
|
||||
Reference in new issue
Block a user