veza/apps/web/src/app/App.tsx
senke c0e06e61b6 feat(legal): versioned terms acceptance ledger (CGU/CGV/mentions)
v1.0.10 légal item 3. RGPD requires explicit re-acceptance of any
terms-of-service-class document on material change. Adds a per-user,
per-document, per-version ledger so disputes can be answered with
evidence (timestamp + originating IP + user-agent).

Backend
  * migrations/991_terms_acceptance.sql — table terms_acceptances with
    UNIQUE (user_id, terms_type, version) so re-accepts are idempotent.
    inet column for IP, varchar(512) for UA, both nullable for the
    internal seed paths.
  * internal/services/terms_service.go — TermsService :
      - CurrentTerms map (ISO date version per class) is the single
        source of truth ; bump on text edit.
      - CurrentVersions(userID) returns versions + the user's
        unaccepted set ; userID==Nil ⇒ versions only (anonymous OK).
      - Accept(userID, []AcceptInput) : validates each (type, version)
        against CurrentTerms (ErrTermsVersionMismatch on stale POST),
        writes one row per accept in a single transaction, idempotent
        via FirstOrCreate against the unique index.
  * internal/handlers/terms_handler.go — REST surface :
      - GET  /api/v1/legal/terms/current  (public, OptionalAuth)
      - POST /api/v1/legal/terms/accept   (RequireAuth)
      - Captures IP via gin's ClientIP() (X-Forwarded-For-aware) and
        UA from the request, truncates UA to fit the column.
  * routes_legal.go — wires the two endpoints. `current` falls back
    to no-middleware when AuthMiddleware is nil so test rigs work.

Frontend
  * features/legal/pages/{CGUPage,CGVPage,MentionsPage}.tsx — initial
    drafts with version constants matching the backend's CurrentTerms.
    Counsel review required before v2.0.0 (text is honest baseline,
    not finalised legal copy).
  * services/api/legalTerms.ts — fetchCurrentTerms() / acceptTerms() ;
    hand-written to keep the consent-modal wiring readable.
  * components/TermsAcceptanceModal.tsx — non-dismissable modal that
    opens on every authenticated session when the unaccepted set is
    non-empty. Per-document checkboxes + single submit ; refusal keeps
    the modal open (no decline-and-continue path because the legal
    contract requires acceptance to use the platform).
  * Mounted in App.tsx alongside CookieBanner ; both must overlay
    every screen.
  * Lazy-component registry + routes for /legal/{cgu,cgv,mentions}.

Operator workflow when text changes :
  1. Edit the text in the relevant page component. Bump the
     `*_VERSION` const in that file.
  2. Bump CurrentTerms[*] in services/terms_service.go to the same
     value.
  3. Deploy. Every existing user gets force-prompted on their next
     session ; new users prompted at registration.

baseline checks : tsc 0 errors, eslint 754, go build clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-01 20:47:07 +02:00

219 lines
7.9 KiB
TypeScript

import { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useQueryClient } from '@tanstack/react-query';
import { useAuthStore } from '@/features/auth/store/authStore';
import { useUIStore } from '@/stores/ui';
import { ErrorBoundary } from '@/components/ui/ErrorBoundary';
import { AstralBackground } from '@/components/ui/AstralBackground';
import { OfflineIndicator } from '@/components/OfflineIndicator';
import { CookieBanner } from '@/components/CookieBanner';
import { TermsAcceptanceModal } from '@/components/TermsAcceptanceModal';
import { AppRouter } from '@/router';
import { csrfService } from '@/services/csrf';
import { useGlobalKeyboardShortcuts } from '@/hooks/useGlobalKeyboardShortcuts';
import { KeyboardShortcutsPanel } from '@/components/ui/KeyboardShortcutsPanel';
import { useStateHydration } from '@/utils/stateHydration';
import { useQueryInvalidation } from '@/hooks/useQueryInvalidation';
import { usePatina } from '@/hooks/usePatina';
import { setupReactQuerySync } from '@/utils/reactQuerySync';
import { logger } from '@/utils/logger';
import { AudioProvider } from '@/context/AudioContext';
export function App() {
const { t } = useTranslation();
const { refreshUser } = useAuthStore();
const { theme, setTheme, language, setLanguage } = useUIStore();
const [showKeyboardHelp, setShowKeyboardHelp] = useState(false);
// P1.2: Auth initialization state to prevent race condition
const [isAuthReady, setIsAuthReady] = useState(false);
const queryClient = useQueryClient();
// FE-COMP-022: Enable global keyboard shortcuts
useGlobalKeyboardShortcuts({
enabled: true,
onHelpOpen: () => setShowKeyboardHelp(true),
});
// FE-STATE-003: Hydrate state from server on app load
useStateHydration({
hydrateAuth: true,
hydrateLibrary: false, // Can be enabled if needed
hydrateChat: false, // Can be enabled if needed
requireAuth: false, // Hydrate auth even if not authenticated (to check status)
});
// FE-STATE-004: Listen for query invalidation events
useQueryInvalidation();
// SUMI v3: Apply patina level based on user profile data
usePatina();
// Action 2.3.1.2: Initialize React Query cache synchronization across tabs
useEffect(() => {
const cleanup = setupReactQuerySync(queryClient, {
enabled: true,
channelName: 'veza-react-query-sync',
});
return cleanup;
}, [queryClient]);
// P1.2: Initialize auth state before rendering app
// With httpOnly cookies we cannot read tokens in JS; always call refreshUser()
// so getMe() is used to verify auth (cookies sent automatically).
// CSRF token is fetched AFTER auth succeeds (no timing hack needed).
useEffect(() => {
const initAuth = async () => {
try {
await refreshUser();
// Fetch CSRF only after auth is confirmed
const { isAuthenticated } = useAuthStore.getState();
if (isAuthenticated) {
csrfService.refreshToken().catch((error) => {
const msg = error instanceof Error ? error.message : String(error);
if (!msg.includes('HTML page instead of JSON')) {
logger.warn('Failed to fetch CSRF token on app init', { message: msg });
}
});
}
} catch (error) {
logger.error('[App] Auth initialization failed', {
error: error instanceof Error ? error.message : String(error),
stack: error instanceof Error ? error.stack : undefined,
});
} finally {
setIsAuthReady(true);
}
};
initAuth();
}, [refreshUser]);
// Apply theme on load
useEffect(() => {
if (!theme || theme === 'system') {
const root = document.documentElement;
if (
!root.classList.contains('dark') &&
!root.classList.contains('light')
) {
setTheme('dark');
} else {
setTheme(theme);
}
} else {
setTheme(theme);
}
// Sync language with i18n on load
if (typeof window !== 'undefined' && window.i18n) {
const currentLang = window.i18n.language || language;
if (currentLang !== language) {
window.i18n.changeLanguage(language);
} else if (language !== currentLang) {
setLanguage(currentLang as 'en' | 'fr' | 'es');
}
}
}, [setTheme, theme, language, setLanguage]);
// Écouter les changements de préférence système pour le mode 'system'
useEffect(() => {
if (theme !== 'system') return;
const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
const handleChange = (e: MediaQueryListEvent) => {
const root = document.documentElement;
if (e.matches) {
root.classList.add('dark');
} else {
root.classList.remove('dark');
}
};
// Écouter les changements
if (mediaQuery.addEventListener) {
mediaQuery.addEventListener('change', handleChange);
} else {
// Fallback pour les navigateurs plus anciens
mediaQuery.addListener(handleChange);
}
return () => {
if (mediaQuery.removeEventListener) {
mediaQuery.removeEventListener('change', handleChange);
} else {
mediaQuery.removeListener(handleChange);
}
};
}, [theme]);
// S5.1: Branded loading screen (Spotify-like splash)
if (!isAuthReady) {
return (
<div className="flex flex-col items-center justify-center min-h-screen bg-[var(--sumi-bg-void)]">
{/* Logo mark */}
<div className="relative mb-8 animate-[sumi-fade-in_0.6s_ease-out]">
<svg
width="56"
height="56"
viewBox="0 0 56 56"
fill="none"
xmlns="http://www.w3.org/2000/svg"
className="text-primary"
aria-hidden="true"
>
<rect width="56" height="56" rx="16" fill="currentColor" fillOpacity="0.15" />
<path
d="M18 38V18l20 10-20 10z"
fill="currentColor"
className="animate-pulse"
/>
</svg>
</div>
{/* Brand name */}
<h1 className="text-2xl font-heading font-bold text-foreground mb-6 animate-[sumi-fade-in_0.8s_ease-out_0.2s_both]">
Veza
</h1>
{/* Progress bar */}
<div className="w-48 h-0.5 bg-muted/30 rounded-full overflow-hidden animate-[sumi-fade-in_1s_ease-out_0.4s_both]">
<div className="h-full bg-primary rounded-full animate-[loading-progress_1.5s_ease-in-out_infinite]" />
</div>
</div>
);
}
return (
<ErrorBoundary>
<AudioProvider>
{/* S3.1: Skip navigation link for keyboard/screen-reader users */}
<a
href="#main-content"
className="sr-only focus:not-sr-only focus:fixed focus:top-4 focus:left-4 focus:z-[var(--sumi-z-max)] focus:bg-primary focus:text-primary-foreground focus:px-4 focus:py-2 focus:rounded-lg focus:shadow-lg"
>
{t('nav.skipToContent')}
</a>
<AstralBackground />
{/* Offline/Online Status Indicator */}
<OfflineIndicator />
<AppRouter />
{/* v1.0.10 légal 1: ePrivacy/RGPD consent gate. Hides itself
once the user has decided ; persists for 13 months per
CNIL guidance. */}
<CookieBanner />
{/* v1.0.10 légal 3: terms-acceptance gate. Mounted alongside
CookieBanner because both must overlay every screen.
Self-hides when the user has accepted every current
version (or is anonymous). */}
<TermsAcceptanceModal />
{/* PWA Install Banner - Disabled for now as it is too intrusive */}
{/* <PWAInstallBanner /> */}
{/* Keyboard Shortcuts Panel (Discord-style overlay) */}
<KeyboardShortcutsPanel
isOpen={showKeyboardHelp}
onClose={() => setShowKeyboardHelp(false)}
/>
</AudioProvider>
</ErrorBoundary>
);
}