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
+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