Files
bobinoo/src/lib/cloud/sync.ts
T
Claude 459101bbf8 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
2026-11-24 15:11:01 +00:00

520 lines
19 KiB
TypeScript

import { t } from '../../i18n'
import type { CustomList, MediaItem, Settings } from '../../types'
import { normalizeItem, normalizeLists, normalizeSettings } from '../backup'
import { mediaDB, onMediaChange, type RemoteDecision } from '../db'
import { blobToPosterDataURL } from '../image'
import { isPlainObject, isSafeId, safeIso } from '../security'
import { getScope, scopedKey } from '../scope'
import { cloudFetch } from './api'
/**
* Synchronisation hors-ligne ↔ compte :
* - toutes les modifications sont d'abord écrites sur l'appareil (l'app marche sans réseau),
* - elles sont notées dans une « boîte d'envoi » puis envoyées dès que possible,
* - on récupère ensuite ce qui a changé ailleurs (autre téléphone, ordinateur…).
* En cas de conflit, la modification la plus récente gagne (vérifié aussi par la base).
*/
export type SyncedSettings = Pick<Settings, 'ratingScale' | 'topCategories' | 'accentColor' | 'themeMode' | 'challenges' | 'statsHiddenMonths'>
export interface SyncHooks {
getLists: () => CustomList[]
applyLists: (lists: CustomList[]) => void
getSettings: () => SyncedSettings
applySettings: (s: Partial<SyncedSettings>) => void
itemsChanged: () => void
}
export interface SyncStatus {
state: 'idle' | 'syncing' | 'offline' | 'error'
lastSyncAt?: string
pending: number
error?: string
}
interface SyncMeta {
itemsCursor?: string
listsCursor?: string
settingsAt?: string
lastSyncAt?: string
/** clé (« i:<id> », « l:<id> », « s ») → horodatage de la modification locale */
outbox: Record<string, string>
}
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
syncNow: () => Promise<void>
markList: (id: string) => void
markSettings: () => void
status: () => SyncStatus
subscribe: (fn: (s: SyncStatus) => void) => () => void
}
export function createSync(userId: string, hooks: SyncHooks): SyncEngine {
const META_KEY = scopedKey('sync', userId)
const loadMeta = (): SyncMeta => {
try {
const raw = JSON.parse(localStorage.getItem(META_KEY) ?? '{}') as unknown
if (!isPlainObject(raw)) return { outbox: {} }
const outbox: Record<string, string> = {}
if (isPlainObject(raw.outbox)) {
for (const [k, v] of Object.entries(raw.outbox)) {
if ((k === 's' || /^[il]:[A-Za-z0-9_-]{1,64}$/.test(k)) && safeIso(v)) outbox[k] = v as string
}
}
return {
itemsCursor: safeIso(raw.itemsCursor),
listsCursor: safeIso(raw.listsCursor),
settingsAt: safeIso(raw.settingsAt),
lastSyncAt: safeIso(raw.lastSyncAt),
outbox,
}
} catch {
return { outbox: {} }
}
}
let meta = loadMeta()
/** 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>) => {
status = { ...status, ...patch, pending: Object.keys(meta.outbox).length }
for (const fn of listeners) fn(status)
}
const mark = (key: string) => {
meta.outbox[key] = new Date().toISOString()
saveMeta()
setStatus({})
schedule()
}
// ─── Envoi ───
/** Réduit une fiche trop lourde (affiche importée en très haute qualité) avant envoi. */
async function fitForUpload(item: MediaItem): Promise<MediaItem> {
if (byteSize(item) <= MAX_ROW_BYTES) return item
if (item.poster?.startsWith('data:image')) {
try {
const blob = dataURLToBlob(item.poster)
const smaller = { ...item, poster: await blobToPosterDataURL(blob, 360, 0.75) }
if (byteSize(smaller) <= MAX_ROW_BYTES) return smaller
} catch {
/* image illisible */
}
}
const { poster: _poster, ...rest } = item
const stripped = rest as MediaItem
return byteSize(stripped) <= MAX_ROW_BYTES ? stripped : { ...stripped, notes: stripped.notes?.slice(0, 5000), overview: undefined }
}
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: UpRow[] = []
let size = 0
const flush = async () => {
if (!batch.length) return
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 = byteSize(r)
if (size + bytes > MAX_BATCH_BYTES || batch.length >= 200) await flush()
batch.push(r)
size += bytes
}
await flush()
}
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: UpRow[] = []
for (const id of itemIds) {
const item = await mediaDB.get(id)
if (item) {
const data = await fitForUpload(item)
rows.push({ id, data, deleted: false, updated_at: item.updatedAt })
} else {
rows.push({ id, data: null, deleted: true, updated_at: snapshot[`i:${id}`] })
}
}
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))
if (listIds.length) {
const current = new Map(hooks.getLists().map((l) => [l.id, l]))
await upsert(
'lists',
listIds.map((id) => {
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),
)
}
if (snapshot.s) {
const res = await cloudFetch('/rest/v1/settings?on_conflict=user_id', {
method: 'POST',
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 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)
}
}
// ─── Réception ───
type Row = { id: string; data: unknown; deleted: boolean; updated_at: string; server_updated_at: string }
async function fetchChanges(table: 'items' | 'lists', cursor?: string): Promise<{ rows: Row[]; cursor?: string }> {
const rows: Row[] = []
let after = cursor ? new Date(new Date(cursor).getTime() - OVERLAP_MS).toISOString() : undefined
let last = cursor
for (let page = 0; page < 200; page++) {
const q = new URLSearchParams({ select: 'id,data,deleted,updated_at,server_updated_at', order: 'server_updated_at.asc,id.asc', limit: String(PAGE) })
if (after) q.set('server_updated_at', `gt.${after}`)
const res = await cloudFetch(`/rest/v1/${table}?${q}`)
if (!res.ok) throw new Error(t('sync.err.pull', { status: res.status }))
const list = (await res.json()) as unknown
if (!Array.isArray(list)) throw new Error(t('auth.err.response'))
for (const r of list) {
if (!isPlainObject(r) || !isSafeId(r.id) || !safeIso(r.updated_at) || !safeIso(r.server_updated_at)) continue
rows.push(r as unknown as Row)
last = r.server_updated_at as string
}
if (list.length < PAGE) break
after = last
}
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)
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 !== 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)) return null
return { put: item }
}
const change = await mediaDB.mergeRemote([...remote.keys()], decide)
if (!alive()) return
meta.itemsCursor = safeIso(cursor)
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}`]) {
held.push(r.server_updated_at)
continue
}
if (r.deleted) {
changed = map.delete(r.id) || changed
continue
}
const [l] = normalizeLists([r.data]) ?? []
if (l && l.id === r.id && JSON.stringify(map.get(l.id)) !== JSON.stringify(l)) {
map.set(l.id, l)
changed = true
}
}
if (changed) hooks.applyLists([...map.values()].sort((a, b) => a.createdAt.localeCompare(b.createdAt)))
}
meta.listsCursor = safeIso(cursor)
const back = heldCursor(meta.listsCursor, held)
if (back) meta.listsCursor = back
saveMeta(back ? { listsCursor: back } : undefined)
}
async function pullSettings() {
if (meta.outbox.s) return
const res = await cloudFetch('/rest/v1/settings?select=data,updated_at&limit=1')
if (!res.ok) throw new Error(t('sync.err.pull', { status: res.status }))
const [row] = (await res.json()) as { data?: unknown; updated_at?: string }[]
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()
}
// ─── Orchestration ───
let running: Promise<void> | null = null
let again = false
let stopped = true
let timer: ReturnType<typeof setTimeout> | undefined
let interval: ReturnType<typeof setInterval> | undefined
async function cycle() {
if (!navigator.onLine) {
setStatus({ state: 'offline' })
return
}
setStatus({ state: 'syncing', error: undefined })
try {
// Un envoi refusé (fiche trop lourde, quota…) ne doit pas empêcher de recevoir les autres appareils
let pushError: unknown
try {
await push()
} catch (e) {
pushError = e
}
// Déconnexion (ou changement de compte) pendant la synchro : on n'écrit plus rien sur l'appareil
if (!alive()) return
await pullItems()
if (!alive()) return
await pullLists()
if (!alive()) return
await pullSettings()
if (pushError) throw pushError
meta.lastSyncAt = new Date().toISOString()
saveMeta()
setStatus({ state: 'idle', lastSyncAt: meta.lastSyncAt })
} catch (e) {
if (!stopped) setStatus({ state: navigator.onLine ? 'error' : 'offline', error: (e as Error).message })
}
}
function syncNow(): Promise<void> {
if (stopped) return Promise.resolve()
if (running) {
again = true
return running
}
running = (async () => {
do {
again = false
await cycle()
} while (again && !stopped)
})().finally(() => {
running = null
})
return running
}
function schedule(delay = 1500) {
if (stopped) return
clearTimeout(timer)
timer = setTimeout(() => void syncNow(), delay)
}
const onOnline = () => schedule(300)
const onOffline = () => setStatus({ state: 'offline' })
const onVisible = () => document.visibilityState === 'visible' && schedule(300)
let unsubscribeDB: (() => void) | undefined
return {
start() {
if (!stopped) return
stopped = false
unsubscribeDB = onMediaChange((c) => {
const now = new Date().toISOString()
for (const i of c.put) meta.outbox[`i:${i.id}`] = now
for (const id of c.removed) meta.outbox[`i:${id}`] = now
saveMeta()
setStatus({})
schedule()
})
window.addEventListener('online', onOnline)
window.addEventListener('offline', onOffline)
document.addEventListener('visibilitychange', onVisible)
interval = setInterval(() => document.visibilityState === 'visible' && void syncNow(), 60_000)
void syncNow()
},
stop() {
stopped = true
clearTimeout(timer)
clearInterval(interval)
unsubscribeDB?.()
window.removeEventListener('online', onOnline)
window.removeEventListener('offline', onOffline)
document.removeEventListener('visibilitychange', onVisible)
},
syncNow,
markList: (id) => mark(`l:${id}`),
markSettings: () => mark('s'),
status: () => status,
subscribe(fn) {
listeners.add(fn)
return () => listeners.delete(fn)
},
}
}