From d5bd08c47fedd12e6eab1b74cd8ef5a6aed60a40 Mon Sep 17 00:00:00 2001 From: Purama Pro Date: Tue, 10 Nov 2026 04:27:25 +0100 Subject: [PATCH] =?UTF-8?q?feat(distribution):=20fiabiliser=20le=20partage?= =?UTF-8?q?=20et=20la=20copie=20priv=C3=A9e?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Expose des présentations publiques minimales, conserve le parcours après authentification et protège la copie contre les doublons et changements de compte. Durcit les accès SQL et le chat, corrige son validateur, rend les couches d’accueil non bloquantes et vérifie le secours PWA. Qualification locale : 333 unités, 31 scénarios SQL, 40 tests sécurité, 25 tests worker et 113 cas navigateur. Admission ONE et services réels restent à qualifier avant activation. --- .github/workflows/ci.yml | 10 +- docs/distribution/README.md | 178 +++++ docs/distribution/verification.json | 203 ++++++ package-lock.json | 70 +- package.json | 12 +- public/offline.html | 2 +- public/sw.js | 156 +++- src/App.tsx | 2 + src/components/shared/CinematicIntro.test.tsx | 281 +++++++ src/components/shared/CinematicIntro.tsx | 150 +++- src/components/shared/ShareButtons.test.tsx | 286 ++++++++ src/components/shared/ShareButtons.tsx | 243 +++++-- src/components/shared/SpiritualLayer.test.tsx | 301 ++++++++ src/components/shared/SpiritualLayer.tsx | 11 + src/hooks/useAuth.continuation.test.tsx | 101 +++ src/hooks/useAuth.tsx | 22 +- src/lib/auth-continuation.test.ts | 125 ++++ src/lib/auth-continuation.ts | 79 ++ src/lib/creator-agent-distribution.test.ts | 100 +++ src/lib/creator-agent.ts | 73 +- src/lib/public-creator-model.test.ts | 51 ++ src/lib/public-creator-model.ts | 50 ++ src/lib/public-share.test.ts | 69 ++ src/lib/public-share.ts | 48 ++ src/pages/CreatorAgent.tsx | 9 +- src/pages/CreatorAgentTemplates.tsx | 112 ++- src/pages/Login.tsx | 78 +- src/pages/PublicCreatorModel.tsx | 188 +++++ src/pages/Signup.tsx | 93 ++- src/pages/auth-continuation.test.tsx | 213 ++++++ .../functions/creator-agent-chat/index.ts | 5 +- ...1110001000_creator_public_distribution.sql | 154 ++++ tests/creator-chat-authorization.test.mjs | 271 +++++++ tests/creator-public-distribution.test.mjs | 688 ++++++++++++++++++ tests/distribution.spec.ts | 278 +++++++ tests/navigation.spec.ts | 8 +- tests/public-pages.spec.ts | 21 +- tests/pwa.spec.ts | 92 ++- tests/release-gates.spec.ts | 52 +- tests/service-worker-distribution.test.mjs | 449 ++++++++++++ vitest.config.ts | 5 + 41 files changed, 5011 insertions(+), 328 deletions(-) create mode 100644 docs/distribution/README.md create mode 100644 docs/distribution/verification.json create mode 100644 src/components/shared/CinematicIntro.test.tsx create mode 100644 src/components/shared/ShareButtons.test.tsx create mode 100644 src/components/shared/SpiritualLayer.test.tsx create mode 100644 src/hooks/useAuth.continuation.test.tsx create mode 100644 src/lib/auth-continuation.test.ts create mode 100644 src/lib/auth-continuation.ts create mode 100644 src/lib/creator-agent-distribution.test.ts create mode 100644 src/lib/public-creator-model.test.ts create mode 100644 src/lib/public-creator-model.ts create mode 100644 src/lib/public-share.test.ts create mode 100644 src/lib/public-share.ts create mode 100644 src/pages/PublicCreatorModel.tsx create mode 100644 src/pages/auth-continuation.test.tsx create mode 100644 supabase/migrations/20261110001000_creator_public_distribution.sql create mode 100644 tests/creator-chat-authorization.test.mjs create mode 100644 tests/creator-public-distribution.test.mjs create mode 100644 tests/distribution.spec.ts create mode 100644 tests/service-worker-distribution.test.mjs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 6c7f14ad..1a42f8ff 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -41,6 +41,12 @@ jobs: - name: Unit tests run: npm run test:unit + - name: Public model data permissions + run: npm run test:distribution:db + + - name: Service worker behavior + run: node --test tests/service-worker-distribution.test.mjs + - name: Security tests run: npm run test:security @@ -134,8 +140,8 @@ jobs: - name: Install dependencies run: npm ci - - name: Install Chromium - run: npx playwright install --with-deps chromium + - name: Install Chromium and WebKit + run: npx playwright install --with-deps chromium webkit - name: Run browser release gates run: npm run test:ci diff --git a/docs/distribution/README.md b/docs/distribution/README.md new file mode 100644 index 00000000..6f9b2c16 --- /dev/null +++ b/docs/distribution/README.md @@ -0,0 +1,178 @@ +# Distribution des modèles Creator Agent + +Ce lot rend un modèle existant consultable par un lien public, puis copiable dans +un espace privé après authentification et action explicite. Il réutilise le +catalogue et le moteur Creator Agent de `purama-ai`. + +Il ne constitue pas une nouvelle application publique ni une intégration déjà +admise dans ONE. Capsule/T17, Growth/T23 et leurs contrats restent des travaux +distincts à raccorder par leurs interfaces existantes. + +## Parcours livré + +1. Un auteur publie son modèle par le mécanisme existant. +2. Le catalogue expose sa présentation `/modeles/` et des liens de partage. +3. Un destinataire consulte cette présentation sans compte. Aucun agent n'est + exécuté à l'ouverture du lien. +4. Une connexion ou une inscription conserve la destination autorisée et un + éventuel code de parrainage structurellement valide. +5. Le destinataire choisit explicitement « Créer ma copie privée ». +6. Le serveur vérifie son identité et la disponibilité du modèle, crée une copie + privée, puis l'interface ouvre la fiche existante de cette copie. + +Le code de parrainage réutilise le stockage existant. Sa présence dans un lien +ne prouve ni son existence métier ni un droit à une commission. + +### Comportements de reprise + +- Une réponse de copie perdue peut être retentée avec le même UUID : le serveur + retrouve la copie du même propriétaire et de la même source. +- L'UUID de tentative est conservé dans l'instance montée de l'interface. Une + reprise après rechargement de page ou sur un autre appareil n'est pas fournie. +- Deux clics avant le prochain rendu n'envoient qu'une demande. +- Un changement de compte est vérifié côté serveur avant toute lecture ou + insertion ; une réponse tardive ne fait pas naviguer l'ancien utilisateur. +- Un modèle retiré ne peut plus être copié. Une copie déjà créée survit à la + suppression de sa source ; elle n'est pas réécrite lors d'une reprise. +- Une panne partielle du catalogue conserve la section disponible et propose + une nouvelle tentative, au lieu de présenter une fausse liste vide. + +## Contrat public et confidentialité + +`purama_ai.public_creator_models(p_id uuid, p_kind text)` retourne seulement : + +```text +id, name, description, emoji, color, category, +is_public, is_template, is_active +``` + +La sélection actif/public, le statut officiel, les bornes des textes et la limite +de 100 résultats sont imposés en SQL. Le client reconstruit aussi un DTO limité. +Le statut officiel exige `is_template = true AND user_id IS NULL`. + +L'aperçu public n'expose ni propriétaire, prompt, planification, historique ni +compteurs privés. En revanche, **publier un modèle autorise la copie de sa +configuration réutilisable, dont son prompt**, par un utilisateur authentifié. +Le prompt d'un modèle publié ne doit donc pas être présenté comme secret. + +`clone_public_creator_model(p_source_id, p_copy_id, p_expected_user_id)` : + +- dérive le propriétaire de `auth.uid()` ; l'identifiant attendu ne donne aucun + droit et sert à refuser une session ayant changé depuis le clic ; +- vérifie la disponibilité du modèle avant une nouvelle insertion ; +- résout les reprises et collisions par propriétaire, source et UUID de copie ; +- crée une copie privée, non officielle, sans calendrier, entrée planifiée, + démarrage KARTA ni historique repris. + +Les lectures directes des tables restent limitées au propriétaire. La migration +retire également les anciens privilèges excessifs, dont `TRUNCATE`, sur agents, +chats et runs. Elle répare les drapeaux officiels hérités attribués à des agents +possédés par des utilisateurs. + +La contrainte étrangère de `cloned_from` est retirée pour conserver une copie +après suppression de la source. Ce champ est une provenance fonctionnelle : +**ce n'est ni une attestation immuable ni une preuve d'attribution financière**. + +Le chat métier exige désormais la propriété de l'agent même si celui-ci est +public et filtre l'historique par utilisateur, agent et session. L'utilisation +d'un modèle d'un autre auteur passe par la création de sa copie privée. +La validation rend `agent_id` obligatoire au niveau du schéma objet ; l'ancien +appel à `required()` sur un champ optionnel provoquait une erreur serveur. +Le test exécute le vrai module de validation avec Zod `3.22.4`, identique à +l'import de la fonction Edge, via une dépendance de test dédiée. + +## Liens, accueil et mode hors ligne + +- Les liens sont construits à partir de l'origine et d'une route publique + explicitement autorisée. Les paramètres et fragments de la page courante ne + sont pas repris. Un code de parrainage est ajouté seulement après validation. +- WhatsApp, Telegram, Twitter/X, Facebook, LinkedIn et email reçoivent une URL + de partage. La livraison effective d'un message externe n'est pas testée. +- Le presse-papiers confirme uniquement une écriture réussie. En cas de refus, + un champ sélectionnable permet la copie manuelle. L'annulation du partage + natif n'est pas présentée comme une erreur ou un succès d'envoi. +- L'introduction est réservée à l'accueil sans paramètres ni fragment et peut + être passée immédiatement. Les préférences de réduction des animations sont + prises en compte. +- L'affirmation automatique est limitée à `/dashboard` sans paramètres ni + fragment, avec session chargée. Navigation, déconnexion ou changement de + compte démontent son overlay et son minuteur. +- Le service worker met en cache les ressources publiques de secours prévues. + Il ne met pas en cache le HTML privé authentifié. Le secours hors ligne + indique honnêtement la limitation réseau. +- Une notification ne déclenche aucune opération métier. Sa destination est + validée à réception et au clic ; seules des routes locales autorisées sont + ouvertes, sans paramètres ni fragment. + +## Vérification et limites + +Les résultats exécutés et leur environnement figurent dans +[`verification.json`](./verification.json). Les tests navigateur manipulent +l'application compilée et son vrai client Supabase avec une API locale simulée. +Ils ne prouvent pas une connexion à un service Supabase distant. + +Les tests SQL exécutent les migrations dans PGlite, avec de vrais rôles et droits +PostgreSQL, mais un contexte d'authentification de test. Ils ne remplacent pas +une recette du transport HTTP Supabase ni une concurrence entre plusieurs +connexions PostgreSQL natives. Les tests du chat exécutent le handler avec des +doubles des services externes ; aucun fournisseur IA n'est appelé. + +Commandes reproductibles, avec Node 22 et npm 10 : + +```sh +npm ci +npm run lint +npm run typecheck +npm run test:unit +npm run test:distribution:db +node --test tests/service-worker-distribution.test.mjs +npm run test:security +npm run test:repo-security +npm run test:release-config +node --test tests/mobile-oauth-pkce.test.mjs +npx playwright install chromium webkit +npm run test:distribution:e2e +``` + +`test:ci` ajoute les contrôles navigateur existants sur ordinateur et les parcours +de livraison, distribution et PWA sur les profils tablette et mobile. Ceux-ci +utilisent WebKit dans la configuration du dépôt ; la CI doit donc installer ce +moteur en plus de Chromium. Une émulation ne certifie pas un appareil physique. + +Playwright est verrouillé à `1.64.1` pour inclure le correctif de navigation +hors ligne WebKit : le même test échouait avec `1.59.1`/WebKit 26.4, puis passe +avec `1.64.1`/WebKit 27.2. Les assertions HTTP 200, réponse du service worker et +affichage du secours sont conservées. Voir le +[correctif officiel #42894](https://github.com/microsoft/playwright/pull/42894) +et la [régression documentée #42775](https://github.com/microsoft/playwright/issues/42775). + +## Admission et livraison + +La migration `20261110001000_creator_public_distribution.sql`, le frontend et le +correctif de `creator-agent-chat` doivent être qualifiés comme un même lot. +L'ancien catalogue lit directement les tables ; le nouveau utilise les RPC. +Un déploiement partiel peut donc rendre le catalogue indisponible. Aucun repli +vers une lecture publique de toutes les colonnes n'est prévu. + +Avant une mise en service : + +1. Intégrer le lot avec sa base `codex/security-integration` et vérifier le diff + final. Aucune fusion automatique dans `main` n'est effectuée par ce lot. +2. Appliquer la migration et publier la fonction Edge dans un environnement de + recette ; vérifier les rôles, le schéma RPC exposé et les anciennes policies + réellement présentes. Déployer le frontend correspondant. +3. Tester connexion Google et confirmation email réelles, avec l'origine finale + autorisée dans les paramètres de redirection. Vérifier également retrait du + modèle, perte de réponse et copie concurrente avec deux connexions réelles. +4. Admettre le module et ses adaptateurs dans le shell ONE selon ses contrats + existants. Ce dépôt ne prouve pas cette admission. +5. Vérifier le routage direct `/modeles/`, les règles de cache et le service + worker sur l'hébergement Hostinger/Cloudflare retenu, puis la recette finale. + +La correction du chat refuse désormais l'exécution directe d'un agent public +appartenant à autrui : tout consommateur externe de cet ancien comportement +doit créer une copie privée avant de l'utiliser. + +Un retour en arrière ne doit pas restaurer les anciens privilèges publics ou +les droits `TRUNCATE`. Préparer une version compatible du frontend et du backend +avant toute bascule de production. diff --git a/docs/distribution/verification.json b/docs/distribution/verification.json new file mode 100644 index 00000000..4759bdea --- /dev/null +++ b/docs/distribution/verification.json @@ -0,0 +1,203 @@ +{ + "schema_version": 1, + "verified_at_utc": "2026-11-10T03:18:28.368496+00:00", + "scope": "purama-ai distribution candidate; local qualification, not a production or ONE admission certificate", + "base_commit": "ca155cdc412d65b78146c3cccc8b44f62e0db5b5", + "branch": "codex/distribution-hardening-20261110", + "qualification": { + "local_candidate": "PASS", + "production_deployment": "NON TESTÉ", + "one_admission": "NON TESTÉ", + "live_providers": "NON TESTÉ" + }, + "environment": { + "os": "macOS 26.7", + "architecture": "arm64", + "node": "22.23.3", + "npm": "10.9.10", + "playwright": "1.64.1", + "desktop_browser": "Google Chrome 157.0.8103.39 (system executable)", + "tablet_mobile_browser": "Playwright WebKit 27.2 revision 2370 (emulated viewports)", + "pglite": "0.5.16", + "edge_validation_zod": "3.22.4 via dev-only alias; matches production Edge import" + }, + "checks": [ + { + "name": "Unit tests", + "status": "PASS", + "command": "npm run test:unit -- --maxWorkers=2", + "scope": "React lifecycles, auth continuation, public URLs and DTOs, client RPC contracts, existing helpers", + "tests": 333, + "files": 13 + }, + { + "name": "TypeScript", + "status": "PASS", + "command": "npm run typecheck", + "scope": "Full tsconfig.app.json" + }, + { + "name": "ESLint", + "status": "PASS", + "command": "npm run lint", + "scope": "Repository-wide plus final changed-test delta", + "errors": 0, + "warnings": 0 + }, + { + "name": "PostgreSQL model permissions", + "status": "PASS", + "command": "npm run test:distribution:db", + "scope": "Local controlled execution; see limitations", + "tests": 32, + "scenarios": 31, + "wrapper_tests": 1 + }, + { + "name": "Service worker behavior", + "status": "PASS", + "command": "node --test tests/service-worker-distribution.test.mjs", + "scope": "Local controlled execution; see limitations", + "tests": 25 + }, + { + "name": "Security and chat validation", + "status": "PASS", + "command": "npm run test:security", + "scope": "Local controlled execution; see limitations", + "tests": 40 + }, + { + "name": "Mobile OAuth contract", + "status": "PASS", + "command": "node --test tests/mobile-oauth-pkce.test.mjs", + "scope": "Local controlled execution; see limitations", + "tests": 3 + }, + { + "name": "Release configuration", + "status": "PASS", + "command": "npm run test:release-config", + "scope": "Local controlled execution; see limitations", + "tests": 4 + }, + { + "name": "Repository security policy", + "status": "PASS", + "command": "npm run test:repo-security", + "scope": "Static repository policy checks" + }, + { + "name": "E2E build", + "status": "PASS", + "command": "npm run build:e2e", + "scope": "Vite e2e mode; loopback API configuration" + }, + { + "name": "Production-mode build", + "status": "PASS", + "command": "npm run build", + "scope": "Vite production mode; artifact only, no deployment or live-service certification" + }, + { + "name": "Browser suite", + "status": "PASS", + "command": "npm run test:ci (equivalent test selection with local browser executable override)", + "scope": "Compiled application, 71 desktop cases and 21 cases each for tablet/mobile; auth/RPC APIs simulated", + "tests": 113, + "desktop": 71, + "tablet": 21, + "mobile": 21, + "retries": 0, + "skipped": 0, + "flaky": 0 + } + ], + "regression_evidence": { + "chat_real_handler_before_fix": { + "passed": 2, + "failed": 9, + "total": 11 + }, + "chat_real_handler_after_fix": { + "passed": 11, + "failed": 0, + "total": 11 + }, + "webkit_offline": { + "before": "Playwright 1.59.1 / WebKit 26.4: internal error during offline navigation", + "after": "Playwright 1.64.1 / WebKit 27.2: unchanged offline test passes; also passes in the complete suite", + "upstream_fix": "https://github.com/microsoft/playwright/pull/42894" + } + }, + "limitations": [ + "Browser sign-in/sign-up and Supabase RPC responses are isolated doubles, not real Google, email confirmation or a remote Supabase deployment.", + "SQL runs real PostgreSQL/WASM with synthetic users/roles and auth.uid context. Native PostgreSQL multi-connection concurrency and the Supabase HTTP layer are not qualified.", + "The chat executes the actual handler and actual validation module with exact-version Zod; rate limiting, auth/database transport and the AI provider are controlled doubles. Deno bootstrap and real model execution are not qualified.", + "Tablet/mobile are WebKit viewport emulations, not physical device testing. Desktop uses system Chrome rather than the CI-downloaded Chromium build.", + "Share URL construction is covered. Actual delivery through social networks/email/native sharing and remote push delivery are not qualified.", + "The offline page is public fallback content. Private app data is not promised offline.", + "Copy retry identifiers persist only in the mounted component, not across reloads/devices.", + "The migration, Edge chat function and frontend require coordinated staging and admission into ONE before production activation.", + "No production mutation, migration application, merge or live provider action has been performed for this candidate." + ], + "source_sha256": { + ".github/workflows/ci.yml": "d1225b5e9b956d1b67db50bd59f8f22f4550533ef09be7f836f37fe113c73e21", + "docs/distribution/README.md": "0d1d81f576c97ccc8b3371857952b3dead57740e149df40205a2cc5d1608569f", + "package-lock.json": "73adf8293653a93d1aecbce5868c27ac429d7b13ccb35302fc8e4a7910ed5bd7", + "package.json": "1b255180b5fff48a6918c213edfe32f2642de4403cfea976ee370fb7a521e319", + "public/offline.html": "d76c62c10bd145bc9e5b14f773f5d22b0fc3fd50345270f6d81fa10b9dbd4aba", + "public/sw.js": "432e34c236a257cab543c5ef0fef33dfc2663f103b97703606909c3e253dff7d", + "src/App.tsx": "62a2d2cd2a5e78898891bab442d448279daef6ee9eab6c5baee2f1d61bcf4da2", + "src/components/shared/CinematicIntro.test.tsx": "0904a090a7ff3010e11ab2f73a2d2fbf589bcd6603d331edda2f5595266a762b", + "src/components/shared/CinematicIntro.tsx": "07fdcb13e0088d278f9ce9f40744ef6532911938f3259c62a9967cd6811d95c0", + "src/components/shared/ShareButtons.test.tsx": "bd4013928fbf8af277d81a50b8d6de415d579a6baf7399c68975b39bc03eaeab", + "src/components/shared/ShareButtons.tsx": "3eda7378f767672775ab1751bf675b6d302a4b15c1b63185c6ce8d840c13c05a", + "src/components/shared/SpiritualLayer.test.tsx": "6410608eb4b036a915724a66f0d9c1a0981c611f52a527cebe65c1fe50f3708f", + "src/components/shared/SpiritualLayer.tsx": "73035b85df859f495449e0d3a9841ae27b44ad3aae0e357a4b8b5f5b1a90600e", + "src/hooks/useAuth.continuation.test.tsx": "5b6aa65f66723cd557d3142a3b765d1bd48afe62345ea250f13746c12bbdd671", + "src/hooks/useAuth.tsx": "26bf3a636062ad8f5f8beb7a6ff186dfa0c7a8faf5d68ae3b0e17dfe4acf7ee3", + "src/lib/auth-continuation.test.ts": "c61379b3b9c32051682858299e1e12a82b34b11172a562026e203c73d9ed67f5", + "src/lib/auth-continuation.ts": "9efe2cbe13e2544beff8ce1c66f464f195b196ecd4225bea4f70e86c63f638f5", + "src/lib/creator-agent-distribution.test.ts": "ce31df23536f6ddfbeb308ed6fc5cabd7b3fe5292d1f1d33522ffb8dc8611a8a", + "src/lib/creator-agent.ts": "4af90b3f08331c1de43e8d6094840a654576e4ef976dfa5c0a23eac992f4258d", + "src/lib/public-creator-model.test.ts": "267c722cd1a810f096939812e5df008693f814b32a047b43a18a6a5e647ed430", + "src/lib/public-creator-model.ts": "080fafa5210e36a21ab1400d624d6d7b18a788db6f06058f51ba34d55faa21ef", + "src/lib/public-share.test.ts": "171783899246b1e9a5d7e109a215a31f0537564489acdaceb92223ebdafe8612", + "src/lib/public-share.ts": "ab56e4102bf0d9c736ceaebd44274fa5d06f861d8e7fe1af9e4541695bc303e9", + "src/pages/CreatorAgent.tsx": "d7ffea2ca40ae08cbcda3c980b210c91da5dd0ce18e14abd4b3a3be7a6381750", + "src/pages/CreatorAgentTemplates.tsx": "becec9482e65505a326064eb6aa506d500f6ed1bd9793e5337e8989b14f266cc", + "src/pages/Login.tsx": "9b78db63675b6f27fcb6e4cabdaafdb223249cc1e52907ac918530ebbd55715b", + "src/pages/PublicCreatorModel.tsx": "9f7f94786e93c522e0b29d67565458234c61a7937aff19cb2332667f40c94bb9", + "src/pages/Signup.tsx": "f0ff2b49b39b2e8285513aa7a368721495187b6eaf373dd2d556eaad9d04671f", + "src/pages/auth-continuation.test.tsx": "e22f57bda4933d158dc53b03f86255bcf755b24022b4090588bf61611efe4ce4", + "supabase/functions/creator-agent-chat/index.ts": "aaa5f5dba589c749ebead5c279686da884df15c439d2994b3f0907ec38972d5c", + "supabase/migrations/20261110001000_creator_public_distribution.sql": "d81e1c867c89ee45ba647282465d0b9b5c7e4428d0ca1dc494f87c1454c630b1", + "tests/creator-chat-authorization.test.mjs": "75e1e58bf4a32a995ee6c921ad66dc0d22de20281b01e4ed3d47dfdc59aea89d", + "tests/creator-public-distribution.test.mjs": "bc141ea5a177a592181a397e88ea6b6c4e9a675da7ab313bea8653fce4e04271", + "tests/distribution.spec.ts": "51d29f937e97bcf2d925d7f65d586b0fbbaaefa21979b359c2905223d08f6378", + "tests/navigation.spec.ts": "b81bfbbc3913e2215cd6beed419eca20c4847f78b7df84c038db7c5934fe036c", + "tests/public-pages.spec.ts": "03612b23505817dc431f0a4ac31282b66e4ba8ee60faf9225af5fd6f6d25c12b", + "tests/pwa.spec.ts": "817ca7ee2b3a8914daf2d7c6f7713d5ca074fcae1ff60c76e7715f87fc608580", + "tests/release-gates.spec.ts": "920c7a897c9ec6e86a745df8d2cf2944fbcaff3468be2ce28caf83f57f8060a6", + "tests/service-worker-distribution.test.mjs": "8f65017dbc40078f38ece34b23dc363bf128610d86987a593f9a65eda6a6a920", + "vitest.config.ts": "19f6711169396561fe1cb6109fcbc069f3ae851b9ed51d0ee1f5e5b88620007b" + }, + "source_manifest_note": "40 changed files matched byte-for-byte between the review copy and tested worktree; this verification file is excluded from its own hash manifest.", + "retained_log_sha256": { + "unit-overlay-final.log": "304067a6d0dae19492ed7f832963e96a4e7662165c4df5a5c03f51f298404b8f", + "typecheck-overlay-final.log": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "lint-complete-final.log": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "lint-last-test-delta.log": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "database.log": "f9f3276c0113121470c6220de1032264d4c8790bebe10dc54986c345a24081b7", + "service-worker.log": "fd780a41fbccab0e066d73c4989a5091e204c96a5b258152aea20eec72692c2a", + "security-real-validator-final.log": "6aca2c53d33dcce988014d397537112741d4c0254b5ad93133e1fc8bd7a35be3", + "mobile-oauth-contract.log": "743391c181575e073a73d0ba395ca670b042f39a09274687f40d2991904a4db5", + "release-config-qualified.log": "1540b39e8d3434b6a4a829fda2f0c13c78b555f3e158e2a407cf7c9ed418c9d1", + "repository-policy-qualified.log": "93c69bcebb380a92822d251e786cd1a8163ba897d7ccbfdebd75f14716da7802", + "build-e2e-final.log": "a02e807325e2d3bad479666b08c3ab174852fb9c9520fb3e4332d3e898efe386", + "production-build.log": "3ee0cb69b4247f573579adf18fc986f80ec933ef4b9cf5abeda0520b8b3fdd47", + "browser-complete.log": "24b0afbdfbbd1a31d4c0972ec8583e0f7436223b287a0f509a44e178109a4170", + "chat-real-validator-before-fix.log": "edef5b5e7b7dba244d1cfac1833f982614085466a34abb68901dd79f34b85f83" + } +} diff --git a/package-lock.json b/package-lock.json index 753efe61..5d860619 100644 --- a/package-lock.json +++ b/package-lock.json @@ -71,8 +71,9 @@ "zod": "^3.25.76" }, "devDependencies": { + "@electric-sql/pglite": "0.5.16", "@eslint/js": "^9.32.0", - "@playwright/test": "^1.59.1", + "@playwright/test": "1.64.1", "@tailwindcss/typography": "^0.5.16", "@types/node": "^22.16.5", "@types/react": "^18.3.23", @@ -91,7 +92,8 @@ "typescript": "^5.8.3", "typescript-eslint": "^8.38.0", "vite": "^5.4.19", - "vitest": "^3.2.7" + "vitest": "^3.2.7", + "zod-edge-validation": "npm:zod@3.22.4" }, "engines": { "node": ">=22 <23", @@ -249,6 +251,13 @@ "node": ">=18" } }, + "node_modules/@electric-sql/pglite": { + "version": "0.5.16", + "resolved": "https://registry.npmjs.org/@electric-sql/pglite/-/pglite-0.5.16.tgz", + "integrity": "sha512-Nj8KcIsJL748W408U2N8q4+9IlONdpRIU8MJypIAAINMJ5nqKyqpX7Mgg/5XKkXiAib3AoZGR6hnJFlrlLBrcg==", + "dev": true, + "license": "Apache-2.0" + }, "node_modules/@esbuild/aix-ppc64": { "version": "0.21.5", "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.21.5.tgz", @@ -1060,19 +1069,19 @@ } }, "node_modules/@playwright/test": { - "version": "1.59.1", - "resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.59.1.tgz", - "integrity": "sha512-PG6q63nQg5c9rIi4/Z5lR5IVF7yU5MqmKaPOe0HSc0O2cX1fPi96sUQu5j7eo4gKCkB2AnNGoWt7y4/Xx3Kcqg==", + "version": "1.64.1", + "resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.64.1.tgz", + "integrity": "sha512-IaYGml/nSOiZWROfPtuIL7neuu9qDOZ3TNvNljUIrhDMxiGTgPjzj/g9p9RxpS2tSepPDRY+UwAaEeiKtUvIAg==", "dev": true, "license": "Apache-2.0", "dependencies": { - "playwright": "1.59.1" + "playwright": "1.64.1" }, "bin": { "playwright": "cli.js" }, "engines": { - "node": ">=18" + "node": ">=20" } }, "node_modules/@radix-ui/number": { @@ -7299,50 +7308,32 @@ } }, "node_modules/playwright": { - "version": "1.59.1", - "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.59.1.tgz", - "integrity": "sha512-C8oWjPR3F81yljW9o5OxcWzfh6avkVwDD2VYdwIGqTkl+OGFISgypqzfu7dOe4QNLL2aqcWBmI3PMtLIK233lw==", + "version": "1.64.1", + "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.64.1.tgz", + "integrity": "sha512-HCrVhHr5QQuwYoswEUGTb7gGp522yflbv/ST8nF4sFWGuLjQCt17Q/EubpGGSNKYn1tsTCPZxqHhHCfVURu7UA==", "dev": true, "license": "Apache-2.0", "dependencies": { - "playwright-core": "1.59.1" + "playwright-core": "1.64.1" }, "bin": { "playwright": "cli.js" }, "engines": { - "node": ">=18" - }, - "optionalDependencies": { - "fsevents": "2.3.2" + "node": ">=20" } }, "node_modules/playwright-core": { - "version": "1.59.1", - "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.59.1.tgz", - "integrity": "sha512-HBV/RJg81z5BiiZ9yPzIiClYV/QMsDCKUyogwH9p3MCP6IYjUFu/MActgYAvK0oWyV9NlwM3GLBjADyWgydVyg==", + "version": "1.64.1", + "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.64.1.tgz", + "integrity": "sha512-BC4s8y6SEVA6Q1rSxZTto8hI1KUI3xXlHGZgvGqP4IqPdI/a6FX9H29IDNz7vKo9l21b6LfYosScPL6M3xxyDQ==", "dev": true, "license": "Apache-2.0", "bin": { "playwright-core": "cli.js" }, "engines": { - "node": ">=18" - } - }, - "node_modules/playwright/node_modules/fsevents": { - "version": "2.3.2", - "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz", - "integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==", - "dev": true, - "hasInstallScript": true, - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + "node": ">=20" } }, "node_modules/postcss": { @@ -9328,6 +9319,17 @@ "url": "https://github.com/sponsors/colinhacks" } }, + "node_modules/zod-edge-validation": { + "name": "zod", + "version": "3.22.4", + "resolved": "https://registry.npmjs.org/zod/-/zod-3.22.4.tgz", + "integrity": "sha512-iC+8Io04lddc+mVqQ9AZ7OQ2MrUKGN+oIQyq1vemgt46jwCwLfhq7/pwnBnNXXXZb8VTVLKwp9EDkx+ryxIWmg==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/colinhacks" + } + }, "node_modules/zwitch": { "version": "2.0.4", "resolved": "https://registry.npmjs.org/zwitch/-/zwitch-2.0.4.tgz", diff --git a/package.json b/package.json index 4f2af730..43d7b9da 100644 --- a/package.json +++ b/package.json @@ -17,11 +17,13 @@ "lint": "eslint .", "preview": "vite preview", "test:unit": "vitest run --config vitest.config.ts", - "test:security": "node --experimental-strip-types --test tests/oauth-google-security.test.mjs tests/contact-submissions-security.test.mjs tests/cors-security.test.mjs tests/edge-auth-hardening.test.mjs supabase/functions/_shared/oauth-state.test.ts supabase/functions/_shared/social-callback-gate.test.ts supabase/functions/_shared/webhook-security.test.ts", + "test:distribution:db": "node --max-old-space-size=768 --max-semi-space-size=16 --wasm-num-compilation-tasks=1 --test tests/creator-public-distribution.test.mjs", + "test:distribution:e2e": "npm run build:e2e && playwright test tests/distribution.spec.ts tests/pwa.spec.ts --workers=2", + "test:security": "node --experimental-strip-types --test tests/oauth-google-security.test.mjs tests/contact-submissions-security.test.mjs tests/cors-security.test.mjs tests/edge-auth-hardening.test.mjs tests/creator-chat-authorization.test.mjs supabase/functions/_shared/oauth-state.test.ts supabase/functions/_shared/social-callback-gate.test.ts supabase/functions/_shared/webhook-security.test.ts", "test:repo-security": "node scripts/security/repository-security-check.mjs", "test:release-config": "node --test tests/release-config.test.mjs", "test:e2e": "npm run build && playwright test", - "test:ci": "npm run build:e2e && playwright test --project=desktop && playwright test tests/release-gates.spec.ts --project=tablet --project=mobile", + "test:ci": "npm run build:e2e && playwright test --project=desktop --workers=2 && playwright test tests/release-gates.spec.ts tests/distribution.spec.ts tests/pwa.spec.ts --project=tablet --project=mobile --workers=2", "test": "npm run test:e2e", "test:desktop": "npm run build && playwright test --project=desktop" }, @@ -89,8 +91,9 @@ "zod": "^3.25.76" }, "devDependencies": { + "@electric-sql/pglite": "0.5.16", "@eslint/js": "^9.32.0", - "@playwright/test": "^1.59.1", + "@playwright/test": "1.64.1", "@tailwindcss/typography": "^0.5.16", "@types/node": "^22.16.5", "@types/react": "^18.3.23", @@ -109,7 +112,8 @@ "typescript": "^5.8.3", "typescript-eslint": "^8.38.0", "vite": "^5.4.19", - "vitest": "^3.2.7" + "vitest": "^3.2.7", + "zod-edge-validation": "npm:zod@3.22.4" }, "overrides": { "form-data": "^4.0.4", diff --git a/public/offline.html b/public/offline.html index f663fbe5..5483557b 100644 --- a/public/offline.html +++ b/public/offline.html @@ -37,7 +37,7 @@
📡

Tu es hors ligne

-

Vérifie ta connexion. Tes agents continuent de tourner sur nos serveurs en arrière-plan — tu retrouveras tout dès que tu seras de nouveau en ligne.

+

La page n’a pas pu être chargée. Vérifie ta connexion, puis appuie sur « Réessayer ».

diff --git a/public/sw.js b/public/sw.js index b429f09e..c312433b 100644 --- a/public/sw.js +++ b/public/sw.js @@ -1,33 +1,146 @@ // Purama AI — Service Worker // Handles: install/activate, offline fallback, web push, notification clicks -const CACHE_NAME = 'purama-v1'; +const CACHE_PREFIX = 'purama-static-'; +const CACHE_NAME = CACHE_PREFIX + 'v2'; const OFFLINE_URL = '/offline.html'; -const PRECACHE = ['/', '/offline.html', '/manifest.json']; +// The previous worker cached "/" with credentials. Retire only that known +// legacy cache; other applications on this origin own their own caches. +const LEGACY_CACHE_NAME = 'purama-v1'; +const PRECACHE = [OFFLINE_URL, '/manifest.json']; +const NOTIFICATION_FALLBACK = '/dashboard'; +const NOTIFICATION_PAGES = new Set([ + '/notifications', + '/notification-settings', + '/my-agents', + '/mes-connexions', + '/fiscal', + '/influenceur/dashboard', + '/admin/dashboard', + '/admin/influenceurs', + '/admin/contracts', + '/ambassadeur/rejoindre', +]); + +// This standalone worker cannot import the application's TypeScript helper. +// Keep its same-origin boundary, then allow only review screens. Notification +// queries and fragments must never carry credentials or execution instructions. +function safeNotificationPath(value) { + if (typeof value !== 'string' || !value || value.length > 2048 || value !== value.trim()) { + return NOTIFICATION_FALLBACK; + } + if (value.startsWith('//') || /[\\\u0000-\u001f\u007f]/.test(value)) { + return NOTIFICATION_FALLBACK; + } + if (!value.startsWith('/') && !/^https?:\/\//i.test(value)) { + return NOTIFICATION_FALLBACK; + } + + try { + const parsed = new URL(value, self.location.origin); + if (parsed.origin !== self.location.origin || parsed.username || parsed.password) { + return NOTIFICATION_FALLBACK; + } + const path = parsed.pathname.replace(/\/$/, ''); + if ( + NOTIFICATION_PAGES.has(path) || + /^\/dashboard(?:\/[a-zA-Z0-9_-]+)*$/.test(path) || + /^\/agent\/[a-zA-Z0-9_-]+$/.test(path) + ) { + return path; + } + } catch { + // Malformed, encoded or non-application destinations use the review hub. + } + return NOTIFICATION_FALLBACK; +} + +function isSameOriginClient(client) { + try { + const parsed = new URL(client.url); + return parsed.origin === self.location.origin && !parsed.username && !parsed.password; + } catch { + return false; + } +} + +async function openNotificationPage(url) { + let clientsList = []; + try { + clientsList = await self.clients.matchAll({ type: 'window', includeUncontrolled: true }); + } catch { + // Window enumeration can fail; opening the validated URL is still safe. + } + + for (const client of clientsList) { + if (!isSameOriginClient(client) || typeof client.focus !== 'function') continue; + try { + if (client.url === url) return await client.focus(); + if (typeof client.navigate !== 'function') continue; + const navigated = await client.navigate(url); + if (isSameOriginClient(navigated) && typeof navigated.focus === 'function') { + return await navigated.focus(); + } + } catch { + // A closed window or rejected focus must not prevent another safe attempt. + } + } + + try { + return await self.clients.openWindow(url); + } catch { + // Browser activation policies may prevent opening a window. Never retry + // with an unvalidated payload or execute a notification action instead. + console.warn('[sw] Unable to open the notification review screen'); + return null; + } +} self.addEventListener('install', (event) => { event.waitUntil( - caches.open(CACHE_NAME).then((cache) => cache.addAll(PRECACHE).catch(() => {})) + (async () => { + const cache = await caches.open(CACHE_NAME); + await cache.addAll(PRECACHE.map((path) => new Request(new URL(path, self.location.origin), { + cache: 'reload', + credentials: 'omit', + redirect: 'error', + }))); + // A failed/offline installation must reject and leave the previous worker + // in place, instead of activating without a usable offline page. + await self.skipWaiting(); + })() ); - self.skipWaiting(); }); self.addEventListener('activate', (event) => { event.waitUntil( - caches.keys().then((keys) => - Promise.all(keys.filter((k) => k !== CACHE_NAME).map((k) => caches.delete(k))) - ) + (async () => { + const keys = await caches.keys(); + await Promise.all(keys + .filter((key) => key === LEGACY_CACHE_NAME || (key.startsWith(CACHE_PREFIX) && key !== CACHE_NAME)) + .map((key) => caches.delete(key))); + await self.clients.claim(); + })() ); - self.clients.claim(); }); // Network-first for navigations, with offline fallback self.addEventListener('fetch', (event) => { const req = event.request; - if (req.mode === 'navigate') { - event.respondWith( - fetch(req).catch(() => caches.match(OFFLINE_URL).then((r) => r || new Response('Hors ligne', { status: 503 }))) - ); - } + if (req.method !== 'GET' || req.mode !== 'navigate' || new URL(req.url).origin !== self.location.origin) return; + event.respondWith( + fetch(req).catch(async () => { + try { + const offline = await caches.match(OFFLINE_URL, { cacheName: CACHE_NAME }); + if (offline) return offline; + } catch { + // Storage can be unavailable or evicted, even after a successful install. + } + return new Response('Hors ligne — reconnecte-toi puis réessaie.', { + status: 503, + headers: { 'Content-Type': 'text/plain; charset=utf-8', 'Cache-Control': 'no-store' }, + }); + }) + ); }); // ============================================================= @@ -40,6 +153,7 @@ self.addEventListener('push', (event) => { } catch { data = { title: 'Purama', body: event.data ? event.data.text() : '' }; } + if (!data || typeof data !== 'object' || Array.isArray(data)) data = {}; const title = data.title || 'Purama AI'; const options = { @@ -51,7 +165,7 @@ self.addEventListener('push', (event) => { renotify: true, requireInteraction: data.priority === 'urgent' || data.priority === 'high', data: { - url: data.action_url || '/dashboard', + url: safeNotificationPath(data.action_url), action_type: data.action_type, }, actions: [], @@ -74,19 +188,9 @@ self.addEventListener('push', (event) => { self.addEventListener('notificationclick', (event) => { event.notification.close(); const data = event.notification.data || {}; - const url = data.url || '/dashboard'; + const url = new URL(safeNotificationPath(data.url), self.location.origin).href; // Every click opens the authenticated application. Sensitive actions are // deliberately never executed directly from notification payload data. - event.waitUntil( - self.clients.matchAll({ type: 'window', includeUncontrolled: true }).then((clientsList) => { - for (const client of clientsList) { - if ('focus' in client) { - client.navigate(url); - return client.focus(); - } - } - return self.clients.openWindow(url); - }) - ); + event.waitUntil(openNotificationPage(url)); }); diff --git a/src/App.tsx b/src/App.tsx index 812c541c..e0de804a 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -79,6 +79,7 @@ const CreatorAgentPage = lazy(() => import('@/pages/CreatorAgent')); const CreatorAgentNew = lazy(() => import('@/pages/CreatorAgentNew')); const CreatorAgentDetail = lazy(() => import('@/pages/CreatorAgentDetail')); const CreatorAgentTemplates = lazy(() => import('@/pages/CreatorAgentTemplates')); +const PublicCreatorModel = lazy(() => import('@/pages/PublicCreatorModel')); const CreatorAgentRuns = lazy(() => import('@/pages/CreatorAgentRuns')); const Wallet = lazy(() => import('@/pages/Wallet')); const Boutique = lazy(() => import('@/pages/Boutique')); @@ -157,6 +158,7 @@ export default function App() { } /> } /> } /> + } /> } /> } /> diff --git a/src/components/shared/CinematicIntro.test.tsx b/src/components/shared/CinematicIntro.test.tsx new file mode 100644 index 00000000..8942a8d0 --- /dev/null +++ b/src/components/shared/CinematicIntro.test.tsx @@ -0,0 +1,281 @@ +import { act, createElement, StrictMode, type HTMLAttributes, type PropsWithChildren } from 'react'; +import { createRoot, type Root } from 'react-dom/client'; +import { MemoryRouter, useNavigate, type NavigateFunction } from 'react-router-dom'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { CinematicIntro } from './CinematicIntro'; + +// Keep real React/router behavior; only decorative motion is replaced. +// Timer assertions below inspect the introduction's scheduled handles because +// React and the DOM environment may also schedule unrelated housekeeping work. +vi.mock('framer-motion', async () => { + const React = await import('react'); + type MotionProps = HTMLAttributes & { + initial?: unknown; animate?: unknown; exit?: unknown; transition?: unknown; + }; + function element(tag: 'div' | 'h1' | 'p') { + return React.forwardRef((props, ref) => { + const attributes = { ...props }; + delete attributes.initial; + delete attributes.animate; + delete attributes.exit; + delete attributes.transition; + return React.createElement(tag, { ...attributes, ref }); + }); + } + return { + motion: { div: element('div'), h1: element('h1'), p: element('p') }, + AnimatePresence: ({ children }: PropsWithChildren) => children, + }; +}); + +const SEEN_KEY = 'purama_ai_intro_seen'; +const INTRO_DELAYS = [800, 2000, 3500]; +const mediaDescriptor = Object.getOwnPropertyDescriptor(window, 'matchMedia'); +let host: HTMLDivElement; +let previousControl: HTMLButtonElement; +let root: Root | null; +let navigate: NavigateFunction; +let reducedMotion: boolean; +let listeners: Set<(event: MediaQueryListEvent) => void>; +let timerSpies: ReturnType; + +function createTimerSpies() { + return { + schedule: vi.spyOn(globalThis, 'setTimeout'), + cancel: vi.spyOn(globalThis, 'clearTimeout'), + }; +} + +function scheduledIntroTimers() { + return timerSpies.schedule.mock.calls.flatMap(([, delay], index) => { + const result = timerSpies.schedule.mock.results[index]; + return delay !== undefined && INTRO_DELAYS.includes(delay) && result.type === 'return' + ? [{ delay, handle: result.value }] + : []; + }); +} + +function uncancelledIntroDelays() { + const cancelled = new Set(timerSpies.cancel.mock.calls.map(([handle]) => handle)); + return scheduledIntroTimers() + .filter(({ handle }) => !cancelled.has(handle)) + .map(({ delay }) => delay); +} + +function expectIntroTimersCancelled() { + const timers = scheduledIntroTimers(); + expect(timers.length).toBeGreaterThanOrEqual(INTRO_DELAYS.length); + for (const { handle } of timers) expect(timerSpies.cancel).toHaveBeenCalledWith(handle); +} + +function Harness() { + navigate = useNavigate(); + return createElement(CinematicIntro); +} + +async function render(path = '/', strict = false) { + const app = createElement(MemoryRouter, { initialEntries: [path] }, createElement(Harness)); + await act(async () => root?.render(strict ? createElement(StrictMode, {}, app) : app)); +} + +function skipButton(): HTMLButtonElement { + const button = host.querySelector('button'); + if (!button) throw new Error('No keyboard-accessible skip button'); + return button; +} + +beforeEach(() => { + vi.useFakeTimers(); + timerSpies = createTimerSpies(); + vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true); + window.localStorage.clear(); + reducedMotion = false; + listeners = new Set(); + const media = { + get matches() { return reducedMotion; }, + media: '(prefers-reduced-motion: reduce)', + onchange: null, + addEventListener: vi.fn((_type: string, listener: (event: MediaQueryListEvent) => void) => listeners.add(listener)), + removeEventListener: vi.fn((_type: string, listener: (event: MediaQueryListEvent) => void) => listeners.delete(listener)), + addListener: vi.fn((listener: (event: MediaQueryListEvent) => void) => listeners.add(listener)), + removeListener: vi.fn((listener: (event: MediaQueryListEvent) => void) => listeners.delete(listener)), + dispatchEvent: vi.fn(), + }; + Object.defineProperty(window, 'matchMedia', { + configurable: true, + value: vi.fn(() => media as unknown as MediaQueryList), + }); + previousControl = document.createElement('button'); + previousControl.textContent = 'Accueil'; + document.body.append(previousControl); + previousControl.focus(); + host = document.createElement('div'); + document.body.append(host); + root = createRoot(host); +}); + +afterEach(async () => { + await act(async () => root?.unmount()); + root = null; + host.remove(); + previousControl.remove(); + vi.restoreAllMocks(); + window.localStorage.clear(); + if (mediaDescriptor) Object.defineProperty(window, 'matchMedia', mediaDescriptor); + else Reflect.deleteProperty(window, 'matchMedia'); + vi.clearAllTimers(); + vi.useRealTimers(); + vi.unstubAllGlobals(); +}); + +describe('CinematicIntro', () => { + it.each([ + '/modeles/a6211822-fc3c-4c77-854a-3bc79dd4405d', + '/login', '/signup', '/oauth/callback?code=private', '/dashboard', '/forge', + '/?code=private', '/#creation', + ])('laisse immédiatement accessible la destination %s', async (path) => { + const get = vi.spyOn(Storage.prototype, 'getItem'); + await render(path); + expect(host.childElementCount).toBe(0); + expect(scheduledIntroTimers()).toEqual([]); + expect(get).not.toHaveBeenCalledWith(SEEN_KEY); + }); + + it('garde une introduction sur le premier accueil avec un bouton immédiatement utilisable', async () => { + await render(); + const button = skipButton(); + expect(button.type).toBe('button'); + expect(button.textContent).toMatch(/passer.*introduction/i); + expect(document.activeElement).toBe(button); + expect(host.querySelector('[role="dialog"]')?.getAttribute('aria-modal')).toBe('true'); + expect(uncancelledIntroDelays()).toEqual(INTRO_DELAYS); + }); + + it('respecte la préférence de mouvement réduit dès la première visite', async () => { + reducedMotion = true; + await render(); + expect(host.childElementCount).toBe(0); + expect(scheduledIntroTimers()).toEqual([]); + }); + + it('ferme immédiatement la séquence si le mouvement réduit est activé', async () => { + await render(); + expect(listeners.size).toBe(1); + reducedMotion = true; + await act(async () => { + for (const listener of [...listeners]) listener({ matches: true } as MediaQueryListEvent); + }); + expect(host.childElementCount).toBe(0); + expectIntroTimersCancelled(); + expect(listeners.size).toBe(0); + }); + + it('privilégie l’accès direct si la lecture du stockage est refusée', async () => { + vi.spyOn(Storage.prototype, 'getItem').mockImplementation(() => { throw new DOMException('Denied', 'SecurityError'); }); + await render(); + expect(host.childElementCount).toBe(0); + expect(scheduledIntroTimers()).toEqual([]); + }); + + it('ferme sans erreur si la mémorisation de la préférence est refusée', async () => { + vi.spyOn(Storage.prototype, 'setItem').mockImplementation(() => { throw new DOMException('Denied', 'SecurityError'); }); + await render(); + await act(async () => skipButton().click()); + expect(host.childElementCount).toBe(0); + expectIntroTimersCancelled(); + await act(async () => navigate('/login')); + await act(async () => navigate('/')); + expect(host.childElementCount).toBe(0); + }); + + it('ne rejoue pas une introduction déjà mémorisée', async () => { + window.localStorage.setItem(SEEN_KEY, '1'); + await render(); + expect(host.childElementCount).toBe(0); + expect(scheduledIntroTimers()).toEqual([]); + }); + + it('permet de passer au clavier et restitue le focus', async () => { + await render(); + const event = new KeyboardEvent('keydown', { key: 'Escape', bubbles: true, cancelable: true }); + await act(async () => { skipButton().dispatchEvent(event); }); + expect(event.defaultPrevented).toBe(true); + expect(host.childElementCount).toBe(0); + expect(document.activeElement).toBe(previousControl); + expect(window.localStorage.getItem(SEEN_KEY)).toBe('1'); + }); + + it('maintient le focus sur le bouton pendant la courte fenêtre modale', async () => { + await render(); + const button = skipButton(); + const event = new KeyboardEvent('keydown', { key: 'Tab', shiftKey: true, bubbles: true, cancelable: true }); + await act(async () => { button.dispatchEvent(event); }); + expect(event.defaultPrevented).toBe(true); + expect(document.activeElement).toBe(button); + }); + + it('annule les transitions dès que l’utilisateur passe la séquence', async () => { + const remember = vi.spyOn(Storage.prototype, 'setItem'); + await render(); + await act(async () => skipButton().click()); + expectIntroTimersCancelled(); + expect(listeners.size).toBe(0); + expect(remember).toHaveBeenCalledTimes(1); + await act(async () => vi.advanceTimersByTime(5000)); + expect(host.childElementCount).toBe(0); + expect(remember).toHaveBeenCalledTimes(1); + }); + + it('conserve les étapes visuelles puis ferme proprement après 3,5 secondes', async () => { + await render(); + await act(async () => vi.advanceTimersByTime(800)); + expect(host.querySelector('h1')?.textContent).toContain('PURAMA'); + await act(async () => vi.advanceTimersByTime(1200)); + expect(host.textContent).toContain('Tes agents IA autonomes'); + await act(async () => vi.advanceTimersByTime(1500)); + expect(host.childElementCount).toBe(0); + expectIntroTimersCancelled(); + expect(listeners.size).toBe(0); + expect(window.localStorage.getItem(SEEN_KEY)).toBe('1'); + }); + + it('retire l’écran et tous ses minuteurs lors d’une navigation', async () => { + await render(); + await act(async () => navigate('/modeles/a6211822-fc3c-4c77-854a-3bc79dd4405d')); + expect(host.childElementCount).toBe(0); + expectIntroTimersCancelled(); + expect(listeners.size).toBe(0); + await act(async () => vi.advanceTimersByTime(5000)); + await act(async () => navigate('/')); + expect(host.childElementCount).toBe(0); + }); + + it('retire les minuteurs et l’écoute de préférence au démontage', async () => { + const remember = vi.spyOn(Storage.prototype, 'setItem'); + await render(); + expect(uncancelledIntroDelays()).toEqual(INTRO_DELAYS); + await act(async () => { root?.unmount(); root = null; }); + expectIntroTimersCancelled(); + expect(listeners.size).toBe(0); + await act(async () => vi.advanceTimersByTime(5000)); + expect(host.childElementCount).toBe(0); + expect(remember).not.toHaveBeenCalled(); + }); + + it('reste utilisable sans API de préférence disponible', async () => { + Object.defineProperty(window, 'matchMedia', { configurable: true, value: undefined }); + await render(); + expect(host.childElementCount).toBe(0); + expect(scheduledIntroTimers()).toEqual([]); + }); + + it('supporte la répétition des effets de React StrictMode', async () => { + await render('/', true); + expect(skipButton()).toBeDefined(); + expect(uncancelledIntroDelays()).toEqual(INTRO_DELAYS); + expect(listeners.size).toBe(1); + await act(async () => skipButton().click()); + expectIntroTimersCancelled(); + expect(listeners.size).toBe(0); + }); +}); diff --git a/src/components/shared/CinematicIntro.tsx b/src/components/shared/CinematicIntro.tsx index 8b71388b..542a07a8 100644 --- a/src/components/shared/CinematicIntro.tsx +++ b/src/components/shared/CinematicIntro.tsx @@ -1,40 +1,135 @@ -import { useState, useEffect } from 'react'; +import { useState, useEffect, useRef } from 'react'; import { motion, AnimatePresence } from 'framer-motion'; import { Bot } from 'lucide-react'; +import { useLocation } from 'react-router-dom'; + +const INTRO_SEEN_KEY = 'purama_ai_intro_seen'; + +function rememberIntroSeen() { + try { + window.localStorage.setItem(INTRO_SEEN_KEY, '1'); + } catch { + // A decorative introduction must not require writable browser storage. + } +} export function CinematicIntro() { - const [show, setShow] = useState(false); + const location = useLocation(); + // Direct links and authentication callbacks must reach their destination. + const eligible = location.pathname === '/' && !location.search && !location.hash; + const [activeVisit, setActiveVisit] = useState(null); const [phase, setPhase] = useState(0); + const attemptedVisit = useRef(null); + const completed = useRef(false); + const dismiss = useRef<(() => void) | null>(null); + const skipControl = useRef(null); useEffect(() => { - const seen = localStorage.getItem('purama_ai_intro_seen'); - if (!seen) { - setShow(true); - // Phase transitions - const t1 = setTimeout(() => setPhase(1), 800); - const t2 = setTimeout(() => setPhase(2), 2000); - const t3 = setTimeout(() => { - setShow(false); - localStorage.setItem('purama_ai_intro_seen', '1'); - }, 3500); - return () => { clearTimeout(t1); clearTimeout(t2); clearTimeout(t3); }; + setActiveVisit(null); + if (!completed.current && attemptedVisit.current !== null && attemptedVisit.current !== location.key) { + completed.current = true; + rememberIntroSeen(); + } + if (!eligible || completed.current) return; + + let preference: MediaQueryList; + try { + if (window.localStorage.getItem(INTRO_SEEN_KEY)) { + completed.current = true; + return; + } + if (typeof window.matchMedia !== 'function') return; + preference = window.matchMedia('(prefers-reduced-motion: reduce)'); + if (preference.matches) return; + } catch { + // Unknown preferences or unavailable storage favor immediate access. + return; + } + + let active = true; + const timers: ReturnType[] = []; + let removePreferenceListener = () => {}; + const dispose = () => { + active = false; + for (const timer of timers) clearTimeout(timer); + try { removePreferenceListener(); } catch { /* Browser listener already unavailable. */ } + if (dismiss.current === finish) dismiss.current = null; + }; + const finish = () => { + if (!active) return; + dispose(); + completed.current = true; + rememberIntroSeen(); + setActiveVisit(null); + }; + const preferenceChanged = (event: MediaQueryListEvent) => { + if (event.matches) finish(); + }; + + try { + if (typeof preference.addEventListener === 'function') { + removePreferenceListener = () => preference.removeEventListener('change', preferenceChanged); + preference.addEventListener('change', preferenceChanged); + } else if (typeof preference.addListener === 'function') { + removePreferenceListener = () => preference.removeListener(preferenceChanged); + preference.addListener(preferenceChanged); + } else { + return; + } + } catch { + dispose(); + return; } - }, []); + + attemptedVisit.current = location.key; + setPhase(0); + setActiveVisit(location.key); + dismiss.current = finish; + timers.push( + setTimeout(() => { if (active) setPhase(1); }, 800), + setTimeout(() => { if (active) setPhase(2); }, 2000), + setTimeout(finish, 3500), + ); + return dispose; + }, [eligible, location.key]); + + const visible = eligible && activeVisit === location.key; + useEffect(() => { + if (!visible) return; + const previous = document.activeElement instanceof HTMLElement ? document.activeElement : null; + const control = skipControl.current; + control?.focus(); + return () => { + if (previous?.isConnected && (document.activeElement === control || document.activeElement === document.body)) { + previous.focus({ preventScroll: true }); + } + }; + }, [visible]); const skip = () => { - setShow(false); - localStorage.setItem('purama_ai_intro_seen', '1'); + dismiss.current?.(); }; - if (!show) return null; + if (!visible) return null; return ( { + if (event.key === 'Escape') { + event.preventDefault(); + skip(); + } else if (event.key === 'Tab') { + event.preventDefault(); + skipControl.current?.focus(); + } + }} > {/* Radial glow */}
@@ -58,7 +153,7 @@ export function CinematicIntro() { className="mb-8" >
- +
@@ -94,15 +189,14 @@ export function CinematicIntro() {
- {/* Skip hint */} - - Appuie pour passer - + Passer l’introduction + {/* Aurora glow */} ({ toastSuccess: vi.fn() })); +vi.mock('sonner', () => ({ toast: { success: toastSuccess } })); +// A signed-in account must never become an implicitly invented referral code. +vi.mock('@/hooks/useAuth', () => ({ + useAuth: () => ({ user: { id: 'd62d6630-95a4-4583-9244-c814e8156779' } }), +})); + +const clipboardDescriptor = Object.getOwnPropertyDescriptor(navigator, 'clipboard'); +const shareDescriptor = Object.getOwnPropertyDescriptor(navigator, 'share'); +let host: HTMLDivElement; +let root: Root | null; +let writeText: ReturnType; +let share: ReturnType; + +function deferred() { + let resolve!: () => void; + let reject!: (reason: unknown) => void; + const promise = new Promise((yes, no) => { resolve = yes; reject = no; }); + return { promise, resolve, reject }; +} + +async function render(props: ComponentProps = {}) { + await act(async () => root?.render(createElement(ShareButtons, props))); +} + +function button(label: string): HTMLButtonElement { + const found = [...host.querySelectorAll('button')].find((element) => + element.getAttribute('aria-label') === label || element.textContent?.trim() === label, + ); + if (!found) throw new Error('Button not found: ' + label); + return found; +} + +function linkedinUrl() { + const link = [...host.querySelectorAll('a')].find((element) => + element.textContent?.includes('LinkedIn'), + ); + if (!link) throw new Error('LinkedIn link not found'); + return new URL(link.href).searchParams.get('url'); +} + +async function click(element: HTMLElement) { + await act(async () => element.click()); +} + +beforeEach(() => { + vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true); + toastSuccess.mockReset(); + writeText = vi.fn().mockResolvedValue(undefined); + share = vi.fn().mockResolvedValue(undefined); + Object.defineProperty(navigator, 'clipboard', { configurable: true, value: { writeText } }); + Object.defineProperty(navigator, 'share', { configurable: true, value: share }); + window.history.replaceState(null, '', '/'); + host = document.createElement('div'); + document.body.append(host); + root = createRoot(host); +}); + +afterEach(async () => { + await act(async () => root?.unmount()); + root = null; + host.remove(); + if (clipboardDescriptor) Object.defineProperty(navigator, 'clipboard', clipboardDescriptor); + else Reflect.deleteProperty(navigator, 'clipboard'); + if (shareDescriptor) Object.defineProperty(navigator, 'share', shareDescriptor); + else Reflect.deleteProperty(navigator, 'share'); + window.history.replaceState(null, '', '/'); + vi.clearAllTimers(); + vi.useRealTimers(); + vi.unstubAllGlobals(); +}); + +describe('ShareButtons', () => { + it('partage l’accueil public sans identifiant ni données de la page courante', async () => { + window.history.replaceState(null, '', '/dashboard?access_token=private&ref=untrusted#private'); + await render(); + expect(linkedinUrl()).toBe(window.location.origin + '/'); + expect(host.innerHTML).not.toContain('d62d6630'); + expect(host.innerHTML).not.toContain('access_token'); + expect(host.innerHTML).not.toContain('untrusted'); + }); + + it('partage la destination explicite et le seul code de recommandation fourni', async () => { + await render({ path: '/forge', referralCode: 'partenaire_42' }); + const expected = window.location.origin + '/forge?ref=partenaire_42'; + expect(linkedinUrl()).toBe(expected); + await click(button('Partager')); + expect(share).toHaveBeenCalledWith(expect.objectContaining({ url: expected })); + expect(writeText).not.toHaveBeenCalled(); + }); + + it('attend la confirmation du presse-papiers avant de signaler une copie', async () => { + const pending = deferred(); + writeText.mockReturnValue(pending.promise); + await render(); + await click(button('Copier le lien')); + try { + expect(toastSuccess).not.toHaveBeenCalled(); + expect(host.textContent).not.toContain('Copié !'); + expect(button('Copier le lien').disabled).toBe(true); + } finally { + await act(async () => pending.resolve()); + } + expect(toastSuccess).toHaveBeenCalledOnce(); + expect(host.textContent).toContain('Copié !'); + expect(writeText).toHaveBeenCalledWith(window.location.origin + '/'); + }); + + it('propose un lien sélectionnable si la copie est refusée, sans faux succès', async () => { + writeText.mockRejectedValue(new DOMException('Denied', 'NotAllowedError')); + await render({ path: '/ecosystem' }); + await click(button('Copier le lien')); + const input = host.querySelector('input'); + expect(input?.value).toBe(window.location.origin + '/ecosystem'); + expect(input?.readOnly).toBe(true); + expect(input?.selectionStart).toBe(0); + expect(input?.selectionEnd).toBe(input?.value.length); + expect(toastSuccess).not.toHaveBeenCalled(); + expect(host.textContent).not.toContain('Copié !'); + expect(host.querySelector('[role="status"]')?.textContent).toMatch(/copie.*indisponible/i); + expect(button('Copier le lien').disabled).toBe(false); + }); + + it('propose la même solution lorsque le presse-papiers est absent', async () => { + Object.defineProperty(navigator, 'clipboard', { configurable: true, value: undefined }); + await render({ compact: true }); + await click(button('Copier le lien')); + expect(host.querySelector('input')?.value).toBe(window.location.origin + '/'); + expect(toastSuccess).not.toHaveBeenCalled(); + }); + + it('traite une annulation du partage comme une action neutre', async () => { + share.mockRejectedValue(new DOMException('Cancelled', 'AbortError')); + await render(); + await click(button('Partager')); + expect(writeText).not.toHaveBeenCalled(); + expect(toastSuccess).not.toHaveBeenCalled(); + expect(host.querySelector('input')).toBeNull(); + expect(host.querySelector('[role="status"]')?.textContent).toBe(''); + expect(button('Partager').disabled).toBe(false); + }); + + it('propose le lien après un vrai échec du partage sans écrire le presse-papiers', async () => { + share.mockRejectedValue(new DOMException('Not permitted', 'NotAllowedError')); + await render({ path: '/forge' }); + await click(button('Partager')); + expect(host.querySelector('input')?.value).toBe(window.location.origin + '/forge'); + expect(host.querySelector('[role="status"]')?.textContent).toMatch(/partage.*indisponible/i); + expect(writeText).not.toHaveBeenCalled(); + expect(toastSuccess).not.toHaveBeenCalled(); + }); + + it('copie le lien quand le navigateur ne fournit pas le partage natif', async () => { + Object.defineProperty(navigator, 'share', { configurable: true, value: undefined }); + await render({ path: '/parrainage' }); + await click(button('Partager')); + expect(writeText).toHaveBeenCalledWith(window.location.origin + '/parrainage'); + expect(toastSuccess).toHaveBeenCalledOnce(); + }); + + it('bloque immédiatement deux clics de copie même avant un nouveau rendu', async () => { + const pending = deferred(); + writeText.mockReturnValue(pending.promise); + await render(); + const copy = button('Copier le lien'); + await act(async () => { copy.click(); copy.click(); }); + expect(writeText).toHaveBeenCalledTimes(1); + await act(async () => pending.resolve()); + }); + + it('bloque les actions concurrentes pendant un partage natif', async () => { + const pending = deferred(); + share.mockReturnValue(pending.promise); + await render(); + const native = button('Partager'); + const copy = button('Copier le lien'); + await act(async () => { native.click(); native.click(); copy.click(); }); + expect(share).toHaveBeenCalledTimes(1); + expect(writeText).not.toHaveBeenCalled(); + await act(async () => pending.resolve()); + expect(button('Partager').disabled).toBe(false); + }); + + it('ne confirme pas une copie terminée après démontage', async () => { + const pending = deferred(); + writeText.mockReturnValue(pending.promise); + await render(); + await click(button('Copier le lien')); + await act(async () => { root?.unmount(); root = null; }); + await act(async () => pending.resolve()); + expect(toastSuccess).not.toHaveBeenCalled(); + }); + + it('ne transporte pas l’état ou la confirmation d’une ancienne destination', async () => { + const pending = deferred(); + writeText.mockReturnValueOnce(pending.promise); + await render({ path: '/forge' }); + await click(button('Copier le lien')); + await render({ path: '/ecosystem' }); + expect(button('Copier le lien').disabled).toBe(false); + await act(async () => pending.resolve()); + expect(toastSuccess).not.toHaveBeenCalled(); + expect(host.textContent).not.toContain('Copié !'); + await click(button('Copier le lien')); + expect(writeText).toHaveBeenLastCalledWith(window.location.origin + '/ecosystem'); + }); + + it('nettoie le minuteur de confirmation au démontage', async () => { + vi.useFakeTimers(); + await render(); + await click(button('Copier le lien')); + expect(vi.getTimerCount()).toBe(1); + await act(async () => { root?.unmount(); root = null; }); + expect(vi.getTimerCount()).toBe(0); + }); + + it('réinitialise le message de copie après son délai', async () => { + vi.useFakeTimers(); + await render(); + await click(button('Copier le lien')); + await act(async () => vi.advanceTimersByTime(2000)); + expect(host.textContent).not.toContain('Copié !'); + expect(host.querySelector('[role="status"]')?.textContent).toBe(''); + }); + + it.each([ + '/dashboard', + '/forge?access_token=secret', + '/forge#secret', + 'https://evil.example/forge', + '//evil.example/forge', + '', + ])('désactive un chemin interdit au lieu de partager autre chose : %s', async (path) => { + await render({ path }); + expect(host.textContent).toMatch(/partage indisponible/i); + expect(host.querySelectorAll('a')).toHaveLength(0); + for (const control of host.querySelectorAll('button')) expect(control.disabled).toBe(true); + expect(writeText).not.toHaveBeenCalled(); + expect(share).not.toHaveBeenCalled(); + }); + + it('refuse un code de recommandation mal formé sans le remplacer', async () => { + await render({ path: '/forge', referralCode: 'valid&token=secret' }); + expect(host.textContent).toMatch(/partage indisponible/i); + expect(host.querySelectorAll('a')).toHaveLength(0); + expect(host.innerHTML).not.toContain('token=secret'); + }); + + it('conserve six liens nommés sans bouton imbriqué dans une ancre', async () => { + await render(); + expect(host.querySelectorAll('a')).toHaveLength(6); + expect(host.querySelector('a button')).toBeNull(); + for (const link of host.querySelectorAll('a')) { + expect(link.textContent?.trim()).not.toBe(''); + expect(link.rel).toContain('noopener'); + expect(link.rel).toContain('noreferrer'); + } + }); + + it('gère les emojis et un fragment Unicode incomplet sans faire tomber la page', async () => { + await render({ title: 'Création 🕊️\ud800', text: 'Exemple 🕊️\ud800' }); + const link = [...host.querySelectorAll('a')].find((element) => element.textContent?.includes('WhatsApp')); + expect(link).toBeDefined(); + const sharedText = new URL(link!.href).searchParams.get('text'); + expect(sharedText).toBe('Exemple 🕊️\ufffd\n' + window.location.origin + '/'); + }); + + it('encode les espaces et les signes plus distinctement pour les clients de courriel', async () => { + await render({ title: 'Créer ensemble + partager' }); + const link = [...host.querySelectorAll('a')].find((element) => element.textContent?.includes('Email')); + expect(link?.href).toContain('subject=Cr%C3%A9er%20ensemble%20%2B%20partager'); + expect(link?.href).not.toContain('+'); + }); + + it('donne un nom accessible et un type explicite aux boutons compacts', async () => { + await render({ compact: true }); + expect(button('Partager le lien').type).toBe('button'); + expect(button('Copier le lien').type).toBe('button'); + expect(host.querySelectorAll('button')).toHaveLength(2); + }); +}); diff --git a/src/components/shared/ShareButtons.tsx b/src/components/shared/ShareButtons.tsx index 6388d165..8ad68464 100644 --- a/src/components/shared/ShareButtons.tsx +++ b/src/components/shared/ShareButtons.tsx @@ -1,87 +1,222 @@ -import { useState } from 'react'; +import { useEffect, useId, useRef, useState } from 'react'; import { Share2, Copy, Check, MessageCircle, Send, Twitter, Facebook, Linkedin, Mail } from 'lucide-react'; import { Button } from '@/components/ui/button'; import { toast } from 'sonner'; -import { useAuth } from '@/hooks/useAuth'; +import { buildPublicShareUrl } from '@/lib/public-share'; interface ShareButtonsProps { title?: string; text?: string; compact?: boolean; + path?: string; + referralCode?: string; } -export function ShareButtons({ title = 'Purama AI', text = 'Découvre Purama AI — des agents IA autonomes pour automatiser ton business !', compact = false }: ShareButtonsProps) { - const { user } = useAuth(); +export function ShareButtons({ + title = 'Purama AI', + text = 'Découvre Purama AI — des agents IA autonomes pour automatiser ton business !', + compact = false, + path, + referralCode, +}: ShareButtonsProps) { + const shareUrl = buildPublicShareUrl({ + origin: typeof window === 'undefined' ? '' : window.location.origin, + path, + referralCode, + }); + + // A new destination owns new state: an old clipboard/share promise must not + // confirm success, unlock controls or display a link for the next destination. + return ; +} + +interface ShareActionsProps { + shareUrl: string | null; + title: string; + text: string; + compact: boolean; +} + +function ShareActions({ shareUrl, title, text, compact }: ShareActionsProps) { const [copied, setCopied] = useState(false); + const [pending, setPending] = useState(false); + const [manualReason, setManualReason] = useState<'copy' | 'share' | null>(null); + const inFlight = useRef(false); + const mounted = useRef(true); + const resetTimer = useRef | null>(null); + const manualInput = useRef(null); + const statusId = useId(); + const inputId = useId(); + + useEffect(() => { + mounted.current = true; + return () => { + mounted.current = false; + inFlight.current = false; + if (resetTimer.current !== null) clearTimeout(resetTimer.current); + }; + }, []); - const shareCode = user?.id?.slice(0, 8) || 'purama'; - const shareUrl = `https://purama-ai.purama.dev/signup?ref=${shareCode}`; - const encodedText = encodeURIComponent(`${text}\n${shareUrl}`); - const encodedUrl = encodeURIComponent(shareUrl); + useEffect(() => { + if (manualReason) { + manualInput.current?.focus(); + manualInput.current?.select(); + } + }, [manualReason]); + + const beginAction = () => { + // React state alone does not stop two clicks occurring before a render. + if (!shareUrl || inFlight.current || !mounted.current) return false; + inFlight.current = true; + if (resetTimer.current !== null) { + clearTimeout(resetTimer.current); + resetTimer.current = null; + } + setCopied(false); + setManualReason(null); + setPending(true); + return true; + }; - const copyLink = () => { - navigator.clipboard.writeText(shareUrl); - setCopied(true); - toast.success('Lien copié !'); - setTimeout(() => setCopied(false), 2000); + const finishAction = () => { + inFlight.current = false; + if (mounted.current) setPending(false); + }; + + const copyPublicLink = async () => { + if (!shareUrl) return; + try { + if (typeof navigator.clipboard?.writeText !== 'function') { + if (mounted.current) setManualReason('copy'); + return; + } + await navigator.clipboard.writeText(shareUrl); + if (!mounted.current) return; + setCopied(true); + toast.success('Lien copié !'); + resetTimer.current = setTimeout(() => { + resetTimer.current = null; + if (mounted.current) setCopied(false); + }, 2000); + } catch { + if (mounted.current) setManualReason('copy'); + } + }; + + const copyLink = async () => { + if (!beginAction()) return; + try { + await copyPublicLink(); + } finally { + finishAction(); + } }; const nativeShare = async () => { - if (navigator.share) { - try { + if (!beginAction()) return; + try { + if (typeof navigator.share === 'function' && shareUrl) { await navigator.share({ title, text, url: shareUrl }); - } catch { - // User cancelled + } else { + await copyPublicLink(); + } + } catch (error) { + const cancelled = typeof error === 'object' && error !== null && 'name' in error && error.name === 'AbortError'; + if (!cancelled && mounted.current) { + setManualReason('share'); } - } else { - copyLink(); + } finally { + finishAction(); } }; + // URLSearchParams encodes Unicode as scalar values, including a safe + // replacement for a truncated surrogate from externally supplied text. + const shareText = text + '\n' + (shareUrl ?? ''); const platforms = [ - { name: 'WhatsApp', icon: MessageCircle, href: `https://wa.me/?text=${encodedText}`, color: 'hover:text-green-400' }, - { name: 'Telegram', icon: Send, href: `https://t.me/share/url?url=${encodedUrl}&text=${encodeURIComponent(text)}`, color: 'hover:text-blue-400' }, - { name: 'Twitter', icon: Twitter, href: `https://twitter.com/intent/tweet?text=${encodedText}`, color: 'hover:text-sky-400' }, - { name: 'Facebook', icon: Facebook, href: `https://www.facebook.com/sharer/sharer.php?u=${encodedUrl}`, color: 'hover:text-blue-500' }, - { name: 'LinkedIn', icon: Linkedin, href: `https://www.linkedin.com/sharing/share-offsite/?url=${encodedUrl}`, color: 'hover:text-blue-600' }, - { name: 'Email', icon: Mail, href: `mailto:?subject=${encodeURIComponent(title)}&body=${encodedText}`, color: 'hover:text-accent-cyan' }, + { name: 'WhatsApp', icon: MessageCircle, href: 'https://wa.me/?' + new URLSearchParams({ text: shareText }), color: 'hover:text-green-400' }, + { name: 'Telegram', icon: Send, href: 'https://t.me/share/url?' + new URLSearchParams({ url: shareUrl ?? '', text }), color: 'hover:text-blue-400' }, + { name: 'Twitter', icon: Twitter, href: 'https://twitter.com/intent/tweet?' + new URLSearchParams({ text: shareText }), color: 'hover:text-sky-400' }, + { name: 'Facebook', icon: Facebook, href: 'https://www.facebook.com/sharer/sharer.php?' + new URLSearchParams({ u: shareUrl ?? '' }), color: 'hover:text-blue-500' }, + { name: 'LinkedIn', icon: Linkedin, href: 'https://www.linkedin.com/sharing/share-offsite/?' + new URLSearchParams({ url: shareUrl ?? '' }), color: 'hover:text-blue-600' }, + { name: 'Email', icon: Mail, href: 'mailto:?' + new URLSearchParams({ subject: title, body: shareText }).toString().replace(/\+/g, '%20'), color: 'hover:text-accent-cyan' }, ]; - if (compact) { - return ( -
- - -
- ); - } + const disabled = !shareUrl || pending; + const message = !shareUrl + ? 'Partage indisponible pour cette destination.' + : manualReason === 'copy' + ? 'La copie automatique est indisponible. Sélectionne le lien ci-dessous pour le copier.' + : manualReason === 'share' + ? 'Le partage automatique est indisponible. Tu peux copier le lien ci-dessous.' + : copied ? 'Lien copié.' : ''; return ( -
-
- -
- + ) : ( + + ))} +
+ )} +

+ {message} +

+ {manualReason && shareUrl && ( +
+ + event.currentTarget.select()} + onClick={(event) => event.currentTarget.select()} + className="w-full min-w-0 rounded-md border bg-background px-3 py-2 text-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring" + /> +
+ )} ); } diff --git a/src/components/shared/SpiritualLayer.test.tsx b/src/components/shared/SpiritualLayer.test.tsx new file mode 100644 index 00000000..789d8e9c --- /dev/null +++ b/src/components/shared/SpiritualLayer.test.tsx @@ -0,0 +1,301 @@ +import { act, createElement, type HTMLAttributes, type PropsWithChildren } from 'react'; +import { createRoot, type Root } from 'react-dom/client'; +import { MemoryRouter, useNavigate, type NavigateFunction } from 'react-router-dom'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { SpiritualLayer } from './SpiritualLayer'; + +const { authState, recordAffirmation, useAwakeningMock } = vi.hoisted(() => { + const recordAffirmation = vi.fn(); + return { + authState: { user: null as { id: string } | null, loading: false }, + recordAffirmation, + useAwakeningMock: vi.fn(() => ({ recordAffirmation })), + }; +}); + +vi.mock('@/hooks/useAuth', () => ({ useAuth: () => authState })); +vi.mock('@/hooks/useAwakening', () => ({ useAwakening: useAwakeningMock })); + +// Preserve React and router lifecycles; decorative animation alone is mocked. +vi.mock('framer-motion', async () => { + const React = await import('react'); + type MotionProps = HTMLAttributes & { + initial?: unknown; animate?: unknown; exit?: unknown; transition?: unknown; + }; + return { + motion: { + div: React.forwardRef((props, ref) => { + const attributes = { ...props }; + delete attributes.initial; + delete attributes.animate; + delete attributes.exit; + delete attributes.transition; + return React.createElement('div', { ...attributes, ref }); + }), + }, + AnimatePresence: ({ children }: PropsWithChildren) => children, + }; +}); + +const SESSION_KEY = 'purama_affirmation_shown'; +const MODEL_PATH = '/modeles/a6211822-fc3c-4c77-854a-3bc79dd4405d'; +const USER_A = { id: 'a3715760-353c-414d-a782-5d3efaf02eb9' }; +const USER_B = { id: 'b648fb21-132c-48e4-aee2-f17ae77bcaca' }; +let host: HTMLDivElement; +let root: Root | null; +let navigate: NavigateFunction; +let initialPath: string; +let timerSpies: ReturnType; + +function createTimerSpies() { + return { + schedule: vi.spyOn(globalThis, 'setTimeout'), + cancel: vi.spyOn(globalThis, 'clearTimeout'), + }; +} + +// Inspect the actual handles of the affirmation's 1,500 ms delay. A global +// fake-timer count also includes React/DOM housekeeping and is not a leak test. +function scheduledAffirmationTimers() { + return timerSpies.schedule.mock.calls.flatMap(([, delay], index) => { + const result = timerSpies.schedule.mock.results[index]; + return delay === 1500 && result.type === 'return' ? [result.value] : []; + }); +} + +function expectCancelled(handles: ReturnType) { + expect(handles.length).toBeGreaterThan(0); + for (const handle of handles) expect(timerSpies.cancel).toHaveBeenCalledWith(handle); +} + +function Harness() { + navigate = useNavigate(); + return createElement(SpiritualLayer); +} + +async function render(path = initialPath) { + initialPath = path; + await act(async () => { + root?.render(createElement(MemoryRouter, { initialEntries: [path] }, createElement(Harness))); + }); +} + +async function advance(milliseconds: number) { + await act(async () => { vi.advanceTimersByTime(milliseconds); }); +} + +function dialog() { + return host.querySelector('[role="dialog"]'); +} + +function acceptButton(): HTMLButtonElement { + const button = [...host.querySelectorAll('button')] + .find(element => element.textContent?.trim().startsWith("J'integre")); + if (!button) throw new Error('Affirmation acceptance button unavailable'); + return button; +} + +function closeButton(): HTMLButtonElement { + const button = host.querySelector('button[aria-label]'); + if (!button) throw new Error('Affirmation close button unavailable'); + expect(button.getAttribute('aria-label')).toBe("Fermer l'affirmation du jour"); + return button; +} + +beforeEach(() => { + vi.clearAllMocks(); + vi.useFakeTimers(); + vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true); + timerSpies = createTimerSpies(); + authState.user = USER_A; + authState.loading = false; + initialPath = '/dashboard'; + window.sessionStorage.clear(); + host = document.createElement('div'); + document.body.append(host); + root = createRoot(host); +}); + +afterEach(async () => { + await act(async () => { root?.unmount(); }); + root = null; + host.remove(); + vi.restoreAllMocks(); + window.sessionStorage.clear(); + vi.clearAllTimers(); + vi.useRealTimers(); + vi.unstubAllGlobals(); +}); + +describe('SpiritualLayer', () => { + it.each([ + MODEL_PATH, + `/login?next=${MODEL_PATH}`, + `/signup?next=${MODEL_PATH}`, + '/forgot-password', + '/reset-password#access_token=private', + '/oauth/callback?code=private', + '/dashboard/creator-agent/templates', + '/dashboard/creator-agent/a6211822-fc3c-4c77-854a-3bc79dd4405d', + '/dashboard/creator-agent/new', + '/dashboard?next=model', + '/dashboard#agents', + '/', + '/?code=private', + '/go/AMB-42', + '/forge', + '/ecosystem', + '/parrainage', + '/purama-compta', + ])('diffère l’affirmation sur la destination %s, même pour un compte connecté', async path => { + await render(path); + await advance(5000); + expect(dialog()).toBeNull(); + expect(scheduledAffirmationTimers()).toEqual([]); + expect(useAwakeningMock).not.toHaveBeenCalled(); + expect(recordAffirmation).not.toHaveBeenCalled(); + expect(window.sessionStorage.getItem(SESSION_KEY)).toBeNull(); + }); + + it.each([ + { label: 'sans utilisateur', user: null, loading: false }, + { label: 'pendant le chargement de l’authentification', user: USER_A, loading: true }, + ])('ne monte pas l’affirmation $label', async ({ user, loading }) => { + authState.user = user; + authState.loading = loading; + await render(); + await advance(5000); + expect(dialog()).toBeNull(); + expect(scheduledAffirmationTimers()).toEqual([]); + expect(useAwakeningMock).not.toHaveBeenCalled(); + expect(recordAffirmation).not.toHaveBeenCalled(); + }); + + it('préserve le délai de 1 500 ms sur l’accueil connecté', async () => { + await render(); + expect(dialog()).toBeNull(); + expect(scheduledAffirmationTimers()).toHaveLength(1); + await advance(1499); + expect(dialog()).toBeNull(); + await advance(1); + expect(dialog()?.getAttribute('aria-modal')).toBe('true'); + expect(host.querySelector('#daily-affirmation-title')?.textContent).toContain('Affirmation du jour'); + expect(recordAffirmation).not.toHaveBeenCalled(); + expect(window.sessionStorage.getItem(SESSION_KEY)).toBeNull(); + }); + + it('commence le délai seulement quand le compte est chargé', async () => { + authState.loading = true; + await render(); + await advance(2000); + expect(dialog()).toBeNull(); + authState.loading = false; + await render(); + expect(scheduledAffirmationTimers()).toHaveLength(1); + await advance(1499); + expect(dialog()).toBeNull(); + await advance(1); + expect(dialog()).not.toBeNull(); + expect(recordAffirmation).not.toHaveBeenCalled(); + }); + + it.each([1000, 1500])('retire l’overlay et annule son minuteur en quittant l’accueil à %i ms', async elapsed => { + await render(); + const handles = scheduledAffirmationTimers(); + await advance(elapsed); + expect(dialog() !== null).toBe(elapsed === 1500); + await act(async () => { navigate(MODEL_PATH); }); + expect(dialog()).toBeNull(); + expectCancelled(handles); + await advance(5000); + expect(dialog()).toBeNull(); + expect(recordAffirmation).not.toHaveBeenCalled(); + expect(window.sessionStorage.getItem(SESSION_KEY)).toBeNull(); + }); + + it('peut proposer l’affirmation au retour à l’accueil après un simple report', async () => { + await render(); + await advance(1000); + await act(async () => { navigate(MODEL_PATH); }); + await advance(5000); + await act(async () => { navigate('/dashboard'); }); + expect(dialog()).toBeNull(); + await advance(1500); + expect(dialog()).not.toBeNull(); + expect(recordAffirmation).not.toHaveBeenCalled(); + expect(window.sessionStorage.getItem(SESSION_KEY)).toBeNull(); + }); + + it.each([1000, 1500])('retire immédiatement l’affirmation lors d’une déconnexion à %i ms', async elapsed => { + await render(); + const handles = scheduledAffirmationTimers(); + await advance(elapsed); + authState.user = null; + await render(); + expect(dialog()).toBeNull(); + expectCancelled(handles); + await advance(5000); + expect(dialog()).toBeNull(); + expect(recordAffirmation).not.toHaveBeenCalled(); + expect(window.sessionStorage.getItem(SESSION_KEY)).toBeNull(); + }); + + it.each([1000, 1500])('isole le délai du nouveau compte après un changement à %i ms', async elapsed => { + await render(); + const oldHandles = scheduledAffirmationTimers(); + await advance(elapsed); + authState.user = USER_B; + await render(); + expect(dialog()).toBeNull(); + expectCancelled(oldHandles); + expect(scheduledAffirmationTimers()).toHaveLength(2); + await advance(1499); + expect(dialog()).toBeNull(); + await advance(1); + expect(dialog()).not.toBeNull(); + expect(recordAffirmation).not.toHaveBeenCalled(); + expect(window.sessionStorage.getItem(SESSION_KEY)).toBeNull(); + }); + + it('ne comptabilise une affirmation qu’après son acceptation explicite', async () => { + await render(); + await advance(1500); + expect(recordAffirmation).not.toHaveBeenCalled(); + await act(async () => { acceptButton().click(); }); + expect(dialog()).toBeNull(); + expect(recordAffirmation).toHaveBeenCalledTimes(1); + expect(window.sessionStorage.getItem(SESSION_KEY)).toBe('true'); + await advance(5000); + expect(recordAffirmation).toHaveBeenCalledTimes(1); + }); + + it('ferme et mémorise un refus sans comptabiliser une acceptation', async () => { + await render(); + await advance(1500); + await act(async () => { closeButton().click(); }); + expect(dialog()).toBeNull(); + expect(window.sessionStorage.getItem(SESSION_KEY)).toBe('true'); + await advance(5000); + expect(recordAffirmation).not.toHaveBeenCalled(); + }); + + it('respecte la mémorisation de session sur l’accueil admissible', async () => { + window.sessionStorage.setItem(SESSION_KEY, 'true'); + await render(); + await advance(5000); + expect(dialog()).toBeNull(); + expect(scheduledAffirmationTimers()).toEqual([]); + expect(recordAffirmation).not.toHaveBeenCalled(); + }); + + it('annule le minuteur au démontage sans enregistrer une acceptation', async () => { + await render(); + const handles = scheduledAffirmationTimers(); + await act(async () => { root?.unmount(); root = null; }); + expectCancelled(handles); + await advance(5000); + expect(dialog()).toBeNull(); + expect(recordAffirmation).not.toHaveBeenCalled(); + expect(window.sessionStorage.getItem(SESSION_KEY)).toBeNull(); + }); +}); diff --git a/src/components/shared/SpiritualLayer.tsx b/src/components/shared/SpiritualLayer.tsx index 300e1205..66766f42 100644 --- a/src/components/shared/SpiritualLayer.tsx +++ b/src/components/shared/SpiritualLayer.tsx @@ -1,6 +1,7 @@ import { useState, useEffect } from 'react'; import { motion, AnimatePresence } from 'framer-motion'; import { Sparkles, X } from 'lucide-react'; +import { useLocation } from 'react-router-dom'; import { useAuth } from '@/hooks/useAuth'; import { useAwakening } from '@/hooks/useAwakening'; @@ -25,6 +26,16 @@ const AFFIRMATIONS = [ const SESSION_KEY = 'purama_affirmation_shown'; export function SpiritualLayer() { + const { user, loading } = useAuth(); + const { pathname, search, hash } = useLocation(); + + // Keep optional welcome content on the overview. Unmount the whole overlay + // on navigation so neither its timer nor an exit animation blocks a task. + if (loading || !user || pathname !== '/dashboard' || search || hash) return null; + return ; +} + +function DailyAffirmationOverlay() { const { user } = useAuth(); const { recordAffirmation } = useAwakening(); const [show, setShow] = useState(false); diff --git a/src/hooks/useAuth.continuation.test.tsx b/src/hooks/useAuth.continuation.test.tsx new file mode 100644 index 00000000..9ba2f628 --- /dev/null +++ b/src/hooks/useAuth.continuation.test.tsx @@ -0,0 +1,101 @@ +import { act } from 'react'; +import { createRoot, type Root } from 'react-dom/client'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { AuthProvider, useAuth } from './useAuth'; + +const provider = vi.hoisted(() => ({ + getSession: vi.fn(), onAuthStateChange: vi.fn(), signUp: vi.fn(), + signInWithOAuth: vi.fn(), unsubscribe: vi.fn(), +})); +vi.mock('@/integrations/supabase/client', () => ({ supabase: { auth: provider } })); + +const TEMPLATE = '/modeles/230dc59b-3fae-436f-8365-e7d24998281d'; +let auth: ReturnType; +let root: Root; +let host: HTMLDivElement; +(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; + +function Probe() { auth = useAuth(); return null; } + +beforeEach(async () => { + vi.clearAllMocks(); + provider.getSession.mockResolvedValue({ data: { session: null } }); + provider.onAuthStateChange.mockReturnValue({ data: { subscription: { unsubscribe: provider.unsubscribe } } }); + provider.signUp.mockReset().mockResolvedValue({ data: { user: null, session: null }, error: null }); + provider.signInWithOAuth.mockReset().mockResolvedValue({ data: { url: 'https://accounts.example.test' }, error: null }); + host = document.createElement('div'); document.body.append(host); root = createRoot(host); + await act(async () => root.render()); +}); +afterEach(async () => { await act(async () => root.unmount()); host.remove(); }); + +describe('auth provider continuation options', () => { + it('keeps the original email redirect when the optional argument is omitted', async () => { + const result = await auth.signUp('person@example.test', 'private-password', 'Person'); + expect(provider.signUp.mock.calls[0][0].options.emailRedirectTo).toBe(window.location.origin); + expect(result).toEqual({ error: null, hasSession: false }); + }); + + it('uses the chosen internal destination for confirmation emails', async () => { + await auth.signUp('person@example.test', 'private-password', 'Person', TEMPLATE); + expect(provider.signUp.mock.calls[0][0]).toEqual({ + email: 'person@example.test', password: 'private-password', + options: { emailRedirectTo: `${window.location.origin}${TEMPLATE}`, data: { full_name: 'Person' } }, + }); + }); + + it('reports only the presence of an issued session, without forwarding its tokens', async () => { + provider.signUp.mockResolvedValueOnce({ data: { session: { access_token: 'private-access', refresh_token: 'private-refresh' } }, error: null }); + const result = await auth.signUp('person@example.test', 'private-password', 'Person', TEMPLATE); + expect(result).toEqual({ error: null, hasSession: true }); + expect(JSON.stringify(result)).not.toContain('private-access'); + expect(provider.signUp.mock.calls[0][0].options.emailRedirectTo).not.toContain('private-access'); + }); + + it('keeps the original Google dashboard destination without a next argument', async () => { + await auth.signInWithGoogle(); + expect(provider.signInWithOAuth.mock.calls[0][0].options.redirectTo).toBe(`${window.location.origin}/dashboard`); + }); + + it('uses a validated template route for Google and preserves provider options', async () => { + await auth.signInWithGoogle(TEMPLATE); + expect(provider.signInWithOAuth.mock.calls[0][0]).toEqual({ + provider: 'google', options: { + redirectTo: `${window.location.origin}${TEMPLATE}`, + queryParams: { access_type: 'offline', prompt: 'consent' }, + }, + }); + }); + + it('preserves an explicit referral in both provider destinations without inventing one', async () => { + const next = `${TEMPLATE}?ref=PARTNER_42-a`; + await auth.signInWithGoogle(next); + await auth.signUp('person@example.test', 'private-password', 'Person', next); + expect(provider.signInWithOAuth.mock.calls[0][0].options.redirectTo).toBe(`${window.location.origin}${next}`); + expect(provider.signUp.mock.calls[0][0].options.emailRedirectTo).toBe(`${window.location.origin}${next}`); + }); + + it.each(['https://attacker.example', '//attacker.example', '/%5cattacker.example', '/login?next=/signup'])( + 'does not pass unsafe redirects to either provider operation: %s', async (next) => { + await auth.signInWithGoogle(next); + await auth.signUp('person@example.test', 'private-password', 'Person', next); + expect(provider.signInWithOAuth.mock.calls[0][0].options.redirectTo).toBe(`${window.location.origin}/dashboard`); + expect(provider.signUp.mock.calls[0][0].options.emailRedirectTo).toBe(`${window.location.origin}/dashboard`); + }); + + it('strips token and false-success parameters before calling the auth service', async () => { + const next = `${TEMPLATE}?access_token=secret&success=true#refresh_token=secret`; + await auth.signInWithGoogle(next); + await auth.signUp('person@example.test', 'private-password', 'Person', next); + expect(provider.signInWithOAuth.mock.calls[0][0].options.redirectTo).toBe(`${window.location.origin}${TEMPLATE}`); + expect(provider.signUp.mock.calls[0][0].options.emailRedirectTo).toBe(`${window.location.origin}${TEMPLATE}`); + }); + + it('keeps provider errors as errors instead of manufacturing authentication success', async () => { + const error = new Error('Authentication failed'); + provider.signUp.mockResolvedValueOnce({ data: { session: null }, error }); + provider.signInWithOAuth.mockResolvedValueOnce({ data: { url: null }, error }); + expect(await auth.signUp('person@example.test', 'private-password', 'Person', TEMPLATE)) + .toEqual({ error, hasSession: false }); + expect(await auth.signInWithGoogle(TEMPLATE)).toEqual({ error }); + }); +}); diff --git a/src/hooks/useAuth.tsx b/src/hooks/useAuth.tsx index 827461f7..8e6888c0 100644 --- a/src/hooks/useAuth.tsx +++ b/src/hooks/useAuth.tsx @@ -1,14 +1,15 @@ import { createContext, useContext, useEffect, useState, ReactNode } from 'react'; import { User, Session } from '@supabase/supabase-js'; import { supabase } from '@/integrations/supabase/client'; +import { DEFAULT_AUTH_CONTINUATION, safeAuthContinuation } from '@/lib/auth-continuation'; interface AuthContextType { user: User | null; session: Session | null; loading: boolean; - signUp: (email: string, password: string, fullName?: string) => Promise<{ error: Error | null }>; + signUp: (email: string, password: string, fullName?: string, next?: string) => Promise<{ error: Error | null; hasSession?: boolean }>; signIn: (email: string, password: string) => Promise<{ error: Error | null }>; - signInWithGoogle: () => Promise<{ error: Error | null }>; + signInWithGoogle: (next?: string) => Promise<{ error: Error | null }>; signOut: () => Promise; } @@ -39,18 +40,19 @@ export function AuthProvider({ children }: { children: ReactNode }) { return () => subscription.unsubscribe(); }, []); - const signUp = async (email: string, password: string, fullName?: string) => { - const { error } = await supabase.auth.signUp({ + const signUp = async (email: string, password: string, fullName?: string, next?: string) => { + const destination = safeAuthContinuation(next) ?? DEFAULT_AUTH_CONTINUATION; + const { data, error } = await supabase.auth.signUp({ email, password, options: { - emailRedirectTo: window.location.origin, + emailRedirectTo: next === undefined ? window.location.origin : `${window.location.origin}${destination}`, data: { full_name: fullName, }, }, }); - return { error }; + return { error, hasSession: Boolean(data.session) }; }; const signIn = async (email: string, password: string) => { @@ -61,12 +63,14 @@ export function AuthProvider({ children }: { children: ReactNode }) { return { error }; }; - const signInWithGoogle = async () => { + const signInWithGoogle = async (next?: string) => { + const destination = safeAuthContinuation(next) ?? DEFAULT_AUTH_CONTINUATION; const { error } = await supabase.auth.signInWithOAuth({ provider: 'google', options: { - // Let Supabase handle the callback, then redirect to dashboard - redirectTo: `${window.location.origin}/dashboard`, + // Supabase handles authentication. Only the validated navigation route + // is supplied here; provider redirect allowlists must be qualified. + redirectTo: `${window.location.origin}${destination}`, queryParams: { access_type: 'offline', prompt: 'consent', diff --git a/src/lib/auth-continuation.test.ts b/src/lib/auth-continuation.test.ts new file mode 100644 index 00000000..822d1768 --- /dev/null +++ b/src/lib/auth-continuation.test.ts @@ -0,0 +1,125 @@ +import { describe, expect, it } from 'vitest'; +import { authPagePath, resolveAuthContinuation, safeAuthContinuation } from './auth-continuation'; + +const TEMPLATE = '/modeles/230dc59b-3fae-436f-8365-e7d24998281d'; + +describe('auth continuation boundary', () => { + it.each([ + ['/dashboard/creator-agent/new', '/dashboard/creator-agent/new'], + [TEMPLATE, TEMPLATE], + ['/ambassadeur/rejoindre', '/ambassadeur/rejoindre'], + ['/dashboard?tab=billing#usage', '/dashboard?tab=billing#usage'], + ['/dashboard?view=grid&page=2#overview', '/dashboard?view=grid&page=2#overview'], + [`${TEMPLATE}?utm_campaign=test#details`, `${TEMPLATE}#details`], + ])('keeps an internal navigation destination %s', (input, expected) => { + expect(safeAuthContinuation(input)).toBe(expected); + }); + + it.each([ + 'https://attacker.example', 'http://attacker.example', '//attacker.example', + '/\\attacker.example', '/%5cattacker.example', '/%255cattacker.example', + '/%2f%2fattacker.example', '/%252f%252fattacker.example', + 'javascript:alert(1)', 'data:text/html,anything', 'dashboard', + ' /dashboard', '/dashboard ', '/dash\nboard', '/%0adashboard', '/invalid%', + '/dashboard%3Faccess_token%3Dprivate', '/dashboard%2523access_token%253Dprivate', + null, undefined, 42, { pathname: '/dashboard' }, `/${'x'.repeat(2048)}`, + ])('rejects non-local or malformed navigation %j', (input) => { + expect(safeAuthContinuation(input)).toBeNull(); + }); + + it.each([ + '/login', '/LOGIN/', '/signup?next=/dashboard', '/%6cogin', '/%256cogin', + '/before/../login', '/%252e%252e/login', '/forgot-password', '/reset-password', + '/auth/callback', '/oauth/callback?code=private', '/logout', '/signout', + '/go/untrusted-destination', '/api/do-something', + ])('does not return into an auth or redirect handler %s', (input) => { + expect(safeAuthContinuation(input)).toBeNull(); + }); + + it('discards tokens, personal data and provider/payment success flags', () => { + expect(safeAuthContinuation('/dashboard?tab=billing&access_token=private&refresh_token=private' + + '&id_token=private&code=private&password=private&email=person%40example.test' + + '&success=true&overage_success=true&gmail=connected&connected=true#access_token=private')) + .toBe('/dashboard?tab=billing'); + }); + + it('does not forward a nested next or ambiguous presentation parameters', () => { + expect(safeAuthContinuation('/pricing?next=%2Flogin&tab=billing&tab=other&page=2&success=true')) + .toBe('/pricing?page=2'); + }); + + it.each([ + '/dashboard?tab=contains%20spaces', '/dashboard?view=https%3A%2F%2Fexample.test', + '/dashboard?page=0', '/dashboard?page=-1', '/dashboard?page=1.5', + '/dashboard?page=2&page=3', '/dashboard?page=1000000', + '/dashboard#access-token', '/dashboard#refresh_token=secret', + '/dashboard#state=secret', '/dashboard#too%20many%20words', + ])('minimizes unsupported selectors and fragments in %s', (input) => { + expect(safeAuthContinuation(input)).toBe('/dashboard'); + }); + + it('prefers a valid next over the previous protected route', () => { + expect(resolveAuthContinuation(`?next=${encodeURIComponent(TEMPLATE)}`, { pathname: '/pricing' })) + .toBe(TEMPLATE); + }); + + it.each([ + '?next=%2Fdashboard%2Fagents&next=%2Fpricing', + '?next=%2Fdashboard%2Fagents&%6eext=%2Fpricing', + '?next=%2Fdashboard%2Fagents&NeXt=%2Fpricing', + '?next=https%3A%2F%2Fattacker.example', '?next=%2Fsignup', '?next=', + ])('falls back safely for an invalid or ambiguous next: %s', (search) => { + expect(resolveAuthContinuation(search, { pathname: '/pricing' })).toBe('/pricing'); + expect(resolveAuthContinuation(search)).toBe('/dashboard'); + }); + + it('preserves a protected-route location with minimized query and hash', () => { + expect(resolveAuthContinuation('', { + pathname: '/dashboard', search: '?tab=billing&token=private', hash: '#usage', + })).toBe('/dashboard?tab=billing#usage'); + }); + + it('also supports a legacy string state.from', () => { + expect(resolveAuthContinuation('', '/notifications')).toBe('/notifications'); + }); + + it.each([ + null, {}, { pathname: '//attacker.example' }, { pathname: '/login' }, + { pathname: '/dashboard', search: 'not-a-search' }, + { pathname: '/dashboard', hash: 'not-a-fragment' }, + { pathname: '/dashboard', search: 12 }, { pathname: '/dashboard', hash: {} }, + ])('does not trust malformed location state %j', (from) => { + expect(resolveAuthContinuation('', from)).toBe('/dashboard'); + }); + + it('bounds query parsing and still preserves a legitimate state fallback', () => { + expect(resolveAuthContinuation(`?noise=${'x'.repeat(8192)}&next=%2Fpricing`, '/notifications')) + .toBe('/notifications'); + }); + + it('carries the same safe route when switching between login and signup', () => { + const href = authPagePath('/signup', `${TEMPLATE}?token=secret#details`); + const url = new URL(href, 'https://app.example'); + expect(url.pathname).toBe('/signup'); + expect(url.searchParams.getAll('next')).toEqual([`${TEMPLATE}#details`]); + expect(resolveAuthContinuation(url.search)).toBe(`${TEMPLATE}#details`); + expect(href).not.toContain('secret'); + }); + + it('never turns an auth link builder into an external redirect', () => { + expect(authPagePath('/login', '//attacker.example')).toBe('/login?next=%2Fdashboard'); + }); + + it('preserves one explicitly supplied valid referral across login/signup', () => { + const next = `${TEMPLATE}?ref=PARTNER_42-a&success=true&token=secret`; + expect(safeAuthContinuation(next)).toBe(`${TEMPLATE}?ref=PARTNER_42-a`); + const signup = new URL(authPagePath('/signup', next), 'https://app.example'); + expect(resolveAuthContinuation(signup.search)).toBe(`${TEMPLATE}?ref=PARTNER_42-a`); + }); + + it.each(['ref=', 'ref=wrong%20code', 'ref=one&ref=two', `ref=${'a'.repeat(65)}`])( + 'does not forward an invalid or ambiguous referral: %s', (search) => { + expect(safeAuthContinuation(`${TEMPLATE}?${search}`)).toBe(TEMPLATE); + }, + ); +}); diff --git a/src/lib/auth-continuation.ts b/src/lib/auth-continuation.ts new file mode 100644 index 00000000..9859dcf6 --- /dev/null +++ b/src/lib/auth-continuation.ts @@ -0,0 +1,79 @@ +import { safeInternalPath } from './safeNavigation'; +import { isValidReferralCode } from './public-share'; + +export const DEFAULT_AUTH_CONTINUATION = '/dashboard'; +const INTERNAL_ORIGIN = 'https://purama.invalid'; +const MAX_SEARCH_LENGTH = 8_192; +const AUTH_OR_REDIRECT_ROUTE = /^\/(?:login|signup|signin|sign-in|sign-up|forgot-password|reset-password|logout|signout|auth|oauth|go|api)(?:\/|$)/i; + +/** A return location is navigation only: never an OAuth callback or an action. */ +export function safeAuthContinuation(value: unknown): string | null { + const internal = safeInternalPath(value); + if (!internal) return null; + + const destination = new URL(internal, INTERNAL_ORIGIN); + let decodedPath = destination.pathname; + // safeInternalPath already bounds decoding. Decode the path again for the + // route check so /%6cogin and encoded dot segments cannot create auth loops. + for (let pass = 0; pass < 5; pass += 1) { + const decoded = decodeURIComponent(decodedPath); + if (decoded === decodedPath) break; + decodedPath = decoded; + } + if (decodedPath.includes('?') || decodedPath.includes('#')) return null; + const route = new URL(decodedPath, INTERNAL_ORIGIN); + if (route.origin !== INTERNAL_ORIGIN || AUTH_OR_REDIRECT_ROUTE.test(route.pathname)) return null; + + // Only small presentation selectors survive. In particular, provider tokens, + // emails, nested redirects and success/connected/payment flags are discarded. + const query = new URLSearchParams(); + for (const key of ['tab', 'view'] as const) { + const values = destination.searchParams.getAll(key); + if (values.length === 1 && /^[a-z][a-z0-9-]{0,39}$/i.test(values[0])) { + query.set(key, values[0]); + } + } + const pages = destination.searchParams.getAll('page'); + if (pages.length === 1 && /^[1-9]\d{0,5}$/.test(pages[0])) query.set('page', pages[0]); + // Preserve only a caller-supplied public referral code. This shape check does + // not grant eligibility or calculate attribution; the existing service does. + const referrals = destination.searchParams.getAll('ref'); + if (referrals.length === 1 && isValidReferralCode(referrals[0])) query.set('ref', referrals[0]); + + const hash = /^#[a-z][a-z0-9-]{0,63}$/i.test(destination.hash) + && !/(?:token|password|secret|credential|session)/i.test(destination.hash) + ? destination.hash : ''; + const search = query.toString(); + return `${destination.pathname}${search ? `?${search}` : ''}${hash}`; +} + +function continuationFromState(from: unknown): string | null { + if (typeof from === 'string') return safeAuthContinuation(from); + if (!from || typeof from !== 'object') return null; + const location = from as { pathname?: unknown; search?: unknown; hash?: unknown }; + if (typeof location.pathname !== 'string') return null; + if (location.search !== undefined && (typeof location.search !== 'string' + || (location.search !== '' && !location.search.startsWith('?')))) return null; + if (location.hash !== undefined && (typeof location.hash !== 'string' + || (location.hash !== '' && !location.hash.startsWith('#')))) return null; + return safeAuthContinuation(`${location.pathname}${location.search ?? ''}${location.hash ?? ''}`); +} + +/** Prefer one valid explicit next; preserve ProtectedRoute's state.from fallback. */ +export function resolveAuthContinuation(search: string, from?: unknown): string { + if (search.length <= MAX_SEARCH_LENGTH) { + const params = new URLSearchParams(search); + const nextKeys = [...params.keys()].filter((key) => key.toLowerCase() === 'next'); + if (nextKeys.length === 1 && nextKeys[0] === 'next') { + const next = safeAuthContinuation(params.get('next')); + if (next) return next; + } + } + return continuationFromState(from) ?? DEFAULT_AUTH_CONTINUATION; +} + +/** Switching login/signup carries only the validated route, never form data. */ +export function authPagePath(page: '/login' | '/signup', next: unknown): string { + const destination = safeAuthContinuation(next) ?? DEFAULT_AUTH_CONTINUATION; + return `${page}?${new URLSearchParams({ next: destination }).toString()}`; +} diff --git a/src/lib/creator-agent-distribution.test.ts b/src/lib/creator-agent-distribution.test.ts new file mode 100644 index 00000000..fc1ac32a --- /dev/null +++ b/src/lib/creator-agent-distribution.test.ts @@ -0,0 +1,100 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +const client = vi.hoisted(() => ({ rpc: vi.fn(), from: vi.fn() })); +vi.mock('@/integrations/supabase/client', () => ({ supabase: client })); + +import { cloneTemplate, getPublicCreatorModel, listPublicAgents, listTemplates } from './creator-agent'; + +const modelId = '81000000-0000-4000-8000-000000000001'; +const ownerId = '82000000-0000-4000-8000-000000000001'; +const copyId = '83000000-0000-4000-8000-000000000001'; +const model = { id: modelId, name: 'Préparer ma semaine', description: null, emoji: '🗓️', color: '#8B5CF6', category: 'productivity', is_public: true, is_template: false, is_active: true }; + +beforeEach(() => vi.resetAllMocks()); + +describe('adaptateur RPC de distribution', () => { + it('n’appelle pas le serveur avec un identifiant invalide', async () => { + expect(await getPublicCreatorModel('all')).toBeNull(); + expect(client.rpc).not.toHaveBeenCalled(); + }); + + it('charge la projection publique par identifiant et propage le signal d’annulation', async () => { + const signal = new AbortController().signal; + const abortSignal = vi.fn().mockResolvedValue({ data: [{ ...model, system_prompt: 'secret' }], error: null }); + client.rpc.mockReturnValue({ abortSignal }); + expect(await getPublicCreatorModel(modelId, signal)).toEqual(model); + expect(client.rpc).toHaveBeenCalledWith('public_creator_models', { p_id: modelId }); + expect(abortSignal).toHaveBeenCalledWith(signal); + expect(client.from).not.toHaveBeenCalled(); + }); + + it('distingue un retrait du modèle d’une erreur de chargement', async () => { + client.rpc.mockResolvedValueOnce({ data: [], error: null }); + expect(await getPublicCreatorModel(modelId)).toBeNull(); + const failure = { code: 'PGRST202', message: 'Migration absente' }; + client.rpc.mockResolvedValueOnce({ data: null, error: failure }); + await expect(getPublicCreatorModel(modelId)).rejects.toEqual(failure); + }); + + it.each([ + { label: 'plusieurs lignes', data: [model, model] }, + { label: 'un autre identifiant', data: [{ ...model, id: copyId }] }, + { label: 'un modèle privé', data: [{ ...model, is_public: false }] }, + { label: 'un résultat nul', data: null }, + ])('refuse un résultat qui ne correspond pas au lien demandé : $label', async ({ data }) => { + client.rpc.mockResolvedValue({ data, error: null }); + await expect(getPublicCreatorModel(modelId)).rejects.toThrow('indisponible'); + }); + + it('réutilise le catalogue public pour les deux écrans existants', async () => { + client.rpc.mockResolvedValue({ data: [model], error: null }); + expect(await listTemplates()).toEqual([model]); + expect(await listPublicAgents()).toEqual([model]); + expect(client.rpc.mock.calls).toEqual([ + ['public_creator_models', { p_kind: 'official' }], + ['public_creator_models', { p_kind: 'community' }], + ]); + expect(client.from).not.toHaveBeenCalled(); + }); + + it('ne laisse pas un titre blanc casser le catalogue entier', async () => { + client.rpc.mockResolvedValue({ data: [{ ...model, name: ' ' }, model], error: null }); + expect(await listPublicAgents()).toEqual([model]); + }); + + it('lie la demande au compte attendu et réutilise le même identifiant lors d’une nouvelle tentative', async () => { + const single = vi.fn().mockResolvedValue({ data: { id: copyId, user_id: ownerId, cloned_from: modelId }, error: null }); + client.rpc.mockReturnValue({ single }); + await cloneTemplate(ownerId, modelId, copyId); + await cloneTemplate(ownerId, modelId, copyId); + expect(client.rpc.mock.calls).toEqual(Array(2).fill([ + 'clone_public_creator_model', { p_source_id: modelId, p_copy_id: copyId, p_expected_user_id: ownerId }, + ])); + expect(client.from).not.toHaveBeenCalled(); + }); + + it.each([ + { id: copyId, user_id: copyId, cloned_from: modelId }, + { id: modelId, user_id: ownerId, cloned_from: modelId }, + { id: copyId, user_id: ownerId, cloned_from: copyId }, + null, + ])('ne confirme jamais la copie d’un autre utilisateur ou d’une autre demande (%j)', async data => { + client.rpc.mockReturnValue({ single: vi.fn().mockResolvedValue({ data, error: null }) }); + await expect(cloneTemplate(ownerId, modelId, copyId)).rejects.toThrow('confirmée'); + }); + + it('propage le retrait intervenu entre la présentation et la copie', async () => { + const error = { code: 'P0002', message: 'Model unavailable' }; + client.rpc.mockReturnValue({ single: vi.fn().mockResolvedValue({ data: null, error }) }); + await expect(cloneTemplate(ownerId, modelId, copyId)).rejects.toEqual(error); + }); + + it('ne confirme pas une demande refusée après un changement de compte', async () => { + const error = { code: '42501', message: 'Authentication changed or required' }; + client.rpc.mockReturnValue({ single: vi.fn().mockResolvedValue({ data: null, error }) }); + await expect(cloneTemplate(ownerId, modelId, copyId)).rejects.toEqual(error); + expect(client.rpc).toHaveBeenCalledWith('clone_public_creator_model', { + p_source_id: modelId, p_copy_id: copyId, p_expected_user_id: ownerId, + }); + }); +}); diff --git a/src/lib/creator-agent.ts b/src/lib/creator-agent.ts index 6e86c6d7..577693e2 100644 --- a/src/lib/creator-agent.ts +++ b/src/lib/creator-agent.ts @@ -1,8 +1,14 @@ // Frontend client for the Creator Agent (meta-agent that builds custom agents). import { supabase } from '@/integrations/supabase/client'; +import { + isCreatorModelId, parsePublicCreatorModel, type PublicCreatorModel, +} from '@/lib/public-creator-model'; type AnyTable = any; // eslint-disable-line @typescript-eslint/no-explicit-any const sb = () => (supabase as unknown as { from: (t: string) => AnyTable }); +const creatorRpc = supabase as unknown as { + rpc: (name: string, args: Record) => AnyTable; +}; // ============================================================= // Types @@ -129,26 +135,35 @@ export async function listMyAgents(userId: string): Promise { return (data ?? []) as CreatorAgent[]; } -export async function listTemplates(): Promise { - const { data, error } = await sb() - .from('creator_agents') - .select('*') - .eq('is_template', true) - .order('name', { ascending: true }); +async function listPublicCreatorModels(kind: 'official' | 'community'): Promise { + const { data, error } = await creatorRpc.rpc('public_creator_models', { p_kind: kind }); if (error) throw error; - return (data ?? []) as CreatorAgent[]; + if (!Array.isArray(data)) throw new Error('Le catalogue de modèles est indisponible.'); + // One malformed community record must not make everybody's catalogue fail. + return data.flatMap((row: unknown) => { + const model = parsePublicCreatorModel(row); + return model ? [model] : []; + }); } -export async function listPublicAgents(): Promise { - const { data, error } = await sb() - .from('creator_agents') - .select('*') - .eq('is_public', true) - .eq('is_template', false) - .order('total_runs', { ascending: false }) - .limit(50); +export async function listTemplates(): Promise { + return listPublicCreatorModels('official'); +} + +export async function listPublicAgents(): Promise { + return listPublicCreatorModels('community'); +} + +export async function getPublicCreatorModel(id: string, signal?: AbortSignal): Promise { + if (!isCreatorModelId(id)) return null; + const query = creatorRpc.rpc('public_creator_models', { p_id: id }); + const { data, error } = await (signal ? query.abortSignal(signal) : query); if (error) throw error; - return (data ?? []) as CreatorAgent[]; + if (!Array.isArray(data)) throw new Error('Le modèle est indisponible.'); + if (data.length === 0) return null; + const model = data.length === 1 ? parsePublicCreatorModel(data[0]) : null; + if (!model || model.id !== id.toLowerCase()) throw new Error('Le modèle est indisponible.'); + return model; } export async function getAgent(id: string): Promise { @@ -220,21 +235,19 @@ export async function deleteAgent(id: string): Promise { export async function cloneTemplate( userId: string, templateId: string, + copyId: string = crypto.randomUUID(), ): Promise { - const tpl = await getAgent(templateId); - return createAgent(userId, { - name: tpl.name, - description: tpl.description, - emoji: tpl.emoji, - color: tpl.color, - category: tpl.category, - system_prompt: tpl.system_prompt, - model: tpl.model, - temperature: tpl.temperature, - max_tokens: tpl.max_tokens, - tools_enabled: tpl.tools_enabled, - cloned_from: tpl.id, - }); + if (![userId, templateId, copyId].every(isCreatorModelId)) throw new Error('Demande de copie invalide.'); + const { data, error } = await creatorRpc.rpc('clone_public_creator_model', { + p_source_id: templateId, + p_copy_id: copyId, + p_expected_user_id: userId, + }).single(); + if (error) throw error; + if (!data || data.id !== copyId || data.user_id !== userId || data.cloned_from !== templateId) { + throw new Error('La copie n’a pas pu être confirmée.'); + } + return data as CreatorAgent; } // ============================================================= diff --git a/src/lib/public-creator-model.test.ts b/src/lib/public-creator-model.test.ts new file mode 100644 index 00000000..87711ff0 --- /dev/null +++ b/src/lib/public-creator-model.test.ts @@ -0,0 +1,51 @@ +import { describe, expect, it } from 'vitest'; +import { isCreatorModelId, parsePublicCreatorModel } from './public-creator-model'; + +const publicRecord = { + id: '81000000-0000-4000-8000-000000000001', + name: 'Préparer ma semaine', + description: 'Un plan clair et personnalisable.', + emoji: '🗓️', color: '#8B5CF6', category: 'productivity', + is_public: true, is_template: false, is_active: true, +}; + +describe('contrat public du modèle', () => { + it('projette seulement les métadonnées publiques, même avec un serveur trop bavard', () => { + const result = parsePublicCreatorModel({ + ...publicRecord, + user_id: 'private-owner', system_prompt: 'private-prompt', + schedule_input: { email: 'private@example.test' }, + history: ['private-history'], credentials: 'private-credential', + }); + expect(result).toEqual(publicRecord); + expect(JSON.stringify(result)).not.toContain('private-'); + }); + + it.each([ + null, [], {}, { ...publicRecord, id: '../../dashboard' }, + { ...publicRecord, name: ' ' }, { ...publicRecord, is_public: false }, + { ...publicRecord, is_active: false }, { ...publicRecord, is_active: 'true' }, + { ...publicRecord, is_template: 'true' }, + ].map(record => ({ record })))('refuse une fiche privée, inactive ou malformée ($record)', ({ record }) => { + expect(parsePublicCreatorModel(record)).toBeNull(); + }); + + it('accepte un modèle officiel actif sans le marquer publié par la communauté', () => { + expect(parsePublicCreatorModel({ ...publicRecord, is_public: false, is_template: true })) + .toMatchObject({ is_public: false, is_template: true }); + }); + + it('borne les textes et refuse une couleur active ou une catégorie inconnue', () => { + const result = parsePublicCreatorModel({ + ...publicRecord, name: '🌍'.repeat(300), description: 'a'.repeat(5000), + emoji: 'a'.repeat(100), color: 'url(https://tracking.invalid)', category: 'unknown', + }); + expect(Array.from(result!.name)).toHaveLength(161); + expect(result!.description).toHaveLength(1601); + expect(result).toMatchObject({ emoji: '🤖', color: '#8B5CF6', category: null }); + }); + + it.each(['', '/', '%2F', 'https://example.test', '81000000-0000-4000-8000-000000000001?token=secret'])('refuse un identifiant ambigu (%s)', value => { + expect(isCreatorModelId(value)).toBe(false); + }); +}); diff --git a/src/lib/public-creator-model.ts b/src/lib/public-creator-model.ts new file mode 100644 index 00000000..fec41b8d --- /dev/null +++ b/src/lib/public-creator-model.ts @@ -0,0 +1,50 @@ +import type { AgentCategory } from '@/lib/creator-agent'; + +/** The public contract deliberately has no owner, prompt, history or schedule input. */ +export interface PublicCreatorModel { + id: string; + name: string; + description: string | null; + emoji: string; + color: string; + category: AgentCategory | null; + is_public: boolean; + is_template: boolean; + is_active: true; +} + +export function isCreatorModelId(value: unknown): value is string { + return typeof value === 'string' && /^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i.test(value); +} + +const categories = new Set([ + 'productivity', 'marketing', 'sales', 'support', 'content', 'dev', 'finance', 'autre', +]); + +function boundedText(value: string, limit: number): string { + const chars = Array.from(value.trim()); + return chars.length > limit ? `${chars.slice(0, limit).join('')}…` : chars.join(''); +} + +/** Defense in depth: never spread a server record into public UI state. */ +export function parsePublicCreatorModel(value: unknown): PublicCreatorModel | null { + if (!value || typeof value !== 'object' || Array.isArray(value)) return null; + const row = value as Record; + if (!isCreatorModelId(row.id) || typeof row.name !== 'string' || !row.name.trim()) return null; + if (row.is_active !== true || (row.is_public !== true && row.is_template !== true)) return null; + if (typeof row.is_public !== 'boolean' || typeof row.is_template !== 'boolean') return null; + return { + id: row.id.toLowerCase(), + name: boundedText(row.name, 160), + description: typeof row.description === 'string' && row.description.trim() + ? boundedText(row.description, 1600) : null, + emoji: typeof row.emoji === 'string' && row.emoji.length <= 32 && row.emoji.trim() + ? row.emoji : '🤖', + color: typeof row.color === 'string' && /^#[0-9a-f]{6}$/i.test(row.color) + ? row.color : '#8B5CF6', + category: categories.has(row.category as AgentCategory) ? row.category as AgentCategory : null, + is_public: row.is_public, + is_template: row.is_template, + is_active: true, + }; +} diff --git a/src/lib/public-share.test.ts b/src/lib/public-share.test.ts new file mode 100644 index 00000000..8d05b046 --- /dev/null +++ b/src/lib/public-share.test.ts @@ -0,0 +1,69 @@ +import { describe, expect, it } from 'vitest'; +import { buildPublicShareUrl } from './public-share'; + +const origin = 'https://purama.example'; +const template = '/modeles/a6211822-fc3c-4c77-854a-3bc79dd4405d'; + +describe('buildPublicShareUrl', () => { + it('utilise l’accueil public si aucun chemin n’est fourni', () => { + expect(buildPublicShareUrl({ origin })).toBe(origin + '/'); + }); + + it.each(['/', '/forge', '/ecosystem', '/parrainage', '/purama-compta', template])( + 'accepte uniquement une destination publique définie : %s', + (path) => expect(buildPublicShareUrl({ origin, path })).toBe(origin + path), + ); + + it('conserve uniquement le code de recommandation explicitement fourni', () => { + const url = new URL(buildPublicShareUrl({ origin, path: template, referralCode: 'partner_A-42' })!); + expect(url.origin).toBe(origin); + expect(url.pathname).toBe(template); + expect([...url.searchParams]).toEqual([['ref', 'partner_A-42']]); + expect(url.hash).toBe(''); + }); + + it.each([ + '', 'forge', '/signup', '/login', '/dashboard', '/dashboard/creator-agent/templates', + '/go/affiliate', '/modeles/not-a-uuid', '/modeles/a6211822-fc3c-4c77-854a-3bc79dd4405d/private', + '/forge/', '/Forge', '/forge?ref=code', '/forge?access_token=secret', '/forge#private', + '/modeles/a6211822-fc3c-4c77-854a-3bc79dd4405d\n', + ' /forge', '/forge ', '/forge\n', '/forge\t', '/forge/../ecosystem', + '/%66orge', '/%2566orge', '/forge%3Ftoken=secret', '/forge%23secret', + '//evil.example/forge', 'https://evil.example/forge', 'https://purama.example/forge', + '/\\evil.example/forge', '\\forge', 'javascript:alert(1)', '/forge\0', + ])('refuse une cible privée, ambiguë ou accompagnée de données : %s', (path) => { + expect(buildPublicShareUrl({ origin, path })).toBeNull(); + }); + + it.each([ + '', ' partner', 'partner ', 'partner\n', 'ref&secret=value', 'ref?secret=value', + 'ref#secret', 'ref=value', 'ref%26secret', 'équipe', 'a'.repeat(65), + ])('refuse un code invalide sans en inventer un autre : %s', (referralCode) => { + expect(buildPublicShareUrl({ origin, referralCode })).toBeNull(); + }); + + it.each(['http://localhost', 'http://localhost:5173', 'http://127.0.0.1:4173', 'http://[::1]:4173'])( + 'permet le développement HTTP sur une origine locale explicite : %s', + (localOrigin) => expect(buildPublicShareUrl({ origin: localOrigin, path: '/forge' })).toBe(localOrigin + '/forge'), + ); + + it.each([ + '', 'null', 'https://purama.example/', 'https://purama.example/forge', + 'https://purama.example?token=secret', 'https://purama.example#secret', + 'https://user:password@purama.example', 'http://purama.example', + 'http://localhost.evil.example', 'http://192.168.1.2', '//purama.example', + 'file:///workspace', 'javascript:alert(1)', ' https://purama.example', + 'https://purama.example\n', 'https://purama.example\\private', 'https://purama.example:443', + ])('refuse une origine incertaine, privée ou non sécurisée : %s', (invalidOrigin) => { + expect(buildPublicShareUrl({ origin: invalidOrigin })).toBeNull(); + }); + + it('refuse aussi des entrées incorrectes reçues à l’exécution', () => { + const build = buildPublicShareUrl as (input: { origin: unknown; path?: unknown; referralCode?: unknown }) => string | null; + expect(build({ origin: null })).toBeNull(); + expect(build({ origin, path: null })).toBeNull(); + expect(build({ origin, path: ['/forge'] })).toBeNull(); + expect(build({ origin, referralCode: null })).toBeNull(); + expect(build({ origin, referralCode: 42 })).toBeNull(); + }); +}); diff --git a/src/lib/public-share.ts b/src/lib/public-share.ts new file mode 100644 index 00000000..942f0db4 --- /dev/null +++ b/src/lib/public-share.ts @@ -0,0 +1,48 @@ +const PUBLIC_PATHS = new Set(['/', '/forge', '/ecosystem', '/parrainage', '/purama-compta']); +const PUBLIC_TEMPLATE_PATH = /^\/modeles\/([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/i; +const REFERRAL_CODE = /^[A-Za-z0-9_-]{1,64}$/; +const LOCAL_HOSTS = new Set(['localhost', '127.0.0.1', '[::1]']); + +interface PublicShareOptions { + /** Pass window.location.origin, never the current page URL. */ + origin: string; + path?: string; + /** A code explicitly supplied by the caller; never inferred from an account ID. */ + referralCode?: string; +} + +/** Structural validation only; eligibility remains a server-side decision. */ +export function isValidReferralCode(value: unknown): value is string { + return typeof value === 'string' && value === value.trim() && REFERRAL_CODE.test(value); +} + +/** + * Builds only public links. This checks URL shape, not template publication or + * referral eligibility: the corresponding server routes must enforce those. + * Invalid explicit inputs fail closed rather than silently changing destination. + */ +export function buildPublicShareUrl({ + origin, + path = '/', + referralCode, +}: PublicShareOptions): string | null { + if (typeof origin !== 'string' || origin.length > 2048 || origin !== origin.trim()) return null; + if (typeof path !== 'string' || path !== path.trim()) return null; + if (!PUBLIC_PATHS.has(path) && !PUBLIC_TEMPLATE_PATH.test(path)) return null; + if (referralCode !== undefined && !isValidReferralCode(referralCode)) return null; + + try { + const source = new URL(origin); + // An origin has no credentials, path, query or fragment. Exact equality also + // rejects URL spellings that a parser would silently repair or normalize. + if (source.origin !== origin || source.username || source.password) return null; + if (source.protocol !== 'https:' && !(source.protocol === 'http:' && LOCAL_HOSTS.has(source.hostname))) { + return null; + } + const url = new URL(path, source.origin); + if (referralCode !== undefined) url.searchParams.set('ref', referralCode); + return url.href; + } catch { + return null; + } +} diff --git a/src/pages/CreatorAgent.tsx b/src/pages/CreatorAgent.tsx index 7aee1804..451424bd 100644 --- a/src/pages/CreatorAgent.tsx +++ b/src/pages/CreatorAgent.tsx @@ -11,6 +11,7 @@ import { Button } from '@/components/ui/button'; import { Badge } from '@/components/ui/badge'; import { toast } from 'sonner'; import { useAuth } from '@/hooks/useAuth'; +import type { PublicCreatorModel } from '@/lib/public-creator-model'; import { listMyAgents, listTemplates, listRuns, CATEGORIES, @@ -20,7 +21,7 @@ import { export default function CreatorAgentPage() { const { user } = useAuth(); const [myAgents, setMyAgents] = useState([]); - const [templates, setTemplates] = useState([]); + const [templates, setTemplates] = useState([]); const [recentRuns, setRecentRuns] = useState([]); const [loading, setLoading] = useState(true); @@ -199,7 +200,7 @@ export default function CreatorAgentPage() { ); } -function AgentCard({ agent, isTemplate }: { agent: CreatorAgent; isTemplate?: boolean }) { +function AgentCard({ agent, isTemplate }: { agent: CreatorAgent | PublicCreatorModel; isTemplate?: boolean }) { const cat = CATEGORIES.find(c => c.value === agent.category); return ( @@ -217,8 +218,8 @@ function AgentCard({ agent, isTemplate }: { agent: CreatorAgent; isTemplate?: bo )}
{cat && {cat.emoji} {cat.label}} - {agent.schedule_enabled && ⏰ Auto} - {agent.total_runs > 0 && {agent.total_runs} runs} + {'schedule_enabled' in agent && agent.schedule_enabled && ⏰ Auto} + {'total_runs' in agent && agent.total_runs > 0 && {agent.total_runs} runs}
diff --git a/src/pages/CreatorAgentTemplates.tsx b/src/pages/CreatorAgentTemplates.tsx index c04d8aa1..57bf5195 100644 --- a/src/pages/CreatorAgentTemplates.tsx +++ b/src/pages/CreatorAgentTemplates.tsx @@ -1,10 +1,12 @@ -import { useEffect, useState } from 'react'; +import { useEffect, useRef, useState } from 'react'; import { Link, useNavigate } from 'react-router-dom'; import { motion } from 'framer-motion'; import { ArrowLeft, Loader2, Store, Copy, Filter } from 'lucide-react'; import { Card, CardContent } from '@/components/ui/card'; import { Button } from '@/components/ui/button'; import { Badge } from '@/components/ui/badge'; +import { ShareButtons } from '@/components/shared/ShareButtons'; +import type { PublicCreatorModel } from '@/lib/public-creator-model'; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from '@/components/ui/select'; @@ -13,45 +15,77 @@ import { useAuth } from '@/hooks/useAuth'; import { listTemplates, listPublicAgents, cloneTemplate, CATEGORIES, - type CreatorAgent, type AgentCategory, + type AgentCategory, } from '@/lib/creator-agent'; export default function CreatorAgentTemplates() { const { user } = useAuth(); const nav = useNavigate(); - const [templates, setTemplates] = useState([]); - const [publicAgents, setPublicAgents] = useState([]); + const [templates, setTemplates] = useState([]); + const [publicAgents, setPublicAgents] = useState([]); const [loading, setLoading] = useState(true); + const [reload, setReload] = useState(0); + const [catalogErrors, setCatalogErrors] = useState({ official: false, community: false }); const [filter, setFilter] = useState<'all' | AgentCategory>('all'); const [cloning, setCloning] = useState(null); + const copying = useRef(false); + const copyIds = useRef(new Map()); + const mounted = useRef(true); + const currentUserId = useRef(user?.id); + currentUserId.current = user?.id; useEffect(() => { - (async () => { - try { - const [t, p] = await Promise.all([listTemplates(), listPublicAgents()]); - setTemplates(t); - setPublicAgents(p); - } catch (e) { - toast.error('Erreur', { description: e instanceof Error ? e.message : String(e) }); - } finally { - setLoading(false); - } - })(); + mounted.current = true; + return () => { mounted.current = false; }; }, []); - const handleClone = async (tpl: CreatorAgent) => { - if (!user) return; + useEffect(() => { + let active = true; + setLoading(true); + Promise.allSettled([listTemplates(), listPublicAgents()]).then(([official, community]) => { + if (!active) return; + setTemplates(official.status === 'fulfilled' ? official.value : []); + setPublicAgents(community.status === 'fulfilled' ? community.value : []); + setCatalogErrors({ official: official.status === 'rejected', community: community.status === 'rejected' }); + setLoading(false); + }); + return () => { active = false; }; + }, [reload]); + + const handleClone = async (tpl: PublicCreatorModel) => { + if (!user || copying.current) return; + const owner = user.id; + const key = `${owner}:${tpl.id}`; + copying.current = true; setCloning(tpl.id); try { - const clone = await cloneTemplate(user.id, tpl.id); + let copyId = copyIds.current.get(key); + if (!copyId) { + copyId = crypto.randomUUID(); + copyIds.current.set(key, copyId); + } + const clone = await cloneTemplate(owner, tpl.id, copyId); + if (!mounted.current || currentUserId.current !== owner) return; toast.success(`✅ ${clone.name} cloné`); nav(`/dashboard/creator-agent/${clone.id}`); - } catch (e) { - toast.error('Erreur', { description: e instanceof Error ? e.message : String(e) }); - } finally { setCloning(null); } + } catch (error) { + if (mounted.current && currentUserId.current === owner) { + const code = error && typeof error === 'object' && 'code' in error ? error.code : undefined; + if (code === 'P0002') { + setTemplates(items => items.filter(item => item.id !== tpl.id)); + setPublicAgents(items => items.filter(item => item.id !== tpl.id)); + toast.error('Ce modèle n’est plus disponible.'); + } else { + toast.error('Copie non confirmée', { description: 'Réessayez pour retrouver la même copie.' }); + } + } + } finally { + copying.current = false; + if (mounted.current) setCloning(null); + } }; - const filtered = (list: CreatorAgent[]) => + const filtered = (list: PublicCreatorModel[]) => filter === 'all' ? list : list.filter(a => a.category === filter); return ( @@ -81,26 +115,39 @@ export default function CreatorAgentTemplates() {
) : ( <> + {(catalogErrors.official || catalogErrors.community) && ( +
+

+ {catalogErrors.official && catalogErrors.community + ? 'Le catalogue est temporairement indisponible.' + : 'Une partie du catalogue n’a pas pu être chargée. Les modèles disponibles restent accessibles.'} +

+ +
+ )} {/* Templates Purama */}

⭐ Templates officiels Purama

{filtered(templates).map(t => ( - handleClone(t)} cloning={cloning === t.id} /> + handleClone(t)} cloning={cloning === t.id} disabled={cloning !== null} /> ))} - {filtered(templates).length === 0 && ( + {catalogErrors.official ? ( +

Modèles PURAMA indisponibles pour le moment.

+ ) : filtered(templates).length === 0 && (

Aucun template dans cette catégorie.

)}
{/* Public agents */} - {publicAgents.length > 0 && ( + {(publicAgents.length > 0 || catalogErrors.community) && (

🌍 Partagés par la communauté

+ {catalogErrors.community &&

Modèles de la communauté indisponibles pour le moment.

} {filtered(publicAgents).map(a => ( - handleClone(a)} cloning={cloning === a.id} /> + handleClone(a)} cloning={cloning === a.id} disabled={cloning !== null} /> ))}
@@ -112,11 +159,12 @@ export default function CreatorAgentTemplates() { } function TemplateCard({ - agent, onClone, cloning, + agent, onClone, cloning, disabled, }: { - agent: CreatorAgent; + agent: PublicCreatorModel; onClone: () => void; cloning: boolean; + disabled: boolean; }) { const cat = CATEGORIES.find(c => c.value === agent.category); return ( @@ -135,10 +183,16 @@ function TemplateCard({ {agent.description && (

{agent.description}

)} - +
+ + Voir la présentation publique + + +
); diff --git a/src/pages/Login.tsx b/src/pages/Login.tsx index 08cbf5a1..6ba38797 100644 --- a/src/pages/Login.tsx +++ b/src/pages/Login.tsx @@ -1,4 +1,4 @@ -import { useState } from 'react'; +import { useEffect, useRef, useState } from 'react'; import { Link, useNavigate, useLocation } from 'react-router-dom'; import { motion } from 'framer-motion'; import { useAuth } from '@/hooks/useAuth'; @@ -7,42 +7,65 @@ import { Input } from '@/components/ui/input'; import { Label } from '@/components/ui/label'; import { toast } from 'sonner'; import { Mail, Lock, Loader2, Sparkles } from 'lucide-react'; -import { safeInternalPath } from '@/lib/safeNavigation'; +import { authPagePath, resolveAuthContinuation } from '@/lib/auth-continuation'; export default function Login() { const [email, setEmail] = useState(''); const [password, setPassword] = useState(''); const [isLoading, setIsLoading] = useState(false); + const [isGoogleLoading, setIsGoogleLoading] = useState(false); + const submitting = useRef(false); + const mounted = useRef(true); const { signIn, signInWithGoogle } = useAuth(); const navigate = useNavigate(); const location = useLocation(); - const from = safeInternalPath(location.state?.from?.pathname, '/dashboard'); + const from = resolveAuthContinuation(location.search, location.state?.from); + const isPending = isLoading || isGoogleLoading; + + useEffect(() => { + mounted.current = true; + return () => { mounted.current = false; }; + }, []); const handleSubmit = async (e: React.FormEvent) => { e.preventDefault(); + if (submitting.current) return; + submitting.current = true; setIsLoading(true); - - const { error } = await signIn(email, password); - - if (error) { - toast.error('Erreur de connexion', { - description: error.message, + try { + const { error } = await signIn(email, password); + if (!mounted.current) return; + if (error) { + toast.error('Erreur de connexion', { description: error.message }); + } else { + toast.success('Connexion réussie !'); + navigate(from, { replace: true }); + } + } catch (error) { + if (mounted.current) toast.error('Erreur de connexion', { + description: error instanceof Error ? error.message : 'La connexion est indisponible. Réessayez.', }); - } else { - toast.success('Connexion réussie !'); - navigate(from, { replace: true }); + } finally { + submitting.current = false; + if (mounted.current) setIsLoading(false); } - - setIsLoading(false); }; const handleGoogleSignIn = async () => { - const { error } = await signInWithGoogle(); - if (error) { - toast.error('Erreur Google', { - description: error.message, + if (submitting.current) return; + submitting.current = true; + setIsGoogleLoading(true); + try { + const { error } = await signInWithGoogle(from); + if (error && mounted.current) toast.error('Erreur Google', { description: error.message }); + } catch (error) { + if (mounted.current) toast.error('Erreur Google', { + description: error instanceof Error ? error.message : 'Google est indisponible. Réessayez.', }); + } finally { + submitting.current = false; + if (mounted.current) setIsGoogleLoading(false); } }; @@ -75,15 +98,17 @@ export default function Login() { variant="outline" className="w-full mb-6 h-12 border-border hover:border-primary/50 hover:bg-primary/5" onClick={handleGoogleSignIn} + disabled={isPending} + aria-busy={isGoogleLoading} aria-label="Se connecter avec Google" > - } + {isGoogleLoading ? 'Ouverture de Google…' : 'Continuer avec Google'}
@@ -96,7 +121,7 @@ export default function Login() {
{/* Email Form */} -
+
@@ -106,6 +131,8 @@ export default function Login() { type="email" placeholder="vous@exemple.com" value={email} + disabled={isPending} + autoComplete="email" onChange={(e) => setEmail(e.target.value)} className="pl-10 h-12 bg-secondary border-border text-foreground placeholder:text-muted-foreground" required @@ -122,6 +149,8 @@ export default function Login() { type="password" placeholder="••••••••" value={password} + disabled={isPending} + autoComplete="current-password" onChange={(e) => setPassword(e.target.value)} className="pl-10 h-12 bg-secondary border-border text-foreground placeholder:text-muted-foreground" required @@ -141,7 +170,8 @@ export default function Login() { + + )} + + {status === 'unavailable' && ( +
+

Ce modèle n’est plus disponible

+

Le lien est invalide ou son auteur a retiré le modèle.

+ +
+ )} + + {status === 'ready' && model && ( + <> +
+
+
+
+ {model.is_template ? 'Modèle PURAMA' : 'Modèle partagé'} + {category && {category.label}} +
+
+ +

{model.name}

+
+ {model.description &&

{model.description}

} + +
+

+

+ {authLoading ? ( + + ) : user ? ( + + ) : ( +
+ +

Déjà un compte ? Se connecter et revenir à ce modèle

+
+ )} + {copyError &&

{copyError}

} +
+
+
+ +
+

Partager ce modèle

+

Le destinataire peut consulter cette présentation avant de créer son compte.

+ +
+ + )} +
+ + ); +} diff --git a/src/pages/Signup.tsx b/src/pages/Signup.tsx index 0a3403a6..800f0562 100644 --- a/src/pages/Signup.tsx +++ b/src/pages/Signup.tsx @@ -1,5 +1,5 @@ -import { useState } from 'react'; -import { Link, useNavigate } from 'react-router-dom'; +import { useEffect, useRef, useState } from 'react'; +import { Link, useLocation, useNavigate } from 'react-router-dom'; import { motion } from 'framer-motion'; import { useAuth } from '@/hooks/useAuth'; import { Button } from '@/components/ui/button'; @@ -8,6 +8,7 @@ import { Label } from '@/components/ui/label'; import { Checkbox } from '@/components/ui/checkbox'; import { toast } from 'sonner'; import { Mail, Lock, User, Loader2, Sparkles } from 'lucide-react'; +import { authPagePath, resolveAuthContinuation } from '@/lib/auth-continuation'; export default function Signup() { const [fullName, setFullName] = useState(''); @@ -16,11 +17,23 @@ export default function Signup() { const [confirmPassword, setConfirmPassword] = useState(''); const [acceptedTerms, setAcceptedTerms] = useState(false); const [isLoading, setIsLoading] = useState(false); + const [isGoogleLoading, setIsGoogleLoading] = useState(false); + const submitting = useRef(false); + const mounted = useRef(true); const { signUp, signInWithGoogle } = useAuth(); const navigate = useNavigate(); + const location = useLocation(); + const from = resolveAuthContinuation(location.search, location.state?.from); + const isPending = isLoading || isGoogleLoading; + + useEffect(() => { + mounted.current = true; + return () => { mounted.current = false; }; + }, []); const handleSubmit = async (e: React.FormEvent) => { e.preventDefault(); + if (submitting.current) return; if (!fullName.trim()) { toast.error('Veuillez entrer votre nom complet'); @@ -42,30 +55,48 @@ export default function Signup() { return; } + submitting.current = true; setIsLoading(true); - - const { error } = await signUp(email, password, fullName); - - if (error) { - toast.error('Erreur d\'inscription', { - description: error.message, + try { + const { error, hasSession } = await signUp(email, password, fullName.trim(), from); + if (!mounted.current) return; + if (error) { + toast.error('Erreur d\'inscription', { description: error.message }); + } else if (hasSession) { + toast.success('Inscription réussie !'); + navigate(from, { replace: true }); + } else { + // A confirmation request is not proof of an authenticated session or of + // a newly created account (the provider also protects existing users). + toast.success('Vérifiez votre email pour continuer', { + description: 'Confirmez votre adresse si nécessaire, puis connectez-vous pour reprendre votre parcours.', + }); + navigate(authPagePath('/login', from), { replace: true }); + } + } catch (error) { + if (mounted.current) toast.error('Erreur d\'inscription', { + description: error instanceof Error ? error.message : 'L’inscription est indisponible. Réessayez.', }); - } else { - toast.success('Compte créé avec succès !', { - description: 'Vérifiez votre email pour confirmer votre compte.', - }); - navigate('/login'); + } finally { + submitting.current = false; + if (mounted.current) setIsLoading(false); } - - setIsLoading(false); }; const handleGoogleSignIn = async () => { - const { error } = await signInWithGoogle(); - if (error) { - toast.error('Erreur Google', { - description: error.message, + if (submitting.current) return; + submitting.current = true; + setIsGoogleLoading(true); + try { + const { error } = await signInWithGoogle(from); + if (error && mounted.current) toast.error('Erreur Google', { description: error.message }); + } catch (error) { + if (mounted.current) toast.error('Erreur Google', { + description: error instanceof Error ? error.message : 'Google est indisponible. Réessayez.', }); + } finally { + submitting.current = false; + if (mounted.current) setIsGoogleLoading(false); } }; @@ -98,15 +129,17 @@ export default function Signup() { variant="outline" className="w-full mb-6 h-12 border-border hover:border-primary/50 hover:bg-primary/5" onClick={handleGoogleSignIn} + disabled={isPending} + aria-busy={isGoogleLoading} aria-label="S'inscrire avec Google" > - } + {isGoogleLoading ? 'Ouverture de Google…' : 'Continuer avec Google'}
@@ -119,7 +152,7 @@ export default function Signup() {
{/* Email Form */} - +
@@ -129,6 +162,8 @@ export default function Signup() { type="text" placeholder="Jean Dupont" value={fullName} + disabled={isPending} + autoComplete="name" onChange={(e) => setFullName(e.target.value)} className="pl-10 h-12 bg-secondary border-border text-foreground placeholder:text-muted-foreground" required @@ -146,6 +181,8 @@ export default function Signup() { type="email" placeholder="vous@exemple.com" value={email} + disabled={isPending} + autoComplete="email" onChange={(e) => setEmail(e.target.value)} className="pl-10 h-12 bg-secondary border-border text-foreground placeholder:text-muted-foreground" required @@ -163,6 +200,8 @@ export default function Signup() { type="password" placeholder="••••••••" value={password} + disabled={isPending} + autoComplete="new-password" onChange={(e) => setPassword(e.target.value)} className="pl-10 h-12 bg-secondary border-border text-foreground placeholder:text-muted-foreground" required @@ -180,6 +219,8 @@ export default function Signup() { type="password" placeholder="••••••••" value={confirmPassword} + disabled={isPending} + autoComplete="new-password" onChange={(e) => setConfirmPassword(e.target.value)} className="pl-10 h-12 bg-secondary border-border text-foreground placeholder:text-muted-foreground" required @@ -193,6 +234,7 @@ export default function Signup() { setAcceptedTerms(checked === true)} className="mt-1" /> @@ -208,7 +250,8 @@ export default function Signup() {