Merge branch 'worktree-agent-ab18ecf78a0bb887b' into claude/relaxed-maxwell-c10wof
# Conflicts: # src/i18n/locales/ar.ts # src/i18n/locales/de.ts # src/i18n/locales/en.ts # src/i18n/locales/es.ts # src/i18n/locales/fr.ts # src/i18n/locales/hi.ts # src/i18n/locales/id.ts # src/i18n/locales/it.ts # src/i18n/locales/ja.ts # src/i18n/locales/ko.ts # src/i18n/locales/nl.ts # src/i18n/locales/pl.ts # src/i18n/locales/pt.ts # src/i18n/locales/ru.ts # src/i18n/locales/th.ts # src/i18n/locales/tr.ts # src/i18n/locales/vi.ts # src/i18n/locales/zh.ts # src/pages/SettingsPage.tsx
This commit is contained in:
42 files changed
+4983
-32
No files matched your search
@@ -0,0 +1,61 @@
|
||||
import { getLang } from '../i18n'
|
||||
import type { ThemeMode } from '../types'
|
||||
|
||||
/** Version de l'app (package.json). */
|
||||
export const APP_VERSION = __APP_VERSION__
|
||||
|
||||
/** Navigateur et système, en clair et sans détail identifiant (« Chrome 129 », « Android 14 »). */
|
||||
export function browserInfo(ua = navigator.userAgent): { browser: string; os: string } {
|
||||
const m = (re: RegExp) => ua.match(re)?.[1]?.split('.')[0]
|
||||
const browser = /Edg\//.test(ua)
|
||||
? `Edge ${m(/Edg\/([\d.]+)/) ?? ''}`
|
||||
: /OPR\//.test(ua)
|
||||
? `Opera ${m(/OPR\/([\d.]+)/) ?? ''}`
|
||||
: /SamsungBrowser\//.test(ua)
|
||||
? `Samsung Internet ${m(/SamsungBrowser\/([\d.]+)/) ?? ''}`
|
||||
: /Firefox\/|FxiOS\//.test(ua)
|
||||
? `Firefox ${m(/(?:Firefox|FxiOS)\/([\d.]+)/) ?? ''}`
|
||||
: /CriOS\/|Chrome\//.test(ua)
|
||||
? `Chrome ${m(/(?:CriOS|Chrome)\/([\d.]+)/) ?? ''}`
|
||||
: /Safari\//.test(ua)
|
||||
? `Safari ${m(/Version\/([\d.]+)/) ?? ''}`
|
||||
: 'Other'
|
||||
const os = /Android/.test(ua)
|
||||
? `Android ${m(/Android ([\d.]+)/) ?? ''}`
|
||||
: /iPhone|iPad|iPod/.test(ua)
|
||||
? `iOS ${ua.match(/OS (\d+)_/)?.[1] ?? ''}`
|
||||
: /Mac OS X/.test(ua)
|
||||
? 'macOS'
|
||||
: /Windows/.test(ua)
|
||||
? 'Windows'
|
||||
: /CrOS/.test(ua)
|
||||
? 'ChromeOS'
|
||||
: /Linux/.test(ua)
|
||||
? 'Linux'
|
||||
: 'Other'
|
||||
return { browser: browser.trim(), os: os.trim() }
|
||||
}
|
||||
|
||||
/** Page affichée, sans ce qui pourrait identifier quelqu'un (« #/u/pseudo » → « #/u »). */
|
||||
export const currentRoute = () => (location.hash.match(/^#\/[a-z-]{1,20}/i)?.[0] ?? '#/') || '#/'
|
||||
|
||||
/**
|
||||
* Infos techniques jointes à un signalement de bug (affichées avant l'envoi).
|
||||
* Rien de personnel : ni compte, ni e-mail, ni contenu de la bibliothèque.
|
||||
*/
|
||||
export function techInfo(theme: ThemeMode): Record<string, string> {
|
||||
const { browser, os } = browserInfo()
|
||||
const standalone = window.matchMedia?.('(display-mode: standalone)').matches || (navigator as { standalone?: boolean }).standalone === true
|
||||
return {
|
||||
version: APP_VERSION,
|
||||
browser,
|
||||
os,
|
||||
lang: getLang(),
|
||||
theme,
|
||||
screen: `${screen.width}×${screen.height} @${Math.round((window.devicePixelRatio || 1) * 10) / 10}x`,
|
||||
viewport: `${window.innerWidth}×${window.innerHeight}`,
|
||||
route: currentRoute(),
|
||||
standalone: standalone ? 'yes' : 'no',
|
||||
online: navigator.onLine ? 'yes' : 'no',
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,266 @@
|
||||
import { cleanText, isPlainObject, safeIso } from '../security'
|
||||
import { cloudFetch } from './api'
|
||||
import type { ReportReason, ReportTargetType } from './moderation'
|
||||
import { REPORT_REASONS } from './moderation'
|
||||
import { safeMediaUrl } from './social'
|
||||
|
||||
/**
|
||||
* Administration : modération (signalements, comptes suspendus), bugs signalés, erreurs de l'app.
|
||||
* Toutes les fonctions SQL appelées ici vérifient is_admin() côté serveur.
|
||||
* Les réponses sont relues champ par champ (un contenu signalé peut être piégé).
|
||||
*/
|
||||
|
||||
async function rpc(name: string, args: Record<string, unknown> = {}): Promise<unknown> {
|
||||
const res = await cloudFetch(`/rest/v1/rpc/${name}`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(args),
|
||||
})
|
||||
if (!res.ok) {
|
||||
const body = (await res.json().catch(() => ({}))) as { message?: unknown }
|
||||
throw new Error(typeof body.message === 'string' ? body.message.slice(0, 120) : `HTTP ${res.status}`)
|
||||
}
|
||||
const text = await res.text()
|
||||
return text ? JSON.parse(text) : null
|
||||
}
|
||||
|
||||
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
|
||||
const int = (v: unknown) => (typeof v === 'number' && Number.isFinite(v) ? Math.max(0, Math.floor(v)) : 0)
|
||||
const iso = (v: unknown) => safeIso(v) ?? new Date(0).toISOString()
|
||||
const list = (v: unknown) => (Array.isArray(v) ? v : [])
|
||||
|
||||
export interface AdminCard {
|
||||
id: string
|
||||
username: string
|
||||
displayName: string
|
||||
avatarUrl?: string
|
||||
suspended: boolean
|
||||
isAdmin: boolean
|
||||
}
|
||||
|
||||
function toCard(v: unknown): AdminCard | null {
|
||||
if (!isPlainObject(v) || typeof v.id !== 'string' || !UUID.test(v.id)) return null
|
||||
const username = cleanText(v.username, 20) ?? ''
|
||||
return {
|
||||
id: v.id,
|
||||
username,
|
||||
displayName: cleanText(v.display_name, 40) ?? username,
|
||||
avatarUrl: safeMediaUrl(v.avatar_url),
|
||||
suspended: v.suspended === true,
|
||||
isAdmin: v.is_admin === true,
|
||||
}
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ Alertes (badge) */
|
||||
|
||||
export interface AdminAlerts {
|
||||
reports: number
|
||||
bugs: number
|
||||
errors: number
|
||||
suspended: number
|
||||
}
|
||||
|
||||
export async function adminAlerts(): Promise<AdminAlerts> {
|
||||
const r = await rpc('admin_alerts')
|
||||
const o = isPlainObject(r) ? r : {}
|
||||
return { reports: int(o.reports), bugs: int(o.bugs), errors: int(o.errors), suspended: int(o.suspended) }
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ Signalements */
|
||||
|
||||
/** Contenu signalé (copie au moment du signalement, ou version actuelle). */
|
||||
export interface ReportedContent {
|
||||
title?: string
|
||||
notes?: string
|
||||
rating?: number
|
||||
username?: string
|
||||
displayName?: string
|
||||
bio?: string
|
||||
avatarUrl?: string
|
||||
}
|
||||
|
||||
export interface ReportEntry {
|
||||
reason: ReportReason
|
||||
details?: string
|
||||
createdAt: string
|
||||
reporter: AdminCard | null
|
||||
}
|
||||
|
||||
export interface ReportGroup {
|
||||
key: string
|
||||
targetType: ReportTargetType
|
||||
targetId: string
|
||||
targetUser: AdminCard | null
|
||||
total: number
|
||||
openCount: number
|
||||
firstAt: string
|
||||
lastAt: string
|
||||
status: 'open' | 'resolved' | 'dismissed'
|
||||
reasons: Partial<Record<ReportReason, number>>
|
||||
reports: ReportEntry[]
|
||||
snapshot?: ReportedContent
|
||||
/** null : le contenu n'existe plus (effacé) ; undefined : pas d'aperçu pour ce type */
|
||||
current?: ReportedContent | null
|
||||
/** Nombre de contenus différents de ce compte déjà signalés */
|
||||
userReportedTargets: number
|
||||
}
|
||||
|
||||
const TARGETS: ReportTargetType[] = ['review', 'profile', 'comment', 'list']
|
||||
const isReason = (v: unknown): v is ReportReason => (REPORT_REASONS as readonly unknown[]).includes(v)
|
||||
|
||||
function toContent(v: unknown): ReportedContent | undefined {
|
||||
if (!isPlainObject(v)) return undefined
|
||||
const rating = typeof v.rating === 'number' && v.rating > 0 && v.rating <= 10 ? v.rating : undefined
|
||||
return {
|
||||
title: cleanText(v.title, 200),
|
||||
notes: cleanText(v.notes, 3000),
|
||||
rating,
|
||||
username: cleanText(v.username, 20),
|
||||
displayName: cleanText(v.display_name, 40),
|
||||
bio: cleanText(v.bio, 300),
|
||||
avatarUrl: safeMediaUrl(v.avatar_url),
|
||||
}
|
||||
}
|
||||
|
||||
function toGroup(v: unknown): ReportGroup | null {
|
||||
if (!isPlainObject(v)) return null
|
||||
const targetType = TARGETS.find((x) => x === v.target_type)
|
||||
const targetId = cleanText(v.target_id, 200)
|
||||
if (!targetType || !targetId) return null
|
||||
const targetUser = toCard(v.target_user)
|
||||
const reasons: Partial<Record<ReportReason, number>> = {}
|
||||
if (isPlainObject(v.reasons)) for (const r of REPORT_REASONS) if (int(v.reasons[r]) > 0) reasons[r] = int(v.reasons[r])
|
||||
const status = v.status === 'resolved' || v.status === 'dismissed' ? v.status : 'open'
|
||||
return {
|
||||
key: `${targetType}:${targetId}:${targetUser?.id ?? ''}`,
|
||||
targetType,
|
||||
targetId,
|
||||
targetUser,
|
||||
total: int(v.total),
|
||||
openCount: int(v.open_count),
|
||||
firstAt: iso(v.first_at),
|
||||
lastAt: iso(v.last_at),
|
||||
status,
|
||||
reasons,
|
||||
reports: list(v.reports).flatMap((r) =>
|
||||
isPlainObject(r) && isReason(r.reason) ? [{ reason: r.reason, details: cleanText(r.details, 500), createdAt: iso(r.created_at), reporter: toCard(r.reporter) }] : [],
|
||||
),
|
||||
snapshot: toContent(v.snapshot),
|
||||
current: targetType === 'review' || targetType === 'profile' ? (toContent(v.current) ?? null) : undefined,
|
||||
userReportedTargets: int(v.user_reported_targets),
|
||||
}
|
||||
}
|
||||
|
||||
export const REPORTS_PAGE = 30
|
||||
|
||||
export async function adminReports(status: 'open' | 'closed', offset = 0): Promise<ReportGroup[]> {
|
||||
return list(await rpc('admin_reports', { p_status: status, p_offset: offset }))
|
||||
.map(toGroup)
|
||||
.filter((g): g is ReportGroup => g !== null)
|
||||
}
|
||||
|
||||
export type ReportAction = 'delete' | 'suspend' | 'unsuspend' | 'dismiss' | 'resolve'
|
||||
|
||||
export async function adminReportAction(g: Pick<ReportGroup, 'targetType' | 'targetId' | 'targetUser'>, action: ReportAction): Promise<void> {
|
||||
if (!g.targetUser) throw new Error('no target user')
|
||||
await rpc('admin_report_action', { p_type: g.targetType, p_target_id: g.targetId, p_target_user: g.targetUser.id, p_action: action })
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ Comptes suspendus */
|
||||
|
||||
export interface SuspendedUser extends AdminCard {
|
||||
suspendedAt?: string
|
||||
suspendedBy?: string
|
||||
reports: number
|
||||
}
|
||||
|
||||
export async function adminSuspendedUsers(offset = 0): Promise<SuspendedUser[]> {
|
||||
return list(await rpc('admin_suspended_users', { p_offset: offset })).flatMap((r) => {
|
||||
const card = toCard(r)
|
||||
if (!card || !isPlainObject(r)) return []
|
||||
return [{ ...card, suspended: true, suspendedAt: safeIso(r.suspended_at), suspendedBy: cleanText(r.suspended_by, 20), reports: int(r.reports) }]
|
||||
})
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ Bugs signalés */
|
||||
|
||||
export type BugStatus = 'new' | 'in_progress' | 'fixed'
|
||||
export const BUG_STATUSES: BugStatus[] = ['new', 'in_progress', 'fixed']
|
||||
|
||||
export interface BugReport {
|
||||
id: number
|
||||
description: string
|
||||
context: Record<string, string>
|
||||
status: BugStatus
|
||||
createdAt: string
|
||||
reporter: AdminCard | null
|
||||
}
|
||||
|
||||
export async function adminBugReports(status: BugStatus | null, offset = 0): Promise<BugReport[]> {
|
||||
return list(await rpc('admin_bug_reports', { p_status: status, p_offset: offset })).flatMap((r) => {
|
||||
if (!isPlainObject(r) || typeof r.id !== 'number') return []
|
||||
const description = cleanText(r.description, 2000)
|
||||
if (!description) return []
|
||||
const context: Record<string, string> = {}
|
||||
if (isPlainObject(r.context)) {
|
||||
for (const [k, v] of Object.entries(r.context).slice(0, 12)) {
|
||||
const val = cleanText(typeof v === 'string' ? v : String(v), 120)
|
||||
if (/^[a-z]{1,20}$/.test(k) && val) context[k] = val
|
||||
}
|
||||
}
|
||||
const status = BUG_STATUSES.find((s) => s === r.status) ?? 'new'
|
||||
return [{ id: r.id, description, context, status, createdAt: iso(r.created_at), reporter: toCard(r.reporter) }]
|
||||
})
|
||||
}
|
||||
|
||||
export async function adminSetBugStatus(id: number, status: BugStatus): Promise<void> {
|
||||
await rpc('admin_set_bug_status', { p_id: id, p_status: status })
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ Erreurs de l'app */
|
||||
|
||||
export type ErrorStatus = 'new' | 'seen' | 'fixed'
|
||||
|
||||
export interface ClientError {
|
||||
fingerprint: string
|
||||
source: 'error' | 'rejection' | 'render'
|
||||
message: string
|
||||
stack?: string
|
||||
url?: string
|
||||
appVersion?: string
|
||||
userAgent?: string
|
||||
count: number
|
||||
status: ErrorStatus
|
||||
firstSeen: string
|
||||
lastSeen: string
|
||||
}
|
||||
|
||||
export async function adminClientErrors(offset = 0): Promise<ClientError[]> {
|
||||
return list(await rpc('admin_client_errors', { p_status: null, p_offset: offset })).flatMap((r) => {
|
||||
if (!isPlainObject(r) || typeof r.fingerprint !== 'string' || !/^[0-9a-f]{32}$/.test(r.fingerprint)) return []
|
||||
const message = cleanText(r.message, 500)
|
||||
if (!message) return []
|
||||
const source = r.source === 'rejection' || r.source === 'render' ? r.source : 'error'
|
||||
const status = r.status === 'seen' || r.status === 'fixed' ? r.status : 'new'
|
||||
return [
|
||||
{
|
||||
fingerprint: r.fingerprint,
|
||||
source,
|
||||
message,
|
||||
stack: cleanText(r.stack, 4000),
|
||||
url: cleanText(r.url, 300),
|
||||
appVersion: cleanText(r.app_version, 40),
|
||||
userAgent: cleanText(r.user_agent, 300),
|
||||
count: int(r.count),
|
||||
status,
|
||||
firstSeen: iso(r.first_seen),
|
||||
lastSeen: iso(r.last_seen),
|
||||
},
|
||||
]
|
||||
})
|
||||
}
|
||||
|
||||
/** fingerprint null + 'seen' : tout marquer comme vu. 'delete' : oublie l'erreur (elle revient si elle se reproduit). */
|
||||
export async function adminSetErrorStatus(fingerprint: string | null, status: ErrorStatus | 'delete'): Promise<void> {
|
||||
await rpc('admin_set_error_status', { p_fingerprint: fingerprint, p_status: status })
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import { t } from '../../i18n'
|
||||
import { cleanText, isPlainObject } from '../security'
|
||||
import { cloudFetch } from './api'
|
||||
import { getSession } from './auth'
|
||||
import { safeMediaUrl } from './social'
|
||||
|
||||
/**
|
||||
* Signalements, blocages et « Signaler un bug » (côté membre).
|
||||
* Tout passe par des fonctions SQL `security definer` qui vérifient les droits et limitent les abus
|
||||
* (voir supabase/migrations/20261009160000_moderation.sql et 20261009160100_bugs_errors.sql).
|
||||
*/
|
||||
|
||||
/** Types de contenus signalables. 'comment' et 'list' : branchés par les fonctionnalités correspondantes. */
|
||||
export type ReportTargetType = 'review' | 'profile' | 'comment' | 'list'
|
||||
|
||||
export interface ReportTarget {
|
||||
type: ReportTargetType
|
||||
/** Identifiant du contenu : id de la fiche (avis), id du compte (profil), id du commentaire / de la liste */
|
||||
id: string
|
||||
/** Auteur du contenu */
|
||||
userId: string
|
||||
}
|
||||
|
||||
export const REPORT_REASONS = ['spoiler', 'harassment', 'hate', 'sexual', 'spam', 'impersonation', 'other'] as const
|
||||
export type ReportReason = (typeof REPORT_REASONS)[number]
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
async function rpc<T>(name: string, args: Record<string, unknown> = {}): Promise<T> {
|
||||
const res = await cloudFetch(`/rest/v1/rpc/${name}`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(args),
|
||||
})
|
||||
if (!res.ok) {
|
||||
const body = (await res.json().catch(() => ({}))) as { message?: unknown }
|
||||
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)
|
||||
}
|
||||
const text = await res.text()
|
||||
return (text ? JSON.parse(text) : null) as T
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ Signalements */
|
||||
|
||||
/** Signale un contenu. `duplicate` : déjà signalé par moi (rien n'est ajouté). */
|
||||
export async function reportContent(target: ReportTarget, reason: ReportReason, details: string): Promise<{ duplicate: boolean }> {
|
||||
const res = await rpc<unknown>('report_content', {
|
||||
p_type: target.type,
|
||||
p_target_id: target.id,
|
||||
p_target_user: target.userId,
|
||||
p_reason: reason,
|
||||
p_details: details.trim().slice(0, REPORT_DETAILS_MAX) || null,
|
||||
})
|
||||
return { duplicate: isPlainObject(res) && res.duplicate === true }
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ Blocages */
|
||||
|
||||
export interface BlockedUser {
|
||||
id: string
|
||||
username: string
|
||||
displayName: string
|
||||
avatarUrl?: string
|
||||
}
|
||||
|
||||
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
|
||||
|
||||
let blocked: BlockedUser[] = []
|
||||
let loaded: Promise<void> | null = null
|
||||
/** Compte pour lequel la liste a été chargée (changement de compte = rechargement) */
|
||||
let loadedFor: string | undefined
|
||||
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> {
|
||||
const uid = getSession()?.user.id
|
||||
if (loaded && !force && loadedFor === uid) return loaded
|
||||
if (loadedFor !== uid) blocked = []
|
||||
loadedFor = uid
|
||||
loaded = rpc<unknown>('my_blocks')
|
||||
.then((rows) => {
|
||||
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) ?? ''
|
||||
return [{ id: r.id, username, displayName: cleanText(r.display_name, 40) ?? username, avatarUrl: safeMediaUrl(r.avatar_url) }]
|
||||
})
|
||||
emit()
|
||||
})
|
||||
.catch(() => {
|
||||
/* fonction pas encore déployée / hors-ligne : rien n'est masqué */
|
||||
})
|
||||
return loaded
|
||||
}
|
||||
|
||||
export const isBlocked = (userId: string | undefined | null) => !!userId && loadedFor === getSession()?.user.id && blocked.some((b) => b.id === userId)
|
||||
|
||||
/** Liste des comptes bloqués, tenue à jour (pour masquer avis / commentaires). */
|
||||
export function useBlocked(enabled = true): { blocked: BlockedUser[]; isBlocked: (userId: string | undefined | null) => boolean } {
|
||||
const [, setTick] = useState(0)
|
||||
useEffect(() => {
|
||||
if (!enabled) return
|
||||
const fn = () => setTick((n) => n + 1)
|
||||
listeners.add(fn)
|
||||
void loadBlocks()
|
||||
return () => {
|
||||
listeners.delete(fn)
|
||||
}
|
||||
}, [enabled])
|
||||
return { blocked: enabled ? blocked : [], isBlocked: (id) => enabled && isBlocked(id) }
|
||||
}
|
||||
|
||||
export async function blockUser(user: BlockedUser): Promise<void> {
|
||||
await rpc('block_user', { p_user: user.id })
|
||||
if (!isBlocked(user.id)) blocked = [user, ...blocked]
|
||||
emit()
|
||||
}
|
||||
|
||||
export async function unblockUser(userId: string): Promise<void> {
|
||||
await rpc('unblock_user', { p_user: userId })
|
||||
blocked = blocked.filter((b) => b.id !== userId)
|
||||
emit()
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ Signaler un bug */
|
||||
|
||||
export async function submitBugReport(description: string, context: Record<string, string>): Promise<void> {
|
||||
await rpc('submit_bug_report', { p_description: description.trim().slice(0, BUG_DESCRIPTION_MAX), p_context: context })
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
import { SUPABASE_ANON_KEY, SUPABASE_URL, cloudEnabled } from './cloud/config'
|
||||
|
||||
/**
|
||||
* Remontée des erreurs de l'app (équivalent Sentry minimal, sans service tiers).
|
||||
* - capte window.onerror, les promesses rejetées non gérées et les plantages d'affichage React ;
|
||||
* - aucune donnée personnelle : e-mails, jetons, identifiants et paramètres d'URL sont retirés
|
||||
* (ici ET côté serveur), aucun identifiant de compte n'est envoyé ;
|
||||
* - dédoublonnage par empreinte (message + 1re ligne de pile) et 10 envois max par session ;
|
||||
* - le serveur (log_client_error) regroupe, compte et limite le débit par empreinte.
|
||||
*/
|
||||
|
||||
export type ErrorSource = 'error' | 'rejection' | 'render'
|
||||
|
||||
const MAX_PER_SESSION = 10
|
||||
const sent = new Set<string>()
|
||||
let budget = MAX_PER_SESSION
|
||||
let installed = false
|
||||
|
||||
/** Envoi activé : en production (ou en dev avec VITE_REPORT_ERRORS=1), et seulement avec Supabase. */
|
||||
const enabled = () => cloudEnabled && (import.meta.env.PROD || import.meta.env.VITE_REPORT_ERRORS === '1')
|
||||
|
||||
/** Retire ce qui pourrait identifier quelqu'un. */
|
||||
export function scrub(text: string, max: number): string {
|
||||
return (
|
||||
text
|
||||
// eslint-disable-next-line no-control-regex
|
||||
.replace(/[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F]/g, '')
|
||||
.replace(/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/g, '[email]')
|
||||
.replace(/eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+(\.[A-Za-z0-9_-]*)?/g, '[token]')
|
||||
.replace(/(sb_(publishable|secret)_|sk_|pk_)[A-Za-z0-9_-]+/g, '[key]')
|
||||
.replace(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi, '[id]')
|
||||
// Adresses : ni paramètres ni ancre (#/u/pseudo, ?code=…)
|
||||
.replace(/(https?:\/\/[^\s?#'"()]+)[?#][^\s'"()]*/g, '$1')
|
||||
.replace(/[A-Za-z0-9_-]{40,}/g, '[token]')
|
||||
.slice(0, max)
|
||||
)
|
||||
}
|
||||
|
||||
/** Petite empreinte locale (dédoublonnage dans la session ; le serveur recalcule la sienne). */
|
||||
function fingerprint(source: ErrorSource, message: string, stack: string): string {
|
||||
const frame = stack.split('\n').find((l) => /^\s*at |@/.test(l)) ?? ''
|
||||
const key = `${source}|${message.toLowerCase().replace(/\d+/g, '0')}|${frame.replace(/:\d+(:\d+)?/g, '')}`
|
||||
let h = 5381
|
||||
for (let i = 0; i < key.length; i++) h = ((h << 5) + h + key.charCodeAt(i)) | 0
|
||||
return (h >>> 0).toString(36)
|
||||
}
|
||||
|
||||
/** Erreurs sans intérêt (réseau coupé, extensions du navigateur, bruit connu des navigateurs). */
|
||||
function isNoise(message: string, stack: string): boolean {
|
||||
if (!message || message === 'Script error.' || message === 'Script error') return true
|
||||
if (/ResizeObserver loop|AbortError|The operation was aborted|NetworkError when attempting|Failed to fetch$|Load failed$|cancelled|annulé/i.test(message)) return true
|
||||
if (/(chrome|moz|safari(-web)?)-extension:\/\//.test(stack)) return true
|
||||
return false
|
||||
}
|
||||
|
||||
function toParts(err: unknown): { message: string; stack: string } {
|
||||
if (err instanceof Error) return { message: `${err.name}: ${err.message}`, stack: err.stack ?? '' }
|
||||
if (typeof err === 'string') return { message: err, stack: '' }
|
||||
try {
|
||||
return { message: `Non-Error: ${JSON.stringify(err)?.slice(0, 200) ?? String(err)}`, stack: '' }
|
||||
} catch {
|
||||
return { message: 'Non-Error value', stack: '' }
|
||||
}
|
||||
}
|
||||
|
||||
/** Remonte une erreur (sans jamais lever d'erreur elle-même). */
|
||||
export function reportError(err: unknown, source: ErrorSource = 'error', extraStack = ''): void {
|
||||
try {
|
||||
if (!enabled() || budget <= 0) return
|
||||
const parts = toParts(err)
|
||||
const message = scrub(parts.message, 500).trim()
|
||||
const stack = scrub([parts.stack, extraStack].filter(Boolean).join('\n--- component stack ---\n'), 4000)
|
||||
if (isNoise(message, stack)) return
|
||||
if (!navigator.onLine) return
|
||||
const fp = fingerprint(source, message, stack)
|
||||
if (sent.has(fp)) return
|
||||
sent.add(fp)
|
||||
budget--
|
||||
const headers: Record<string, string> = { apikey: SUPABASE_ANON_KEY, 'Content-Type': 'application/json' }
|
||||
// Ancienne clé « anon » (JWT) : elle sert aussi de jeton. Les clés « sb_publishable_ » se passent de ce champ.
|
||||
if (SUPABASE_ANON_KEY.split('.').length === 3) headers.Authorization = `Bearer ${SUPABASE_ANON_KEY}`
|
||||
void fetch(`${SUPABASE_URL}/rest/v1/rpc/log_client_error`, {
|
||||
method: 'POST',
|
||||
headers,
|
||||
body: JSON.stringify({
|
||||
p_message: message,
|
||||
p_stack: stack || null,
|
||||
p_url: `${location.origin}${location.pathname}`,
|
||||
p_version: __APP_VERSION__,
|
||||
p_ua: navigator.userAgent.slice(0, 300),
|
||||
p_source: source,
|
||||
}),
|
||||
credentials: 'omit',
|
||||
referrerPolicy: 'no-referrer',
|
||||
keepalive: true,
|
||||
}).catch(() => {})
|
||||
} catch {
|
||||
/* la remontée d'erreurs ne doit jamais casser l'app */
|
||||
}
|
||||
}
|
||||
|
||||
/** À appeler une fois au démarrage. */
|
||||
export function installErrorReporting(): void {
|
||||
if (installed || typeof window === 'undefined') return
|
||||
installed = true
|
||||
window.addEventListener('error', (e) => {
|
||||
// Erreurs de chargement de ressources (image cassée…) : ignorées
|
||||
if (!(e instanceof ErrorEvent)) return
|
||||
reportError(e.error ?? e.message, 'error')
|
||||
})
|
||||
window.addEventListener('unhandledrejection', (e) => reportError(e.reason, 'rejection'))
|
||||
}
|
||||
Reference in new issue
Block a user