Administration retirée : signalements et bugs par e-mail, base allégée
deploy / deploy (push) Successful in 46s
deploy / deploy (push) Successful in 46s
- Écran d'administration supprimé (page, onglets de modération, alertes, appels admin). - « Signaler » (avis, commentaire, profil, liste) et « Signaler un bug » ouvrent un e-mail pré-rempli vers contact@bobinoo.org (motifs en rappel, références du contenu ; version et appareil pour un bug). - Remontée automatique des erreurs supprimée. À la place : une ancienne version ouverte qui ne trouve plus un fichier après une mise à jour se recharge d'elle-même (« Importing a module script failed »). - Base (20261130120000_remove_admin, appliquée) : 20 fonctions et 5 tables d'administration supprimées (admins, reports, bug_reports, client_errors, moderation_log) ; get_profile, get_review_comments, delete_review_comment, delete_shared_list et la garde de suspension réécrites sans « admin ». Suspension d'un compte : à la main dans Supabase. - 116 textes inutilisés retirés dans chacune des 18 langues. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01YVo1qxKoBQCaMd7Ue8PGbe
This commit is contained in:
38 files changed
+299
-4008
No files matched your search
+1
-1
@@ -51,7 +51,7 @@ export function browserInfo(ua = navigator.userAgent): { browser: string; os: st
|
||||
export const currentRoute = () => (location.hash.match(/^#\/[a-z-]{1,20}/i)?.[0] ?? '#/') || '#/'
|
||||
|
||||
/**
|
||||
* Infos techniques jointes à un signalement de bug (affichées avant l'envoi).
|
||||
* Infos techniques ajoutées en bas de l'e-mail « Signaler un bug ».
|
||||
* Rien de personnel : ni compte, ni e-mail, ni contenu de la bibliothèque.
|
||||
*/
|
||||
export function techInfo(theme: ThemeMode): Record<string, string> {
|
||||
|
||||
@@ -1,86 +0,0 @@
|
||||
import { t } from '../../i18n'
|
||||
import { cloudFetch } from './api'
|
||||
|
||||
/**
|
||||
* Accès à la partie administration (réservée aux comptes de la table `admins`).
|
||||
* Toutes les fonctions appellent des RPC Supabase verrouillées côté serveur par is_admin() :
|
||||
* même en forçant l'URL, un non-admin reçoit une erreur.
|
||||
*/
|
||||
|
||||
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) throw new Error(t('social.err.server', { status: res.status }))
|
||||
return res.json() as Promise<T>
|
||||
}
|
||||
|
||||
export interface AdminOverview {
|
||||
users: number
|
||||
profiles: number
|
||||
public_profiles: number
|
||||
private_profiles: number
|
||||
suspended: number
|
||||
items: number
|
||||
reviews: number
|
||||
films: number
|
||||
series: number
|
||||
follows: number
|
||||
pending_follows: number
|
||||
media_files: number
|
||||
signups_7d: number
|
||||
signups_30d: number
|
||||
active_7d: number
|
||||
new_items_7d: number
|
||||
signups_by_day: { day: string; n: number }[]
|
||||
}
|
||||
|
||||
export interface AdminUser {
|
||||
id: string
|
||||
email: string | null
|
||||
created_at: string
|
||||
last_sign_in_at: string | null
|
||||
username: string | null
|
||||
display_name: string | null
|
||||
is_private: boolean | null
|
||||
suspended: boolean
|
||||
items: number
|
||||
reviews: number
|
||||
followers: number
|
||||
}
|
||||
|
||||
export interface AdminReview {
|
||||
item_id: string
|
||||
user_id: string
|
||||
updated_at: string
|
||||
username: string | null
|
||||
display_name: string | null
|
||||
suspended: boolean
|
||||
title: string | null
|
||||
type: string | null
|
||||
notes: string | null
|
||||
rating: number | null
|
||||
}
|
||||
|
||||
/** Le compte connecté est-il administrateur ? (false si l'app est en mode local sans compte) */
|
||||
export async function isAdmin(): Promise<boolean> {
|
||||
try {
|
||||
return (await rpc<boolean>('is_admin')) === true
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
export const adminOverview = () => rpc<AdminOverview>('admin_overview')
|
||||
export const adminUsers = (q: string, offset = 0) => rpc<AdminUser[]>('admin_users', { q: q || null, p_offset: offset })
|
||||
export const adminRecentReviews = (offset = 0) => rpc<AdminReview[]>('admin_recent_reviews', { p_offset: offset })
|
||||
|
||||
export async function adminSetSuspended(userId: string, value: boolean): Promise<void> {
|
||||
await rpc('admin_set_suspended', { p_user: userId, p_value: value })
|
||||
}
|
||||
|
||||
export async function adminClearReview(userId: string, itemId: string): Promise<void> {
|
||||
await rpc('admin_clear_review', { p_user: userId, p_item: itemId })
|
||||
}
|
||||
@@ -1,266 +0,0 @@
|
||||
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 })
|
||||
}
|
||||
@@ -6,7 +6,7 @@ import { safeMediaUrl } from './social'
|
||||
/**
|
||||
* Commentaires sous les avis. Lecture / écriture uniquement via les fonctions de la base
|
||||
* (get_review_comments, add_review_comment, delete_review_comment) qui vérifient les droits :
|
||||
* mêmes règles de visibilité que l'avis, anti-spam, suppression par l'auteur, l'auteur de l'avis ou un admin.
|
||||
* mêmes règles de visibilité que l'avis, anti-spam, suppression par l'auteur du commentaire ou celui de l'avis.
|
||||
*/
|
||||
|
||||
export const COMMENT_MAX = 500
|
||||
@@ -30,7 +30,7 @@ export interface ReviewComment {
|
||||
export interface CommentThread {
|
||||
/** L'avis existe et je peux le voir */
|
||||
visible: boolean
|
||||
/** Je peux supprimer tous les commentaires (auteur de l'avis ou admin) */
|
||||
/** Je peux supprimer tous les commentaires (je suis l'auteur de l'avis) */
|
||||
canModerate: boolean
|
||||
comments: ReviewComment[]
|
||||
}
|
||||
|
||||
@@ -6,12 +6,11 @@ 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).
|
||||
* Blocages entre membres, et ce qu'on peut signaler (le signalement lui-même part par e-mail,
|
||||
* voir components/moderation/ReportButton.tsx). Les blocages passent par des fonctions SQL `security definer`.
|
||||
*/
|
||||
|
||||
/** Types de contenus signalables. 'comment' et 'list' : branchés par les fonctionnalités correspondantes. */
|
||||
/** Types de contenus signalables. */
|
||||
export type ReportTargetType = 'review' | 'profile' | 'comment' | 'list'
|
||||
|
||||
export interface ReportTarget {
|
||||
@@ -24,12 +23,6 @@ export interface ReportTarget {
|
||||
|
||||
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 (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}`, {
|
||||
@@ -38,30 +31,13 @@ async function rpc<T>(name: string, args: Record<string, unknown> = {}): Promise
|
||||
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)
|
||||
await res.body?.cancel()
|
||||
throw new Error(t('social.err.server', { status: res.status }))
|
||||
}
|
||||
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 {
|
||||
@@ -136,9 +112,3 @@ export async function unblockUser(userId: string): Promise<void> {
|
||||
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 })
|
||||
}
|
||||
@@ -1,112 +0,0 @@
|
||||
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|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