Compare commits
28 commits
e8c3221cb3
...
2ab317fa9a
| Author | SHA1 | Date | |
|---|---|---|---|
| 2ab317fa9a | |||
| c50c0fe11c | |||
| 156aeadf88 | |||
| 2965ad8eab | |||
| ae3f0b4095 | |||
| 9b877a16f5 | |||
| 254b14ea4c | |||
| 0e159da47a | |||
| 1d6f6e1544 | |||
| 74b8d27b6c | |||
| 4158f6f9d6 | |||
| 23da49fdc7 | |||
| ae4eaa1e5b | |||
| 10c118496b | |||
| 8c6955119d | |||
| c98e68be7a | |||
| 7c9fd0be35 | |||
| 97e856189a | |||
| e9164b323c | |||
| abfbf02199 | |||
| 2fa90072dc | |||
| 65158b0ca7 | |||
| de3ee9936b | |||
| b2608a8635 | |||
| a7bcbcdc33 | |||
| 637ac8ccb6 | |||
| 53edd27066 | |||
| 782fc20e57 |
73 changed files with 7300 additions and 1249 deletions
39
.env.example
39
.env.example
|
|
@ -3,22 +3,53 @@ APP_URL=https://ai.tony-averty.dev
|
||||||
PORT=3100
|
PORT=3100
|
||||||
HOST=127.0.0.1
|
HOST=127.0.0.1
|
||||||
|
|
||||||
# Google OAuth (console.cloud.google.com > Identifiants > ID client OAuth "Application Web")
|
# Connexion Google (console.cloud.google.com > Identifiants > ID client OAuth "Application Web")
|
||||||
# URI de redirection autorisée : https://ai.tony-averty.dev/auth/google/callback
|
# URI de redirection autorisée : https://ai.tony-averty.dev/auth/google/callback
|
||||||
GOOGLE_CLIENT_ID=
|
GOOGLE_CLIENT_ID=
|
||||||
GOOGLE_CLIENT_SECRET=
|
GOOGLE_CLIENT_SECRET=
|
||||||
|
|
||||||
# Seuls ces emails peuvent se connecter (séparés par des virgules)
|
# Connexion Apple (facultatif : sans ces 4 variables, le bouton Apple est masqué ; toutes ou aucune)
|
||||||
ALLOWED_EMAILS=tony.prive35@gmail.com
|
# developer.apple.com > Identifiers > Services IDs (APPLE_CLIENT_ID), Keys > Sign in with Apple (APPLE_KEY_ID + fichier .p8)
|
||||||
|
# Domaine et URL de retour à déclarer : https://ai.tony-averty.dev/auth/apple/callback
|
||||||
|
# APPLE_PRIVATE_KEY : contenu du .p8 sur UNE ligne, les retours à la ligne écrits \n
|
||||||
|
APPLE_TEAM_ID=
|
||||||
|
APPLE_KEY_ID=
|
||||||
|
APPLE_CLIENT_ID=
|
||||||
|
APPLE_PRIVATE_KEY=
|
||||||
|
|
||||||
|
# Administrateurs (séparés par des virgules). Tout le monde peut créer un compte en se connectant ;
|
||||||
|
# seuls ces emails sont admins (mode « Claude du serveur » : la configuration du CLI de cette machine).
|
||||||
|
# Le premier devient aussi propriétaire des données existantes lors de la migration vers les comptes.
|
||||||
|
ADMIN_EMAILS=tony.prive35@gmail.com
|
||||||
|
|
||||||
# Clé de chiffrement des secrets stockés en BDD (mots de passe SMTP/BDD, token Forgejo)
|
# Clé de chiffrement des secrets stockés en BDD (mots de passe SMTP/BDD, token Forgejo)
|
||||||
# Générer avec : node -e "console.log(require('crypto').randomBytes(32).toString('hex'))"
|
# Générer avec : node -e "console.log(require('crypto').randomBytes(32).toString('hex'))"
|
||||||
SECRET_KEY=
|
SECRET_KEY=
|
||||||
|
|
||||||
# Dossier des données (SQLite + clones Git). Idéalement sur un SSD USB.
|
# Base de données MySQL / MariaDB (créée dans CloudPanel : Databases > Add Database)
|
||||||
|
# Les tables sont créées et mises à jour au démarrage (migrations versionnées).
|
||||||
|
DB_HOST=127.0.0.1
|
||||||
|
DB_PORT=3306
|
||||||
|
DB_USER=aitools
|
||||||
|
DB_PASSWORD=
|
||||||
|
DB_NAME=aitools
|
||||||
|
|
||||||
|
# Dossier des clones Git des projets analysés (la base de données n'y est plus stockée)
|
||||||
DATA_DIR=./data
|
DATA_DIR=./data
|
||||||
|
|
||||||
# Claude Code headless
|
# Claude Code headless
|
||||||
CLAUDE_BIN=claude
|
CLAUDE_BIN=claude
|
||||||
|
# Mode « Connexion avec Claude (abonnement) » : true (défaut) ou false. À false, il est masqué et refusé côté serveur.
|
||||||
|
CLAUDE_CLI_MODE_ENABLED=true
|
||||||
|
|
||||||
|
# Environnement : en production (NODE_ENV=production) tout job IA passe par bubblewrap et est refusé si bwrap manque.
|
||||||
|
# Posé par deploy/aitools.service ; à poser à la main sous un autre gestionnaire de processus.
|
||||||
|
# NODE_ENV=production
|
||||||
|
# Développement seulement : SANDBOX=off lance Claude sans bac à sable (ignoré en production, avertissement au démarrage).
|
||||||
|
# SANDBOX=off
|
||||||
|
# Dossiers supplémentaires montés en lecture seule dans le bac à sable (ex. Node ou le CLI installés hors de /usr), séparés par des virgules
|
||||||
|
# SANDBOX_RO_BINDS=
|
||||||
|
# Binaire bubblewrap si hors du PATH
|
||||||
|
# BWRAP_BIN=bwrap
|
||||||
# Pause des jobs au-delà de cette température CPU (°C)
|
# Pause des jobs au-delà de cette température CPU (°C)
|
||||||
THERMAL_MAX=75
|
THERMAL_MAX=75
|
||||||
|
|
|
||||||
113
README.md
113
README.md
|
|
@ -1,13 +1,15 @@
|
||||||
# AiTools
|
# AiTools
|
||||||
|
|
||||||
Panel perso pour piloter Claude Code (headless) sur mes projets : prospection client par email,
|
Panel pour piloter Claude Code (headless) sur des projets : prospection client par email,
|
||||||
idées d'évolutions et récap business. Pensé pour un **Raspberry Pi 4 sans ventilateur**.
|
idées d'évolutions et récap business. L'instance perso tourne sur un Raspberry Pi 4 sans ventilateur ;
|
||||||
|
la version publique cible un serveur CloudPanel avec une base MySQL/MariaDB (voir `docs/CADRAGE.md`).
|
||||||
|
|
||||||
## Choix techniques
|
## Choix techniques
|
||||||
|
|
||||||
- **Node 22, zéro framework** : `node:http`, `node:sqlite` intégré (rien à compiler sur ARM). 3 dépendances : `nodemailer`, `mysql2`, `pg`.
|
- **Node 22, zéro framework** : `node:http`. Dépendances : `nodemailer`, `imapflow`, `mysql2`, `pg`.
|
||||||
|
- **Base MySQL / MariaDB** (`mysql2`, pool, utf8mb4, InnoDB), accès entièrement asynchrone via `src/db.js`. SQLite (`node:sqlite`, en mémoire) ne sert plus que pour les tests locaux et comme source du script de migration.
|
||||||
- **Rendu serveur + JS vanilla**, pas de build.
|
- **Rendu serveur + JS vanilla**, pas de build.
|
||||||
- **Un seul job IA à la fois** (file SQLite). Le process Claude tourne en `nice 10`. Pause automatique si le CPU dépasse `THERMAL_MAX`.
|
- **Un seul job IA à la fois** (file en base). Le process Claude tourne en `nice 10`. Pause automatique si le CPU dépasse `THERMAL_MAX`.
|
||||||
- **Économie de tokens** :
|
- **Économie de tokens** :
|
||||||
- outils Claude restreints à chaque job (lecture seule pour le code, WebSearch/WebFetch pour la prospection) ;
|
- outils Claude restreints à chaque job (lecture seule pour le code, WebSearch/WebFetch pour la prospection) ;
|
||||||
- `--max-turns` borné ;
|
- `--max-turns` borné ;
|
||||||
|
|
@ -17,12 +19,26 @@ idées d'évolutions et récap business. Pensé pour un **Raspberry Pi 4 sans ve
|
||||||
l'Évolution), uniquement quand Haiku ne suffit pas — utile avec un abonnement Pro dont le quota
|
l'Évolution), uniquement quand Haiku ne suffit pas — utile avec un abonnement Pro dont le quota
|
||||||
est limité à la semaine.
|
est limité à la semaine.
|
||||||
- **Sécurité** :
|
- **Sécurité** :
|
||||||
- login Google avec whitelist d'emails ;
|
- connexion Google ou Apple (OIDC), inscription automatique, sans mot de passe ;
|
||||||
- PKCE + state + nonce ;
|
- state + nonce (+ PKCE pour Google), id_token vérifié (signature RS256 via les JWKS du fournisseur, émetteur, audience, expiration) ;
|
||||||
|
- données cloisonnées par compte (voir « Comptes et multi-utilisateur ») ;
|
||||||
- anti-CSRF par contrôle d'`Origin` ;
|
- anti-CSRF par contrôle d'`Origin` ;
|
||||||
- secrets chiffrés en AES-256-GCM en base ;
|
- secrets chiffrés en AES-256-GCM en base ;
|
||||||
- token Forgejo jamais écrit sur disque.
|
- token Forgejo jamais écrit sur disque.
|
||||||
|
|
||||||
|
## Site public
|
||||||
|
|
||||||
|
Le site (`ai.tony-averty.dev`) est servi par la même application, dans `src/site/`, en rendu serveur sans JavaScript ni dépendance.
|
||||||
|
|
||||||
|
- **Pages** : `/` (accueil pour un visiteur, tableau de bord pour un compte connecté), `/fonctionnement`, `/tarifs`, `/login`, `/mentions-legales`, `/confidentialite`, `/cgu`, et une 404 propre. Toutes répondent sans session.
|
||||||
|
- **Identité** : `public/site.css` s'ajoute à `public/app.css` et n'utilise que ses jetons (`--bg`, `--card`, `--text`, `--muted`, `--line`, `--accent`, thème sombre compris). Pas de seconde palette : pour changer une couleur, on modifie `app.css`.
|
||||||
|
- **Textes** : `src/site/pages.js` (accueil, fonctionnement, tarifs, connexion, 404) et `src/site/legal.js` (pages légales). Les limites annoncées viennent du code ; si elles changent, relire ces textes.
|
||||||
|
- **Marqueurs** : les informations légales manquantes (adresse du siège, hébergeur, téléphone) et les points à valider s'affichent en `[À COMPLÉTER : …]` / `[À VALIDER : …]`. La liste vit dans `docs/JOURNAL.md` (« Marqueurs à compléter ») et dans `MARKERS` de `legal.js` ; un test vérifie qu'elles concordent. Pour en finir avec un marqueur, remplace-le dans `legal.js` puis retire-le des deux listes.
|
||||||
|
- **SEO** : title, description, canonical et Open Graph par page, `/robots.txt`, `/sitemap.xml`. Tout ce qui n'est pas une page publique répond `noindex` (balise et `X-Robots-Tag`).
|
||||||
|
- **En-têtes** : CSP stricte (aucun style ni script en ligne, aucune ressource externe), `X-Content-Type-Options`, `Referrer-Policy`, `Permissions-Policy`, `frame-ancestors 'none'`. HSTS seulement si `APP_URL` commence par `https://`. Les fichiers statiques ont un ETag (réponse 304).
|
||||||
|
- **Ajouter une page** : une fonction dans `pages.js` qui appelle `siteLayout`, une route dans `src/site/routes.js`, et son chemin dans `INDEXABLE_PATHS` (`src/site/seo.js`) si elle doit être référencée.
|
||||||
|
- **Essayer en local** : `APP_URL=http://localhost:3199 PORT=3199 SECRET_KEY=<64 hexa> GOOGLE_CLIENT_ID=x GOOGLE_CLIENT_SECRET=y DB_DRIVER=sqlite SANDBOX=off node src/server.js` (base SQLite en mémoire, perdue à l'arrêt).
|
||||||
|
|
||||||
## Suivi des réponses, relances et test A/B
|
## Suivi des réponses, relances et test A/B
|
||||||
|
|
||||||
- **Détection des réponses** : la boîte de réception du projet est lue en IMAP toutes les 15 minutes, et à la demande avec « Vérifier maintenant ».
|
- **Détection des réponses** : la boîte de réception du projet est lue en IMAP toutes les 15 minutes, et à la demande avec « Vérifier maintenant ».
|
||||||
|
|
@ -113,7 +129,78 @@ idées d'évolutions et récap business. Pensé pour un **Raspberry Pi 4 sans ve
|
||||||
- La liste d'opposition vaut pour tous les projets. Un statut « Refus » y ajoute aussi l'adresse.
|
- La liste d'opposition vaut pour tous les projets. Un statut « Refus » y ajoute aussi l'adresse.
|
||||||
- La source publique de l'email est stockée et rappelée dans le pied de mail (RGPD).
|
- La source publique de l'email est stockée et rappelée dans le pied de mail (RGPD).
|
||||||
|
|
||||||
## Installation sur le Pi
|
## Comptes et multi-utilisateur
|
||||||
|
|
||||||
|
- **Connexion** : Google ou Apple, sans mot de passe. Le compte est créé à la première connexion réussie (plan gratuit). Un même email ne se lie qu'à un seul fournisseur ; un compte suspendu ne peut plus se connecter et ses sessions tombent aussitôt.
|
||||||
|
- **Cloisonnement** : projets, prospects, notes, modèles, journaux d'envoi, jobs, métriques et **réglages** (SMTP, Discord, budget IA, plafonds, hôte Forgejo…) sont propres à chaque compte. Toute requête est filtrée par l'utilisateur courant ; la ressource d'un autre compte répond « introuvable » (404). Un même dépôt Git peut être un projet pour deux comptes (unicité par utilisateur).
|
||||||
|
- **Liste d'opposition** : volontairement commune à tous les comptes (une personne désinscrite ne doit plus être contactée par personne). Un compte n'y voit que le nombre de ses propres prospects concernés, jamais l'origine ni le motif d'un autre compte.
|
||||||
|
- **Liaison Claude obligatoire** : après la connexion, un compte sans liaison valide est renvoyé vers `/link` et ne peut rien utiliser d'autre que cette page, Mon compte, la déconnexion et la suppression du compte (garde côté serveur sur toutes les routes, dans la file, le worker et le wrapper d'exécution). Voir « Liaison Claude et exécution isolée ».
|
||||||
|
- **Mon compte** (`/account`) : email, fournisseur, état de la liaison Claude (mode, dates, valide ou non, 4 derniers caractères de la clé API) avec Tester, Changer de mode et Délier, et suppression du compte (confirmation par saisie de l'email). Elle efface tout : projets, prospects, notes, modèles, journaux, jobs, réglages, sessions et clones Git. Seule la liste d'opposition est conservée.
|
||||||
|
|
||||||
|
### Liaison Claude et exécution isolée
|
||||||
|
|
||||||
|
Chaque utilisateur relie SON accès ; ses jobs IA tournent avec cet accès uniquement.
|
||||||
|
|
||||||
|
- **Clé API Anthropic** (recommandé) : vérifiée par `GET /v1/models` (aucun token consommé), chiffrée AES-256-GCM dans `users.claude_link_json`, jamais réaffichée. Passée par `ANTHROPIC_API_KEY` au seul processus enfant, jamais écrite sur disque. Pas de barre de quota d'abonnement dans ce mode.
|
||||||
|
- **Connexion avec Claude (abonnement)** : une fenêtre d'avertissement (risque pour le compte Claude au regard des conditions d'Anthropic) impose de cocher « J'ai compris et j'accepte ce risque » ; l'acceptation est horodatée avec la version du texte. L'utilisateur génère un jeton sur sa machine avec `claude setup-token` et le colle ; il est vérifié par un appel minimal du CLI (quelques tokens décomptés de l'abonnement), chiffré, et passé par `CLAUDE_CODE_OAUTH_TOKEN` au seul processus enfant. `CLAUDE_CLI_MODE_ENABLED=false` masque ce mode et le refuse côté serveur.
|
||||||
|
- **Claude du serveur** (admins de `ADMIN_EMAILS`) : la configuration du CLI de la machine, comme avant.
|
||||||
|
- **Bac à sable** : chaque job passe par bubblewrap (racine reconstruite en lecture seule, `/tmp` et `HOME` vides, seul le clone du projet de l'utilisateur monté en lecture seule, PID/IPC/UTS isolés, réseau conservé) avec un environnement en liste blanche (`PATH`, `LANG`, `HOME` jetable, le secret de l'utilisateur). En production le job est refusé si `bwrap` manque ; `SANDBOX=off` ne vaut qu'en développement. Installation : `apt install bubblewrap`. Si Node ou le CLI sont installés hors de `/usr`, liste leurs dossiers dans `SANDBOX_RO_BINDS`.
|
||||||
|
- **Clones git** d'URL fournies par les utilisateurs : https uniquement (`GIT_ALLOW_PROTOCOL=https`), pas de hooks ni de sous-modules, 2 minutes et 300 Mo au plus.
|
||||||
|
- **Quota, budget IA, pauses et notifications** sont propres à chaque compte.
|
||||||
|
|
||||||
|
### Connexion Google et Apple
|
||||||
|
|
||||||
|
- **Google** : voir « Google OAuth » plus bas. URI de redirection : `https://<domaine>/auth/google/callback`.
|
||||||
|
- **Apple** (facultatif) : dans developer.apple.com, crée un *Services ID* (c'est `APPLE_CLIENT_ID`), active « Sign in with Apple » avec ton domaine et l'URL de retour `https://<domaine>/auth/apple/callback`, puis une clé *Sign in with Apple* : son identifiant est `APPLE_KEY_ID`, le fichier `.p8` va dans `APPLE_PRIVATE_KEY` sur une seule ligne (retours à la ligne écrits `\n`). `APPLE_TEAM_ID` est l'identifiant d'équipe. Le secret client (JWT ES256) est généré à chaque connexion, rien n'est stocké. Apple répond par un POST cross-site : le flux est protégé par state, nonce et un cookie de liaison `SameSite=None` limité à `/auth`.
|
||||||
|
|
||||||
|
## Installation sur un serveur (CloudPanel ou autre, sans Raspberry)
|
||||||
|
|
||||||
|
Pré-requis : Node 22.13 ou plus, git, la CLI `claude` si les jobs IA doivent tourner sur ce serveur, et une base MySQL 8.0.16 ou plus / MariaDB 10.4 ou plus (contraintes `CHECK`).
|
||||||
|
|
||||||
|
1. **Base de données** : dans CloudPanel, Databases > Add Database. Note le nom, l'utilisateur et le mot de passe. Les tables sont créées par l'application au premier démarrage, rien à importer à la main.
|
||||||
|
2. **Code** :
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git clone -b develop https://git.tony-averty.dev/Tony/AiTools.git
|
||||||
|
cd AiTools
|
||||||
|
npm ci --omit=dev
|
||||||
|
cp .env.example .env # puis renseigne le fichier, voir ci-dessous
|
||||||
|
chmod 600 .env
|
||||||
|
```
|
||||||
|
|
||||||
|
3. **Variables d'environnement** (`.env`, jamais commité) :
|
||||||
|
|
||||||
|
| Variable | Rôle |
|
||||||
|
|---|---|
|
||||||
|
| `DB_HOST`, `DB_PORT` (3306 par défaut), `DB_USER`, `DB_PASSWORD`, `DB_NAME` | connexion MySQL / MariaDB |
|
||||||
|
| `SECRET_KEY` | clé AES-256-GCM (64 caractères hexa) des secrets stockés en base |
|
||||||
|
| `APP_URL`, `PORT`, `HOST` | URL publique et écoute locale (reverse proxy Nginx devant) |
|
||||||
|
| `GOOGLE_CLIENT_ID`, `GOOGLE_CLIENT_SECRET` | connexion Google (voir « Connexion Google et Apple ») |
|
||||||
|
| `APPLE_TEAM_ID`, `APPLE_KEY_ID`, `APPLE_CLIENT_ID`, `APPLE_PRIVATE_KEY` | connexion Apple, facultative : les quatre ou aucune (sans elles, le bouton Apple est masqué) |
|
||||||
|
| `ADMIN_EMAILS` | emails des administrateurs, séparés par des virgules. Le premier est aussi propriétaire des données migrées. Remplace `ALLOWED_EMAILS`, supprimée : n'importe qui peut créer un compte |
|
||||||
|
| `CLAUDE_CLI_MODE_ENABLED` | `true` (défaut) ou `false` : active le mode abonnement |
|
||||||
|
| `NODE_ENV`, `SANDBOX`, `SANDBOX_RO_BINDS`, `BWRAP_BIN` | bac à sable : obligatoire en production, `SANDBOX=off` en développement seulement |
|
||||||
|
| `DATA_DIR` | clones Git des projets analysés, rangés par utilisateur (`repos/<utilisateur>/<projet>`) |
|
||||||
|
|
||||||
|
4. **Démarrage** : `npm start`. Au lancement, les migrations en attente sont appliquées (table `schema_migrations`, verrou pour éviter deux migrations simultanées). Lance le service sous un gestionnaire de processus (systemd ou celui de CloudPanel) et mets un reverse proxy TLS devant `HOST:PORT`.
|
||||||
|
5. **Sauvegardes** : sauvegarde quotidienne de la base avec `mysqldump --single-transaction` (ou la sauvegarde CloudPanel) ; teste une restauration.
|
||||||
|
|
||||||
|
### Reprendre les données de l'ancienne instance SQLite
|
||||||
|
|
||||||
|
Arrête l'ancien service, puis, avec le `.env` pointant sur la nouvelle base :
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm run migrate:sqlite -- data/aitools.sqlite # refuse si la base cible contient déjà des données
|
||||||
|
npm run migrate:sqlite -- data/aitools.sqlite --force # vide les tables cibles avant la copie
|
||||||
|
```
|
||||||
|
|
||||||
|
Toutes les tables sont copiées dans une seule transaction, ids conservés, avec un rapport de lignes par table. En cas d'écart ou d'erreur, rien n'est écrit. L'ancienne base est mono-utilisateur : tout est rattaché au compte propriétaire (première adresse de `ADMIN_EMAILS`, créé s'il n'existe pas) et les anciens réglages deviennent les siens. Les sessions de l'ancienne base ne sont pas copiées : reconnecte-toi. Les clones Git sont à recloner : le dossier est maintenant `DATA_DIR/repos/<utilisateur>/<projet>`.
|
||||||
|
|
||||||
|
Une base MySQL/MariaDB déjà utilisée **avant les comptes** (migration 1) se met à niveau toute seule au démarrage : la migration « comptes_multi_tenant » rattache ses données au propriétaire (`ADMIN_EMAILS` doit alors être défini, sinon le démarrage s'arrête avec un message clair). Au premier login Google ou Apple avec cet email, tu retrouves tes données.
|
||||||
|
|
||||||
|
## Installation sur le Pi (instance perso, héritage)
|
||||||
|
|
||||||
|
> `install.sh` date de la version SQLite : il ne renseigne pas encore les variables `DB_*` ni ne sauvegarde MySQL. À reprendre avec le déploiement (jalon J6) ; en attendant, suis la section ci-dessus.
|
||||||
|
|
||||||
Pré-requis : **Raspberry Pi OS Lite 64 bits** fraîchement installé, accès SSH, et ton HDD branché.
|
Pré-requis : **Raspberry Pi OS Lite 64 bits** fraîchement installé, accès SSH, et ton HDD branché.
|
||||||
|
|
||||||
|
|
@ -199,4 +286,16 @@ npm run check # lint + tests
|
||||||
|
|
||||||
Les tests utilisent un faux binaire Claude (`test/fixtures/fake-claude.js`) : aucun token consommé.
|
Les tests utilisent un faux binaire Claude (`test/fixtures/fake-claude.js`) : aucun token consommé.
|
||||||
|
|
||||||
|
Par défaut ils tournent sur SQLite en mémoire, sans rien à installer. Pour les rejouer contre un vrai MySQL/MariaDB :
|
||||||
|
|
||||||
|
```bash
|
||||||
|
TEST_DB_HOST=127.0.0.1 TEST_DB_USER=root TEST_DB_PASSWORD=... TEST_DB_NAME=aitools_test npm run test:mysql
|
||||||
|
```
|
||||||
|
|
||||||
|
Utilise une base **dédiée aux tests** : toutes ses tables sont supprimées à chaque test. `test:mysql` force l'exécution des fichiers un par un, car ils partagent la même base.
|
||||||
|
|
||||||
|
Les tests d'isolation (`test/isolation.test.js`), de connexion (`test/auth.test.js`, fournisseurs simulés), de suppression de compte, de blocage des jobs IA et de migration des données existantes tournent avec le reste de la suite.
|
||||||
|
|
||||||
|
Le SQL est écrit dans un sous-ensemble commun aux deux moteurs (`INSERT OR IGNORE`, `ON CONFLICT ... excluded.x`, colonnes réservées entre accents graves) et `src/db.js` le traduit pour MySQL. Le schéma est déclaré deux fois dans `src/migrations.js` (SQLite et MySQL) ; `test/schema.test.js` vérifie qu'ils décrivent les mêmes tables et colonnes. Pour changer le schéma, ajoute une entrée aux deux dialectes sans modifier les précédentes.
|
||||||
|
|
||||||
`test/install.test.sh` teste les fonctions d'`install.sh` qui écrivent des fichiers : `.env`, unit systemd, migration, sauvegarde. Il tourne en root et écrit dans `/opt/aitools` et `/etc/systemd`, donc **uniquement dans une VM ou un conteneur jetable**, jamais sur le Pi en service.
|
`test/install.test.sh` teste les fonctions d'`install.sh` qui écrivent des fichiers : `.env`, unit systemd, migration, sauvegarde. Il tourne en root et écrit dans `/opt/aitools` et `/etc/systemd`, donc **uniquement dans une VM ou un conteneur jetable**, jamais sur le Pi en service.
|
||||||
|
|
|
||||||
118
docs/CADRAGE.md
Normal file
118
docs/CADRAGE.md
Normal file
|
|
@ -0,0 +1,118 @@
|
||||||
|
Statut : validé (2026-10-22)
|
||||||
|
|
||||||
|
# Cadrage — AiTools public (SaaS multi-utilisateurs)
|
||||||
|
|
||||||
|
## 1. Contexte et objectif
|
||||||
|
|
||||||
|
AiTools est aujourd'hui un panel **mono-utilisateur** (login Google en whitelist, SQLite local, Raspberry Pi) qui pilote Claude Code en headless : prospection par mail, analyse de projets, évolutions, CRM, récap business.
|
||||||
|
|
||||||
|
**Objectif** : ouvrir le produit au public. N'importe qui crée un compte sur un site web, relie son accès Claude, et utilise ses propres projets/prospects, sans voir les données des autres. Le site reprend l'identité visuelle du dashboard. La base de données est une base MySQL/MariaDB créée dans CloudPanel.
|
||||||
|
|
||||||
|
## 2. Utilisateurs / cibles
|
||||||
|
|
||||||
|
- **Visiteur** : découvre le produit sur le site public, s'inscrit.
|
||||||
|
- **Utilisateur** : freelance / agence / TPE qui prospecte pour ses propres projets.
|
||||||
|
- **Admin (Tony)** : gère les comptes, voit l'usage, peut suspendre un compte.
|
||||||
|
|
||||||
|
## 3. Périmètre
|
||||||
|
|
||||||
|
### Inclus (MoSCoW)
|
||||||
|
|
||||||
|
**Must**
|
||||||
|
- Site public : accueil, fonctionnement, tarifs/conditions (à définir), connexion, inscription. Mêmes couleurs que le dashboard (tokens `--bg #f4f5f7`, `--card`, `--text`, `--accent #2f5bea`, etc., et thème sombre `--bg #111317`, `--accent #5b82ff`), mêmes polices et composants.
|
||||||
|
- Comptes : inscription (email + mot de passe haché argon2/scrypt, ou Google), vérification d'email, réinitialisation du mot de passe, sessions, suppression de compte.
|
||||||
|
- **Liaison Claude obligatoire** à l'inscription, avec deux modes au choix de l'utilisateur :
|
||||||
|
1. **Clé API Anthropic** : saisie, test de validité par un appel minimal, stockage chiffré AES-256-GCM, jamais réaffichée.
|
||||||
|
2. **Login CLI Claude** : l'utilisateur se connecte via `claude login` dans un répertoire de config **isolé par utilisateur** (flux d'autorisation guidé dans le navigateur, URL + code collé).
|
||||||
|
Un compte non relié ne peut lancer aucun job IA (accès au profil et à la liaison uniquement).
|
||||||
|
- **Multi-tenant** : toutes les tables métier rattachées à un `user_id` ; chaque requête filtrée par utilisateur ; tests d'isolation.
|
||||||
|
- **Base MySQL CloudPanel** : migration de SQLite (`node:sqlite`) vers MySQL/MariaDB via `mysql2` (déjà en dépendance). Migrations versionnées. Identifiants en variables d'environnement.
|
||||||
|
- Isolation de l'exécution Claude par utilisateur : dossier de travail et config séparés, outils restreints (déjà le cas), pas d'accès au système de fichiers d'un autre utilisateur.
|
||||||
|
- Quotas/budgets, plafonds d'envoi et liste d'opposition **par utilisateur** (la liste d'opposition globale reste protégée côté RGPD).
|
||||||
|
- Pages légales : mentions légales, CGU, politique de confidentialité, bandeau cookies (cookies strictement nécessaires seulement, donc pas de bandeau bloquant si aucun traceur).
|
||||||
|
- Déploiement sur serveur CloudPanel : site Node avec reverse proxy Nginx, TLS, service managé, sauvegardes de la BDD.
|
||||||
|
|
||||||
|
**Should**
|
||||||
|
- Écran « Mon compte » : état de la liaison Claude (mode, dernier test, bouton délier/changer), export et suppression des données (RGPD).
|
||||||
|
- Anti-abus : limitation de débit sur login/inscription, CAPTCHA à décider (voir §8), liste d'emails jetables bloqués.
|
||||||
|
- Back-office admin : liste des comptes, suspension, usage IA par compte.
|
||||||
|
- File d'attente équitable entre utilisateurs (un seul job IA à la fois par utilisateur, plafond global serveur).
|
||||||
|
|
||||||
|
**Could**
|
||||||
|
- Paiement / abonnement (Stripe) et plans.
|
||||||
|
- Invitation sur liste d'attente avant ouverture complète.
|
||||||
|
|
||||||
|
**Won't (cette version)**
|
||||||
|
- Application mobile, API publique, organisations/équipes multi-membres.
|
||||||
|
|
||||||
|
### Hors périmètre
|
||||||
|
- Gestion du Raspberry Pi (le Pi n'exécute plus les jobs publics ; il reste utilisable pour l'instance perso).
|
||||||
|
- Conseil juridique définitif sur les CGU/RGPD : un modèle est préparé, validation par un juriste recommandée.
|
||||||
|
- Revente de crédits Claude.
|
||||||
|
|
||||||
|
## 4. Contraintes
|
||||||
|
|
||||||
|
- **Techno** : rester sur Node 22, zéro framework serveur, rendu serveur + JS vanilla (cohérent avec l'existant). Pas d'ajout de framework front.
|
||||||
|
- **Hébergement** : serveur CloudPanel (site Node + base MySQL/MariaDB CloudPanel). Ressources CPU/RAM du serveur à confirmer : les jobs Claude CLI sont lourds, d'où un plafond global de jobs simultanés.
|
||||||
|
- **Sécurité** : secrets chiffrés au repos, clé de chiffrement hors BDD, anti-CSRF, validation des entrées, en-têtes de sécurité, limitation de débit, journal d'audit minimal.
|
||||||
|
- **RGPD** : données de prospects = données personnelles traitées pour le compte de chaque utilisateur. Rôles à clarifier (l'utilisateur = responsable de traitement, AiTools = sous-traitant), DPA/CGU, durée de conservation, export/suppression, hébergement UE.
|
||||||
|
- **Accessibilité** : contrastes et navigation clavier conformes (viser RGAA/WCAG AA sur le site public).
|
||||||
|
- **Existant** : le code actuel (≈4 800 lignes) reste la base ; la migration doit garder les tests au vert (`npm run check`).
|
||||||
|
|
||||||
|
## 5. Livrables et critères d'acceptation
|
||||||
|
|
||||||
|
| Livrable | Critères vérifiables |
|
||||||
|
|---|---|
|
||||||
|
| Site public aux couleurs du dashboard | Mêmes tokens CSS clair/sombre ; pages accueil, connexion, inscription, légales accessibles sans compte ; score Lighthouse a11y ≥ 90 |
|
||||||
|
| Inscription + liaison Claude | Impossible de terminer l'onboarding sans liaison valide ; clé API invalide refusée ; clé jamais présente en clair en base ni dans les logs |
|
||||||
|
| Mode CLI par utilisateur | Config Claude stockée dans un dossier propre à l'utilisateur, permissions 700 ; un utilisateur ne peut pas lancer un job avec la config d'un autre (test automatisé) |
|
||||||
|
| Multi-tenant | Tests d'isolation : l'utilisateur A reçoit 404/403 sur toute ressource de B (projets, prospects, jobs, mails, notes, métriques) |
|
||||||
|
| BDD CloudPanel | App connectée à la base MySQL CloudPanel via variables d'environnement ; migrations rejouables ; script de migration SQLite → MySQL pour l'instance de Tony |
|
||||||
|
| Comptes | Vérification d'email, reset mot de passe, suppression de compte efface toutes les données liées |
|
||||||
|
| Légal | Mentions légales, CGU, confidentialité publiées ; aucun traceur tiers sans consentement |
|
||||||
|
| Déploiement | Site en HTTPS sur le domaine, redémarrage auto, sauvegarde BDD quotidienne testée en restauration |
|
||||||
|
| Qualité | `npm run check` vert (lint + tests) ; docs/JOURNAL.md à jour ; README mis à jour |
|
||||||
|
|
||||||
|
## 6. Risques et hypothèses
|
||||||
|
|
||||||
|
- **Risque majeur — CGU Anthropic** : les conditions d'Anthropic restreignent l'usage de l'abonnement Pro/Max d'un utilisateur via une application tierce. Le mode « login CLI » peut conduire à la **suspension du compte Claude de l'utilisateur** et exposer le service. *Décision de Tony : mode proposé quand même.* Mitigation : avertissement clair et consentement explicite avant liaison, option désactivable globalement (flag), mode clé API proposé en premier. À revérifier auprès d'Anthropic avant ouverture.
|
||||||
|
- **Sécurité du mode CLI** : exécuter des CLI avec des identifiants d'utilisateurs sur un même serveur. Mitigation : un dossier de config par utilisateur (700), outils restreints, idéalement un utilisateur système ou conteneur par compte (à trancher, impact charge).
|
||||||
|
- **Charge serveur** : jobs Claude concurrents. Mitigation : file globale avec plafond, `nice`, quotas.
|
||||||
|
- **Réputation d'envoi mail / spam** : un site public de prospection par mail peut être détourné. Mitigation : plafonds stricts par compte, désinscription obligatoire, signalement d'abus, suspension, validation manuelle des nouveaux comptes si besoin (à confirmer, §8).
|
||||||
|
- **Migration SQLite → MySQL** : différences de SQL (dates, `INSERT OR`, `AUTOINCREMENT`), synchrone → asynchrone (`node:sqlite` est synchrone, `mysql2` non) : touche une grande partie du code. Risque de régression, d'où les tests d'abord.
|
||||||
|
- **Hypothèses** : Tony fournit l'accès à CloudPanel (création de la base, du site Node, du domaine) ; un nom de domaine est disponible ; Tony reste seul exploitant.
|
||||||
|
|
||||||
|
## 7. Plan par jalons et estimation
|
||||||
|
|
||||||
|
| Jalon | Contenu | Jours |
|
||||||
|
|---|---|---|
|
||||||
|
| J1 Fondations | Branche, couche d'accès BDD asynchrone, schéma MySQL + migrations, script de migration des données de Tony | 3–4 |
|
||||||
|
| J2 Comptes | Inscription, connexion, vérification email, reset, sessions, `user_id` partout, tests d'isolation | 3–5 |
|
||||||
|
| J3 Liaison Claude | Mode clé API + mode CLI isolé, onboarding bloquant, écran de compte | 3–4 |
|
||||||
|
| J4 Site public | Accueil, pages, légales, thème identique au dashboard, accessibilité | 2–3 |
|
||||||
|
| J5 Anti-abus & admin | Rate limiting, plafonds par compte, back-office minimal, file équitable | 2–3 |
|
||||||
|
| J6 Déploiement & recette | CloudPanel, TLS, sauvegardes, recette, doc, journal | 2–3 |
|
||||||
|
| **Total** | | **15–22 jours** |
|
||||||
|
|
||||||
|
Hors paiement Stripe (Could, +3–5 j).
|
||||||
|
|
||||||
|
## 8. Décisions de Tony et points restants
|
||||||
|
|
||||||
|
### Décisions (réponses de Tony)
|
||||||
|
1. **Domaine** : `ai.tony-averty.dev`.
|
||||||
|
2. **Inscription** : validation automatique, connexion **Google ou Apple** uniquement (pas de mot de passe), puis liaison Claude obligatoire. Le §3 « email + mot de passe, vérification, reset » est donc supprimé du périmètre.
|
||||||
|
3. **Modèle** : freemium (plan gratuit limité + plan payant → le paiement passe de Could à **Should**).
|
||||||
|
4. **Isolation du mode CLI** : la plus optimisée en ressources, avec garantie qu'un utilisateur n'accède jamais au Claude d'un autre. Retenu : un seul utilisateur système, un dossier de config par compte en 700, et chaque job lancé dans un bac à sable (bubblewrap ou `systemd-run` avec montages privés) qui ne voit que le dossier de son propriétaire. Mode clé API : clé passée par variable d'environnement au processus uniquement, jamais écrite sur disque.
|
||||||
|
5. **CAPTCHA** : Google reCAPTCHA (v3). À mentionner dans la politique de confidentialité et à charger après consentement (cookies / transfert vers Google).
|
||||||
|
6. **Ressources serveur** (mesurées) : 6 cœurs Xeon E5-2697 v3, 21 Go de RAM (≈ 18 Go disponibles), 271 Go de disque libre, Node 22.23. Plafond global retenu : **4 jobs Claude simultanés**, en gardant 2 cœurs pour MySQL, Nginx et les autres sites CloudPanel. `bubblewrap` n'est pas installé : à ajouter (`apt install bubblewrap`) et à tester (user namespaces non privilégiés).
|
||||||
|
7. **Raspberry Pi** : plus rien dessus. Tout tourne sur CloudPanel ; l'instance de Tony est migrée dans le SaaS (Tony = admin). Les contraintes thermiques (`thermal.js`, `nice`) sont remplacées par des limites serveur.
|
||||||
|
|
||||||
|
### Décisions complémentaires
|
||||||
|
8. **Plan gratuit** : 1 projet, 50 prospects, 100 mails/mois, 5 jobs IA/mois. Prix du plan payant : à fixer avant l'ouverture des paiements (jalon Stripe).
|
||||||
|
9. **Apple** : compte Apple Developer disponible → Google **et** Apple dès la première version.
|
||||||
|
10. **Mode login CLI** : au clic sur « Connecter via Claude CLI », une fenêtre d'avertissement s'affiche (risque de suspension du compte Claude au regard des conditions d'Anthropic). L'utilisateur doit cocher une case d'acceptation des risques pour continuer ; l'acceptation est horodatée en base. Les CGU contiennent la clause correspondante. Flag global pour désactiver ce mode. *Note : la case et les CGU documentent le consentement mais ne garantissent pas juridiquement l'exonération totale ; relecture juridique recommandée.*
|
||||||
|
|
||||||
|
### Points restants
|
||||||
|
- **Prix du plan payant** (avant le jalon Stripe).
|
||||||
|
- **Pages légales** : infos EI fournies (SIRET connu) ; relecture juridique ou non.
|
||||||
|
- **Installation de bubblewrap** sur le serveur et test (voir point 6).
|
||||||
160
docs/JOURNAL.md
Normal file
160
docs/JOURNAL.md
Normal file
|
|
@ -0,0 +1,160 @@
|
||||||
|
# Journal de projet — AiTools
|
||||||
|
|
||||||
|
Branches de travail : `feat/saas-mysql` (J1), `feat/saas-accounts` (J2, depuis la précédente) `feat/saas-claude-link` (J3, depuis J2) puis `feat/saas-site` (J4, depuis J3) — version publique, voir `docs/CADRAGE.md`.
|
||||||
|
|
||||||
|
## 2026-10-22 — J4 « Site public »
|
||||||
|
|
||||||
|
### Fait
|
||||||
|
- **Site servi par la même application** (`src/site/`), rendu serveur, zéro JavaScript sur les pages publiques, zéro dépendance. Un visiteur sans session voit le site à la racine ; connecté, `/` mène au tableau de bord (et à l'onboarding de liaison si besoin) comme avant. `/login` renvoie vers `/` si on est déjà connecté.
|
||||||
|
- **Pages** : accueil (avec une maquette du tableau de bord construite avec les vrais composants, données d'exemple signalées), fonctionnement (7 étapes, limites annoncées), tarifs (Gratuit : 1 projet, 50 prospects, 100 mails, 5 jobs IA par mois ; payant « Bientôt », sans prix ; accès Claude à la charge de l'utilisateur, clé API ou abonnement avec le risque expliqué ; responsabilité des envois), connexion (la page existante, intégrée au site), mentions légales, confidentialité, CGU, 404.
|
||||||
|
- **Identité** : `public/site.css` chargé après `app.css`, uniquement les jetons du tableau de bord (`--bg`, `--card`, `--text`, `--muted`, `--line`, `--accent`, thème sombre inclus), composants `.btn`, `.card`, `.badge`, `.bar`. Signature visuelle : un carré à coin rabattu (logo, numéros d'étapes, repères) et une règle graduée comme séparateur. Les effets du tableau de bord (fond dégradé, verre dépoli, dégradé violet des boutons) sont neutralisés sous `body.site`. Typographie système, une seule animation d'entrée, désactivée par `prefers-reduced-motion`.
|
||||||
|
- **SEO** : title, description, canonical, Open Graph par page, une h1, `lang="fr"`, liens d'évitement, `robots.txt` (pages d'application en `Disallow`), `sitemap.xml` (6 pages), JSON-LD `SoftwareApplication` sur l'accueil, favicon SVG (clair/sombre), `noindex` (balise et en-tête `X-Robots-Tag`) sur tout ce qui n'est pas une page publique, y compris connexion et 404.
|
||||||
|
- **Sécurité** : CSP stricte (`default-src 'self'`, pas d'inline, `object-src 'none'`, `base-uri 'self'`, `frame-ancestors 'none'`, `form-action` limité à l'application, Google et Apple), `X-Content-Type-Options`, `Referrer-Policy`, `Permissions-Policy`, `Cross-Origin-Opener-Policy`, HSTS **seulement si `APP_URL` est en https**. Statiques avec ETag (304) et `Cache-Control` (1 h, 1 jour pour le favicon). HEAD répond comme GET.
|
||||||
|
- **Tests** : `test/site.test.js`. Deux tests existants adaptés : la racine anonyme n'est plus une redirection (elle sert le site), et le contrôle de redirection vers la connexion passe par `/account`.
|
||||||
|
|
||||||
|
### Décisions
|
||||||
|
- **« Tu »** partout, y compris dans les pages légales, comme dans le tableau de bord. À valider avec le juriste (usage plus courant : « vous »).
|
||||||
|
- **Ce qui est dit sur le site vient du code** : limites d'envoi (100 mails par lot, plafonds 200/300 par 24 h, délai 20–60 s), lecture IMAP toutes les 15 minutes, une seule relance en heures ouvrées, etc. Si le code change, les pages Fonctionnement et Tarifs sont à relire.
|
||||||
|
- **Plafonds du plan gratuit annoncés mais non appliqués** : la page Tarifs le dit en clair (application technique au J5).
|
||||||
|
- **Pas de bandeau cookies** : seuls `sid` (30 jours) et `oauth_b` (10 minutes, `/auth`) sont posés, tous deux strictement nécessaires ; pas d'analytics, pas de police externe. Dit dans la page confidentialité. Le `sessionStorage` du tableau de bord (projet ouvert) y est mentionné.
|
||||||
|
- **Acceptation des CGU par la connexion** (phrase sous les boutons, pas de case à cocher) : à valider ; une case serait plus solide juridiquement mais casse le flux « un clic ».
|
||||||
|
- **« Apple » n'apparaît que si Apple est configuré** (accueil, connexion, confidentialité, CGU), sinon le site mentionnerait un bouton absent.
|
||||||
|
- **Pas d'image Open Graph** : aucune illustration réelle pour l'instant (`twitter:card=summary`).
|
||||||
|
- **reCAPTCHA (J5)** : le paragraphe de confidentialité prêt à l'emploi est en commentaire dans `src/site/legal.js` (au-dessus de `privacyPage`), avec la liste des autres endroits à mettre à jour (CSP, cookies, transferts, consentement).
|
||||||
|
- **`/login` n'est pas en `Disallow` mais en `noindex`**, pour que le robot puisse lire le noindex.
|
||||||
|
|
||||||
|
### Marqueurs à compléter
|
||||||
|
Visibles en jaune sur les pages légales tant que l'information manque. Un test compare cette liste aux pages et au code : ajouter ou retirer un marqueur impose de mettre cette liste à jour.
|
||||||
|
|
||||||
|
- `[À COMPLÉTER : adresse du siège]` : mentions légales et confidentialité (adresse de l'EI).
|
||||||
|
- `[À COMPLÉTER : hébergeur]` : mentions légales et confidentialité (nom, adresse, contact de l'hébergeur du serveur).
|
||||||
|
- `[À COMPLÉTER : téléphone]` : mentions légales. La loi sur la confiance dans l'économie numérique demande un moyen de contact rapide pour l'éditeur ; à confirmer avec un juriste (un numéro, ou autre solution), sinon retirer la ligne.
|
||||||
|
- `[À VALIDER : durées de conservation]` : confidentialité. Propositions : compte inactif supprimé après 24 mois (**non implémenté**, à coder ou à retirer), sessions 30 jours, sauvegardes environ 14 jours, journaux d'accès du serveur 12 mois (à vérifier avec la configuration réelle de Nginx/CloudPanel), prospects : recommandation de 3 ans après le dernier contact.
|
||||||
|
- `[À VALIDER : transferts hors UE]` : confidentialité (Google, Apple, Anthropic aux États-Unis ; mécanismes cités de façon générale).
|
||||||
|
- `[À VALIDER : cadre de sous-traitance]` : confidentialité et CGU. Les CGU et la politique tiennent lieu de cadre de l'article 28 RGPD ; un accord de sous-traitance dédié est peut-être préférable.
|
||||||
|
- `[À VALIDER : limitation de responsabilité]` : CGU.
|
||||||
|
|
||||||
|
### À faire relire par un juriste
|
||||||
|
- Clause d'abonnement (risque de suspension du compte Claude, exclusion de responsabilité « dans la mesure permise par la loi ») et sa case d'acceptation (décision 10 du cadrage).
|
||||||
|
- Rôles RGPD (utilisateur responsable de traitement, AiTools sous-traitant), contenu de l'article 28 réellement couvert.
|
||||||
|
- Affirmation de la page Tarifs sur la prospection B2B sans accord préalable (règle CNIL résumée, formulation prudente « en règle générale »).
|
||||||
|
- Mentions du siège et du téléphone, médiation de la consommation (service réservé aux professionnels, donc non traitée), juridiction compétente.
|
||||||
|
- Liens sortants, saisis de mémoire et à vérifier à la main : `anthropic.com/legal/consumer-terms`, `anthropic.com/legal/privacy`, `policies.google.com/privacy`, `apple.com/legal/privacy/fr-fr/`, `cnil.fr/fr/plaintes`.
|
||||||
|
|
||||||
|
### Non vérifié
|
||||||
|
- **Rendu réel** : vu dans le navigateur intégré (accueil sur ordinateur et mobile 375 px, fonctionnement en sombre sur tablette, confidentialité), mais la fenêtre du volet est petite et les captures sont partielles. Pas de Lighthouse, pas de Safari ni Firefox, pas de lecteur d'écran, pas de vrai téléphone.
|
||||||
|
- **Contrastes** : calculés par un test à partir des jetons (AA 4,5:1) ; pas de mesure sur la page rendue.
|
||||||
|
- **Sur le serveur** : en-têtes derrière le reverse proxy (Nginx/CloudPanel peut en ajouter ou en dupliquer, notamment HSTS), cache d'un éventuel CDN (`Vary: Cookie` est posé sur `/`).
|
||||||
|
- **Connexion Apple** : le POST cross-site reste testé avec un fournisseur simulé uniquement (déjà le cas au J2).
|
||||||
|
|
||||||
|
### À faire
|
||||||
|
- Renseigner les marqueurs, relire les pages légales, vérifier les liens sortants, et retirer chaque marqueur de cette liste et de `MARKERS` (`src/site/legal.js`) une fois traité.
|
||||||
|
- Une image Open Graph et de vraies captures du produit quand il y aura des données réelles (aucun témoignage ni chiffre n'a été inventé : il n'y en a pas).
|
||||||
|
- J5 : appliquer les plafonds du plan gratuit, reCAPTCHA (paragraphe prêt), suppression des comptes inactifs si la durée est confirmée.
|
||||||
|
- Les pages d'erreur HTML autres que 404 (403, 500) utilisent encore l'ancien gabarit.
|
||||||
|
|
||||||
|
## 2026-10-22 — J3 « Liaison Claude »
|
||||||
|
|
||||||
|
### Fait
|
||||||
|
- **Liaison par utilisateur** (`src/claudelink.js`, stockée dans `users.claude_link_json`, secret chiffré AES-256-GCM avec `crypto.js`) : trois modes. Clé API Anthropic (vérifiée par `GET /v1/models`, sans coût ; 401/403 refusent, une erreur réseau ou un 5xx donne un message distinct ; `fetch` injectable). Jeton d'abonnement (`claude setup-token` sur la machine de l'utilisateur, collé dans un formulaire). « Claude du serveur » (admins de `ADMIN_EMAILS`, configuration CLI de la machine, comme avant). La clé n'est jamais réaffichée (4 derniers caractères seulement), ni journalisée ; les erreurs du CLI sont masquées (`***`) avant d'atteindre la base, les journaux ou les réponses.
|
||||||
|
- **Consentement du mode abonnement** : fenêtre `<dialog>` d'avertissement avec case obligatoire ; le serveur refuse (400) sans la case, avant toute validation, et ne stocke rien. L'acceptation est horodatée avec la version du texte (`CONSENT_VERSION`) dans la liaison et dans `user_settings.claude_cli_consent_json` (conservée après « Délier », effacée avec le compte). `CLAUDE_CLI_MODE_ENABLED=false` masque le mode et le refuse côté serveur (liaison, test, exécution).
|
||||||
|
- **Onboarding bloquant** : garde centrale dans `server.js` (défaut = refus) : sans liaison valide, redirection vers `/link` (HTML) ou 403 `link_required` (JSON) sur toute route, sauf `/link*`, Mon compte, suppression du compte et déconnexion. La garde « admin seulement » du J2 est remplacée par `aiRefusal` / `assertCanRunAi`, appelés dans les routes, `enqueue`, le worker (`jobRefusal`) et le wrapper `makeClaude()`.
|
||||||
|
- **Le secret vient toujours du `user_id` du job** (`resolveCredentials`) ; les projets sont relus avec ce même `user_id` (404 sinon). Le répertoire de travail doit être sous `repos/<user_id>` (`allowedRoot`).
|
||||||
|
- **Exécution isolée** (`src/services/sandbox.js`, `claude.js`) : ligne bubblewrap construite par une fonction pure (racine reconstruite en lecture seule : `/usr`, `/etc`, bibliothèques ; `/tmp` et `HOME` en tmpfs ; clone de l'utilisateur monté en lecture seule ; `--unshare-pid/ipc/uts`, `--die-with-parent`, `--new-session`, `--cap-drop ALL` ; réseau conservé). Le secret est dans l'environnement du processus, pas dans argv (visible dans `ps`). Environnement enfant en liste blanche (`PATH`, `LANG`, `HOME` jetable, le secret). Production : job refusé si `bwrap` manque, même avec `SANDBOX=off` ; développement : `SANDBOX=off` désactive avec avertissement au démarrage. Les clones git passent par `git.js` durci (https seulement, `GIT_ALLOW_PROTOCOL`, pas de hooks, pas de sous-modules, symlinks désactivés, 2 min, 300 Mo, environnement assaini). `syncRepo` revalide l'URL lue en base.
|
||||||
|
- **Par utilisateur** : quota remonté par le CLI, alertes, budget, pauses, notifications étaient déjà dans `user_settings` depuis le J2 ; le wrapper n'enregistre plus de quota en mode clé API, `/api/system` n'en renvoie pas, et la barre l'efface. Le quota est remis à zéro quand la liaison change.
|
||||||
|
- **Mon compte** : mode, état, date de liaison, dernier test, 4 derniers caractères (clé), consentement ; Tester (marque la liaison invalide sur refus d'authentification, la laisse intacte sur panne réseau ou CLI), Changer de mode (`/link?change=1`), Délier (efface le secret, annule les jobs IA en file ou en cours, interrompt le job IA en cours).
|
||||||
|
- Tests : `claude-link.test.js` et `claude-run.test.js` (remplacent `ai-guard.test.js`). Fixtures : `fake-claude.js` gagne ENVDUMP, LEAK et le jeton révoqué ; `helpers/claude-bin.js` fabrique un faux `claude` qui fixe des variables (l'environnement enfant étant assaini, un test ne peut plus piloter la fixture par `process.env`).
|
||||||
|
|
||||||
|
### Décisions
|
||||||
|
- **Racine du bac à sable reconstruite plutôt que `--ro-bind / /`** : une racine entière en lecture seule laisserait voir `/home`, la base, le `.env` et la configuration Claude du serveur. On monte `/usr`, `/etc` et les bibliothèques, plus le dossier du binaire Claude et `SANDBOX_RO_BINDS`. Le clone est monté en lecture seule (les outils autorisés ne font que lire).
|
||||||
|
- **Statut HTTP 502 « exposé »** (`HttpError.expose`) pour les échecs de validation (réseau, CLI) : sans cela le serveur masquait le message en « Erreur interne ».
|
||||||
|
- **Mode serveur** : n'importe aucune variable d'environnement d'identification de la machine ; il s'appuie sur la configuration CLI du serveur montée dans le bac à sable (`~/.claude`, `~/.claude.json`, en écriture pour le rafraîchissement des jetons). Une `ANTHROPIC_API_KEY` posée dans l'environnement du serveur n'est plus transmise.
|
||||||
|
- **Tests des clones** : `syncRepo` refuse désormais `file://`; le test de flux complet injecte `app.syncRepo` (clone local).
|
||||||
|
|
||||||
|
### Ce qui reste à valider en conditions réelles (non vérifié ici)
|
||||||
|
- **Aucun CLI `claude` installé sur ce poste** : `claude --help`, `claude setup-token --help` et `claude auth --help` n'ont donc pas pu être lus. Les consignes affichées (« lance `claude setup-token`, connecte-toi, copie le jeton ») et le nom de la variable `CLAUDE_CODE_OAUTH_TOKEN` reposent sur la documentation connue, pas sur la version installée sur le serveur. À vérifier sur le serveur : `claude setup-token --help`, forme exacte du jeton (la validation de format est volontairement large : 20 à 800 caractères sans espace, et refuse un préfixe `sk-ant-api` qui est une clé API), et que le jeton fonctionne avec `-p` sans `HOME` préexistant.
|
||||||
|
- **Validation du jeton** : aucune commande du CLI ne vérifie un jeton sans appel au modèle ; on lance un appel minimal (Haiku, 1 tour, aucun outil), qui consomme quelques tokens de l'abonnement. La distinction « jeton refusé » (400) / « impossible de juger » (502) repose sur une correspondance de texte dans la réponse du CLI : à confirmer avec de vraies réponses d'erreur.
|
||||||
|
- **bwrap réel** : non exécutable sous Windows. Seule la ligne de commande est testée. À essayer sur le serveur : un job complet avec chaque mode ; que `claude` et `node` sont bien visibles dans le bac à sable (sinon `SANDBOX_RO_BINDS`) ; la résolution DNS (`/etc/resolv.conf` pointant vers `/run/systemd/resolve`) ; le mode serveur (écriture dans `~/.claude`). Vérifier aussi que `deploy/aitools.service` (`NoNewPrivileges`, `ProtectSystem=strict`, `ProtectKernelTunables`) laisse bwrap monter `/proc` ; si ce n'est pas le cas, assouplir ces options ou ajouter `--proc` conditionnel. Contrôle d'isolation à faire à la main : depuis un job, `ls /home /var /srv` doit être vide ou absent.
|
||||||
|
- **MySQL réel** : toujours aucun essai (pas de changement de schéma au J3, la colonne `claude_link_json` existait). `npm run test:mysql` reste à lancer.
|
||||||
|
- **Dépôts malveillants** : un `.claude/settings.json` ou un `CLAUDE.md` dans un dépôt cloné est lu par le CLI. Le bac à sable (lecture seule, sans la config du serveur) limite l'impact, mais le réseau reste ouvert : un hook ou un serveur MCP déclaré par le dépôt peut tenter de sortir des données de CE seul utilisateur. À étudier (désactiver les réglages de projet côté CLI si une option existe).
|
||||||
|
- Le surcoût de CPU/RAM du bac à sable par job n'est pas mesuré ; la concurrence de plusieurs jobs reste hors périmètre (J5).
|
||||||
|
|
||||||
|
### Risques connus, hors périmètre J3
|
||||||
|
- Rate limiting des routes `/link/*` (un utilisateur peut tester des clés à volonté, avec un appel réseau par essai), reCAPTCHA, back-office, plafond global de jobs : J5.
|
||||||
|
- Hôtes SMTP/IMAP/BDD/Forgejo saisis par l'utilisateur (SSRF) : non traités, non aggravés (le bac à sable conserve le réseau, comme demandé).
|
||||||
|
- Le texte d'avertissement du mode abonnement est une proposition de rédaction ; relecture juridique recommandée avec les CGU (décision 10).
|
||||||
|
|
||||||
|
## 2026-10-22 — J2 « Comptes et multi-tenant »
|
||||||
|
|
||||||
|
### Fait
|
||||||
|
- **Comptes** (migration 2 `comptes_multi_tenant`, SQLite et MySQL ensemble) : table `users` (email unique insensible à la casse, nom, fournisseur + `sub`, statut `active|suspended`, `is_admin`, plan `free`, dates, `claude_link_json` réservé au J3). Inscription automatique à la première connexion réussie, sans validation manuelle ni mot de passe.
|
||||||
|
- **Connexion Google et Apple** (`src/auth.js`, zéro dépendance) : state + nonce, PKCE pour Google, `response_mode=form_post` pour Apple, secret client Apple en JWT ES256 signé avec `node:crypto`. L'id_token est vérifié pour les deux fournisseurs : signature RS256 via les JWKS (cache 1 h, relecture sur clé inconnue), puis émetteur, audience, expiration, nonce, `sub`, email vérifié. Le bouton Apple n'apparaît que si les quatre variables `APPLE_*` sont définies (trois sur quatre = erreur au démarrage). `ALLOWED_EMAILS` est supprimée ; `ADMIN_EMAILS` désigne les admins (relue au démarrage et à chaque connexion).
|
||||||
|
- **Sessions** liées à `users.id`. Un compte suspendu ne peut plus se connecter, et sa session existante est refusée puis supprimée.
|
||||||
|
- **Multi-tenant** : `user_id` sur `projects` (unicité du dépôt par utilisateur) et sur `jobs` ; `settings` global remplacé par `user_settings` (SMTP, Discord, budget, plafonds, Forgejo…, quota Claude). `getProject`, `listProjects`, `createProject`, `enqueue`, `cancelJob`, budget, usage, rapport hebdo, notifications, planificateur, boîtes IMAP, métriques, export/import CSV : tout est filtré par utilisateur. Dossier des clones : `DATA_DIR/repos/<utilisateur>/<projet>`.
|
||||||
|
- **Rattachement des données existantes** : la migration crée le propriétaire depuis le premier email de `ADMIN_EMAILS` et lui rattache projets, jobs (y compris sans projet) et réglages. Il retrouve ses données à sa première connexion, par correspondance d'email. `scripts/migrate-sqlite-to-mysql.js` reste valide : il rattache de même au propriétaire, convertit les réglages et ne copie pas les sessions.
|
||||||
|
- **Jobs IA réservés aux admins** (en attendant le J3), refusés à quatre niveaux : route (403 « Liaison Claude requise (bientôt disponible) »), `enqueue`, worker (le job d'un non-admin déjà en base passe en erreur sans s'exécuter) et wrapper `claude()` des handlers. À la création d'un projet par un non-admin, l'analyse n'est pas lancée.
|
||||||
|
- **Pages** : connexion (Google, Apple si configuré, thème clair/sombre avec les jetons de `app.css`), bannière « liaison Claude » pour les non-admins, « Mon compte » (email, fournisseur, suppression du compte avec saisie de l'email).
|
||||||
|
- **Suppression de compte** : cascade des clés étrangères (projets, prospects, notes, modèles, journaux, métriques, jobs, réglages, sessions), clones git effacés, job en cours interrompu, session détruite. Le schéma est testé : toute table métier descend d'un utilisateur par cascade.
|
||||||
|
- **Tests** : suite existante adaptée ; nouveaux fichiers `isolation` (A contre B sur chaque route, listes et exports compris), `auth` (fournisseurs simulés : jeton forgé, alg `none`, kid inconnu, iss/aud/exp/nonce/state/cookie de liaison, rejeu, expiration, Apple form_post, secret ES256), `account`, `ai-guard`, `accounts-migration`.
|
||||||
|
|
||||||
|
### Décisions
|
||||||
|
- **Un compte = un fournisseur.** Même email déjà lié à l'autre fournisseur : refus avec message, pas de fusion automatique (risque de prise de compte). Seul un compte « préparé » par la migration (sans fournisseur) est rattaché à la première identité vérifiée portant son email.
|
||||||
|
- **ADMIN_EMAILS fait foi** pour le rôle admin (au démarrage et à chaque login) ; vide, plus personne ne peut lancer de job IA (avertissement au démarrage). Les futures promotions depuis un back-office (J5) devront remplacer cette règle.
|
||||||
|
- **Cookie de liaison OAuth** (`oauth_b`, `SameSite=None; Secure; HttpOnly; Path=/auth`, 10 min) pour les deux fournisseurs : sans lui, un POST d'Apple (ou un lien de callback) forgé par un tiers connecterait la victime au compte de l'attaquant. Le callback Apple est public, sans contrôle d'`Origin` (c'est un POST d'Apple), protégé par state + nonce + cookie.
|
||||||
|
- **`jobs.user_id` dénormalisé** (en plus de `project_id`) : un job sans projet doit rester attribuable, et le budget / l'usage se calculent sans jointure. Les autres tables filles héritent via `project_id`.
|
||||||
|
- **Tous les réglages sont par utilisateur**, y compris l'état du quota Claude (`claude_rate_limit_json`) : en J3 chaque compte Claude a son propre quota.
|
||||||
|
- **Liste d'opposition globale** conservée à la suppression d'un compte. Elle ne sort plus dans le prompt de prospection (domaines exclus), n'est comptée que sur les prospects du compte, et le motif affiché sur une fiche prospect est générique, sauf la désinscription.
|
||||||
|
- **Désinscription** (lien public signé) : met à `refused` les prospects de cet email chez tous les comptes (la personne ne veut plus être contactée, par personne).
|
||||||
|
- **Sessions et états OAuth recréés** par la migration (éphémères) : tout le monde doit se reconnecter après la mise à jour.
|
||||||
|
|
||||||
|
### Non vérifié (à faire par Tony ou au prochain passage)
|
||||||
|
- **Aucun test contre un vrai MySQL/MariaDB** (toujours pas de serveur, Docker exclu). Nouveautés MySQL non exécutées : les `ALTER TABLE` conditionnels de la migration 2 (interrogent `information_schema`), `ADD CONSTRAINT ... FOREIGN KEY`, `DROP INDEX`, le `UPDATE ... (SELECT ...)` de rattachement, l'unique `(user_id, git_url(500))` (2 008 octets en utf8mb4, sous la limite de 3 072 d'InnoDB DYNAMIC), le `CHECK` sur `users.status` (appliqué à partir de MySQL 8.0.16 / MariaDB 10.2), `UPDATE users SET is_admin = CASE WHEN email IN (...)`. Commande dès qu'une base de test existe : `TEST_DB_HOST=... TEST_DB_USER=... TEST_DB_PASSWORD=... TEST_DB_NAME=aitools_test npm run test:mysql`. Si une migration 2 échoue à mi-chemin sur MySQL, elle est rejouable (les ALTER sont gardés), mais à vérifier réellement.
|
||||||
|
- **Aucun flux Google ni Apple réel** : tout est testé avec des fournisseurs simulés. À valider sur le domaine : redirections, JWKS réels, cookie `SameSite=None` dans Safari (le POST d'Apple), URL de retour déclarée côté Apple, secret client accepté par Apple (claims `iss`/`sub`/`aud`, durée).
|
||||||
|
- `test/install.test.sh` et `install.sh` (Pi) : seul le nom de la variable `ADMIN_EMAILS` a changé dans `install.sh` ; le test shell n'est pas exécutable sur ce poste (root, systemd).
|
||||||
|
|
||||||
|
### Risques connus, hors périmètre J2
|
||||||
|
- **Sorties réseau pilotées par l'utilisateur** : hôtes SMTP, IMAP et base du récap, hôte Forgejo (clone), qu'un compte non admin peut renseigner. Sans filtre, ils permettent de sonder le réseau interne du serveur (MySQL local, etc.). À traiter avec l'isolation du J3/J5 (interdire les adresses privées/loopback pour les non-admins, ou sortir ces appels dans le bac à sable).
|
||||||
|
- Plan gratuit (1 projet, 50 prospects, 100 mails/mois, 5 jobs IA/mois), anti-abus, rate limiting, CAPTCHA, back-office de suspension : J5. La suspension se fait pour l'instant en base (`UPDATE users SET status = 'suspended'`).
|
||||||
|
- Les clones git d'avant J2 (`repos/<projet>`) sont orphelins : ils se reclonent au prochain job et peuvent être supprimés.
|
||||||
|
|
||||||
|
### À faire ensuite
|
||||||
|
- J3 : liaison Claude (`users.claude_link_json`), levée du blocage des jobs IA pour les comptes liés (remplacer `canRunAi`), isolation par compte de l'exécution.
|
||||||
|
- Essai complet sur la base CloudPanel (`npm run test:mysql`, migration réelle), puis test des connexions Google et Apple sur le domaine.
|
||||||
|
|
||||||
|
## 2026-10-22 — J1 « Fondations » : couche de données MySQL/MariaDB
|
||||||
|
|
||||||
|
### Fait
|
||||||
|
- `src/db.js` : une seule API asynchrone, deux drivers.
|
||||||
|
- MySQL/MariaDB (`mysql2/promise`, pool, utf8mb4) en production, configuré par `DB_HOST`, `DB_PORT` (3306), `DB_USER`, `DB_PASSWORD`, `DB_NAME`.
|
||||||
|
- `node:sqlite` en mémoire pour les tests locaux (`openDb(':memory:')`, ou `DB_DRIVER=sqlite` pour un essai local non persistant).
|
||||||
|
- Shim `db.prepare(sql).get/all/run(...params)` (promesses ; `run` → `{ changes, lastInsertRowid }`) et `db.transaction(async (tx) => ...)`.
|
||||||
|
- `src/migrations.js` : migrations versionnées en deux jeux de DDL (SQLite et MySQL) maintenus ensemble. Table `schema_migrations`, verrou `GET_LOCK` côté MySQL, `CREATE TABLE IF NOT EXISTS`, InnoDB, utf8mb4, `VARCHAR` de longueur définie pour les clés et index, FK `ON DELETE CASCADE`.
|
||||||
|
- Tout `src/**` en async/await (routes, handlers de jobs, worker, planificateur, services). File de jobs inchangée : un job à la fois. `thermal.js` conservé (seul changement : `await` du callback `onWait`).
|
||||||
|
- `scripts/migrate-sqlite-to-mysql.js` (`npm run migrate:sqlite -- data/aitools.sqlite [--force]`) : copie toutes les tables, ids conservés, une transaction, rapport par table, refuse une cible non vide sauf `--force`.
|
||||||
|
- Tests adaptés au shim asynchrone ; nouveaux tests : parité des schémas, shim/transactions, migration des données, cycle de vie du worker. Si `TEST_DB_HOST` est défini, la même suite tourne contre un vrai MySQL/MariaDB (`npm run test:mysql`).
|
||||||
|
- `.env.example` et README (installation sur un serveur sans Raspberry, variables `DB_*`, migration des données, tests MySQL).
|
||||||
|
|
||||||
|
### Décisions
|
||||||
|
- **SQL canonique = forme SQLite/ANSI**, traduit à la volée pour MySQL (`translate()` dans `src/db.js`) : `INSERT OR IGNORE` → `INSERT IGNORE`, `ON CONFLICT(...) DO UPDATE SET x = excluded.x` → `ON DUPLICATE KEY UPDATE x = VALUES(x)`, `COLLATE NOCASE` retiré. Les colonnes réservées (`key`) sont entre accents graves, acceptés par les deux moteurs.
|
||||||
|
- **Requêtes réécrites plutôt que traduites** : `project_id IS ?` (deux requêtes selon NULL ou non), `ORDER BY ... COLLATE NOCASE` → `ORDER BY LOWER(...)`, `LIKE ... ESCAPE '\'` → `ESCAPE '!'` (le backslash n'a pas le même sens dans un littéral MySQL), `INSERT ... SELECT ... WHERE NOT EXISTS` sans `FROM` → test de la liste d'opposition puis `INSERT OR IGNORE`, alias `last` → `lj`.
|
||||||
|
- **Schéma initial consolidé** : les 8 migrations SQLite historiques deviennent la migration 1 (état final identique). La migration des données copie les colonnes de l'ancienne base et exige la version 8 (`user_version`) ou un `schema_migrations` à jour.
|
||||||
|
- **SQLite = une seule connexion** : pendant une transaction, les autres requêtes attendent sa fin (sinon elles s'exécuteraient dans la transaction). Dans le callback de `transaction`, utiliser `tx`, jamais `db`.
|
||||||
|
- **Callbacks synchrones du flux Claude** (`onText`, `onTurn`) : leurs écritures passent par une file ordonnée (`makeSink`) attendue en fin de phase ; une erreur d'écriture fait échouer le job.
|
||||||
|
- **Aucune promesse laissée en l'air** : le worker suit ses notifications (`idle()`, `stop()` les attend), le planificateur suit son passage en cours, `createApp` est asynchrone et `app.close()` attend job, tâches de fond puis base.
|
||||||
|
- **`npm test`** : le glob avec guillemets simples ne trouvait aucun fichier sous Windows (0 test lancé) ; remplacé par des guillemets doubles, valables partout.
|
||||||
|
- Ancien test « migration 2 » supprimé : l'ancien chemin de migration SQLite incrémentale n'existe plus, le script de migration des données le remplace.
|
||||||
|
|
||||||
|
### Non vérifié (à faire par Tony ou au prochain passage)
|
||||||
|
- **Aucun test contre un vrai MySQL/MariaDB** : pas de serveur disponible et Docker exclu sur ce poste. Le DDL MySQL, la traduction SQL, `GET_LOCK`, la transaction `mysql2` et le script de migration vers MySQL ne sont donc validés que par lecture et par les tests SQLite. Commande à lancer dès qu'une base de test existe : `TEST_DB_HOST=... TEST_DB_USER=... TEST_DB_PASSWORD=... TEST_DB_NAME=aitools_test npm run test:mysql`.
|
||||||
|
- Mode strict MySQL (`STRICT_TRANS_TABLES`) : une chaîne plus longue qu'un `VARCHAR` fait échouer l'écriture (SQLite ne vérifie rien). Les longueurs côté code (entreprise 200, ville/secteur 100, site/source 300) sont sous les limites, les noms de projet sont limités à 80, mais l'email n'est pas tronqué (limite 255, cohérente avec le format d'une adresse).
|
||||||
|
- Comparaisons d'emails : SQLite est sensible à la casse, MySQL (`utf8mb4_unicode_ci`) non. Le code met déjà les emails en minuscules ; à garder en tête pour J2 (comptes).
|
||||||
|
- `git_url` en `VARCHAR(500)` unique : 2000 octets en utf8mb4, OK avec InnoDB `DYNAMIC` (MySQL ≥ 5.7, MariaDB ≥ 10.2), pas avec l'ancien format `COMPACT`.
|
||||||
|
|
||||||
|
### À faire ensuite
|
||||||
|
- Essai complet sur la base CloudPanel (création de la base, `npm start`, `npm run test:mysql`, migration réelle de `data/aitools.sqlite`).
|
||||||
|
- `install.sh`, `deploy/aitools-backup.sh` et `test/install.test.sh` sont encore ceux de la version SQLite (sauvegarde `sqlite3 .backup`, pas de `DB_*` dans le `.env` généré) : à reprendre au jalon J6 (déploiement).
|
||||||
|
- Connexion TLS à la base distante (option `ssl` de `mysql2`) si la base n'est pas locale.
|
||||||
|
- J2 : comptes, `user_id` sur toutes les tables métier, tests d'isolation.
|
||||||
|
|
||||||
|
### Reprise
|
||||||
|
Une session précédente avait été interrompue avec `src/auth.js`, `src/config.js`, `src/db.js` et `src/projects.js` modifiés (environ 15 %). Ces fichiers étaient cohérents avec le plan et ont été conservés ; `db.js` a été réécrit pour porter les deux drivers, et un `ON DUPLICATE KEY` laissé en dur dans `projects.js` a été remis dans la forme commune (commit `fix(projects)`).
|
||||||
|
|
@ -340,9 +340,9 @@ ask_app() {
|
||||||
warn "Domaine invalide (ex. ai.mondomaine.fr)."
|
warn "Domaine invalide (ex. ai.mondomaine.fr)."
|
||||||
done
|
done
|
||||||
|
|
||||||
local def; def=$(sed -n 's/^ALLOWED_EMAILS=//p' "$SRC_DIR/.env.example" 2>/dev/null | head -n1)
|
local def; def=$(sed -n 's/^ADMIN_EMAILS=//p' "$SRC_DIR/.env.example" 2>/dev/null | head -n1)
|
||||||
while :; do
|
while :; do
|
||||||
ask ALLOWED "Emails Google autorisés (séparés par des virgules)" "$def"
|
ask ALLOWED "Emails administrateurs (séparés par des virgules)" "$def"
|
||||||
[[ $ALLOWED =~ ^[^,[:space:]]+@[^,[:space:]]+(,[^,[:space:]]+@[^,[:space:]]+)*$ ]] && break
|
[[ $ALLOWED =~ ^[^,[:space:]]+@[^,[:space:]]+(,[^,[:space:]]+@[^,[:space:]]+)*$ ]] && break
|
||||||
warn "Format attendu : moi@gmail.com,autre@gmail.com"
|
warn "Format attendu : moi@gmail.com,autre@gmail.com"
|
||||||
done
|
done
|
||||||
|
|
@ -603,7 +603,7 @@ PORT=$PORT
|
||||||
HOST=127.0.0.1
|
HOST=127.0.0.1
|
||||||
GOOGLE_CLIENT_ID=$GOOGLE_ID
|
GOOGLE_CLIENT_ID=$GOOGLE_ID
|
||||||
GOOGLE_CLIENT_SECRET=$GOOGLE_SECRET
|
GOOGLE_CLIENT_SECRET=$GOOGLE_SECRET
|
||||||
ALLOWED_EMAILS=$ALLOWED
|
ADMIN_EMAILS=$ALLOWED
|
||||||
SECRET_KEY=$(openssl rand -hex 32 2>/dev/null || node -e "console.log(require('crypto').randomBytes(32).toString('hex'))")
|
SECRET_KEY=$(openssl rand -hex 32 2>/dev/null || node -e "console.log(require('crypto').randomBytes(32).toString('hex'))")
|
||||||
DATA_DIR=$DATA_DIR
|
DATA_DIR=$DATA_DIR
|
||||||
CLAUDE_BIN=$claude_bin
|
CLAUDE_BIN=$claude_bin
|
||||||
|
|
|
||||||
|
|
@ -11,7 +11,9 @@
|
||||||
"start": "node --env-file=.env --no-warnings=ExperimentalWarning src/server.js",
|
"start": "node --env-file=.env --no-warnings=ExperimentalWarning src/server.js",
|
||||||
"dev": "node --env-file=.env --watch --no-warnings=ExperimentalWarning src/server.js",
|
"dev": "node --env-file=.env --watch --no-warnings=ExperimentalWarning src/server.js",
|
||||||
"lint": "node scripts/check-syntax.js",
|
"lint": "node scripts/check-syntax.js",
|
||||||
"test": "node --no-warnings=ExperimentalWarning --test 'test/**/*.test.js'",
|
"test": "node --no-warnings=ExperimentalWarning --test \"test/**/*.test.js\"",
|
||||||
|
"test:mysql": "node --no-warnings=ExperimentalWarning --test --test-concurrency=1 \"test/**/*.test.js\"",
|
||||||
|
"migrate:sqlite": "node --env-file=.env --no-warnings=ExperimentalWarning scripts/migrate-sqlite-to-mysql.js",
|
||||||
"check": "npm run lint && npm run test",
|
"check": "npm run lint && npm run test",
|
||||||
"hooks": "git config core.hooksPath .githooks"
|
"hooks": "git config core.hooksPath .githooks"
|
||||||
},
|
},
|
||||||
|
|
|
||||||
|
|
@ -28,6 +28,16 @@ a { color: var(--accent); }
|
||||||
|
|
||||||
.card { background: var(--card); border: 1px solid var(--line); border-radius: var(--radius); padding: 14px 16px; margin: 12px 0; }
|
.card { background: var(--card); border: 1px solid var(--line); border-radius: var(--radius); padding: 14px 16px; margin: 12px 0; }
|
||||||
.login { max-width: 380px; margin: 12vh auto; text-align: center; }
|
.login { max-width: 380px; margin: 12vh auto; text-align: center; }
|
||||||
|
.login-btns { display: flex; flex-direction: column; gap: 10px; margin-top: 14px; }
|
||||||
|
.btn.apple { background: var(--text); border-color: var(--text); color: var(--bg); }
|
||||||
|
.notice { border-color: var(--warn); color: var(--text); }
|
||||||
|
.check { display: flex; align-items: flex-start; gap: 8px; }
|
||||||
|
.check input { margin-top: 4px; }
|
||||||
|
.row-actions { display: flex; gap: 8px; flex-wrap: wrap; align-items: center; margin-top: 12px; }
|
||||||
|
.row-actions form { margin: 0; }
|
||||||
|
dl.account { display: grid; grid-template-columns: max-content 1fr; gap: 6px 16px; margin: 0; }
|
||||||
|
dl.account dt { color: var(--muted); }
|
||||||
|
dl.account dd { margin: 0; overflow-wrap: anywhere; }
|
||||||
.muted { color: var(--muted); }
|
.muted { color: var(--muted); }
|
||||||
.small { font-size: .85rem; }
|
.small { font-size: .85rem; }
|
||||||
.ok { color: var(--ok); }
|
.ok { color: var(--ok); }
|
||||||
|
|
|
||||||
|
|
@ -55,6 +55,14 @@
|
||||||
followup_template: 'Modèle de relance', followup: 'Relances',
|
followup_template: 'Modèle de relance', followup: 'Relances',
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// ---------- Liaison Claude : fenêtre d'avertissement du mode abonnement ----------
|
||||||
|
// Le serveur refuse de toute façon (400) une requête sans la case cochée ; ici on évite seulement l'envoi inutile.
|
||||||
|
$('[data-open-dialog]').forEach((b) => b.addEventListener('click', () => $('#' + b.dataset.openDialog)?.showModal()));
|
||||||
|
$('[data-close-dialog]').forEach((b) => b.addEventListener('click', () => b.closest('dialog')?.close()));
|
||||||
|
const consentBox = $('#consent-accept');
|
||||||
|
const consentBtn = $('#consent-submit');
|
||||||
|
if (consentBox && consentBtn) consentBox.addEventListener('change', () => { consentBtn.disabled = !consentBox.checked; });
|
||||||
|
|
||||||
// ---------- Barre système ----------
|
// ---------- Barre système ----------
|
||||||
// "IA 24 h : 0,42 $ / 2 $" : orange à 80 %, rouge une fois atteint
|
// "IA 24 h : 0,42 $ / 2 $" : orange à 80 %, rouge une fois atteint
|
||||||
function gauge(label, x) {
|
function gauge(label, x) {
|
||||||
|
|
@ -76,7 +84,9 @@
|
||||||
const reset = resetLabel(w.resetsAt);
|
const reset = resetLabel(w.resetsAt);
|
||||||
return `<span class="${cls}"${reset ? ` title="Réinitialisation ${esc(reset)}"` : ''}>Claude ${label} : ${pct(w.utilization)}</span>`;
|
return `<span class="${cls}"${reset ? ` title="Réinitialisation ${esc(reset)}"` : ''}>Claude ${label} : ${pct(w.utilization)}</span>`;
|
||||||
}
|
}
|
||||||
function claudeQuota(rl) {
|
function claudeQuota(rl, mode) {
|
||||||
|
// Clé API : pas de quota d'abonnement à afficher
|
||||||
|
if (mode === 'api_key') return '';
|
||||||
if (!rl) return '<span class="muted" title="Mesuré après le premier job IA">Claude : pas encore mesuré</span>';
|
if (!rl) return '<span class="muted" title="Mesuré après le premier job IA">Claude : pas encore mesuré</span>';
|
||||||
return `${claudeBit('session 5h', rl.fiveHour)} ${claudeBit('semaine', rl.sevenDay)}`.trim();
|
return `${claudeBit('session 5h', rl.fiveHour)} ${claudeBit('semaine', rl.sevenDay)}`.trim();
|
||||||
}
|
}
|
||||||
|
|
@ -161,7 +171,7 @@
|
||||||
const s = await api('/api/system');
|
const s = await api('/api/system');
|
||||||
const hot = s.temp !== null && s.temp >= s.thermalMax - 5;
|
const hot = s.temp !== null && s.temp >= s.thermalMax - 5;
|
||||||
el.innerHTML = `${s.temp !== null ? `<span class="${hot ? 'warn' : ''}">${s.temp} °C</span>` : ''}
|
el.innerHTML = `${s.temp !== null ? `<span class="${hot ? 'warn' : ''}">${s.temp} °C</span>` : ''}
|
||||||
${claudeQuota(s.claudeRateLimit)}
|
${claudeQuota(s.claudeRateLimit, s.linkMode)}
|
||||||
${gauge('24 h', s.budget.day)} ${gauge('30 j', s.budget.month)}
|
${gauge('24 h', s.budget.day)} ${gauge('30 j', s.budget.month)}
|
||||||
${s.budget.blocked ? '<span class="error">Budget IA atteint : jobs IA en attente</span>' : ''}`;
|
${s.budget.blocked ? '<span class="error">Budget IA atteint : jobs IA en attente</span>' : ''}`;
|
||||||
renderJobsMenu(s);
|
renderJobsMenu(s);
|
||||||
|
|
@ -429,7 +439,7 @@
|
||||||
try {
|
try {
|
||||||
switch (action) {
|
switch (action) {
|
||||||
case 'create': {
|
case 'create': {
|
||||||
await api('/api/projects', data);
|
const r = await api('/api/projects', data);
|
||||||
toast('Projet créé, analyse lancée');
|
toast('Projet créé, analyse lancée');
|
||||||
setTimeout(() => location.reload(), 600);
|
setTimeout(() => location.reload(), 600);
|
||||||
break;
|
break;
|
||||||
|
|
|
||||||
1
public/favicon.svg
Normal file
1
public/favicon.svg
Normal file
|
|
@ -0,0 +1 @@
|
||||||
|
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32"><style>path{fill:#2f5bea}@media (prefers-color-scheme:dark){path{fill:#5b82ff}}</style><path d="M4 4h16.8L28 11.2V28H4z"/></svg>
|
||||||
|
After Width: | Height: | Size: 189 B |
237
public/site.css
Normal file
237
public/site.css
Normal file
|
|
@ -0,0 +1,237 @@
|
||||||
|
/* Site public AiTools. Chargé APRÈS app.css : les couleurs viennent uniquement des jetons de app.css
|
||||||
|
(--bg, --card, --text, --muted, --line, --accent, thème sombre inclus). Aucune seconde palette ici.
|
||||||
|
Les habillages « tableau de bord » (fond dégradé, verre dépoli, dégradé violet) sont neutralisés sous body.site. */
|
||||||
|
|
||||||
|
body.site {
|
||||||
|
background: var(--bg);
|
||||||
|
background-attachment: scroll;
|
||||||
|
line-height: 1.6;
|
||||||
|
overflow-wrap: break-word;
|
||||||
|
}
|
||||||
|
body.site main { max-width: none; margin: 0; padding: 0; }
|
||||||
|
body.site a { text-underline-offset: .2em; }
|
||||||
|
body.site :focus-visible { outline: 2px solid var(--accent); outline-offset: 3px; border-radius: 3px; }
|
||||||
|
|
||||||
|
/* Composants du tableau de bord, sans les effets d'habillage */
|
||||||
|
body.site .card { background: var(--card); backdrop-filter: none; box-shadow: none; animation: none; margin: 0; }
|
||||||
|
body.site .btn { padding: 9px 18px; font-weight: 500; }
|
||||||
|
body.site .btn.primary { background: var(--accent); border-color: var(--accent); color: var(--accent-text); }
|
||||||
|
body.site .btn.primary:hover:not(:disabled) { box-shadow: none; }
|
||||||
|
body.site .btn:hover:not(:disabled) { box-shadow: none; transform: none; }
|
||||||
|
body.site .badge { animation: none; }
|
||||||
|
body.site .bar > span { background: var(--accent); transition: none; }
|
||||||
|
body.site .bar > span::after { content: none; }
|
||||||
|
body.site h1, body.site h2, body.site h3 { color: var(--text); background: none; -webkit-text-fill-color: currentColor; }
|
||||||
|
|
||||||
|
/* Texte clair sur le bouton principal : le blanc ne passe pas le contraste AA sur l'accent du thème sombre */
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
body.site .btn.primary { color: var(--bg); }
|
||||||
|
}
|
||||||
|
|
||||||
|
.wrap { width: 100%; max-width: 1080px; margin: 0 auto; padding: 0 20px; }
|
||||||
|
|
||||||
|
/* ---------- Lien d'évitement ---------- */
|
||||||
|
.skip { position: absolute; left: 12px; top: -80px; z-index: 100; background: var(--card); color: var(--text);
|
||||||
|
border: 2px solid var(--accent); border-radius: 8px; padding: 8px 14px; text-decoration: none; }
|
||||||
|
.skip:focus { top: 12px; }
|
||||||
|
|
||||||
|
/* ---------- En-tête ---------- */
|
||||||
|
.site-head { border-bottom: 1px solid var(--line); background: var(--card); }
|
||||||
|
.head-in { display: flex; align-items: center; flex-wrap: wrap; gap: 6px 22px; padding-top: 12px; padding-bottom: 12px; }
|
||||||
|
.site-head .brand { display: inline-flex; align-items: center; gap: 9px; font-size: 1.1rem; letter-spacing: -.01em; }
|
||||||
|
/* Signature visuelle : un carré à coin rabattu, repris sur les numéros d'étapes et les repères de section */
|
||||||
|
.mark { display: inline-block; width: 15px; height: 15px; background: var(--accent);
|
||||||
|
clip-path: polygon(0 0, 68% 0, 100% 32%, 100% 100%, 0 100%); }
|
||||||
|
.site-nav { margin-left: auto; }
|
||||||
|
.site-nav ul { display: flex; flex-wrap: wrap; align-items: center; gap: 4px 20px; list-style: none; margin: 0; padding: 0; }
|
||||||
|
.site-nav a { color: var(--text); text-decoration: none; padding: 6px 0; border-bottom: 2px solid transparent; }
|
||||||
|
.site-nav a:hover { border-bottom-color: var(--line); }
|
||||||
|
.site-nav a[aria-current="page"] { border-bottom-color: var(--accent); }
|
||||||
|
.site-nav .btn { border-bottom: 1px solid var(--accent); padding: 6px 14px; }
|
||||||
|
@media (max-width: 560px) {
|
||||||
|
.head-in { justify-content: space-between; }
|
||||||
|
.site-nav { margin-left: 0; flex-basis: 100%; }
|
||||||
|
.site-nav ul { gap: 2px 18px; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---------- Typographie ---------- */
|
||||||
|
.site h1 { font-size: clamp(2rem, 6.2vw, 3.4rem); line-height: 1.06; letter-spacing: -.03em; font-weight: 700; margin: 0 0 .5em; }
|
||||||
|
.site h2 { font-size: clamp(1.45rem, 3.6vw, 2rem); line-height: 1.15; letter-spacing: -.02em; font-weight: 700; margin: 0 0 .6em; }
|
||||||
|
.site h3 { font-size: 1.08rem; line-height: 1.3; margin: 1.6em 0 .4em; }
|
||||||
|
.site p { margin: 0 0 1em; }
|
||||||
|
.eyebrow { display: flex; align-items: center; gap: 9px; font-size: .84rem; font-weight: 600; letter-spacing: .06em; text-transform: uppercase; color: var(--muted); margin: 0 0 14px; }
|
||||||
|
.eyebrow .mark { width: 11px; height: 11px; }
|
||||||
|
.lead { font-size: clamp(1.05rem, 2.4vw, 1.2rem); line-height: 1.55; max-width: 36em; }
|
||||||
|
.fine { font-size: .86rem; color: var(--muted); }
|
||||||
|
.cta-row { display: flex; flex-wrap: wrap; align-items: center; gap: 12px 18px; margin: 26px 0 14px; }
|
||||||
|
.textlink { color: var(--text); font-weight: 500; }
|
||||||
|
.textlink:hover { color: var(--accent); }
|
||||||
|
|
||||||
|
/* ---------- Accueil : en-tête de page ---------- */
|
||||||
|
.hero { display: grid; gap: 38px; padding-top: 44px; padding-bottom: 56px; overflow-x: clip; }
|
||||||
|
.hero-text { align-self: center; }
|
||||||
|
@media (min-width: 900px) {
|
||||||
|
.hero { grid-template-columns: minmax(0, 5fr) minmax(0, 6fr); gap: 48px; padding-top: 72px; padding-bottom: 80px; }
|
||||||
|
.shot { margin-right: -64px; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---------- Maquette du tableau de bord (vrais composants, données d'exemple) ---------- */
|
||||||
|
.shot { margin: 0; }
|
||||||
|
.shot figcaption { margin-top: 10px; }
|
||||||
|
.mock { border: 1px solid var(--line); border-radius: 14px; background: var(--bg); padding: 12px; user-select: none; }
|
||||||
|
.mock-top { display: flex; align-items: center; gap: 10px; padding: 2px 4px 12px; font-size: .85rem; }
|
||||||
|
.mock-top .brand { display: inline-flex; align-items: center; gap: 7px; }
|
||||||
|
.mock-top .mark { width: 11px; height: 11px; }
|
||||||
|
.mock-top .push { margin-left: auto; color: var(--muted); }
|
||||||
|
.mock .card { padding: 12px 14px; margin-bottom: 10px; }
|
||||||
|
.mock-name { display: flex; align-items: center; justify-content: space-between; gap: 10px; font-weight: 600; }
|
||||||
|
.mock-sub { font-size: .82rem; color: var(--muted); margin: 2px 0 0; }
|
||||||
|
.mock .running { margin-top: 10px; padding: 10px 12px; }
|
||||||
|
.mock .run-head { font-size: .84rem; }
|
||||||
|
.mock .bar { margin-top: 8px; }
|
||||||
|
.mock .w-60 { width: 60%; }
|
||||||
|
.mock table { font-size: .82rem; }
|
||||||
|
.mock th, .mock td { padding: 6px 6px; }
|
||||||
|
.mock th { font-weight: 600; color: var(--muted); font-size: .76rem; }
|
||||||
|
.mock td.st-replied { color: var(--ok); font-weight: 600; }
|
||||||
|
.mock td.st-new { color: var(--accent); }
|
||||||
|
.mock .table-wrap { margin: 0 -4px; }
|
||||||
|
@media (max-width: 480px) {
|
||||||
|
.mock .col-city { display: none; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---------- Sections ---------- */
|
||||||
|
.block { padding-top: 56px; padding-bottom: 56px; }
|
||||||
|
.block + .block { border-top: 1px solid var(--line); }
|
||||||
|
/* Repère gradué : une règle fine à graduations, unique élément décoratif des séparations */
|
||||||
|
.rule { height: 9px; border-top: 1px solid var(--line); border-bottom: 1px solid var(--line);
|
||||||
|
background: repeating-linear-gradient(90deg, var(--line) 0 1px, transparent 1px 14px); }
|
||||||
|
.split { display: grid; gap: 22px; }
|
||||||
|
@media (min-width: 900px) {
|
||||||
|
.split { grid-template-columns: minmax(0, 4fr) minmax(0, 7fr); gap: 56px; }
|
||||||
|
.split > .sticky { position: sticky; top: 24px; align-self: start; }
|
||||||
|
.block { padding-top: 80px; padding-bottom: 80px; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Liste de faits : des lignes séparées par un filet, pas des cartes */
|
||||||
|
.facts { margin: 0; padding: 0; list-style: none; border-top: 1px solid var(--line); }
|
||||||
|
.facts > li { padding: 18px 0; border-bottom: 1px solid var(--line); }
|
||||||
|
.facts h3 { margin: 0 0 .3em; font-size: 1.05rem; }
|
||||||
|
.facts p { margin: 0; color: var(--text); }
|
||||||
|
.facts p + p { margin-top: .6em; }
|
||||||
|
.facts .muted { color: var(--muted); }
|
||||||
|
|
||||||
|
/* Étapes numérotées */
|
||||||
|
.steps { list-style: none; margin: 0; padding: 0; counter-reset: etape; }
|
||||||
|
.steps > li { counter-increment: etape; position: relative; padding: 0 0 28px 56px; }
|
||||||
|
.steps > li::before { content: counter(etape); position: absolute; left: 0; top: 2px; width: 36px; height: 36px;
|
||||||
|
display: grid; place-items: center; font-weight: 700; font-variant-numeric: tabular-nums; color: var(--accent-text);
|
||||||
|
background: var(--accent); clip-path: polygon(0 0, 70% 0, 100% 30%, 100% 100%, 0 100%); }
|
||||||
|
@media (prefers-color-scheme: dark) { .steps > li::before { color: var(--bg); } }
|
||||||
|
.steps > li::after { content: ""; position: absolute; left: 17px; top: 44px; bottom: 6px; width: 1px; background: var(--line); }
|
||||||
|
.steps > li:last-child { padding-bottom: 0; }
|
||||||
|
.steps > li:last-child::after { content: none; }
|
||||||
|
.steps h2, .steps h3 { margin: 0 0 .3em; font-size: 1.2rem; line-height: 1.3; letter-spacing: -.01em; }
|
||||||
|
.steps p { margin: 0 0 .6em; }
|
||||||
|
.steps ul { margin: .2em 0 .8em; padding-left: 1.2em; }
|
||||||
|
.steps li li { padding: 0; margin: .25em 0; }
|
||||||
|
.steps li li::before, .steps li li::after { content: none; }
|
||||||
|
|
||||||
|
/* Version compacte (accueil) : deux colonnes dès la tablette */
|
||||||
|
.steps.compact > li { padding-bottom: 20px; }
|
||||||
|
.steps.compact h3 { font-size: 1.02rem; }
|
||||||
|
.steps.compact p { margin: 0; color: var(--muted); }
|
||||||
|
@media (min-width: 760px) {
|
||||||
|
.steps.compact { display: grid; grid-template-columns: 1fr 1fr; column-gap: 48px; }
|
||||||
|
.steps.compact > li::after { content: none; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Texte posé en grand, sans cartes ni puces */
|
||||||
|
.statement { max-width: 40rem; }
|
||||||
|
.statement p { font-size: clamp(1.1rem, 2.6vw, 1.4rem); line-height: 1.5; letter-spacing: -.01em; margin: 0 0 .9em; }
|
||||||
|
.statement h3 { margin-top: 1.4em; font-size: 1.05rem; }
|
||||||
|
.statement h3 + p { font-size: 1rem; line-height: 1.6; letter-spacing: 0; max-width: 34rem; }
|
||||||
|
@media (min-width: 900px) { .statement { margin-left: calc(36% + 4px); } }
|
||||||
|
code { font-size: .88em; background: var(--locked); padding: 1px 5px; border-radius: 4px; }
|
||||||
|
|
||||||
|
/* ---------- Tarifs ---------- */
|
||||||
|
.plans { display: grid; gap: 18px; }
|
||||||
|
@media (min-width: 820px) { .plans { grid-template-columns: minmax(0, 6fr) minmax(0, 5fr); align-items: start; } }
|
||||||
|
.plan { padding: 24px 22px; }
|
||||||
|
.plan h2 { font-size: 1.4rem; margin: 0 0 4px; }
|
||||||
|
.plan .price { font-size: 2.4rem; font-weight: 700; letter-spacing: -.03em; line-height: 1.1; margin: 8px 0 14px; }
|
||||||
|
.plan .price small { font-size: .95rem; font-weight: 400; color: var(--muted); letter-spacing: 0; }
|
||||||
|
.plan.soon { background: transparent; border-style: dashed; }
|
||||||
|
.limits { list-style: none; margin: 0 0 18px; padding: 0; }
|
||||||
|
.limits li { display: flex; align-items: baseline; justify-content: space-between; gap: 14px; padding: 9px 0; border-top: 1px solid var(--line); }
|
||||||
|
.limits li:last-child { border-bottom: 1px solid var(--line); }
|
||||||
|
.limits strong { font-variant-numeric: tabular-nums; font-size: 1.1rem; white-space: nowrap; }
|
||||||
|
|
||||||
|
/* ---------- Bandeau final ---------- */
|
||||||
|
.closing { display: grid; gap: 18px; align-items: center; }
|
||||||
|
@media (min-width: 820px) { .closing { grid-template-columns: 1fr auto; gap: 40px; } }
|
||||||
|
.closing h2 { margin: 0; }
|
||||||
|
.closing p { margin: .4em 0 0; }
|
||||||
|
|
||||||
|
/* ---------- Pages de texte (légal) ---------- */
|
||||||
|
.page-head { padding-top: 44px; padding-bottom: 24px; }
|
||||||
|
.page-head h1 { font-size: clamp(1.9rem, 5vw, 2.7rem); }
|
||||||
|
.page-head .lead { margin-bottom: 0; }
|
||||||
|
.prose-wrap { display: grid; gap: 28px; padding-bottom: 72px; }
|
||||||
|
@media (min-width: 900px) {
|
||||||
|
.prose-wrap { grid-template-columns: minmax(0, 220px) minmax(0, 1fr); gap: 56px; }
|
||||||
|
.toc { position: sticky; top: 24px; align-self: start; }
|
||||||
|
}
|
||||||
|
.toc { font-size: .9rem; }
|
||||||
|
.toc h2 { font-size: .8rem; letter-spacing: .06em; text-transform: uppercase; color: var(--muted); margin: 0 0 .6em; }
|
||||||
|
.toc ol { list-style: none; margin: 0; padding: 0; }
|
||||||
|
.toc li { margin: 0; }
|
||||||
|
.toc a { display: block; padding: 5px 0; color: var(--text); text-decoration: none; border-left: 2px solid var(--line); padding-left: 12px; }
|
||||||
|
.toc a:hover { border-left-color: var(--accent); }
|
||||||
|
.prose { max-width: 44rem; }
|
||||||
|
.prose h2 { margin-top: 2.2em; padding-top: .2em; scroll-margin-top: 16px; }
|
||||||
|
.prose h2:first-child { margin-top: 0; }
|
||||||
|
.prose ul, .prose ol { padding-left: 1.3em; margin: 0 0 1em; }
|
||||||
|
.prose li { margin: .35em 0; }
|
||||||
|
.prose dl { margin: 0 0 1em; display: grid; grid-template-columns: max-content 1fr; gap: 8px 22px; }
|
||||||
|
.prose dt { color: var(--muted); }
|
||||||
|
.prose dd { margin: 0; }
|
||||||
|
@media (max-width: 560px) { .prose dl { grid-template-columns: 1fr; gap: 0; } .prose dd { margin-bottom: .8em; } }
|
||||||
|
.prose .table-wrap { margin: 0 0 1.2em; border: 1px solid var(--line); border-radius: 10px; background: var(--card); }
|
||||||
|
.prose th, .prose td { white-space: normal; vertical-align: top; padding: 10px 12px; }
|
||||||
|
.prose tr:last-child td { border-bottom: 0; }
|
||||||
|
.prose caption { text-align: left; padding: 10px 12px; font-weight: 600; }
|
||||||
|
.prose .notice { padding: 12px 16px; margin: 0 0 1.2em; }
|
||||||
|
.prose .notice p:last-child { margin-bottom: 0; }
|
||||||
|
.updated { color: var(--muted); font-size: .88rem; }
|
||||||
|
/* Marqueurs à compléter : bien visibles tant que le texte n'est pas final */
|
||||||
|
mark.todo { background: color-mix(in srgb, var(--warn) 16%, transparent); color: var(--text); padding: 1px 6px; border-radius: 4px;
|
||||||
|
outline: 1px dashed var(--warn); font-weight: 600; }
|
||||||
|
|
||||||
|
/* ---------- Connexion ---------- */
|
||||||
|
.auth { display: grid; gap: 28px; padding-top: 44px; padding-bottom: 72px; }
|
||||||
|
@media (min-width: 900px) { .auth { grid-template-columns: minmax(0, 6fr) minmax(0, 5fr); gap: 64px; align-items: start; padding-top: 72px; } }
|
||||||
|
.auth .card { padding: 22px; }
|
||||||
|
.auth .login-btns { margin-top: 12px; }
|
||||||
|
.auth .login-btns .btn { text-align: center; padding: 11px 18px; }
|
||||||
|
.auth .card h2 { font-size: 1.25rem; }
|
||||||
|
.auth p.ok, .auth p.error { padding: 10px 14px; border: 1px solid currentColor; border-radius: 8px; margin: 0 0 1em; }
|
||||||
|
|
||||||
|
/* ---------- Pied de page ---------- */
|
||||||
|
.site-foot { border-top: 1px solid var(--line); background: var(--card); margin-top: 0; font-size: .92rem; }
|
||||||
|
.foot-in { display: grid; gap: 26px; padding-top: 36px; padding-bottom: 36px; }
|
||||||
|
@media (min-width: 760px) { .foot-in { grid-template-columns: 1.4fr 1fr 1fr; gap: 48px; } }
|
||||||
|
.site-foot h2 { font-size: .8rem; letter-spacing: .06em; text-transform: uppercase; color: var(--muted); margin: 0 0 .7em; }
|
||||||
|
.site-foot ul { list-style: none; margin: 0; padding: 0; }
|
||||||
|
.site-foot li { margin: .3em 0; }
|
||||||
|
.site-foot a { color: var(--text); }
|
||||||
|
.site-foot a:hover { color: var(--accent); }
|
||||||
|
.site-foot p { margin: 0 0 .6em; }
|
||||||
|
.site-foot .brand { display: inline-flex; align-items: center; gap: 9px; margin-bottom: .6em; font-size: 1.05rem; }
|
||||||
|
|
||||||
|
/* ---------- Mouvement : une seule entrée sobre, supprimée si l'utilisateur le demande ---------- */
|
||||||
|
@media (prefers-reduced-motion: no-preference) {
|
||||||
|
.hero-text, .shot { animation: site-in .5s var(--ease, ease-out) both; }
|
||||||
|
.shot { animation-delay: .08s; }
|
||||||
|
@keyframes site-in { from { opacity: 0; transform: translateY(8px); } }
|
||||||
|
}
|
||||||
149
scripts/migrate-sqlite-to-mysql.js
Normal file
149
scripts/migrate-sqlite-to-mysql.js
Normal file
|
|
@ -0,0 +1,149 @@
|
||||||
|
// Copie une ancienne base SQLite (data/aitools.sqlite) vers la base MySQL/MariaDB, ids conservés.
|
||||||
|
//
|
||||||
|
// node --env-file=.env scripts/migrate-sqlite-to-mysql.js data/aitools.sqlite [--force]
|
||||||
|
//
|
||||||
|
// - cible = variables DB_HOST, DB_PORT, DB_USER, DB_PASSWORD, DB_NAME (les migrations sont appliquées avant la copie) ;
|
||||||
|
// - l'ancienne base est mono-utilisateur : toutes ses données sont rattachées au propriétaire, c'est-à-dire la
|
||||||
|
// première adresse de ADMIN_EMAILS (compte créé s'il n'existe pas) ; les anciens réglages deviennent ses réglages ;
|
||||||
|
// - les sessions et les états OAuth de l'ancienne base ne sont pas copiés (éphémères, liés à l'ancien modèle) ;
|
||||||
|
// - tout se passe dans UNE transaction : en cas d'erreur ou de comptes différents, rien n'est écrit ;
|
||||||
|
// - refuse si la cible contient déjà des données, sauf --force (qui VIDE alors les tables cibles avant la copie) ;
|
||||||
|
// - la source est ouverte en lecture seule. Arrête l'ancien service avant, pour copier une base figée.
|
||||||
|
import { DatabaseSync } from 'node:sqlite';
|
||||||
|
import { existsSync } from 'node:fs';
|
||||||
|
import { fileURLToPath } from 'node:url';
|
||||||
|
import { openDb, dbConfigFromEnv, now } from '../src/db.js';
|
||||||
|
|
||||||
|
// Ordre de copie : parents avant enfants (clés étrangères). La suppression (--force) suit l'ordre inverse.
|
||||||
|
// `settings` (clé/valeur globale) devient `user_settings` du propriétaire.
|
||||||
|
export const TABLES = [
|
||||||
|
'settings', 'projects', 'templates', 'prospects', 'blacklist',
|
||||||
|
'jobs', 'mail_log', 'prospect_notes', 'metrics_daily',
|
||||||
|
];
|
||||||
|
export const SKIPPED = ['sessions', 'oauth_states'];
|
||||||
|
const TARGET_TABLE = { settings: 'user_settings' };
|
||||||
|
const OWNED = new Set(['settings', 'projects', 'jobs']); // tables de la cible qui portent un user_id
|
||||||
|
const LEGACY_USER_VERSION = 8; // dernière version du schéma de l'ancienne base SQLite à user_version
|
||||||
|
const LEGACY_MIGRATION = 1; // schéma consolidé de la migration 1 (avant les comptes)
|
||||||
|
const BATCH = 200;
|
||||||
|
|
||||||
|
const q = (name) => `\`${name}\``;
|
||||||
|
|
||||||
|
// Vérifie que la source est au schéma attendu (sinon des colonnes manqueraient en silence)
|
||||||
|
function checkSourceVersion(src) {
|
||||||
|
const hasTable = (n) => src.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?").get(n);
|
||||||
|
if (hasTable('schema_migrations')) {
|
||||||
|
const v = src.prepare('SELECT MAX(version) v FROM schema_migrations').get().v;
|
||||||
|
if (v !== LEGACY_MIGRATION) {
|
||||||
|
throw new Error(`Schéma source en version ${v}, attendu ${LEGACY_MIGRATION} (base d'avant les comptes). Une base déjà au schéma multi-utilisateur ne se copie pas avec ce script.`);
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const { user_version: uv } = src.prepare('PRAGMA user_version').get();
|
||||||
|
if (uv !== LEGACY_USER_VERSION) {
|
||||||
|
throw new Error(`Base SQLite en version ${uv}, attendue ${LEGACY_USER_VERSION} : lance d'abord l'ancienne version de l'application pour la mettre à jour.`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function targetColumns(dialect, db, table) {
|
||||||
|
if (dialect === 'sqlite') return (await db.query(`PRAGMA table_info(${table})`)).map((c) => c.name);
|
||||||
|
const rows = await db.query('SELECT column_name c FROM information_schema.columns WHERE table_schema = DATABASE() AND table_name = ?', [table]);
|
||||||
|
return rows.map((r) => r.c ?? r.COLUMN_NAME);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param {{ sourcePath: string, db: object, ownerEmail: string, force?: boolean, log?: (line: string) => void }} o
|
||||||
|
* @returns {Promise<{ tables: {table: string, source: number, copied: number, target: number}[], total: number, ownerId: number }>}
|
||||||
|
*/
|
||||||
|
export async function migrateSqliteToMysql({ sourcePath, db, ownerEmail, force = false, log = () => {} }) {
|
||||||
|
const owner = String(ownerEmail || '').trim().toLowerCase();
|
||||||
|
if (!owner) throw new Error('Propriétaire des données manquant : définis ADMIN_EMAILS (la première adresse est utilisée).');
|
||||||
|
if (!existsSync(sourcePath)) throw new Error(`Fichier introuvable : ${sourcePath}`);
|
||||||
|
const src = new DatabaseSync(sourcePath, { readOnly: true });
|
||||||
|
try {
|
||||||
|
checkSourceVersion(src);
|
||||||
|
|
||||||
|
// Cible vide ?
|
||||||
|
const filled = [];
|
||||||
|
for (const t of TABLES) {
|
||||||
|
const target = TARGET_TABLE[t] || t;
|
||||||
|
const n = (await db.prepare(`SELECT COUNT(*) n FROM ${q(target)}`).get()).n;
|
||||||
|
if (n > 0) filled.push(`${target} (${n})`);
|
||||||
|
}
|
||||||
|
if (filled.length && !force) {
|
||||||
|
throw new Error(`La base cible n'est pas vide : ${filled.join(', ')}. Relance avec --force pour la vider avant la copie.`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const report = [];
|
||||||
|
let ownerId;
|
||||||
|
await db.transaction(async (tx) => {
|
||||||
|
if (filled.length) {
|
||||||
|
log(`--force : vidage de la cible (${filled.join(', ')})`);
|
||||||
|
for (const t of [...TABLES].reverse()) await tx.prepare(`DELETE FROM ${q(TARGET_TABLE[t] || t)}`).run();
|
||||||
|
}
|
||||||
|
// Le propriétaire : compte existant (même email) ou créé ici, administrateur
|
||||||
|
const found = await tx.prepare('SELECT id FROM users WHERE email = ?').get(owner);
|
||||||
|
ownerId = found
|
||||||
|
? Number(found.id)
|
||||||
|
: Number((await tx.prepare("INSERT INTO users(email, status, is_admin, plan, created_at) VALUES(?, 'active', 1, 'free', ?)").run(owner, now())).lastInsertRowid);
|
||||||
|
log(`propriétaire ${owner} (id ${ownerId})`);
|
||||||
|
|
||||||
|
for (const table of TABLES) {
|
||||||
|
const targetTable = TARGET_TABLE[table] || table;
|
||||||
|
const srcCols = src.prepare(`PRAGMA table_info(${table})`).all().map((c) => c.name);
|
||||||
|
if (!srcCols.length) throw new Error(`Table source absente : ${table}`);
|
||||||
|
const dstCols = new Set(await targetColumns(db.dialect, tx, targetTable));
|
||||||
|
const lost = srcCols.filter((c) => !dstCols.has(c));
|
||||||
|
if (lost.length) throw new Error(`${table} : colonnes sans équivalent dans la cible (${lost.join(', ')})`);
|
||||||
|
|
||||||
|
const owned = OWNED.has(table);
|
||||||
|
const cols = owned ? ['user_id', ...srcCols] : srcCols;
|
||||||
|
const rows = src.prepare(`SELECT ${srcCols.map(q).join(', ')} FROM ${q(table)}`).all();
|
||||||
|
const sqlHead = `INSERT INTO ${q(targetTable)} (${cols.map(q).join(', ')}) VALUES `;
|
||||||
|
const one = `(${cols.map(() => '?').join(', ')})`;
|
||||||
|
let copied = 0;
|
||||||
|
for (let i = 0; i < rows.length; i += BATCH) {
|
||||||
|
const chunk = rows.slice(i, i + BATCH);
|
||||||
|
const values = chunk.flatMap((r) => (owned ? [ownerId] : []).concat(srcCols.map((c) => r[c])));
|
||||||
|
const res = await tx.prepare(sqlHead + chunk.map(() => one).join(', ')).run(...values);
|
||||||
|
copied += res.changes;
|
||||||
|
}
|
||||||
|
const target = (await tx.prepare(`SELECT COUNT(*) n FROM ${q(targetTable)}${owned ? ' WHERE user_id = ?' : ''}`).get(...(owned ? [ownerId] : []))).n;
|
||||||
|
report.push({ table, source: rows.length, copied, target });
|
||||||
|
log(`${table.padEnd(16)} source ${String(rows.length).padStart(6)} copiées ${String(copied).padStart(6)} cible ${String(target).padStart(6)}`);
|
||||||
|
// Toute différence annule la transaction : on ne laisse jamais une copie partielle
|
||||||
|
if (copied !== rows.length || target !== rows.length) {
|
||||||
|
throw new Error(`${table} : ${rows.length} lignes en source, ${copied} copiées, ${target} en cible. Copie annulée.`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
return { tables: report, total: report.reduce((t, r) => t + r.copied, 0), ownerId };
|
||||||
|
} finally {
|
||||||
|
src.close();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function main() {
|
||||||
|
const args = process.argv.slice(2);
|
||||||
|
const force = args.includes('--force');
|
||||||
|
const sourcePath = args.find((a) => !a.startsWith('--'));
|
||||||
|
if (!sourcePath) {
|
||||||
|
console.error('Usage : node --env-file=.env scripts/migrate-sqlite-to-mysql.js <chemin/aitools.sqlite> [--force]');
|
||||||
|
process.exit(2);
|
||||||
|
}
|
||||||
|
const cfg = dbConfigFromEnv();
|
||||||
|
if (cfg.driver !== 'mysql') throw new Error('La cible doit être MySQL/MariaDB (DB_HOST, DB_USER, DB_NAME).');
|
||||||
|
const adminEmails = (process.env.ADMIN_EMAILS || '').split(',').map((e) => e.trim().toLowerCase()).filter(Boolean);
|
||||||
|
console.log(`Source : ${sourcePath}\nCible : ${cfg.user}@${cfg.host}:${cfg.port}/${cfg.database}${force ? ' (--force)' : ''}\n`);
|
||||||
|
const db = await openDb(cfg, { adminEmails });
|
||||||
|
try {
|
||||||
|
const { total } = await migrateSqliteToMysql({ sourcePath, db, ownerEmail: adminEmails[0], force, log: console.log });
|
||||||
|
console.log(`\nTerminé : ${total} lignes copiées, comptes identiques entre source et cible. Sessions de l'ancienne base non copiées : reconnecte-toi.`);
|
||||||
|
} finally {
|
||||||
|
await db.close();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (process.argv[1] === fileURLToPath(import.meta.url)) {
|
||||||
|
main().catch((e) => { console.error(`\nÉchec : ${e.message}`); process.exit(1); });
|
||||||
|
}
|
||||||
293
src/auth.js
293
src/auth.js
|
|
@ -1,106 +1,261 @@
|
||||||
// Auth Google (OIDC, code flow + PKCE) avec whitelist d'emails. Sessions en SQLite.
|
// Connexion Google et Apple (OIDC, code flow), sessions en base liées à users.id.
|
||||||
import { createHash } from 'node:crypto';
|
// Pas de mot de passe : l'inscription est automatique à la première connexion réussie.
|
||||||
|
import { createHash, createPrivateKey, createPublicKey, sign, verify, timingSafeEqual } from 'node:crypto';
|
||||||
import { now } from './db.js';
|
import { now } from './db.js';
|
||||||
import { randomId } from './crypto.js';
|
import { randomId } from './crypto.js';
|
||||||
import { parseCookies, setCookie, redirect, HttpError } from './http.js';
|
import { parseCookies, setCookie, redirect, HttpError } from './http.js';
|
||||||
|
import { loginIdentity } from './users.js';
|
||||||
|
|
||||||
const SESSION_COOKIE = 'sid';
|
const SESSION_COOKIE = 'sid';
|
||||||
|
const BIND_COOKIE = 'oauth_b';
|
||||||
const SESSION_TTL = 30 * 24 * 3600;
|
const SESSION_TTL = 30 * 24 * 3600;
|
||||||
const STATE_TTL = 600;
|
const STATE_TTL = 600;
|
||||||
const GOOGLE_AUTH = 'https://accounts.google.com/o/oauth2/v2/auth';
|
const JWKS_TTL = 3600;
|
||||||
const GOOGLE_TOKEN = 'https://oauth2.googleapis.com/token';
|
const APPLE_AUD = 'https://appleid.apple.com';
|
||||||
|
|
||||||
export function getSession(db, req) {
|
export const PROVIDERS = {
|
||||||
|
google: {
|
||||||
|
label: 'Google',
|
||||||
|
authUrl: 'https://accounts.google.com/o/oauth2/v2/auth',
|
||||||
|
tokenUrl: 'https://oauth2.googleapis.com/token',
|
||||||
|
jwksUrl: 'https://www.googleapis.com/oauth2/v3/certs',
|
||||||
|
issuers: ['https://accounts.google.com', 'accounts.google.com'],
|
||||||
|
scope: 'openid email profile',
|
||||||
|
extra: { prompt: 'select_account' },
|
||||||
|
pkce: true,
|
||||||
|
},
|
||||||
|
apple: {
|
||||||
|
label: 'Apple',
|
||||||
|
authUrl: 'https://appleid.apple.com/auth/authorize',
|
||||||
|
tokenUrl: 'https://appleid.apple.com/auth/token',
|
||||||
|
jwksUrl: 'https://appleid.apple.com/auth/keys',
|
||||||
|
issuers: [APPLE_AUD],
|
||||||
|
scope: 'name email',
|
||||||
|
extra: { response_mode: 'form_post' }, // obligatoire dès que le scope demande le nom ou l'email
|
||||||
|
pkce: false,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
// ---------- Sessions ----------
|
||||||
|
|
||||||
|
/** Session valide d'un compte actif. Un compte suspendu n'a plus de session utilisable (elles sont supprimées). */
|
||||||
|
export async function getSession(db, req) {
|
||||||
const sid = parseCookies(req)[SESSION_COOKIE];
|
const sid = parseCookies(req)[SESSION_COOKIE];
|
||||||
if (!sid) return null;
|
if (!sid) return null;
|
||||||
const s = db.prepare('SELECT * FROM sessions WHERE id = ? AND expires_at > ?').get(sid, now());
|
const s = await db.prepare(`SELECT s.id, s.user_id, u.email, u.name, u.provider, u.status, u.is_admin
|
||||||
return s || null;
|
FROM sessions s JOIN users u ON u.id = s.user_id WHERE s.id = ? AND s.expires_at > ?`).get(sid, now());
|
||||||
|
if (!s) return null;
|
||||||
|
if (s.status !== 'active') {
|
||||||
|
await db.prepare('DELETE FROM sessions WHERE user_id = ?').run(s.user_id);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
id: s.id, userId: Number(s.user_id), email: s.email,
|
||||||
|
user: { id: Number(s.user_id), email: s.email, name: s.name, provider: s.provider, status: s.status, isAdmin: !!s.is_admin },
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
export function createSession(db, res, email) {
|
export async function createSession(db, res, userId) {
|
||||||
const id = randomId();
|
const id = randomId();
|
||||||
db.prepare('INSERT INTO sessions(id, email, created_at, expires_at) VALUES(?, ?, ?, ?)')
|
await db.prepare('INSERT INTO sessions(id, user_id, created_at, expires_at) VALUES(?, ?, ?, ?)')
|
||||||
.run(id, email, now(), now() + SESSION_TTL);
|
.run(id, userId, now(), now() + SESSION_TTL);
|
||||||
setCookie(res, SESSION_COOKIE, id, { maxAge: SESSION_TTL });
|
setCookie(res, SESSION_COOKIE, id, { maxAge: SESSION_TTL });
|
||||||
}
|
}
|
||||||
|
|
||||||
export function destroySession(db, req, res) {
|
export async function destroySession(db, req, res) {
|
||||||
const sid = parseCookies(req)[SESSION_COOKIE];
|
const sid = parseCookies(req)[SESSION_COOKIE];
|
||||||
if (sid) db.prepare('DELETE FROM sessions WHERE id = ?').run(sid);
|
if (sid) await db.prepare('DELETE FROM sessions WHERE id = ?').run(sid);
|
||||||
setCookie(res, SESSION_COOKIE, '', { maxAge: 0 });
|
setCookie(res, SESSION_COOKIE, '', { maxAge: 0 });
|
||||||
}
|
}
|
||||||
|
|
||||||
export function purgeExpired(db) {
|
/** Suspension : toutes les sessions du compte tombent tout de suite. */
|
||||||
db.prepare('DELETE FROM sessions WHERE expires_at < ?').run(now());
|
export async function destroyUserSessions(db, userId) {
|
||||||
db.prepare('DELETE FROM oauth_states WHERE created_at < ?').run(now() - STATE_TTL);
|
await db.prepare('DELETE FROM sessions WHERE user_id = ?').run(userId);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function startGoogleLogin(db, cfg, res) {
|
export async function purgeExpired(db) {
|
||||||
const state = randomId(24);
|
await db.prepare('DELETE FROM sessions WHERE expires_at < ?').run(now());
|
||||||
const nonce = randomId(24);
|
await db.prepare('DELETE FROM oauth_states WHERE created_at < ?').run(now() - STATE_TTL);
|
||||||
const verifier = randomId(48);
|
|
||||||
const challenge = createHash('sha256').update(verifier).digest('base64url');
|
|
||||||
db.prepare('INSERT INTO oauth_states(state, verifier, nonce, created_at) VALUES(?, ?, ?, ?)')
|
|
||||||
.run(state, verifier, nonce, now());
|
|
||||||
const q = new URLSearchParams({
|
|
||||||
client_id: cfg.google.clientId,
|
|
||||||
redirect_uri: `${cfg.appUrl}/auth/google/callback`,
|
|
||||||
response_type: 'code',
|
|
||||||
scope: 'openid email',
|
|
||||||
state, nonce,
|
|
||||||
code_challenge: challenge,
|
|
||||||
code_challenge_method: 'S256',
|
|
||||||
prompt: 'select_account',
|
|
||||||
});
|
|
||||||
redirect(res, `${GOOGLE_AUTH}?${q}`);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Vérifie les claims de l'id_token. Il est reçu directement de Google en TLS (code flow),
|
// ---------- JWT ----------
|
||||||
// la validation TLS remplace la vérification de signature (OIDC Core §3.1.3.7).
|
|
||||||
export function checkIdTokenClaims(claims, { clientId, nonce, allowedEmails, at = now() }) {
|
const b64json = (part) => JSON.parse(Buffer.from(part, 'base64url').toString('utf8'));
|
||||||
if (!['https://accounts.google.com', 'accounts.google.com'].includes(claims.iss)) throw new HttpError(401, 'Émetteur invalide');
|
const b64 = (obj) => Buffer.from(JSON.stringify(obj)).toString('base64url');
|
||||||
if (claims.aud !== clientId) throw new HttpError(401, 'Audience invalide');
|
|
||||||
if (!claims.exp || claims.exp < at) throw new HttpError(401, 'Token expiré');
|
|
||||||
if (claims.nonce !== nonce) throw new HttpError(401, 'Nonce invalide');
|
|
||||||
if (!claims.email_verified) throw new HttpError(403, 'Email Google non vérifié');
|
|
||||||
const email = String(claims.email || '').toLowerCase();
|
|
||||||
if (!allowedEmails.includes(email)) throw new HttpError(403, 'Compte non autorisé');
|
|
||||||
return email;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function decodeJwtPayload(jwt) {
|
export function decodeJwtPayload(jwt) {
|
||||||
const part = String(jwt).split('.')[1];
|
const part = String(jwt).split('.')[1];
|
||||||
if (!part) throw new HttpError(401, 'id_token invalide');
|
if (!part) throw new HttpError(401, 'id_token invalide');
|
||||||
return JSON.parse(Buffer.from(part, 'base64url').toString('utf8'));
|
try { return b64json(part); } catch { throw new HttpError(401, 'id_token invalide'); }
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function finishGoogleLogin(db, cfg, url, res) {
|
/**
|
||||||
const code = url.searchParams.get('code');
|
* Secret client Apple : un JWT signé en ES256 avec la clé privée du compte développeur
|
||||||
const state = url.searchParams.get('state');
|
* (APPLE_KEY_ID / APPLE_TEAM_ID / APPLE_CLIENT_ID). Signature brute r||s (ieee-p1363), comme l'exige JWS.
|
||||||
|
*/
|
||||||
|
export function appleClientSecret(apple, { at = now(), ttl = 300 } = {}) {
|
||||||
|
const head = b64({ alg: 'ES256', kid: apple.keyId, typ: 'JWT' });
|
||||||
|
const body = b64({ iss: apple.teamId, iat: at, exp: at + ttl, aud: APPLE_AUD, sub: apple.clientId });
|
||||||
|
const sig = sign('sha256', Buffer.from(`${head}.${body}`), { key: createPrivateKey(apple.privateKey), dsaEncoding: 'ieee-p1363' });
|
||||||
|
return `${head}.${body}.${sig.toString('base64url')}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
const fetcher = (app) => app.fetch || fetch;
|
||||||
|
|
||||||
|
async function loadJwks(app, url) {
|
||||||
|
const r = await fetcher(app)(url, { signal: AbortSignal.timeout(10_000) });
|
||||||
|
if (!r.ok) throw new HttpError(502, `Clés publiques indisponibles (${r.status})`);
|
||||||
|
const keys = (await r.json()).keys;
|
||||||
|
if (!Array.isArray(keys)) throw new HttpError(502, 'Clés publiques invalides');
|
||||||
|
return keys;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Clés du fournisseur en cache ; une clé inconnue (rotation) déclenche une seule relecture, pas plus d'une par minute
|
||||||
|
async function findJwk(app, url, kid) {
|
||||||
|
const cache = (app.jwksCache ??= new Map());
|
||||||
|
let entry = cache.get(url);
|
||||||
|
const find = (e) => e?.keys.find((k) => k.kid === kid && k.kty === 'RSA');
|
||||||
|
if (!entry || now() - entry.at > JWKS_TTL) {
|
||||||
|
entry = { keys: await loadJwks(app, url), at: now() };
|
||||||
|
cache.set(url, entry);
|
||||||
|
} else if (!find(entry) && now() - entry.at > 60) {
|
||||||
|
entry = { keys: await loadJwks(app, url), at: now() };
|
||||||
|
cache.set(url, entry);
|
||||||
|
}
|
||||||
|
return find(entry);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Vérifie la signature RS256 d'un id_token avec les JWKS du fournisseur, et renvoie ses claims (pas encore validés). */
|
||||||
|
export async function verifyIdTokenSignature(app, jwt, jwksUrl) {
|
||||||
|
const parts = String(jwt || '').split('.');
|
||||||
|
if (parts.length !== 3) throw new HttpError(401, 'id_token invalide');
|
||||||
|
let header;
|
||||||
|
try { header = b64json(parts[0]); } catch { throw new HttpError(401, 'id_token invalide'); }
|
||||||
|
if (header.alg !== 'RS256') throw new HttpError(401, 'Algorithme de signature refusé');
|
||||||
|
const jwk = await findJwk(app, jwksUrl, header.kid);
|
||||||
|
if (!jwk) throw new HttpError(401, 'Clé de signature inconnue');
|
||||||
|
let ok = false;
|
||||||
|
try {
|
||||||
|
ok = verify('RSA-SHA256', Buffer.from(`${parts[0]}.${parts[1]}`), createPublicKey({ key: jwk, format: 'jwk' }), Buffer.from(parts[2], 'base64url'));
|
||||||
|
} catch { ok = false; }
|
||||||
|
if (!ok) throw new HttpError(401, 'Signature de l\'id_token invalide');
|
||||||
|
return decodeJwtPayload(jwt);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Valide les claims d'un id_token déjà authentifié (signature vérifiée) : émetteur, audience, expiration,
|
||||||
|
* nonce, identifiant (sub) et email vérifié. Renvoie l'identité à inscrire / connecter.
|
||||||
|
*/
|
||||||
|
export function checkIdTokenClaims(claims, { issuers, clientId, nonce, at = now() }) {
|
||||||
|
if (!issuers.includes(claims.iss)) throw new HttpError(401, 'Émetteur invalide');
|
||||||
|
const aud = Array.isArray(claims.aud) ? claims.aud : [claims.aud];
|
||||||
|
if (!aud.includes(clientId)) throw new HttpError(401, 'Audience invalide');
|
||||||
|
if (!claims.exp || claims.exp < at) throw new HttpError(401, 'Token expiré');
|
||||||
|
if (!claims.nonce || claims.nonce !== nonce) throw new HttpError(401, 'Nonce invalide');
|
||||||
|
if (!claims.sub) throw new HttpError(401, 'Identifiant fournisseur manquant');
|
||||||
|
// Apple renvoie parfois "true" en chaîne
|
||||||
|
if (claims.email_verified !== true && claims.email_verified !== 'true') throw new HttpError(403, 'Email non vérifié par le fournisseur');
|
||||||
|
const email = String(claims.email || '').trim().toLowerCase();
|
||||||
|
if (!email) throw new HttpError(401, 'Email manquant');
|
||||||
|
return { sub: String(claims.sub), email, name: claims.name || null };
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- Flux OAuth ----------
|
||||||
|
|
||||||
|
const hashBind = (v) => createHash('sha256').update(String(v)).digest('hex');
|
||||||
|
|
||||||
|
function providerOf(cfg, name) {
|
||||||
|
const p = PROVIDERS[name];
|
||||||
|
if (!p || (name === 'apple' && !cfg.apple)) throw new HttpError(404, 'Fournisseur de connexion indisponible');
|
||||||
|
return p;
|
||||||
|
}
|
||||||
|
|
||||||
|
const clientIdOf = (cfg, name) => (name === 'apple' ? cfg.apple.clientId : cfg.google.clientId);
|
||||||
|
const redirectUri = (cfg, name) => `${cfg.appUrl}/auth/${name}/callback`;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Démarre la connexion : state + nonce (+ PKCE pour Google) en base, et un cookie qui lie le flux à CE navigateur.
|
||||||
|
* Le retour d'Apple est un POST cross-site (form_post) : ni le cookie de session ni un cookie SameSite=Lax ne
|
||||||
|
* suivent. Le cookie de liaison est donc SameSite=None, Secure, HttpOnly, limité à /auth et à 10 minutes.
|
||||||
|
*/
|
||||||
|
export async function startLogin(app, name, res) {
|
||||||
|
const { db, cfg } = app;
|
||||||
|
const p = providerOf(cfg, name);
|
||||||
|
const state = randomId(24);
|
||||||
|
const nonce = randomId(24);
|
||||||
|
const verifier = randomId(48);
|
||||||
|
const bind = randomId(24);
|
||||||
|
await db.prepare('INSERT INTO oauth_states(state, provider, verifier, nonce, binding, created_at) VALUES(?, ?, ?, ?, ?, ?)')
|
||||||
|
.run(state, name, verifier, nonce, hashBind(bind), now());
|
||||||
|
setCookie(res, BIND_COOKIE, bind, { maxAge: STATE_TTL, sameSite: 'None', path: '/auth' });
|
||||||
|
const q = new URLSearchParams({
|
||||||
|
client_id: clientIdOf(cfg, name),
|
||||||
|
redirect_uri: redirectUri(cfg, name),
|
||||||
|
response_type: 'code',
|
||||||
|
scope: p.scope,
|
||||||
|
state, nonce,
|
||||||
|
...p.extra,
|
||||||
|
});
|
||||||
|
if (p.pkce) {
|
||||||
|
q.set('code_challenge', createHash('sha256').update(verifier).digest('base64url'));
|
||||||
|
q.set('code_challenge_method', 'S256');
|
||||||
|
}
|
||||||
|
redirect(res, `${p.authUrl}?${q}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Apple n'envoie le nom que lors de la toute première autorisation, dans le champ `user` du formulaire
|
||||||
|
function appleName(raw) {
|
||||||
|
try {
|
||||||
|
const n = JSON.parse(raw)?.name;
|
||||||
|
return [n?.firstName, n?.lastName].filter((x) => typeof x === 'string').join(' ').trim() || null;
|
||||||
|
} catch { return null; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Termine la connexion. `params` = paramètres de retour (query pour Google, corps du POST pour Apple).
|
||||||
|
* Contrôles : state connu, à usage unique, non expiré, du bon fournisseur et lié au navigateur (cookie) ;
|
||||||
|
* signature RS256 de l'id_token vérifiée avec les JWKS du fournisseur ; iss / aud / exp / nonce validés.
|
||||||
|
*/
|
||||||
|
export async function finishLogin(app, name, params, req, res) {
|
||||||
|
const { db, cfg } = app;
|
||||||
|
const p = providerOf(cfg, name);
|
||||||
|
const get = (k) => (typeof params.get === 'function' ? params.get(k) : params[k]);
|
||||||
|
const state = get('state');
|
||||||
|
const row = state
|
||||||
|
? await db.prepare('SELECT * FROM oauth_states WHERE state = ? AND created_at > ?').get(String(state), now() - STATE_TTL)
|
||||||
|
: null;
|
||||||
|
if (state) await db.prepare('DELETE FROM oauth_states WHERE state = ?').run(String(state)); // usage unique
|
||||||
|
setCookie(res, BIND_COOKIE, '', { maxAge: 0, sameSite: 'None', path: '/auth' });
|
||||||
|
|
||||||
|
if (get('error')) throw new HttpError(401, get('error') === 'user_cancelled_authorize' ? 'Connexion annulée' : `Connexion refusée (${String(get('error')).slice(0, 60)})`);
|
||||||
|
const code = get('code');
|
||||||
if (!code || !state) throw new HttpError(400, 'Paramètres OAuth manquants');
|
if (!code || !state) throw new HttpError(400, 'Paramètres OAuth manquants');
|
||||||
|
if (!row || row.provider !== name) throw new HttpError(400, 'State OAuth invalide ou expiré');
|
||||||
|
const bind = parseCookies(req)[BIND_COOKIE];
|
||||||
|
const a = Buffer.from(hashBind(bind || ''));
|
||||||
|
const b = Buffer.from(String(row.binding));
|
||||||
|
if (!bind || a.length !== b.length || !timingSafeEqual(a, b)) throw new HttpError(400, 'Connexion démarrée depuis un autre navigateur');
|
||||||
|
|
||||||
const row = db.prepare('SELECT * FROM oauth_states WHERE state = ? AND created_at > ?').get(state, now() - STATE_TTL);
|
const body = new URLSearchParams({
|
||||||
db.prepare('DELETE FROM oauth_states WHERE state = ?').run(state);
|
code: String(code),
|
||||||
if (!row) throw new HttpError(400, 'State OAuth invalide ou expiré');
|
client_id: clientIdOf(cfg, name),
|
||||||
|
client_secret: name === 'apple' ? appleClientSecret(cfg.apple) : cfg.google.clientSecret,
|
||||||
const r = await fetch(GOOGLE_TOKEN, {
|
redirect_uri: redirectUri(cfg, name),
|
||||||
method: 'POST',
|
grant_type: 'authorization_code',
|
||||||
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
|
||||||
body: new URLSearchParams({
|
|
||||||
code,
|
|
||||||
client_id: cfg.google.clientId,
|
|
||||||
client_secret: cfg.google.clientSecret,
|
|
||||||
redirect_uri: `${cfg.appUrl}/auth/google/callback`,
|
|
||||||
grant_type: 'authorization_code',
|
|
||||||
code_verifier: row.verifier,
|
|
||||||
}),
|
|
||||||
});
|
});
|
||||||
if (!r.ok) throw new HttpError(401, `Échange du code Google refusé (${r.status})`);
|
if (p.pkce) body.set('code_verifier', row.verifier);
|
||||||
|
const r = await fetcher(app)(p.tokenUrl, {
|
||||||
|
method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body, signal: AbortSignal.timeout(10_000),
|
||||||
|
});
|
||||||
|
if (!r.ok) throw new HttpError(401, `Échange du code ${p.label} refusé (${r.status})`);
|
||||||
const tokens = await r.json();
|
const tokens = await r.json();
|
||||||
const email = checkIdTokenClaims(decodeJwtPayload(tokens.id_token), {
|
|
||||||
clientId: cfg.google.clientId, nonce: row.nonce, allowedEmails: cfg.allowedEmails,
|
const claims = await verifyIdTokenSignature(app, tokens.id_token, p.jwksUrl);
|
||||||
});
|
const id = checkIdTokenClaims(claims, { issuers: p.issuers, clientId: clientIdOf(cfg, name), nonce: row.nonce });
|
||||||
createSession(db, res, email);
|
if (name === 'apple') id.name = appleName(get('user')) || id.name;
|
||||||
|
|
||||||
|
const user = await loginIdentity(db, cfg, { provider: name, sub: id.sub, email: id.email, name: id.name });
|
||||||
|
await createSession(db, res, user.id);
|
||||||
redirect(res, '/');
|
redirect(res, '/');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
255
src/claudelink.js
Normal file
255
src/claudelink.js
Normal file
|
|
@ -0,0 +1,255 @@
|
||||||
|
// Liaison Claude de chaque utilisateur : clé API Anthropic, jeton d'abonnement (claude setup-token) ou, pour les admins,
|
||||||
|
// configuration du CLI du serveur. Le secret est chiffré (AES-256-GCM) dans users.claude_link_json ; il ne sort jamais
|
||||||
|
// de ce module que sous forme d'environnement du processus enfant, et toujours à partir du user_id du job.
|
||||||
|
import { execFile } from 'node:child_process';
|
||||||
|
import { promisify } from 'node:util';
|
||||||
|
import { now, getSetting, setSetting } from './db.js';
|
||||||
|
import { encrypt, decrypt } from './crypto.js';
|
||||||
|
import { HttpError } from './http.js';
|
||||||
|
import { getUser } from './users.js';
|
||||||
|
import { runClaude } from './services/claude.js';
|
||||||
|
import { buildChildEnv } from './services/sandbox.js';
|
||||||
|
import { AI_JOBS } from './services/budget.js';
|
||||||
|
|
||||||
|
const execFileP = promisify(execFile);
|
||||||
|
|
||||||
|
export const MODES = { api_key: 'api_key', subscription_token: 'subscription_token', server: 'server' };
|
||||||
|
export const MODE_LABELS = {
|
||||||
|
api_key: 'Clé API Anthropic',
|
||||||
|
subscription_token: 'Abonnement Claude (jeton)',
|
||||||
|
server: 'Claude du serveur',
|
||||||
|
};
|
||||||
|
export const LINK_REQUIRED_MESSAGE = 'Relie ton accès Claude pour utiliser cette fonction';
|
||||||
|
export const LINK_INVALID_MESSAGE = "Ta liaison Claude n'est plus valide : teste-la ou relie-la de nouveau (Mon compte)";
|
||||||
|
export const CLI_DISABLED_MESSAGE = "Le mode abonnement est désactivé sur ce service : relie une clé API";
|
||||||
|
export const SERVER_MODE_MESSAGE = 'Le mode « Claude du serveur » est réservé aux administrateurs';
|
||||||
|
|
||||||
|
// Texte de l'avertissement affiché avant le mode abonnement. Toute modification change la version : l'acceptation
|
||||||
|
// enregistrée en base indique à quelle version du texte l'utilisateur a consenti.
|
||||||
|
export const CONSENT_VERSION = '2026-10-22.1';
|
||||||
|
export const CONSENT_TEXT = [
|
||||||
|
"Utiliser un abonnement Claude (Pro, Max) à travers une application tierce peut contrevenir aux conditions d'utilisation d'Anthropic et entraîner la suspension ou la fermeture de ton compte Claude.",
|
||||||
|
'AiTools ne peut en être tenu responsable. Tu utilises ton abonnement à tes propres risques.',
|
||||||
|
"La clé API Anthropic reste l'option recommandée : elle est prévue pour cet usage.",
|
||||||
|
];
|
||||||
|
export const CONSENT_CHECKBOX = "J'ai compris et j'accepte ce risque";
|
||||||
|
|
||||||
|
const API_KEY_RE = /^sk-ant-[A-Za-z0-9_-]{20,400}$/;
|
||||||
|
const TOKEN_RE = /^[A-Za-z0-9_.-]{20,800}$/;
|
||||||
|
const MODELS_URL = 'https://api.anthropic.com/v1/models';
|
||||||
|
const SECRET_ENV = { api_key: 'ANTHROPIC_API_KEY', subscription_token: 'CLAUDE_CODE_OAUTH_TOKEN' };
|
||||||
|
|
||||||
|
const truthy = (v) => v === true || v === 'true' || v === 'on' || v === '1' || v === 1;
|
||||||
|
|
||||||
|
async function readLink(db, userId) {
|
||||||
|
const row = await db.prepare('SELECT claude_link_json FROM users WHERE id = ?').get(Number(userId));
|
||||||
|
if (!row?.claude_link_json) return null;
|
||||||
|
try { return JSON.parse(row.claude_link_json); } catch { return null; }
|
||||||
|
}
|
||||||
|
|
||||||
|
async function writeLink(db, userId, link) {
|
||||||
|
await db.prepare('UPDATE users SET claude_link_json = ? WHERE id = ?').run(link ? JSON.stringify(link) : null, Number(userId));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Forme exposée à l'interface : jamais le secret, seulement ses 4 derniers caractères pour la clé API. */
|
||||||
|
export function publicLink(link) {
|
||||||
|
if (!link?.mode) return null;
|
||||||
|
return {
|
||||||
|
mode: link.mode, label: MODE_LABELS[link.mode], valid: !!link.valid,
|
||||||
|
linkedAt: link.linked_at ?? null, validatedAt: link.validated_at ?? null, lastTestAt: link.last_test_at ?? null,
|
||||||
|
last4: link.mode === 'api_key' ? link.last4 ?? null : null,
|
||||||
|
consentAt: link.consent?.at ?? null, consentVersion: link.consent?.version ?? null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getLinkState(db, userId) {
|
||||||
|
return publicLink(await readLink(db, userId));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Quota d'abonnement et alertes : propres à un compte Claude, repartent de zéro quand la liaison change
|
||||||
|
async function resetQuotaState(db, userId) {
|
||||||
|
await setSetting(db, userId, 'claude_rate_limit_json', null);
|
||||||
|
await setSetting(db, userId, 'claude_quota_notified_json', null);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Pourquoi cet utilisateur ne peut pas lancer de job IA (message destiné à l'écran), ou null s'il le peut.
|
||||||
|
* Garde unique, appelée par les routes, enqueue, le worker et le wrapper claude().
|
||||||
|
*/
|
||||||
|
export async function aiRefusal(db, userId, { cliModeEnabled = true } = {}) {
|
||||||
|
const user = await getUser(db, userId);
|
||||||
|
if (!user) return 'Compte supprimé';
|
||||||
|
if (user.status !== 'active') return 'Compte suspendu';
|
||||||
|
const link = await readLink(db, userId);
|
||||||
|
if (!link?.mode || !MODES[link.mode]) return LINK_REQUIRED_MESSAGE;
|
||||||
|
if (!link.valid) return LINK_INVALID_MESSAGE;
|
||||||
|
if (link.mode === MODES.server && !user.isAdmin) return SERVER_MODE_MESSAGE;
|
||||||
|
if (link.mode === MODES.subscription_token && !cliModeEnabled) return CLI_DISABLED_MESSAGE;
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function assertCanRunAi(db, userId, opts) {
|
||||||
|
const msg = await aiRefusal(db, userId, opts);
|
||||||
|
if (msg) throw new HttpError(403, msg);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** L'utilisateur a-t-il une liaison utilisable ? Sert à l'onboarding bloquant. */
|
||||||
|
export async function hasUsableLink(db, userId, opts) {
|
||||||
|
return (await aiRefusal(db, userId, opts)) === null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Identifiants d'exécution du job : lus dans la ligne de CET utilisateur, jamais ailleurs.
|
||||||
|
* @returns {{mode:string, secretEnv:Record<string,string>, serverConfig:boolean}}
|
||||||
|
*/
|
||||||
|
export async function resolveCredentials(app, userId) {
|
||||||
|
await assertCanRunAi(app.db, userId, { cliModeEnabled: app.cfg.cliModeEnabled !== false });
|
||||||
|
const link = await readLink(app.db, userId);
|
||||||
|
if (link.mode === MODES.server) return { mode: link.mode, secretEnv: {}, serverConfig: true };
|
||||||
|
let secret;
|
||||||
|
try { secret = decrypt(app.cfg.secretKey, link.secret_enc); }
|
||||||
|
catch { throw new HttpError(403, 'Secret de liaison illisible : relie de nouveau ton accès Claude'); }
|
||||||
|
if (!secret) throw new HttpError(403, LINK_REQUIRED_MESSAGE);
|
||||||
|
return { mode: link.mode, secretEnv: { [SECRET_ENV[link.mode]]: secret }, serverConfig: false };
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- Validation ----------
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Valide une clé API par un appel qui ne consomme aucun token : GET /v1/models.
|
||||||
|
* 401/403 : refusée ; erreur réseau ou réponse inattendue : message distinct (la clé n'est pas jugée).
|
||||||
|
* @returns {Promise<void>}
|
||||||
|
*/
|
||||||
|
export async function validateApiKey(key, fetchFn = fetch) {
|
||||||
|
let r;
|
||||||
|
try {
|
||||||
|
r = await fetchFn(MODELS_URL, {
|
||||||
|
headers: { 'x-api-key': key, 'anthropic-version': '2023-06-01' },
|
||||||
|
signal: AbortSignal.timeout(10_000),
|
||||||
|
});
|
||||||
|
} catch {
|
||||||
|
throw new HttpError(502, "Impossible de joindre Anthropic pour vérifier la clé (réseau). Réessaie dans un instant.", { expose: true });
|
||||||
|
}
|
||||||
|
if (r.status === 401 || r.status === 403) throw new HttpError(400, 'Clé API refusée par Anthropic');
|
||||||
|
if (!r.ok) throw new HttpError(502, `Anthropic ne répond pas normalement (HTTP ${r.status}) : la clé n'a pas pu être vérifiée. Réessaie plus tard.`, { expose: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
// Appel minimal du CLI avec le jeton (modèle le plus petit, 1 tour, aucun outil). Ce n'est PAS gratuit : quelques tokens
|
||||||
|
// sont décomptés de l'abonnement. Aucune commande du CLI ne vérifie un jeton sans appel au modèle.
|
||||||
|
async function validateSubscriptionToken(app, token) {
|
||||||
|
let r;
|
||||||
|
try {
|
||||||
|
r = await runClaude({
|
||||||
|
bin: app.cfg.claudeBin, prompt: 'Réponds uniquement : ok', model: 'haiku', maxTurns: 1, tools: [], timeoutMs: 90_000,
|
||||||
|
sandbox: app.cfg.sandbox, secretEnv: { CLAUDE_CODE_OAUTH_TOKEN: token },
|
||||||
|
});
|
||||||
|
} catch {
|
||||||
|
throw new HttpError(502, "Le CLI Claude n'a pas pu être lancé sur le serveur (bac à sable ou installation). Préviens l'administrateur.", { expose: true });
|
||||||
|
}
|
||||||
|
if (r.ok) return;
|
||||||
|
if (/auth|login|token|credential|401|403|invalid|expired|unauthor/i.test(`${r.text} ${r.subtype}`)) {
|
||||||
|
throw new HttpError(400, 'Jeton refusé par Claude (invalide ou expiré)');
|
||||||
|
}
|
||||||
|
throw new HttpError(502, "Le jeton n'a pas pu être vérifié (réponse inattendue du CLI). Réessaie plus tard.", { expose: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- Liaison ----------
|
||||||
|
|
||||||
|
async function saveLink(app, userId, link) {
|
||||||
|
const t = now();
|
||||||
|
await writeLink(app.db, userId, { v: 1, valid: true, linked_at: t, validated_at: t, last_test_at: t, ...link });
|
||||||
|
await resetQuotaState(app.db, userId);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Mode A : clé API. Validée, chiffrée, jamais réaffichée. */
|
||||||
|
export async function linkApiKey(app, userId, apiKey) {
|
||||||
|
const key = String(apiKey ?? '').trim();
|
||||||
|
if (!API_KEY_RE.test(key)) throw new HttpError(400, 'Clé API invalide (elle commence par sk-ant-)');
|
||||||
|
await (app.validateApiKey || validateApiKey)(key, app.fetch || fetch);
|
||||||
|
await saveLink(app, userId, { mode: MODES.api_key, secret_enc: encrypt(app.cfg.secretKey, key), last4: key.slice(-4) });
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Mode B : jeton d'abonnement (claude setup-token, généré par l'utilisateur sur sa machine).
|
||||||
|
* Le consentement est vérifié AVANT tout (sans case cochée : 400, rien n'est stocké ni validé).
|
||||||
|
*/
|
||||||
|
export async function linkSubscriptionToken(app, userId, { token, accept }) {
|
||||||
|
if (app.cfg.cliModeEnabled === false) throw new HttpError(403, CLI_DISABLED_MESSAGE);
|
||||||
|
if (!truthy(accept)) throw new HttpError(400, `Tu dois cocher « ${CONSENT_CHECKBOX} » pour utiliser ton abonnement`);
|
||||||
|
const tok = String(token ?? '').trim();
|
||||||
|
if (/^sk-ant-api/.test(tok)) throw new HttpError(400, "Ceci est une clé API : utilise l'option « Clé API Anthropic »");
|
||||||
|
if (!TOKEN_RE.test(tok)) throw new HttpError(400, 'Jeton invalide : colle le jeton affiché par « claude setup-token », en entier');
|
||||||
|
await (app.validateToken || ((t) => validateSubscriptionToken(app, t)))(tok);
|
||||||
|
const consent = { at: now(), version: CONSENT_VERSION };
|
||||||
|
await saveLink(app, userId, { mode: MODES.subscription_token, secret_enc: encrypt(app.cfg.secretKey, tok), consent });
|
||||||
|
// Trace d'acceptation conservée même si l'utilisateur délie ensuite (supprimée avec le compte)
|
||||||
|
await setSetting(app.db, userId, 'claude_cli_consent_json', JSON.stringify(consent));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Mode « Claude du serveur » : administrateurs seulement, aucun secret stocké. */
|
||||||
|
export async function linkServer(app, userId) {
|
||||||
|
const user = await getUser(app.db, userId);
|
||||||
|
if (!user?.isAdmin) throw new HttpError(403, SERVER_MODE_MESSAGE);
|
||||||
|
await saveLink(app, userId, { mode: MODES.server });
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Délie : supprime le secret chiffré, annule les jobs IA en file ou en cours de CET utilisateur.
|
||||||
|
* @returns {Promise<number>} jobs annulés
|
||||||
|
*/
|
||||||
|
export async function unlink(app, userId) {
|
||||||
|
await writeLink(app.db, userId, null);
|
||||||
|
await resetQuotaState(app.db, userId);
|
||||||
|
const types = [...AI_JOBS];
|
||||||
|
const r = await app.db.prepare(`UPDATE jobs SET status = 'cancelled', finished_at = ?
|
||||||
|
WHERE user_id = ? AND status IN ('queued','running') AND type IN (${types.map(() => '?').join(', ')})`).run(now(), Number(userId), ...types);
|
||||||
|
app.worker?.abortUserAi(userId);
|
||||||
|
return r.changes || 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Teste la liaison. Une réponse d'authentification négative invalide la liaison ; une erreur réseau ou du CLI ne la touche pas.
|
||||||
|
* @returns {Promise<{ok:boolean, message:string}>}
|
||||||
|
*/
|
||||||
|
export async function testLink(app, userId) {
|
||||||
|
const link = await readLink(app.db, userId);
|
||||||
|
if (!link?.mode) throw new HttpError(400, LINK_REQUIRED_MESSAGE);
|
||||||
|
const mark = async (valid) => writeLink(app.db, userId, { ...link, valid, last_test_at: now(), ...(valid ? { validated_at: now() } : {}) });
|
||||||
|
try {
|
||||||
|
if (link.mode === MODES.server) {
|
||||||
|
const user = await getUser(app.db, userId);
|
||||||
|
if (!user?.isAdmin) throw new HttpError(400, SERVER_MODE_MESSAGE);
|
||||||
|
try { await execFileP(app.cfg.claudeBin, ['--version'], { env: buildChildEnv(process.env, { home: app.cfg.sandbox?.serverHome || '/tmp' }), timeout: 15_000 }); }
|
||||||
|
catch { throw new HttpError(502, 'Le CLI Claude du serveur est introuvable ou ne répond pas', { expose: true }); }
|
||||||
|
} else {
|
||||||
|
let secret;
|
||||||
|
try { secret = decrypt(app.cfg.secretKey, link.secret_enc); } catch { secret = null; }
|
||||||
|
if (!secret) { await mark(false); return { ok: false, message: 'Secret illisible : relie de nouveau ton accès Claude' }; }
|
||||||
|
if (link.mode === MODES.api_key) await (app.validateApiKey || validateApiKey)(secret, app.fetch || fetch);
|
||||||
|
else {
|
||||||
|
if (app.cfg.cliModeEnabled === false) return { ok: false, message: CLI_DISABLED_MESSAGE };
|
||||||
|
await (app.validateToken || ((t) => validateSubscriptionToken(app, t)))(secret);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
if (!(e instanceof HttpError)) throw e;
|
||||||
|
// 400 = refus d'authentification (liaison invalide) ; 502 = impossible de juger (réseau, CLI) : on ne touche à rien
|
||||||
|
if (e.status === 400) await mark(false);
|
||||||
|
return { ok: false, message: e.message };
|
||||||
|
}
|
||||||
|
await mark(true);
|
||||||
|
return { ok: true, message: 'Liaison valide' };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Dernière acceptation du risque du mode abonnement (conservée après « Délier »). */
|
||||||
|
export async function lastConsent(db, userId) {
|
||||||
|
const raw = await getSetting(db, userId, 'claude_cli_consent_json');
|
||||||
|
try { return raw ? JSON.parse(raw) : null; } catch { return null; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Routes accessibles sans liaison valide : lier, Mon compte, déconnexion, suppression du compte. */
|
||||||
|
export function isLinkExempt(method, pathname) {
|
||||||
|
if (pathname === '/link' || pathname.startsWith('/link/')) return true;
|
||||||
|
if (pathname === '/account' || pathname === '/account/delete') return true;
|
||||||
|
return method === 'POST' && pathname === '/logout';
|
||||||
|
}
|
||||||
|
|
@ -1,4 +1,6 @@
|
||||||
import { resolve } from 'node:path';
|
import { resolve } from 'node:path';
|
||||||
|
import { homedir } from 'node:os';
|
||||||
|
import { dbConfigFromEnv } from './db.js';
|
||||||
|
|
||||||
const env = process.env;
|
const env = process.env;
|
||||||
|
|
||||||
|
|
@ -8,6 +10,40 @@ function required(name) {
|
||||||
return v;
|
return v;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Connexion Apple : les quatre variables ensemble, ou aucune (le bouton Apple est alors masqué)
|
||||||
|
function appleConfig() {
|
||||||
|
const keys = ['APPLE_TEAM_ID', 'APPLE_KEY_ID', 'APPLE_CLIENT_ID', 'APPLE_PRIVATE_KEY'];
|
||||||
|
const set = keys.filter((k) => env[k]);
|
||||||
|
if (!set.length) return null;
|
||||||
|
if (set.length < keys.length) {
|
||||||
|
throw new Error(`Connexion Apple : variables incomplètes (manque ${keys.filter((k) => !env[k]).join(', ')})`);
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
teamId: env.APPLE_TEAM_ID, keyId: env.APPLE_KEY_ID, clientId: env.APPLE_CLIENT_ID,
|
||||||
|
// Le PEM tient sur une ligne dans un .env : les séquences \n littérales redeviennent des retours à la ligne
|
||||||
|
privateKey: env.APPLE_PRIVATE_KEY.replace(/\\n/g, '\n'),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const flag = (v, def) => (v == null || v === '' ? def : !/^(0|false|off|no|non)$/i.test(String(v).trim()));
|
||||||
|
|
||||||
|
// Bac à sable des exécutions Claude. En production il est obligatoire : SANDBOX=off n'y est pas pris en compte.
|
||||||
|
// En développement, SANDBOX=off le désactive (avertissement au démarrage).
|
||||||
|
function sandboxConfig() {
|
||||||
|
const production = env.NODE_ENV === 'production';
|
||||||
|
const off = String(env.SANDBOX || '').trim().toLowerCase() === 'off';
|
||||||
|
return {
|
||||||
|
production,
|
||||||
|
enabled: production || !off,
|
||||||
|
offIgnored: production && off,
|
||||||
|
bwrapBin: env.BWRAP_BIN || 'bwrap',
|
||||||
|
// Dossiers supplémentaires montés en lecture seule (ex. Node installé hors de /usr), séparés par des virgules
|
||||||
|
roBinds: (env.SANDBOX_RO_BINDS || '').split(',').map((p) => p.trim()).filter(Boolean),
|
||||||
|
// Configuration du CLI du serveur, montée seulement pour le mode « Claude du serveur » (admins)
|
||||||
|
serverHome: env.HOME || homedir(),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
export function loadConfig() {
|
export function loadConfig() {
|
||||||
const secretKey = required('SECRET_KEY');
|
const secretKey = required('SECRET_KEY');
|
||||||
if (!/^[0-9a-f]{64}$/i.test(secretKey)) {
|
if (!/^[0-9a-f]{64}$/i.test(secretKey)) {
|
||||||
|
|
@ -21,10 +57,16 @@ export function loadConfig() {
|
||||||
clientId: required('GOOGLE_CLIENT_ID'),
|
clientId: required('GOOGLE_CLIENT_ID'),
|
||||||
clientSecret: required('GOOGLE_CLIENT_SECRET'),
|
clientSecret: required('GOOGLE_CLIENT_SECRET'),
|
||||||
},
|
},
|
||||||
allowedEmails: required('ALLOWED_EMAILS').split(',').map((e) => e.trim().toLowerCase()).filter(Boolean),
|
apple: appleConfig(),
|
||||||
|
// Administrateurs : ces adresses seulement (la première est aussi propriétaire des données migrées)
|
||||||
|
adminEmails: (env.ADMIN_EMAILS || '').split(',').map((e) => e.trim().toLowerCase()).filter(Boolean),
|
||||||
secretKey: Buffer.from(secretKey, 'hex'),
|
secretKey: Buffer.from(secretKey, 'hex'),
|
||||||
|
db: dbConfigFromEnv(env),
|
||||||
dataDir: resolve(env.DATA_DIR || './data'),
|
dataDir: resolve(env.DATA_DIR || './data'),
|
||||||
claudeBin: env.CLAUDE_BIN || 'claude',
|
claudeBin: env.CLAUDE_BIN || 'claude',
|
||||||
|
// Mode « abonnement » (jeton claude setup-token) : désactivable globalement
|
||||||
|
cliModeEnabled: flag(env.CLAUDE_CLI_MODE_ENABLED, true),
|
||||||
|
sandbox: sandboxConfig(),
|
||||||
thermalMax: Number(env.THERMAL_MAX || 75),
|
thermalMax: Number(env.THERMAL_MAX || 75),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
|
||||||
416
src/db.js
416
src/db.js
|
|
@ -1,169 +1,289 @@
|
||||||
|
// Couche d'accès aux données : une seule API asynchrone, deux drivers.
|
||||||
|
// - MySQL / MariaDB (mysql2/promise, pool) en production ;
|
||||||
|
// - SQLite en mémoire (node:sqlite) pour les tests locaux, sans serveur à installer.
|
||||||
|
// Le SQL de l'application est écrit dans un sous-ensemble commun ; translate() ne fait que le strict
|
||||||
|
// minimum entre dialectes (voir plus bas). Les requêtes vraiment différentes sont réécrites à la source.
|
||||||
import { DatabaseSync } from 'node:sqlite';
|
import { DatabaseSync } from 'node:sqlite';
|
||||||
import { mkdirSync } from 'node:fs';
|
import { mkdirSync } from 'node:fs';
|
||||||
import { join } from 'node:path';
|
import { dirname } from 'node:path';
|
||||||
|
import { MIGRATIONS } from './migrations.js';
|
||||||
|
|
||||||
// Chaque entrée = une migration. Ne jamais modifier une migration déjà livrée, en ajouter une.
|
export { MIGRATIONS };
|
||||||
export const MIGRATIONS = [
|
|
||||||
`
|
|
||||||
CREATE TABLE sessions (
|
|
||||||
id TEXT PRIMARY KEY, email TEXT NOT NULL,
|
|
||||||
created_at INTEGER NOT NULL, expires_at INTEGER NOT NULL
|
|
||||||
);
|
|
||||||
CREATE TABLE oauth_states (
|
|
||||||
state TEXT PRIMARY KEY, verifier TEXT NOT NULL, nonce TEXT NOT NULL, created_at INTEGER NOT NULL
|
|
||||||
);
|
|
||||||
CREATE TABLE settings (key TEXT PRIMARY KEY, value TEXT);
|
|
||||||
CREATE TABLE projects (
|
|
||||||
id INTEGER PRIMARY KEY,
|
|
||||||
name TEXT NOT NULL,
|
|
||||||
git_url TEXT NOT NULL UNIQUE,
|
|
||||||
profile_json TEXT, -- fiche projet générée par Claude
|
|
||||||
profile_commit TEXT, -- commit analysé
|
|
||||||
profile_at INTEGER,
|
|
||||||
target_json TEXT, -- cible déduite (modifiable)
|
|
||||||
target_validated INTEGER NOT NULL DEFAULT 0,
|
|
||||||
smtp_enc TEXT, -- config SMTP chiffrée
|
|
||||||
db_enc TEXT, -- accès BDD chiffré (récap)
|
|
||||||
daily_mail_cap INTEGER NOT NULL DEFAULT 30,
|
|
||||||
created_at INTEGER NOT NULL
|
|
||||||
);
|
|
||||||
CREATE TABLE mail_templates (
|
|
||||||
project_id INTEGER PRIMARY KEY REFERENCES projects(id) ON DELETE CASCADE,
|
|
||||||
subject TEXT NOT NULL, body TEXT NOT NULL,
|
|
||||||
status TEXT NOT NULL DEFAULT 'draft', -- draft | validated
|
|
||||||
updated_at INTEGER NOT NULL
|
|
||||||
);
|
|
||||||
CREATE TABLE prospects (
|
|
||||||
id INTEGER PRIMARY KEY,
|
|
||||||
project_id INTEGER NOT NULL REFERENCES projects(id) ON DELETE CASCADE,
|
|
||||||
company TEXT NOT NULL, email TEXT NOT NULL, website TEXT, city TEXT, sector TEXT,
|
|
||||||
hook TEXT, -- accroche perso (1 phrase)
|
|
||||||
source TEXT, -- page où l'email a été trouvé (RGPD : origine des données)
|
|
||||||
score INTEGER,
|
|
||||||
status TEXT NOT NULL DEFAULT 'new', -- new | sent | replied | client | refused | bounced
|
|
||||||
sent_at INTEGER, created_at INTEGER NOT NULL,
|
|
||||||
UNIQUE(project_id, email)
|
|
||||||
);
|
|
||||||
CREATE INDEX prospects_project ON prospects(project_id, status);
|
|
||||||
CREATE TABLE blacklist (email TEXT PRIMARY KEY, reason TEXT, created_at INTEGER NOT NULL);
|
|
||||||
CREATE TABLE jobs (
|
|
||||||
id INTEGER PRIMARY KEY,
|
|
||||||
project_id INTEGER REFERENCES projects(id) ON DELETE CASCADE,
|
|
||||||
type TEXT NOT NULL, -- analyze | prospect | template | send | evolution
|
|
||||||
status TEXT NOT NULL DEFAULT 'queued', -- queued | running | done | error | cancelled
|
|
||||||
params_json TEXT, progress_json TEXT, result_json TEXT, error TEXT,
|
|
||||||
cost_usd REAL, tokens_in INTEGER, tokens_out INTEGER,
|
|
||||||
created_at INTEGER NOT NULL, started_at INTEGER, finished_at INTEGER
|
|
||||||
);
|
|
||||||
CREATE INDEX jobs_status ON jobs(status, id);
|
|
||||||
CREATE TABLE mail_log (
|
|
||||||
id INTEGER PRIMARY KEY,
|
|
||||||
project_id INTEGER NOT NULL REFERENCES projects(id) ON DELETE CASCADE,
|
|
||||||
prospect_id INTEGER, email TEXT NOT NULL, sent_at INTEGER NOT NULL, error TEXT
|
|
||||||
);
|
|
||||||
CREATE INDEX mail_log_day ON mail_log(project_id, sent_at);
|
|
||||||
`,
|
|
||||||
// 2 — modèles de mail par type (premier mail / relance)
|
|
||||||
`
|
|
||||||
CREATE TABLE templates (
|
|
||||||
project_id INTEGER NOT NULL REFERENCES projects(id) ON DELETE CASCADE,
|
|
||||||
kind TEXT NOT NULL CHECK (kind IN ('initial', 'followup')),
|
|
||||||
subject TEXT NOT NULL DEFAULT '', -- relance : vide = "Re: <objet du 1er mail>"
|
|
||||||
body TEXT NOT NULL,
|
|
||||||
status TEXT NOT NULL DEFAULT 'draft',
|
|
||||||
updated_at INTEGER NOT NULL,
|
|
||||||
PRIMARY KEY (project_id, kind)
|
|
||||||
);
|
|
||||||
INSERT INTO templates(project_id, kind, subject, body, status, updated_at)
|
|
||||||
SELECT project_id, 'initial', subject, body, status, updated_at FROM mail_templates;
|
|
||||||
DROP TABLE mail_templates;
|
|
||||||
`,
|
|
||||||
// 3 — suivi des mails envoyés + test A/B de l'objet
|
|
||||||
`
|
|
||||||
ALTER TABLE templates ADD COLUMN subject_b TEXT; -- objet B (premier mail uniquement)
|
|
||||||
ALTER TABLE prospects ADD COLUMN variant TEXT; -- A | B
|
|
||||||
ALTER TABLE mail_log ADD COLUMN kind TEXT NOT NULL DEFAULT 'initial';
|
|
||||||
ALTER TABLE mail_log ADD COLUMN variant TEXT;
|
|
||||||
ALTER TABLE mail_log ADD COLUMN subject TEXT;
|
|
||||||
ALTER TABLE mail_log ADD COLUMN message_id TEXT;
|
|
||||||
CREATE INDEX mail_log_msgid ON mail_log(message_id);
|
|
||||||
`,
|
|
||||||
// 4 — détection des réponses via IMAP
|
|
||||||
`
|
|
||||||
ALTER TABLE prospects ADD COLUMN replied_at INTEGER;
|
|
||||||
ALTER TABLE prospects ADD COLUMN reply_subject TEXT;
|
|
||||||
ALTER TABLE projects ADD COLUMN imap_enc TEXT;
|
|
||||||
ALTER TABLE projects ADD COLUMN inbox_json TEXT; -- état de la dernière lecture IMAP
|
|
||||||
`,
|
|
||||||
// 5 — relance automatique
|
|
||||||
`
|
|
||||||
ALTER TABLE prospects ADD COLUMN followup_at INTEGER;
|
|
||||||
ALTER TABLE projects ADD COLUMN followup_enabled INTEGER NOT NULL DEFAULT 0;
|
|
||||||
ALTER TABLE projects ADD COLUMN followup_days INTEGER NOT NULL DEFAULT 7;
|
|
||||||
`,
|
|
||||||
// 6 — jobs programmés (la nuit)
|
|
||||||
`
|
|
||||||
ALTER TABLE jobs ADD COLUMN run_after INTEGER; -- ne pas démarrer avant (epoch s)
|
|
||||||
`,
|
|
||||||
// 7 — fiche prospect : notes et prochaine action
|
|
||||||
`
|
|
||||||
CREATE TABLE prospect_notes (
|
|
||||||
id INTEGER PRIMARY KEY,
|
|
||||||
prospect_id INTEGER NOT NULL REFERENCES prospects(id) ON DELETE CASCADE,
|
|
||||||
body TEXT NOT NULL,
|
|
||||||
created_at INTEGER NOT NULL
|
|
||||||
);
|
|
||||||
CREATE INDEX prospect_notes_p ON prospect_notes(prospect_id, created_at);
|
|
||||||
ALTER TABLE prospects ADD COLUMN next_action TEXT;
|
|
||||||
ALTER TABLE prospects ADD COLUMN next_action_at INTEGER;
|
|
||||||
`,
|
|
||||||
// 8 — historique quotidien des KPI business (pour les courbes)
|
|
||||||
`
|
|
||||||
CREATE TABLE metrics_daily (
|
|
||||||
project_id INTEGER NOT NULL REFERENCES projects(id) ON DELETE CASCADE,
|
|
||||||
day TEXT NOT NULL, -- AAAA-MM-JJ, heure de Paris
|
|
||||||
users REAL, clients REAL, revenue REAL,
|
|
||||||
PRIMARY KEY (project_id, day)
|
|
||||||
);
|
|
||||||
`,
|
|
||||||
];
|
|
||||||
|
|
||||||
export function openDb(dataDir) {
|
/** Paramètres de connexion depuis les variables d'environnement (DB_HOST, DB_PORT, DB_USER, DB_PASSWORD, DB_NAME). */
|
||||||
let db;
|
export function dbConfigFromEnv(env = process.env, prefix = 'DB_') {
|
||||||
if (dataDir === ':memory:') db = new DatabaseSync(':memory:');
|
const get = (k) => env[`${prefix}${k}`];
|
||||||
else {
|
if (get('DRIVER') === 'sqlite') return { driver: 'sqlite', file: get('FILE') || ':memory:' };
|
||||||
mkdirSync(dataDir, { recursive: true });
|
for (const k of ['HOST', 'USER', 'NAME']) {
|
||||||
db = new DatabaseSync(join(dataDir, 'aitools.sqlite'));
|
if (!get(k)) throw new Error(`Variable d'environnement manquante : ${prefix}${k}`);
|
||||||
}
|
}
|
||||||
// WAL + synchronous NORMAL : moins d'écritures sur la carte SD / SSD
|
return {
|
||||||
db.exec('PRAGMA journal_mode = WAL; PRAGMA synchronous = NORMAL; PRAGMA foreign_keys = ON; PRAGMA busy_timeout = 5000;');
|
driver: 'mysql', host: get('HOST'), port: Number(get('PORT') || 3306), user: get('USER'),
|
||||||
migrate(db);
|
password: get('PASSWORD') ?? '', database: get('NAME'),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Traduit le SQL "canonique" (écrit une seule fois dans le code) vers le dialecte cible.
|
||||||
|
* Forme canonique = celle de SQLite : INSERT OR IGNORE, ON CONFLICT(cols) DO UPDATE SET x = excluded.x.
|
||||||
|
* Les noms réservés (`key`) sont entre accents graves, acceptés par les deux moteurs.
|
||||||
|
*/
|
||||||
|
export function translate(sql, dialect) {
|
||||||
|
if (dialect !== 'mysql') return sql;
|
||||||
|
return sql
|
||||||
|
.replace(/\bINSERT\s+OR\s+IGNORE\b/gi, 'INSERT IGNORE')
|
||||||
|
.replace(/\bON\s+CONFLICT\s*\([^)]*\)\s*DO\s+UPDATE\s+SET\b/gi, 'ON DUPLICATE KEY UPDATE')
|
||||||
|
.replace(/\bexcluded\.(\w+)/gi, 'VALUES($1)')
|
||||||
|
.replace(/\s+COLLATE\s+NOCASE\b/gi, ''); // MySQL compare déjà sans casse (utf8mb4_unicode_ci)
|
||||||
|
}
|
||||||
|
|
||||||
|
// undefined et NaN (Number('abc') dans une route) deviennent NULL, comme avec SQLite
|
||||||
|
const norm = (params) => params.map((p) => (p === undefined || (typeof p === 'number' && !Number.isFinite(p)) ? null : p));
|
||||||
|
|
||||||
|
// API commune : db.prepare(sql).get / all / run(...params), toutes asynchrones.
|
||||||
|
// Les sous-classes fournissent _exec(sql, params, mode) avec mode = 'get' | 'all' | 'run'.
|
||||||
|
class Executor {
|
||||||
|
prepare(sql) {
|
||||||
|
return {
|
||||||
|
get: (...params) => this._exec(sql, norm(params), 'get'),
|
||||||
|
all: (...params) => this._exec(sql, norm(params), 'all'),
|
||||||
|
/** @returns {Promise<{changes: number, lastInsertRowid: number}>} */
|
||||||
|
run: (...params) => this._exec(sql, norm(params), 'run'),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Requête libre (renvoie les lignes). */
|
||||||
|
query(sql, params = []) { return this._exec(sql, norm(params), 'all'); }
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- MySQL / MariaDB ----------
|
||||||
|
|
||||||
|
class MysqlExecutor extends Executor {
|
||||||
|
constructor(conn) { super(); this.conn = conn; }
|
||||||
|
|
||||||
|
async _exec(sql, params, mode) {
|
||||||
|
const [r] = await this.conn.query(translate(sql, 'mysql'), params);
|
||||||
|
if (mode === 'get') return r[0];
|
||||||
|
if (mode === 'all') return r;
|
||||||
|
return { changes: r.affectedRows ?? 0, lastInsertRowid: r.insertId ?? 0 };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class MysqlDb extends MysqlExecutor {
|
||||||
|
constructor(pool) { super(pool); this.pool = pool; this.dialect = 'mysql'; }
|
||||||
|
|
||||||
|
/** Applique les migrations en attente (jusqu'à `upTo`), avec le contexte { adminEmails }. */
|
||||||
|
migrate(opts = {}) { return migrateMysql(this, opts); }
|
||||||
|
|
||||||
|
/** fn(tx) reçoit un exécuteur lié à UNE connexion ; commit si tout va bien, rollback sinon. */
|
||||||
|
async transaction(fn) {
|
||||||
|
const conn = await this.pool.getConnection();
|
||||||
|
try {
|
||||||
|
await conn.beginTransaction();
|
||||||
|
const result = await fn(new MysqlExecutor(conn));
|
||||||
|
await conn.commit();
|
||||||
|
return result;
|
||||||
|
} catch (e) {
|
||||||
|
await conn.rollback().catch(() => {});
|
||||||
|
throw e;
|
||||||
|
} finally {
|
||||||
|
conn.release();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
close() { return this.pool.end(); }
|
||||||
|
}
|
||||||
|
|
||||||
|
async function openMysql(cfg, opts) {
|
||||||
|
const { default: mysql } = await import('mysql2/promise');
|
||||||
|
const pool = mysql.createPool({
|
||||||
|
host: cfg.host, port: cfg.port || 3306, user: cfg.user, password: cfg.password, database: cfg.database,
|
||||||
|
charset: 'UTF8MB4_UNICODE_CI',
|
||||||
|
waitForConnections: true, connectionLimit: cfg.connectionLimit || 10,
|
||||||
|
decimalNumbers: true, // SUM()/AVG() en nombres, pas en chaînes
|
||||||
|
supportBigNumbers: true, bigNumberStrings: false,
|
||||||
|
flags: ['+FOUND_ROWS'], // affectedRows = lignes trouvées (comme SQLite), pas seulement modifiées
|
||||||
|
timezone: 'Z',
|
||||||
|
});
|
||||||
|
const db = new MysqlDb(pool);
|
||||||
|
try { await db.migrate(opts); }
|
||||||
|
catch (e) { await pool.end().catch(() => {}); throw e; }
|
||||||
return db;
|
return db;
|
||||||
}
|
}
|
||||||
|
|
||||||
function migrate(db) {
|
// Verrou applicatif (GET_LOCK) : deux instances qui démarrent en même temps ne migrent pas en parallèle.
|
||||||
const { user_version: current } = db.prepare('PRAGMA user_version').get();
|
// Le verrou est lié à la connexion : on garde la même du début à la fin.
|
||||||
for (let i = current; i < MIGRATIONS.length; i++) {
|
async function migrateMysql(db, opts = {}) {
|
||||||
db.exec('BEGIN');
|
const conn = await db.pool.getConnection();
|
||||||
|
const ctx = migrationContext(opts);
|
||||||
|
const q = async (sql, params = []) => (await conn.query(sql, params))[0];
|
||||||
|
const LOCK = 'aitools_migrate';
|
||||||
|
try {
|
||||||
|
const [[lock]] = await conn.query('SELECT GET_LOCK(?, 60) ok', [LOCK]);
|
||||||
|
if (lock.ok !== 1) throw new Error('Migrations : verrou non obtenu (une autre instance migre ?)');
|
||||||
try {
|
try {
|
||||||
db.exec(MIGRATIONS[i]);
|
await conn.query(`CREATE TABLE IF NOT EXISTS schema_migrations (
|
||||||
db.exec(`PRAGMA user_version = ${i + 1}`);
|
version INT NOT NULL PRIMARY KEY, name VARCHAR(100) NOT NULL, applied_at BIGINT NOT NULL
|
||||||
db.exec('COMMIT');
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci`);
|
||||||
|
const [rows] = await conn.query('SELECT version FROM schema_migrations');
|
||||||
|
const done = new Set(rows.map((r) => r.version));
|
||||||
|
for (let i = 0; i < Math.min(MIGRATIONS.length, opts.upTo ?? Infinity); i++) {
|
||||||
|
const version = i + 1;
|
||||||
|
if (done.has(version)) continue;
|
||||||
|
await MIGRATIONS[i].check?.(q, ctx);
|
||||||
|
for (const st of MIGRATIONS[i].mysql) await runStatement(st, q, ctx);
|
||||||
|
await conn.query('INSERT INTO schema_migrations(version, name, applied_at) VALUES(?, ?, ?)',
|
||||||
|
[version, MIGRATIONS[i].name, now()]);
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
await conn.query('SELECT RELEASE_LOCK(?)', [LOCK]).catch(() => {});
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
conn.release();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- SQLite (tests locaux) ----------
|
||||||
|
|
||||||
|
class SqliteExecutor extends Executor {
|
||||||
|
constructor(raw) { super(); this.raw = raw; this.cache = new Map(); }
|
||||||
|
|
||||||
|
_stmt(sql) {
|
||||||
|
let s = this.cache.get(sql);
|
||||||
|
if (!s) { s = this.raw.prepare(translate(sql, 'sqlite')); this.cache.set(sql, s); }
|
||||||
|
return s;
|
||||||
|
}
|
||||||
|
|
||||||
|
_run(sql, params, mode) {
|
||||||
|
const s = this._stmt(sql);
|
||||||
|
if (mode === 'get') return s.get(...params);
|
||||||
|
if (mode === 'all') return s.all(...params);
|
||||||
|
const r = s.run(...params);
|
||||||
|
return { changes: Number(r.changes), lastInsertRowid: Number(r.lastInsertRowid) };
|
||||||
|
}
|
||||||
|
|
||||||
|
async _exec(sql, params, mode) { return this._run(sql, params, mode); }
|
||||||
|
}
|
||||||
|
|
||||||
|
class SqliteDb extends SqliteExecutor {
|
||||||
|
constructor(raw) { super(raw); this.dialect = 'sqlite'; this.txLock = null; }
|
||||||
|
|
||||||
|
/** Applique les migrations en attente (jusqu'à `upTo`), avec le contexte { adminEmails }. */
|
||||||
|
migrate(opts = {}) { return migrateSqlite(this.raw, opts); }
|
||||||
|
|
||||||
|
// Une seule connexion : pendant une transaction, les autres requêtes attendent sa fin
|
||||||
|
// (sinon elles s'exécuteraient DANS la transaction). Ne pas appeler db.* depuis le callback : utiliser tx.*.
|
||||||
|
async _exec(sql, params, mode) {
|
||||||
|
while (this.txLock) await this.txLock;
|
||||||
|
return this._run(sql, params, mode);
|
||||||
|
}
|
||||||
|
|
||||||
|
async transaction(fn) {
|
||||||
|
while (this.txLock) await this.txLock;
|
||||||
|
let release;
|
||||||
|
this.txLock = new Promise((r) => { release = r; });
|
||||||
|
this.raw.exec('BEGIN');
|
||||||
|
try {
|
||||||
|
const result = await fn(new SqliteExecutor(this.raw));
|
||||||
|
this.raw.exec('COMMIT');
|
||||||
|
return result;
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
db.exec('ROLLBACK');
|
try { this.raw.exec('ROLLBACK'); } catch { /* déjà annulée */ }
|
||||||
throw e;
|
throw e;
|
||||||
|
} finally {
|
||||||
|
this.txLock = null;
|
||||||
|
release();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async close() { this.raw.close(); }
|
||||||
|
}
|
||||||
|
|
||||||
|
async function openSqlite(file = ':memory:', opts = {}) {
|
||||||
|
if (file !== ':memory:') mkdirSync(dirname(file), { recursive: true });
|
||||||
|
const raw = new DatabaseSync(file);
|
||||||
|
raw.exec('PRAGMA foreign_keys = ON; PRAGMA busy_timeout = 5000;');
|
||||||
|
const db = new SqliteDb(raw);
|
||||||
|
try { await db.migrate(opts); }
|
||||||
|
catch (e) { raw.close(); throw e; }
|
||||||
|
return db;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function migrateSqlite(raw, opts = {}) {
|
||||||
|
raw.exec(`CREATE TABLE IF NOT EXISTS schema_migrations (
|
||||||
|
version INTEGER PRIMARY KEY, name TEXT NOT NULL, applied_at INTEGER NOT NULL
|
||||||
|
)`);
|
||||||
|
const ctx = migrationContext(opts);
|
||||||
|
const q = async (sql, params = []) => raw.prepare(sql).all(...params);
|
||||||
|
const done = new Set(raw.prepare('SELECT version FROM schema_migrations').all().map((r) => r.version));
|
||||||
|
for (let i = 0; i < Math.min(MIGRATIONS.length, opts.upTo ?? Infinity); i++) {
|
||||||
|
const version = i + 1;
|
||||||
|
if (done.has(version)) continue;
|
||||||
|
const m = MIGRATIONS[i];
|
||||||
|
// PRAGMA foreign_keys est sans effet dans une transaction : on le règle avant BEGIN
|
||||||
|
if (m.sqliteForeignKeysOff) raw.exec('PRAGMA foreign_keys = OFF');
|
||||||
|
try {
|
||||||
|
raw.exec('BEGIN');
|
||||||
|
try {
|
||||||
|
await m.check?.(q, ctx);
|
||||||
|
for (const st of m.sqlite) await runStatement(st, q, ctx, (sql, params) => raw.prepare(sql).run(...params));
|
||||||
|
if (m.sqliteForeignKeysOff) {
|
||||||
|
const bad = raw.prepare('PRAGMA foreign_key_check').all();
|
||||||
|
if (bad.length) throw new Error(`Migration ${version} : clés étrangères violées (${bad[0].table} → ${bad[0].parent})`);
|
||||||
|
}
|
||||||
|
raw.prepare('INSERT INTO schema_migrations(version, name, applied_at) VALUES(?, ?, ?)').run(version, m.name, now());
|
||||||
|
raw.exec('COMMIT');
|
||||||
|
} catch (e) {
|
||||||
|
raw.exec('ROLLBACK');
|
||||||
|
throw e;
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
if (m.sqliteForeignKeysOff) raw.exec('PRAGMA foreign_keys = ON');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Ouvre la base et applique les migrations en attente.
|
||||||
|
* cfg = { driver: 'mysql', host, port, user, password, database } ou { driver: 'sqlite', file } ;
|
||||||
|
* sans argument (ou ':memory:') : SQLite en mémoire.
|
||||||
|
* opts = { adminEmails } (propriétaire des données existantes, voir migration 2) ; { upTo } limite la version
|
||||||
|
* migrée (tests de migration), db.migrate() applique ensuite le reste.
|
||||||
|
*/
|
||||||
|
export async function openDb(cfg = ':memory:', opts = {}) {
|
||||||
|
if (typeof cfg === 'string') return openSqlite(cfg, opts);
|
||||||
|
if (cfg.driver === 'sqlite') return openSqlite(cfg.file, opts);
|
||||||
|
return openMysql(cfg, opts);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Contexte des migrations : le propriétaire des données existantes est la première adresse de ADMIN_EMAILS
|
||||||
|
function migrationContext({ adminEmails } = {}) {
|
||||||
|
const list = (Array.isArray(adminEmails) ? adminEmails : String(adminEmails || '').split(','))
|
||||||
|
.map((e) => String(e).trim().toLowerCase()).filter(Boolean);
|
||||||
|
return { ownerEmail: list[0] || null, now: now() };
|
||||||
|
}
|
||||||
|
|
||||||
|
// Instruction de migration : chaîne SQL ou { sql, params(ctx), when(q, ctx) }
|
||||||
|
async function runStatement(st, q, ctx, exec = q) {
|
||||||
|
if (typeof st === 'string') return exec(st, []);
|
||||||
|
if (st.when && !(await st.when(q, ctx))) return undefined;
|
||||||
|
return exec(st.sql, st.params ? st.params(ctx) : []);
|
||||||
|
}
|
||||||
|
|
||||||
export const now = () => Math.floor(Date.now() / 1000);
|
export const now = () => Math.floor(Date.now() / 1000);
|
||||||
|
|
||||||
export function getSetting(db, key, fallback = null) {
|
// Réglages par utilisateur (aucun réglage global : chaque compte a les siens)
|
||||||
const row = db.prepare('SELECT value FROM settings WHERE key = ?').get(key);
|
function uid(userId) {
|
||||||
|
if (!Number.isInteger(Number(userId)) || Number(userId) <= 0) throw new Error('Réglage : utilisateur requis');
|
||||||
|
return Number(userId);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getSetting(db, userId, key, fallback = null) {
|
||||||
|
const row = await db.prepare('SELECT value FROM user_settings WHERE user_id = ? AND `key` = ?').get(uid(userId), key);
|
||||||
return row ? row.value : fallback;
|
return row ? row.value : fallback;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function setSetting(db, key, value) {
|
export async function setSetting(db, userId, key, value) {
|
||||||
db.prepare('INSERT INTO settings(key, value) VALUES(?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value')
|
await db.prepare('INSERT INTO user_settings(user_id, `key`, value) VALUES(?, ?, ?) ON CONFLICT(user_id, `key`) DO UPDATE SET value = excluded.value')
|
||||||
.run(key, value);
|
.run(uid(userId), key, value);
|
||||||
}
|
}
|
||||||
|
|
|
||||||
194
src/handlers.js
194
src/handlers.js
|
|
@ -7,6 +7,8 @@ import { analyzePrompt, prospectPrompt, templatePrompt, followupTemplatePrompt,
|
||||||
import { followupCandidates, followupSubject, isBusinessHours } from './services/followup.js';
|
import { followupCandidates, followupSubject, isBusinessHours } from './services/followup.js';
|
||||||
import { EMAIL_RE, createTransport, buildProspectMail, allowedToSend, makeMessageId } from './services/mailer.js';
|
import { EMAIL_RE, createTransport, buildProspectMail, allowedToSend, makeMessageId } from './services/mailer.js';
|
||||||
import { unsubToken } from './crypto.js';
|
import { unsubToken } from './crypto.js';
|
||||||
|
import { resolveCredentials } from './claudelink.js';
|
||||||
|
import { userRepoRoot } from './users.js';
|
||||||
import { quotaAlerts } from './services/budget.js';
|
import { quotaAlerts } from './services/budget.js';
|
||||||
import { notify } from './services/notify.js';
|
import { notify } from './services/notify.js';
|
||||||
import { evolutionMail } from './services/mailhtml.js';
|
import { evolutionMail } from './services/mailhtml.js';
|
||||||
|
|
@ -17,6 +19,16 @@ const sleep = (ms, signal) => new Promise((resolve, reject) => {
|
||||||
signal?.addEventListener('abort', () => { clearTimeout(t); reject(new Error('Annulé')); }, { once: true });
|
signal?.addEventListener('abort', () => { clearTimeout(t); reject(new Error('Annulé')); }, { once: true });
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Les callbacks du flux Claude (onText, onTurn) sont synchrones : leurs écritures en base passent par une file
|
||||||
|
// ordonnée, attendue à la fin de la phase (flush). Une erreur d'écriture fait échouer le job au lieu de se perdre.
|
||||||
|
function makeSink() {
|
||||||
|
let chain = Promise.resolve();
|
||||||
|
return {
|
||||||
|
push(fn) { chain = chain.then(fn); chain.catch(() => {}); },
|
||||||
|
flush: () => chain,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
// Avancement d'une phase Claude : de `from` à `to` % au fil des messages, sur `maxTurns` au plus (estimation)
|
// Avancement d'une phase Claude : de `from` à `to` % au fil des messages, sur `maxTurns` au plus (estimation)
|
||||||
const turnPct = (from, to, n, maxTurns) => Math.round(from + (to - from) * Math.min(1, n / Math.max(1, maxTurns)));
|
const turnPct = (from, to, n, maxTurns) => Math.round(from + (to - from) * Math.min(1, n / Math.max(1, maxTurns)));
|
||||||
|
|
||||||
|
|
@ -42,16 +54,26 @@ export function parseProspectLine(line) {
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
export function makeHandlers(app) {
|
/**
|
||||||
|
* Tout appel à Claude passe par ici. Le secret est relu pour le user_id du job (jamais un autre), l'exécution se fait
|
||||||
|
* dans le bac à sable avec un environnement assaini, et le quota remonté par le CLI est enregistré pour CET utilisateur.
|
||||||
|
*/
|
||||||
|
export function makeClaude(app) {
|
||||||
const { db, cfg } = app;
|
const { db, cfg } = app;
|
||||||
const claude = async (o) => {
|
return async (userId, o) => {
|
||||||
const r = await runClaude({ bin: cfg.claudeBin, ...o });
|
const cred = await resolveCredentials(app, userId); // refuse sans liaison valide (dernier garde-fou)
|
||||||
// État du quota Pro (session 5h + semaine), affiché dans la barre système
|
const r = await runClaude({
|
||||||
const w = rateLimitWindows(r.rateLimit);
|
bin: cfg.claudeBin, ...o,
|
||||||
|
sandbox: cfg.sandbox, secretEnv: cred.secretEnv, serverConfig: cred.serverConfig,
|
||||||
|
allowedRoot: userRepoRoot(cfg, userId),
|
||||||
|
});
|
||||||
|
// État du quota d'abonnement (session 5h + semaine), affiché dans la barre système. Une clé API n'en a pas.
|
||||||
|
const w = cred.mode === 'api_key' ? null : rateLimitWindows(r.rateLimit);
|
||||||
if (w) {
|
if (w) {
|
||||||
setSetting(db, 'claude_rate_limit_json', JSON.stringify({ at: now(), ...w }));
|
await setSetting(db, userId, 'claude_rate_limit_json', JSON.stringify({ at: now(), ...w }));
|
||||||
for (const a of quotaAlerts(db, w)) {
|
for (const a of await quotaAlerts(db, userId, w)) {
|
||||||
notify(app, 'quota', {
|
// notify ne lève jamais : un Discord indisponible ne fait pas échouer le job
|
||||||
|
await notify(app, userId, 'quota', {
|
||||||
title: `Quota Claude : ${a.level}+ % (${a.label})`,
|
title: `Quota Claude : ${a.level}+ % (${a.label})`,
|
||||||
level: a.level >= 95 ? 'error' : 'warn',
|
level: a.level >= 95 ? 'error' : 'warn',
|
||||||
description: `${Math.round(a.utilization * 100)} % utilisé sur la ${a.label}.`,
|
description: `${Math.round(a.utilization * 100)} % utilisé sur la ${a.label}.`,
|
||||||
|
|
@ -60,37 +82,43 @@ export function makeHandlers(app) {
|
||||||
}
|
}
|
||||||
return r;
|
return r;
|
||||||
};
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function makeHandlers(app) {
|
||||||
|
const { db, cfg } = app;
|
||||||
|
const claude = makeClaude(app);
|
||||||
|
const sync = (...a) => (app.syncRepo || syncRepo)(...a);
|
||||||
const inHours = () => (app.isBusinessHours || isBusinessHours)();
|
const inHours = () => (app.isBusinessHours || isBusinessHours)();
|
||||||
|
|
||||||
// Premier mail ou relance : mêmes plafonds, mêmes délais, même journal
|
// Premier mail ou relance : mêmes plafonds, mêmes délais, même journal
|
||||||
async function sendMails(ctx, kind) {
|
async function sendMails(ctx, kind) {
|
||||||
// Une relance mise en file à 17h55 ne doit pas partir à 19h si le worker était occupé
|
// Une relance mise en file à 17h55 ne doit pas partir à 19h si le worker était occupé
|
||||||
if (kind === 'followup' && !inHours()) return { sent: 0, failed: 0, total: 0, postponed: true };
|
if (kind === 'followup' && !inHours()) return { sent: 0, failed: 0, total: 0, postponed: true };
|
||||||
const project = getProject(app, ctx.job.project_id, { secrets: true });
|
const userId = ctx.job.user_id;
|
||||||
const template = getTemplate(db, project.id, kind, { validatedOnly: true });
|
const project = await getProject(app, ctx.job.project_id, { userId, secrets: true });
|
||||||
|
const template = await getTemplate(db, project.id, kind, { validatedOnly: true });
|
||||||
if (!template) throw new Error(kind === 'followup' ? 'Modèle de relance non validé' : 'Modèle de mail non validé');
|
if (!template) throw new Error(kind === 'followup' ? 'Modèle de relance non validé' : 'Modèle de mail non validé');
|
||||||
if (!project.smtp) throw new Error('SMTP non configuré pour ce projet');
|
if (!project.smtp) throw new Error('SMTP non configuré pour ce projet');
|
||||||
|
|
||||||
const day = now() - 86400;
|
const day = now() - 86400;
|
||||||
const candidates = kind === 'followup'
|
const candidates = kind === 'followup'
|
||||||
? followupCandidates(db, project)
|
? await followupCandidates(db, project)
|
||||||
: db.prepare(`SELECT * FROM prospects WHERE project_id = ? AND status = 'new'
|
: await db.prepare(`SELECT * FROM prospects WHERE project_id = ? AND status = 'new'
|
||||||
AND email NOT IN (SELECT email FROM blacklist) ORDER BY score DESC, id LIMIT 100`).all(project.id);
|
AND email NOT IN (SELECT email FROM blacklist) ORDER BY score DESC, id LIMIT 100`).all(project.id);
|
||||||
const n = allowedToSend({
|
const n = allowedToSend({
|
||||||
requested: ctx.params.count,
|
requested: ctx.params.count,
|
||||||
available: candidates.length,
|
available: candidates.length,
|
||||||
projectCap: project.dailyMailCap,
|
projectCap: project.dailyMailCap,
|
||||||
sentTodayProject: sentSince(db, day, project.id),
|
sentTodayProject: await sentSince(db, day, userId, project.id),
|
||||||
globalCap: Number(getSetting(db, 'global_daily_cap', '100')),
|
globalCap: Number(await getSetting(db, userId, 'global_daily_cap', '100')),
|
||||||
sentTodayGlobal: sentSince(db, day),
|
sentTodayGlobal: await sentSince(db, day, userId),
|
||||||
});
|
});
|
||||||
if (n === 0) throw new Error(kind === 'followup' ? 'Plafond quotidien atteint ou aucune relance due' : 'Plafond quotidien atteint ou aucun prospect à contacter');
|
if (n === 0) throw new Error(kind === 'followup' ? 'Plafond quotidien atteint ou aucune relance due' : 'Plafond quotidien atteint ou aucun prospect à contacter');
|
||||||
|
|
||||||
const transport = (app.createTransport || createTransport)(project.smtp);
|
const transport = (app.createTransport || createTransport)(project.smtp);
|
||||||
await transport.verify();
|
await transport.verify();
|
||||||
const minDelay = Number(getSetting(db, 'send_delay_min', '20')) * 1000;
|
const minDelay = Number(await getSetting(db, userId, 'send_delay_min', '20')) * 1000;
|
||||||
const maxDelay = Number(getSetting(db, 'send_delay_max', '60')) * 1000;
|
const maxDelay = Number(await getSetting(db, userId, 'send_delay_max', '60')) * 1000;
|
||||||
const log = db.prepare(`INSERT INTO mail_log(project_id, prospect_id, email, sent_at, error, kind, variant, subject, message_id)
|
const log = db.prepare(`INSERT INTO mail_log(project_id, prospect_id, email, sent_at, error, kind, variant, subject, message_id)
|
||||||
VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?)`);
|
VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?)`);
|
||||||
const markInitial = db.prepare('UPDATE prospects SET status = ?, sent_at = ?, variant = ? WHERE id = ?');
|
const markInitial = db.prepare('UPDATE prospects SET status = ?, sent_at = ?, variant = ? WHERE id = ?');
|
||||||
|
|
@ -99,24 +127,24 @@ export function makeHandlers(app) {
|
||||||
const original = db.prepare("SELECT subject, message_id FROM mail_log WHERE prospect_id = ? AND kind = 'initial' AND error IS NULL ORDER BY id LIMIT 1");
|
const original = db.prepare("SELECT subject, message_id FROM mail_log WHERE prospect_id = ? AND kind = 'initial' AND error IS NULL ORDER BY id LIMIT 1");
|
||||||
const current = db.prepare('SELECT status, followup_at FROM prospects WHERE id = ?');
|
const current = db.prepare('SELECT status, followup_at FROM prospects WHERE id = ?');
|
||||||
let sent = 0, failed = 0;
|
let sent = 0, failed = 0;
|
||||||
ctx.progress({ sent, failed, total: n, message: `0/${n} ${kind === 'followup' ? 'relances envoyées' : 'envoyés'}`, pct: 0 });
|
await ctx.progress({ sent, failed, total: n, message: `0/${n} ${kind === 'followup' ? 'relances envoyées' : 'envoyés'}`, pct: 0 });
|
||||||
|
|
||||||
for (const p of candidates.slice(0, n)) {
|
for (const p of candidates.slice(0, n)) {
|
||||||
if (ctx.cancelled()) break;
|
if (await ctx.cancelled()) break;
|
||||||
if (kind === 'followup' && !inHours()) break; // le reste repartira au prochain créneau
|
if (kind === 'followup' && !inHours()) break; // le reste repartira au prochain créneau
|
||||||
// Re-vérifie juste avant l'envoi : désinscription, réponse arrivée pendant le batch…
|
// Re-vérifie juste avant l'envoi : désinscription, réponse arrivée pendant le batch…
|
||||||
if (db.prepare('SELECT 1 FROM blacklist WHERE email = ?').get(p.email)) continue;
|
if (await db.prepare('SELECT 1 FROM blacklist WHERE email = ?').get(p.email)) continue;
|
||||||
if (kind === 'followup') {
|
if (kind === 'followup') {
|
||||||
const c = current.get(p.id);
|
const c = await current.get(p.id);
|
||||||
if (c.status !== 'sent' || c.followup_at) continue;
|
if (c.status !== 'sent' || c.followup_at) continue;
|
||||||
}
|
}
|
||||||
const unsubUrl = `${cfg.appUrl}/u/${encodeURIComponent(p.email)}/${unsubToken(cfg.secretKey, p.email)}`;
|
const unsubUrl = `${cfg.appUrl}/u/${encodeURIComponent(p.email)}/${unsubToken(cfg.secretKey, p.email)}`;
|
||||||
let variant = null, subject, inReplyTo;
|
let variant = null, subject, inReplyTo;
|
||||||
if (kind === 'initial') {
|
if (kind === 'initial') {
|
||||||
variant = pickVariant(db, project.id, template);
|
variant = await pickVariant(db, project.id, template);
|
||||||
subject = variant === 'B' ? template.subject_b : template.subject;
|
subject = variant === 'B' ? template.subject_b : template.subject;
|
||||||
} else {
|
} else {
|
||||||
const orig = original.get(p.id);
|
const orig = await original.get(p.id);
|
||||||
subject = followupSubject(template, orig);
|
subject = followupSubject(template, orig);
|
||||||
inReplyTo = orig?.message_id;
|
inReplyTo = orig?.message_id;
|
||||||
}
|
}
|
||||||
|
|
@ -126,17 +154,17 @@ export function makeHandlers(app) {
|
||||||
});
|
});
|
||||||
try {
|
try {
|
||||||
await transport.sendMail(mail);
|
await transport.sendMail(mail);
|
||||||
log.run(project.id, p.id, p.email, now(), null, kind, variant, mail.subject, mail.messageId);
|
await log.run(project.id, p.id, p.email, now(), null, kind, variant, mail.subject, mail.messageId);
|
||||||
if (kind === 'initial') markInitial.run('sent', now(), variant, p.id);
|
if (kind === 'initial') await markInitial.run('sent', now(), variant, p.id);
|
||||||
else markFollowup.run(now(), p.id);
|
else await markFollowup.run(now(), p.id);
|
||||||
sent++;
|
sent++;
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
log.run(project.id, p.id, p.email, now(), String(e.message).slice(0, 500), kind, variant, mail.subject, mail.messageId);
|
await log.run(project.id, p.id, p.email, now(), String(e.message).slice(0, 500), kind, variant, mail.subject, mail.messageId);
|
||||||
if (/^5\d\d/.test(String(e.responseCode))) markBounced.run(p.id);
|
if (/^5\d\d/.test(String(e.responseCode))) await markBounced.run(p.id);
|
||||||
failed++;
|
failed++;
|
||||||
}
|
}
|
||||||
const label = kind === 'followup' ? 'relances envoyées' : 'envoyés';
|
const label = kind === 'followup' ? 'relances envoyées' : 'envoyés';
|
||||||
ctx.progress({ sent, failed, total: n, message: `${sent + failed}/${n} ${label}`, pct: Math.round(((sent + failed) / n) * 100) });
|
await ctx.progress({ sent, failed, total: n, message: `${sent + failed}/${n} ${label}`, pct: Math.round(((sent + failed) / n) * 100) });
|
||||||
if (sent + failed < n) await sleep(minDelay + Math.random() * (maxDelay - minDelay), ctx.signal).catch(() => {});
|
if (sent + failed < n) await sleep(minDelay + Math.random() * (maxDelay - minDelay), ctx.signal).catch(() => {});
|
||||||
}
|
}
|
||||||
transport.close();
|
transport.close();
|
||||||
|
|
@ -145,41 +173,48 @@ export function makeHandlers(app) {
|
||||||
|
|
||||||
return {
|
return {
|
||||||
async analyze(ctx) {
|
async analyze(ctx) {
|
||||||
const project = getProject(app, ctx.job.project_id);
|
const userId = ctx.job.user_id;
|
||||||
ctx.progress({ message: 'Récupération du repo…', pct: 3 });
|
const project = await getProject(app, ctx.job.project_id, { userId });
|
||||||
const dir = repoDir(cfg, project.id);
|
await ctx.progress({ message: 'Récupération du repo…', pct: 3 });
|
||||||
const commit = await syncRepo(project.gitUrl, dir, forgejoToken(app));
|
const dir = repoDir(cfg, userId, project.id);
|
||||||
|
const commit = await sync(project.gitUrl, dir, await forgejoToken(app, userId));
|
||||||
|
|
||||||
ctx.progress({ message: 'Analyse du code par Claude…', pct: 10 });
|
await ctx.progress({ message: 'Analyse du code par Claude…', pct: 10 });
|
||||||
const { prompt, system } = analyzePrompt(project.name);
|
const { prompt, system } = analyzePrompt(project.name);
|
||||||
const model = getSetting(db, 'analyze_model', 'haiku');
|
const model = await getSetting(db, userId, 'analyze_model', 'haiku');
|
||||||
const r = await claude({
|
const sink = makeSink();
|
||||||
|
const r = await claude(userId, {
|
||||||
prompt, system, cwd: dir, model, maxTurns: 20, tools: ['Read', 'Glob', 'Grep'], signal: ctx.signal,
|
prompt, system, cwd: dir, model, maxTurns: 20, tools: ['Read', 'Glob', 'Grep'], signal: ctx.signal,
|
||||||
onTurn: (n) => ctx.progress({ message: `Lecture du code par Claude (étape ${n})…`, pct: turnPct(10, 95, n, 20) }),
|
onTurn: (n) => sink.push(() => ctx.progress({ message: `Lecture du code par Claude (étape ${n})…`, pct: turnPct(10, 95, n, 20) })),
|
||||||
});
|
});
|
||||||
|
await sink.flush();
|
||||||
addUsage(ctx, r);
|
addUsage(ctx, r);
|
||||||
if (!r.ok) throw new Error(`Analyse incomplète (${r.subtype})`);
|
if (!r.ok) throw new Error(`Analyse incomplète (${r.subtype})`);
|
||||||
const profile = extractJson(r.text);
|
const profile = extractJson(r.text);
|
||||||
if (!profile.resume || !profile.cible) throw new Error('Fiche projet incomplète');
|
if (!profile.resume || !profile.cible) throw new Error('Fiche projet incomplète');
|
||||||
const { cible, ...rest } = profile;
|
const { cible, ...rest } = profile;
|
||||||
db.prepare('UPDATE projects SET profile_json = ?, profile_commit = ?, profile_at = ?, target_json = ?, target_validated = 0 WHERE id = ?')
|
await db.prepare('UPDATE projects SET profile_json = ?, profile_commit = ?, profile_at = ?, target_json = ?, target_validated = 0 WHERE id = ?')
|
||||||
.run(JSON.stringify(rest), commit, now(), JSON.stringify(cible), project.id);
|
.run(JSON.stringify(rest), commit, now(), JSON.stringify(cible), project.id);
|
||||||
return { commit };
|
return { commit };
|
||||||
},
|
},
|
||||||
|
|
||||||
async prospect(ctx) {
|
async prospect(ctx) {
|
||||||
const project = getProject(app, ctx.job.project_id);
|
const userId = ctx.job.user_id;
|
||||||
|
const project = await getProject(app, ctx.job.project_id, { userId });
|
||||||
if (!project.profile || !project.targetValidated) throw new Error('Valide la cible du projet avant de prospecter');
|
if (!project.profile || !project.targetValidated) throw new Error('Valide la cible du projet avant de prospecter');
|
||||||
const count = Math.max(1, Math.min(50, Math.floor(Number(ctx.params.count) || 10)));
|
const count = Math.max(1, Math.min(50, Math.floor(Number(ctx.params.count) || 10)));
|
||||||
|
|
||||||
// Domaines déjà connus (tous projets) : Claude ne les recherche pas une 2e fois
|
// Domaines déjà connus de ce projet : Claude ne les recherche pas une 2e fois. La liste d'opposition,
|
||||||
const exclude = db.prepare(`
|
// commune à tous les comptes, n'entre pas dans le prompt (elle est appliquée à l'insertion, ci-dessous).
|
||||||
|
const exclude = (await db.prepare(`
|
||||||
SELECT DISTINCT substr(email, instr(email, '@') + 1) d FROM prospects WHERE project_id = ?
|
SELECT DISTINCT substr(email, instr(email, '@') + 1) d FROM prospects WHERE project_id = ?
|
||||||
UNION SELECT substr(email, instr(email, '@') + 1) FROM blacklist
|
LIMIT 300`).all(project.id)).map((r) => r.d);
|
||||||
LIMIT 300`).all(project.id).map((r) => r.d);
|
|
||||||
|
|
||||||
|
// Deux requêtes plutôt qu'un INSERT ... SELECT sans FROM (non portable) ; l'unicité (projet, email) reste garantie par la base
|
||||||
|
const optedOut = db.prepare('SELECT 1 FROM blacklist WHERE email = ?');
|
||||||
const insert = db.prepare(`INSERT OR IGNORE INTO prospects(project_id, company, email, website, city, sector, hook, source, score, created_at)
|
const insert = db.prepare(`INSERT OR IGNORE INTO prospects(project_id, company, email, website, city, sector, hook, source, score, created_at)
|
||||||
SELECT ?, ?, ?, ?, ?, ?, ?, ?, ?, ? WHERE NOT EXISTS (SELECT 1 FROM blacklist WHERE email = ?)`);
|
VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`);
|
||||||
|
const sink = makeSink();
|
||||||
let found = 0;
|
let found = 0;
|
||||||
let pending = '';
|
let pending = '';
|
||||||
let turns = 0;
|
let turns = 0;
|
||||||
|
|
@ -194,53 +229,59 @@ export function makeHandlers(app) {
|
||||||
pending += text + '\n';
|
pending += text + '\n';
|
||||||
const lines = pending.split('\n');
|
const lines = pending.split('\n');
|
||||||
pending = lines.pop();
|
pending = lines.pop();
|
||||||
for (const line of lines) {
|
const parsed = lines.map(parseProspectLine).filter(Boolean);
|
||||||
const p = parseProspectLine(line);
|
if (!parsed.length) return;
|
||||||
if (!p) continue;
|
sink.push(async () => {
|
||||||
const res = insert.run(project.id, p.company, p.email, p.website, p.city, p.sector, p.hook, p.source, p.score, now(), p.email);
|
for (const p of parsed) {
|
||||||
if (res.changes) {
|
if (await optedOut.get(p.email)) continue;
|
||||||
found++;
|
const res = await insert.run(project.id, p.company, p.email, p.website, p.city, p.sector, p.hook, p.source, p.score, now());
|
||||||
message = `${found}/${count} — ${p.company}`;
|
if (res.changes) {
|
||||||
report();
|
found++;
|
||||||
|
message = `${found}/${count} — ${p.company}`;
|
||||||
|
await report();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
});
|
||||||
};
|
};
|
||||||
report();
|
await report();
|
||||||
const { prompt, system } = prospectPrompt({ profile: project.profile, target: project.target, count, exclude });
|
const { prompt, system } = prospectPrompt({ profile: project.profile, target: project.target, count, exclude });
|
||||||
const model = getSetting(db, 'prospect_model', 'haiku');
|
const model = await getSetting(db, userId, 'prospect_model', 'haiku');
|
||||||
const r = await claude({
|
const r = await claude(userId, {
|
||||||
prompt, system, model, tools: ['WebSearch', 'WebFetch'],
|
prompt, system, model, tools: ['WebSearch', 'WebFetch'],
|
||||||
maxTurns, onText, signal: ctx.signal,
|
maxTurns, onText, signal: ctx.signal,
|
||||||
onTurn: (n) => { turns = n; report(); },
|
onTurn: (n) => { turns = n; sink.push(report); },
|
||||||
});
|
});
|
||||||
onText('\n');
|
onText('\n');
|
||||||
|
await sink.flush();
|
||||||
addUsage(ctx, r);
|
addUsage(ctx, r);
|
||||||
return { found, requested: count, stoppedBy: r.subtype };
|
return { found, requested: count, stoppedBy: r.subtype };
|
||||||
},
|
},
|
||||||
|
|
||||||
async template(ctx) {
|
async template(ctx) {
|
||||||
const project = getProject(app, ctx.job.project_id, { secrets: true });
|
const userId = ctx.job.user_id;
|
||||||
|
const project = await getProject(app, ctx.job.project_id, { userId, secrets: true });
|
||||||
if (!project.profile) throw new Error('Analyse le projet d\'abord');
|
if (!project.profile) throw new Error('Analyse le projet d\'abord');
|
||||||
ctx.progress({ message: 'Rédaction du modèle par Claude…', pct: 40 });
|
await ctx.progress({ message: 'Rédaction du modèle par Claude…', pct: 40 });
|
||||||
const { prompt, system } = templatePrompt({ profile: project.profile, target: project.target || {}, senderName: project.smtp?.fromName });
|
const { prompt, system } = templatePrompt({ profile: project.profile, target: project.target || {}, senderName: project.smtp?.fromName });
|
||||||
const r = await claude({ prompt, system, model: 'haiku', maxTurns: 1, tools: [], signal: ctx.signal });
|
const r = await claude(userId, { prompt, system, model: 'haiku', maxTurns: 1, tools: [], signal: ctx.signal });
|
||||||
addUsage(ctx, r);
|
addUsage(ctx, r);
|
||||||
const t = extractJson(r.text);
|
const t = extractJson(r.text);
|
||||||
if (!t.subject || !t.body) throw new Error('Modèle de mail invalide');
|
if (!t.subject || !t.body) throw new Error('Modèle de mail invalide');
|
||||||
saveTemplate(db, project.id, 'initial', { subject: t.subject, body: t.body });
|
await saveTemplate(db, project.id, 'initial', { subject: t.subject, body: t.body });
|
||||||
return { ok: true };
|
return { ok: true };
|
||||||
},
|
},
|
||||||
|
|
||||||
async followup_template(ctx) {
|
async followup_template(ctx) {
|
||||||
const project = getProject(app, ctx.job.project_id, { secrets: true });
|
const userId = ctx.job.user_id;
|
||||||
|
const project = await getProject(app, ctx.job.project_id, { userId, secrets: true });
|
||||||
if (!project.profile) throw new Error('Analyse le projet d\'abord');
|
if (!project.profile) throw new Error('Analyse le projet d\'abord');
|
||||||
ctx.progress({ message: 'Rédaction de la relance par Claude…', pct: 40 });
|
await ctx.progress({ message: 'Rédaction de la relance par Claude…', pct: 40 });
|
||||||
const { prompt, system } = followupTemplatePrompt({ profile: project.profile, senderName: project.smtp?.fromName });
|
const { prompt, system } = followupTemplatePrompt({ profile: project.profile, senderName: project.smtp?.fromName });
|
||||||
const r = await claude({ prompt, system, model: 'haiku', maxTurns: 1, tools: [], signal: ctx.signal });
|
const r = await claude(userId, { prompt, system, model: 'haiku', maxTurns: 1, tools: [], signal: ctx.signal });
|
||||||
addUsage(ctx, r);
|
addUsage(ctx, r);
|
||||||
const t = extractJson(r.text);
|
const t = extractJson(r.text);
|
||||||
if (!t.body) throw new Error('Modèle de relance invalide');
|
if (!t.body) throw new Error('Modèle de relance invalide');
|
||||||
saveTemplate(db, project.id, 'followup', { subject: '', body: t.body });
|
await saveTemplate(db, project.id, 'followup', { subject: '', body: t.body });
|
||||||
return { ok: true };
|
return { ok: true };
|
||||||
},
|
},
|
||||||
|
|
||||||
|
|
@ -248,29 +289,32 @@ export function makeHandlers(app) {
|
||||||
followup: (ctx) => sendMails(ctx, 'followup'),
|
followup: (ctx) => sendMails(ctx, 'followup'),
|
||||||
|
|
||||||
async evolution(ctx) {
|
async evolution(ctx) {
|
||||||
const project = getProject(app, ctx.job.project_id, { secrets: true });
|
const userId = ctx.job.user_id;
|
||||||
|
const project = await getProject(app, ctx.job.project_id, { userId, secrets: true });
|
||||||
const count = Math.max(1, Math.min(20, Math.floor(Number(ctx.params.count) || 5)));
|
const count = Math.max(1, Math.min(20, Math.floor(Number(ctx.params.count) || 5)));
|
||||||
const level = LEVELS[ctx.params.level] ? ctx.params.level : 'normal';
|
const level = LEVELS[ctx.params.level] ? ctx.params.level : 'normal';
|
||||||
const to = getSetting(db, 'notify_email');
|
const to = await getSetting(db, userId, 'notify_email');
|
||||||
const smtp = globalSmtp(app) || project.smtp;
|
const smtp = (await globalSmtp(app, userId)) || project.smtp;
|
||||||
if (!to) throw new Error('Adresse de réception non configurée (Réglages)');
|
if (!to) throw new Error('Adresse de réception non configurée (Réglages)');
|
||||||
if (!smtp) throw new Error('Aucun SMTP configuré (Réglages ou projet)');
|
if (!smtp) throw new Error('Aucun SMTP configuré (Réglages ou projet)');
|
||||||
|
|
||||||
ctx.progress({ message: 'Mise à jour du repo…', pct: 3 });
|
await ctx.progress({ message: 'Mise à jour du repo…', pct: 3 });
|
||||||
const dir = repoDir(cfg, project.id);
|
const dir = repoDir(cfg, userId, project.id);
|
||||||
await syncRepo(project.gitUrl, dir, forgejoToken(app));
|
await sync(project.gitUrl, dir, await forgejoToken(app, userId));
|
||||||
|
|
||||||
ctx.progress({ message: `Recherche de ${count} évolutions (${level})…`, pct: 10 });
|
await ctx.progress({ message: `Recherche de ${count} évolutions (${level})…`, pct: 10 });
|
||||||
const { prompt, system } = evolutionPrompt({ projectName: project.name, profile: project.profile, count, level });
|
const { prompt, system } = evolutionPrompt({ projectName: project.name, profile: project.profile, count, level });
|
||||||
const { model, maxTurns } = LEVELS[level];
|
const { model, maxTurns } = LEVELS[level];
|
||||||
const r = await claude({
|
const sink = makeSink();
|
||||||
|
const r = await claude(userId, {
|
||||||
prompt, system, cwd: dir, model, maxTurns, tools: ['Read', 'Glob', 'Grep'], signal: ctx.signal,
|
prompt, system, cwd: dir, model, maxTurns, tools: ['Read', 'Glob', 'Grep'], signal: ctx.signal,
|
||||||
onTurn: (n) => ctx.progress({ message: `Recherche de ${count} évolutions (${level}) · étape ${n}…`, pct: turnPct(10, 90, n, maxTurns) }),
|
onTurn: (n) => sink.push(() => ctx.progress({ message: `Recherche de ${count} évolutions (${level}) · étape ${n}…`, pct: turnPct(10, 90, n, maxTurns) })),
|
||||||
});
|
});
|
||||||
|
await sink.flush();
|
||||||
addUsage(ctx, r);
|
addUsage(ctx, r);
|
||||||
if (!r.text?.trim()) throw new Error(`Pas de résultat (${r.subtype})`);
|
if (!r.text?.trim()) throw new Error(`Pas de résultat (${r.subtype})`);
|
||||||
|
|
||||||
ctx.progress({ message: 'Envoi par mail…', pct: 95 });
|
await ctx.progress({ message: 'Envoi par mail…', pct: 95 });
|
||||||
const transport = (app.createTransport || createTransport)(smtp);
|
const transport = (app.createTransport || createTransport)(smtp);
|
||||||
await transport.sendMail({
|
await transport.sendMail({
|
||||||
from: smtp.fromEmail, to,
|
from: smtp.fromEmail, to,
|
||||||
|
|
|
||||||
|
|
@ -32,8 +32,8 @@ export function parseCookies(req) {
|
||||||
return out;
|
return out;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function setCookie(res, name, value, { maxAge, httpOnly = true } = {}) {
|
export function setCookie(res, name, value, { maxAge, httpOnly = true, sameSite = 'Lax', path = '/' } = {}) {
|
||||||
const parts = [`${name}=${encodeURIComponent(value)}`, 'Path=/', 'SameSite=Lax', 'Secure'];
|
const parts = [`${name}=${encodeURIComponent(value)}`, `Path=${path}`, `SameSite=${sameSite}`, 'Secure'];
|
||||||
if (httpOnly) parts.push('HttpOnly');
|
if (httpOnly) parts.push('HttpOnly');
|
||||||
if (maxAge !== undefined) parts.push(`Max-Age=${maxAge}`);
|
if (maxAge !== undefined) parts.push(`Max-Age=${maxAge}`);
|
||||||
const prev = res.getHeader('Set-Cookie');
|
const prev = res.getHeader('Set-Cookie');
|
||||||
|
|
@ -65,8 +65,9 @@ export const html = (res, body, status = 200) => send(res, status, body);
|
||||||
export const json = (res, data, status = 200) => send(res, status, JSON.stringify(data), 'application/json; charset=utf-8');
|
export const json = (res, data, status = 200) => send(res, status, JSON.stringify(data), 'application/json; charset=utf-8');
|
||||||
export function redirect(res, location) { res.writeHead(303, { Location: location }); res.end(); }
|
export function redirect(res, location) { res.writeHead(303, { Location: location }); res.end(); }
|
||||||
|
|
||||||
|
// `expose` : message sûr destiné à l'utilisateur même pour un 5xx (ex. impossible de joindre un service tiers)
|
||||||
export class HttpError extends Error {
|
export class HttpError extends Error {
|
||||||
constructor(status, message) { super(message); this.status = status; }
|
constructor(status, message, { expose = false } = {}) { super(message); this.status = status; this.expose = expose; }
|
||||||
}
|
}
|
||||||
|
|
||||||
// Échappement HTML pour les templates
|
// Échappement HTML pour les templates
|
||||||
|
|
|
||||||
402
src/migrations.js
Normal file
402
src/migrations.js
Normal file
|
|
@ -0,0 +1,402 @@
|
||||||
|
// Migrations versionnées, en deux dialectes maintenus ENSEMBLE : MySQL/MariaDB (production)
|
||||||
|
// et SQLite en mémoire (tests locaux). Une entrée = une version, avec les mêmes tables et colonnes
|
||||||
|
// des deux côtés (test/schema.test.js le vérifie). Ne jamais modifier une migration déjà livrée,
|
||||||
|
// en ajouter une. Côté MySQL, chaque instruction est idempotente (CREATE ... IF NOT EXISTS) : MySQL
|
||||||
|
// valide implicitement chaque DDL, une migration interrompue peut donc être rejouée.
|
||||||
|
//
|
||||||
|
// Une instruction est soit une chaîne SQL, soit { sql, params?(ctx), when?(q, ctx) } :
|
||||||
|
// - params(ctx) fournit les paramètres liés (ctx = { ownerEmail, now }) ;
|
||||||
|
// - when(q, ctx) décide si l'instruction s'applique (q(sql, params) renvoie les lignes) : c'est ce qui rend
|
||||||
|
// les ALTER TABLE rejouables côté MySQL (pas de IF NOT EXISTS sur ADD COLUMN) ;
|
||||||
|
// - check(q, ctx), au niveau de la migration, est lancé avant toute écriture et peut refuser de migrer.
|
||||||
|
// sqliteForeignKeysOff : la migration reconstruit des tables (SQLite ne sait pas retirer un UNIQUE) ; les clés
|
||||||
|
// étrangères sont suspendues pendant la migration, puis PRAGMA foreign_key_check vérifie le résultat.
|
||||||
|
|
||||||
|
const T = 'ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci';
|
||||||
|
|
||||||
|
export const MIGRATIONS = [
|
||||||
|
{
|
||||||
|
// Schéma initial = consolidation des 8 migrations SQLite historiques de l'instance perso
|
||||||
|
name: 'initial',
|
||||||
|
sqlite: [
|
||||||
|
`CREATE TABLE sessions (
|
||||||
|
id TEXT PRIMARY KEY, email TEXT NOT NULL,
|
||||||
|
created_at INTEGER NOT NULL, expires_at INTEGER NOT NULL
|
||||||
|
)`,
|
||||||
|
`CREATE TABLE oauth_states (
|
||||||
|
state TEXT PRIMARY KEY, verifier TEXT NOT NULL, nonce TEXT NOT NULL, created_at INTEGER NOT NULL
|
||||||
|
)`,
|
||||||
|
'CREATE TABLE settings (key TEXT PRIMARY KEY, value TEXT)',
|
||||||
|
`CREATE TABLE projects (
|
||||||
|
id INTEGER PRIMARY KEY,
|
||||||
|
name TEXT NOT NULL,
|
||||||
|
git_url TEXT NOT NULL UNIQUE,
|
||||||
|
profile_json TEXT, -- fiche projet générée par Claude
|
||||||
|
profile_commit TEXT, -- commit analysé
|
||||||
|
profile_at INTEGER,
|
||||||
|
target_json TEXT, -- cible déduite (modifiable)
|
||||||
|
target_validated INTEGER NOT NULL DEFAULT 0,
|
||||||
|
smtp_enc TEXT, -- config SMTP chiffrée
|
||||||
|
db_enc TEXT, -- accès BDD chiffré (récap)
|
||||||
|
imap_enc TEXT, -- config IMAP chiffrée
|
||||||
|
inbox_json TEXT, -- état de la dernière lecture IMAP
|
||||||
|
daily_mail_cap INTEGER NOT NULL DEFAULT 30,
|
||||||
|
followup_enabled INTEGER NOT NULL DEFAULT 0,
|
||||||
|
followup_days INTEGER NOT NULL DEFAULT 7,
|
||||||
|
created_at INTEGER NOT NULL
|
||||||
|
)`,
|
||||||
|
`CREATE TABLE templates (
|
||||||
|
project_id INTEGER NOT NULL REFERENCES projects(id) ON DELETE CASCADE,
|
||||||
|
kind TEXT NOT NULL CHECK (kind IN ('initial', 'followup')),
|
||||||
|
subject TEXT NOT NULL DEFAULT '', -- relance : vide = "Re: <objet du 1er mail>"
|
||||||
|
subject_b TEXT, -- objet B (premier mail uniquement)
|
||||||
|
body TEXT NOT NULL,
|
||||||
|
status TEXT NOT NULL DEFAULT 'draft',
|
||||||
|
updated_at INTEGER NOT NULL,
|
||||||
|
PRIMARY KEY (project_id, kind)
|
||||||
|
)`,
|
||||||
|
`CREATE TABLE prospects (
|
||||||
|
id INTEGER PRIMARY KEY,
|
||||||
|
project_id INTEGER NOT NULL REFERENCES projects(id) ON DELETE CASCADE,
|
||||||
|
company TEXT NOT NULL, email TEXT NOT NULL, website TEXT, city TEXT, sector TEXT,
|
||||||
|
hook TEXT, -- accroche perso (1 phrase)
|
||||||
|
source TEXT, -- page où l'email a été trouvé (RGPD : origine des données)
|
||||||
|
score INTEGER,
|
||||||
|
status TEXT NOT NULL DEFAULT 'new', -- new | sent | replied | client | refused | bounced
|
||||||
|
variant TEXT, -- A | B
|
||||||
|
sent_at INTEGER, created_at INTEGER NOT NULL,
|
||||||
|
replied_at INTEGER, reply_subject TEXT,
|
||||||
|
followup_at INTEGER,
|
||||||
|
next_action TEXT, next_action_at INTEGER,
|
||||||
|
UNIQUE(project_id, email)
|
||||||
|
)`,
|
||||||
|
'CREATE INDEX prospects_project ON prospects(project_id, status)',
|
||||||
|
'CREATE TABLE blacklist (email TEXT PRIMARY KEY, reason TEXT, created_at INTEGER NOT NULL)',
|
||||||
|
`CREATE TABLE jobs (
|
||||||
|
id INTEGER PRIMARY KEY,
|
||||||
|
project_id INTEGER REFERENCES projects(id) ON DELETE CASCADE,
|
||||||
|
type TEXT NOT NULL, -- analyze | prospect | template | send | evolution…
|
||||||
|
status TEXT NOT NULL DEFAULT 'queued', -- queued | running | done | error | cancelled
|
||||||
|
params_json TEXT, progress_json TEXT, result_json TEXT, error TEXT,
|
||||||
|
cost_usd REAL, tokens_in INTEGER, tokens_out INTEGER,
|
||||||
|
created_at INTEGER NOT NULL, started_at INTEGER, finished_at INTEGER,
|
||||||
|
run_after INTEGER -- ne pas démarrer avant (epoch s)
|
||||||
|
)`,
|
||||||
|
'CREATE INDEX jobs_status ON jobs(status, id)',
|
||||||
|
`CREATE TABLE mail_log (
|
||||||
|
id INTEGER PRIMARY KEY,
|
||||||
|
project_id INTEGER NOT NULL REFERENCES projects(id) ON DELETE CASCADE,
|
||||||
|
prospect_id INTEGER, email TEXT NOT NULL, sent_at INTEGER NOT NULL, error TEXT,
|
||||||
|
kind TEXT NOT NULL DEFAULT 'initial',
|
||||||
|
variant TEXT, subject TEXT, message_id TEXT
|
||||||
|
)`,
|
||||||
|
'CREATE INDEX mail_log_day ON mail_log(project_id, sent_at)',
|
||||||
|
'CREATE INDEX mail_log_msgid ON mail_log(message_id)',
|
||||||
|
`CREATE TABLE prospect_notes (
|
||||||
|
id INTEGER PRIMARY KEY,
|
||||||
|
prospect_id INTEGER NOT NULL REFERENCES prospects(id) ON DELETE CASCADE,
|
||||||
|
body TEXT NOT NULL,
|
||||||
|
created_at INTEGER NOT NULL
|
||||||
|
)`,
|
||||||
|
'CREATE INDEX prospect_notes_p ON prospect_notes(prospect_id, created_at)',
|
||||||
|
`CREATE TABLE metrics_daily (
|
||||||
|
project_id INTEGER NOT NULL REFERENCES projects(id) ON DELETE CASCADE,
|
||||||
|
day TEXT NOT NULL, -- AAAA-MM-JJ, heure de Paris
|
||||||
|
users REAL, clients REAL, revenue REAL,
|
||||||
|
PRIMARY KEY (project_id, day)
|
||||||
|
)`,
|
||||||
|
],
|
||||||
|
mysql: [
|
||||||
|
// Identifiants sensibles à la casse (base64url) : collation binaire
|
||||||
|
`CREATE TABLE IF NOT EXISTS sessions (
|
||||||
|
id VARCHAR(128) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL PRIMARY KEY,
|
||||||
|
email VARCHAR(255) NOT NULL,
|
||||||
|
created_at BIGINT NOT NULL, expires_at BIGINT NOT NULL
|
||||||
|
) ${T}`,
|
||||||
|
`CREATE TABLE IF NOT EXISTS oauth_states (
|
||||||
|
state VARCHAR(128) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL PRIMARY KEY,
|
||||||
|
verifier VARCHAR(255) NOT NULL, nonce VARCHAR(255) NOT NULL, created_at BIGINT NOT NULL
|
||||||
|
) ${T}`,
|
||||||
|
`CREATE TABLE IF NOT EXISTS settings (
|
||||||
|
\`key\` VARCHAR(190) NOT NULL PRIMARY KEY,
|
||||||
|
value TEXT
|
||||||
|
) ${T}`,
|
||||||
|
`CREATE TABLE IF NOT EXISTS projects (
|
||||||
|
id BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY,
|
||||||
|
name VARCHAR(255) NOT NULL,
|
||||||
|
git_url VARCHAR(500) NOT NULL,
|
||||||
|
profile_json MEDIUMTEXT, -- fiche projet générée par Claude
|
||||||
|
profile_commit VARCHAR(64), -- commit analysé
|
||||||
|
profile_at BIGINT,
|
||||||
|
target_json TEXT, -- cible déduite (modifiable)
|
||||||
|
target_validated TINYINT NOT NULL DEFAULT 0,
|
||||||
|
smtp_enc TEXT, -- config SMTP chiffrée
|
||||||
|
db_enc TEXT, -- accès BDD chiffré (récap)
|
||||||
|
imap_enc TEXT, -- config IMAP chiffrée
|
||||||
|
inbox_json TEXT, -- état de la dernière lecture IMAP
|
||||||
|
daily_mail_cap INT NOT NULL DEFAULT 30,
|
||||||
|
followup_enabled TINYINT NOT NULL DEFAULT 0,
|
||||||
|
followup_days INT NOT NULL DEFAULT 7,
|
||||||
|
created_at BIGINT NOT NULL,
|
||||||
|
UNIQUE KEY projects_git_url (git_url)
|
||||||
|
) ${T}`,
|
||||||
|
`CREATE TABLE IF NOT EXISTS templates (
|
||||||
|
project_id BIGINT NOT NULL,
|
||||||
|
kind VARCHAR(20) NOT NULL,
|
||||||
|
subject VARCHAR(500) NOT NULL DEFAULT '', -- relance : vide = "Re: <objet du 1er mail>"
|
||||||
|
subject_b VARCHAR(500), -- objet B (premier mail uniquement)
|
||||||
|
body TEXT NOT NULL,
|
||||||
|
status VARCHAR(20) NOT NULL DEFAULT 'draft',
|
||||||
|
updated_at BIGINT NOT NULL,
|
||||||
|
PRIMARY KEY (project_id, kind),
|
||||||
|
CONSTRAINT templates_kind CHECK (kind IN ('initial', 'followup')),
|
||||||
|
CONSTRAINT templates_project FOREIGN KEY (project_id) REFERENCES projects(id) ON DELETE CASCADE
|
||||||
|
) ${T}`,
|
||||||
|
`CREATE TABLE IF NOT EXISTS prospects (
|
||||||
|
id BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY,
|
||||||
|
project_id BIGINT NOT NULL,
|
||||||
|
company VARCHAR(255) NOT NULL, email VARCHAR(255) NOT NULL,
|
||||||
|
website VARCHAR(500), city VARCHAR(255), sector VARCHAR(255),
|
||||||
|
hook TEXT, -- accroche perso (1 phrase)
|
||||||
|
source TEXT, -- page où l'email a été trouvé (RGPD : origine des données)
|
||||||
|
score INT,
|
||||||
|
status VARCHAR(20) NOT NULL DEFAULT 'new', -- new | sent | replied | client | refused | bounced
|
||||||
|
variant VARCHAR(4), -- A | B
|
||||||
|
sent_at BIGINT, created_at BIGINT NOT NULL,
|
||||||
|
replied_at BIGINT, reply_subject TEXT,
|
||||||
|
followup_at BIGINT,
|
||||||
|
next_action VARCHAR(255), next_action_at BIGINT,
|
||||||
|
UNIQUE KEY prospects_project_email (project_id, email),
|
||||||
|
KEY prospects_project (project_id, status),
|
||||||
|
CONSTRAINT prospects_project_fk FOREIGN KEY (project_id) REFERENCES projects(id) ON DELETE CASCADE
|
||||||
|
) ${T}`,
|
||||||
|
`CREATE TABLE IF NOT EXISTS blacklist (
|
||||||
|
email VARCHAR(255) NOT NULL PRIMARY KEY, reason VARCHAR(255), created_at BIGINT NOT NULL
|
||||||
|
) ${T}`,
|
||||||
|
`CREATE TABLE IF NOT EXISTS jobs (
|
||||||
|
id BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY,
|
||||||
|
project_id BIGINT NULL,
|
||||||
|
type VARCHAR(40) NOT NULL, -- analyze | prospect | template | send | evolution…
|
||||||
|
status VARCHAR(20) NOT NULL DEFAULT 'queued', -- queued | running | done | error | cancelled
|
||||||
|
params_json TEXT, progress_json TEXT, result_json MEDIUMTEXT, error TEXT,
|
||||||
|
cost_usd DOUBLE, tokens_in BIGINT, tokens_out BIGINT,
|
||||||
|
created_at BIGINT NOT NULL, started_at BIGINT, finished_at BIGINT,
|
||||||
|
run_after BIGINT, -- ne pas démarrer avant (epoch s)
|
||||||
|
KEY jobs_status (status, id),
|
||||||
|
CONSTRAINT jobs_project FOREIGN KEY (project_id) REFERENCES projects(id) ON DELETE CASCADE
|
||||||
|
) ${T}`,
|
||||||
|
`CREATE TABLE IF NOT EXISTS mail_log (
|
||||||
|
id BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY,
|
||||||
|
project_id BIGINT NOT NULL,
|
||||||
|
prospect_id BIGINT, email VARCHAR(255) NOT NULL, sent_at BIGINT NOT NULL, error TEXT,
|
||||||
|
kind VARCHAR(20) NOT NULL DEFAULT 'initial',
|
||||||
|
variant VARCHAR(4), subject TEXT, message_id VARCHAR(255),
|
||||||
|
KEY mail_log_day (project_id, sent_at),
|
||||||
|
KEY mail_log_msgid (message_id),
|
||||||
|
CONSTRAINT mail_log_project FOREIGN KEY (project_id) REFERENCES projects(id) ON DELETE CASCADE
|
||||||
|
) ${T}`,
|
||||||
|
`CREATE TABLE IF NOT EXISTS prospect_notes (
|
||||||
|
id BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY,
|
||||||
|
prospect_id BIGINT NOT NULL,
|
||||||
|
body TEXT NOT NULL,
|
||||||
|
created_at BIGINT NOT NULL,
|
||||||
|
KEY prospect_notes_p (prospect_id, created_at),
|
||||||
|
CONSTRAINT prospect_notes_prospect FOREIGN KEY (prospect_id) REFERENCES prospects(id) ON DELETE CASCADE
|
||||||
|
) ${T}`,
|
||||||
|
`CREATE TABLE IF NOT EXISTS metrics_daily (
|
||||||
|
project_id BIGINT NOT NULL,
|
||||||
|
day VARCHAR(10) NOT NULL, -- AAAA-MM-JJ, heure de Paris
|
||||||
|
users DOUBLE, clients DOUBLE, revenue DOUBLE,
|
||||||
|
PRIMARY KEY (project_id, day),
|
||||||
|
CONSTRAINT metrics_daily_project FOREIGN KEY (project_id) REFERENCES projects(id) ON DELETE CASCADE
|
||||||
|
) ${T}`,
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
// J2 : comptes et multi-tenant. Les données existantes sont rattachées à l'utilisateur « propriétaire »
|
||||||
|
// (première adresse de ADMIN_EMAILS). Sessions et états OAuth, éphémères, sont recréés.
|
||||||
|
name: 'comptes_multi_tenant',
|
||||||
|
sqliteForeignKeysOff: true,
|
||||||
|
check: checkOwner,
|
||||||
|
sqlite: [
|
||||||
|
`CREATE TABLE users (
|
||||||
|
id INTEGER PRIMARY KEY,
|
||||||
|
email TEXT NOT NULL COLLATE NOCASE UNIQUE,
|
||||||
|
name TEXT,
|
||||||
|
provider TEXT, -- google | apple (NULL = compte préparé par la migration, jamais connecté)
|
||||||
|
provider_sub TEXT, -- identifiant (sub) chez le fournisseur
|
||||||
|
status TEXT NOT NULL DEFAULT 'active' CHECK (status IN ('active', 'suspended')),
|
||||||
|
is_admin INTEGER NOT NULL DEFAULT 0,
|
||||||
|
plan TEXT NOT NULL DEFAULT 'free',
|
||||||
|
created_at INTEGER NOT NULL,
|
||||||
|
last_login_at INTEGER,
|
||||||
|
claude_link_json TEXT, -- liaison Claude (J3)
|
||||||
|
UNIQUE(provider, provider_sub)
|
||||||
|
)`,
|
||||||
|
{ sql: "INSERT OR IGNORE INTO users(email, status, is_admin, plan, created_at) VALUES(?, 'active', 1, 'free', ?)", params: ownerParams, when: hasLegacyData },
|
||||||
|
`CREATE TABLE projects_new (
|
||||||
|
id INTEGER PRIMARY KEY,
|
||||||
|
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||||
|
name TEXT NOT NULL,
|
||||||
|
git_url TEXT NOT NULL,
|
||||||
|
profile_json TEXT, -- fiche projet générée par Claude
|
||||||
|
profile_commit TEXT, -- commit analysé
|
||||||
|
profile_at INTEGER,
|
||||||
|
target_json TEXT, -- cible déduite (modifiable)
|
||||||
|
target_validated INTEGER NOT NULL DEFAULT 0,
|
||||||
|
smtp_enc TEXT, -- config SMTP chiffrée
|
||||||
|
db_enc TEXT, -- accès BDD chiffré (récap)
|
||||||
|
imap_enc TEXT, -- config IMAP chiffrée
|
||||||
|
inbox_json TEXT, -- état de la dernière lecture IMAP
|
||||||
|
daily_mail_cap INTEGER NOT NULL DEFAULT 30,
|
||||||
|
followup_enabled INTEGER NOT NULL DEFAULT 0,
|
||||||
|
followup_days INTEGER NOT NULL DEFAULT 7,
|
||||||
|
created_at INTEGER NOT NULL,
|
||||||
|
UNIQUE(user_id, git_url)
|
||||||
|
)`,
|
||||||
|
{ sql: `INSERT INTO projects_new(id, user_id, name, git_url, profile_json, profile_commit, profile_at, target_json, target_validated,
|
||||||
|
smtp_enc, db_enc, imap_enc, inbox_json, daily_mail_cap, followup_enabled, followup_days, created_at)
|
||||||
|
SELECT id, (SELECT id FROM users WHERE email = ?), name, git_url, profile_json, profile_commit, profile_at, target_json, target_validated,
|
||||||
|
smtp_enc, db_enc, imap_enc, inbox_json, daily_mail_cap, followup_enabled, followup_days, created_at FROM projects`, params: ownerParams0 },
|
||||||
|
'DROP TABLE projects',
|
||||||
|
'ALTER TABLE projects_new RENAME TO projects',
|
||||||
|
`CREATE TABLE jobs_new (
|
||||||
|
id INTEGER PRIMARY KEY,
|
||||||
|
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||||
|
project_id INTEGER REFERENCES projects(id) ON DELETE CASCADE,
|
||||||
|
type TEXT NOT NULL, -- analyze | prospect | template | send | evolution…
|
||||||
|
status TEXT NOT NULL DEFAULT 'queued', -- queued | running | done | error | cancelled
|
||||||
|
params_json TEXT, progress_json TEXT, result_json TEXT, error TEXT,
|
||||||
|
cost_usd REAL, tokens_in INTEGER, tokens_out INTEGER,
|
||||||
|
created_at INTEGER NOT NULL, started_at INTEGER, finished_at INTEGER,
|
||||||
|
run_after INTEGER -- ne pas démarrer avant (epoch s)
|
||||||
|
)`,
|
||||||
|
{ sql: `INSERT INTO jobs_new(id, user_id, project_id, type, status, params_json, progress_json, result_json, error,
|
||||||
|
cost_usd, tokens_in, tokens_out, created_at, started_at, finished_at, run_after)
|
||||||
|
SELECT id, COALESCE((SELECT user_id FROM projects WHERE projects.id = jobs.project_id), (SELECT id FROM users WHERE email = ?)),
|
||||||
|
project_id, type, status, params_json, progress_json, result_json, error,
|
||||||
|
cost_usd, tokens_in, tokens_out, created_at, started_at, finished_at, run_after FROM jobs`, params: ownerParams0 },
|
||||||
|
'DROP TABLE jobs',
|
||||||
|
'ALTER TABLE jobs_new RENAME TO jobs',
|
||||||
|
'CREATE INDEX jobs_status ON jobs(status, id)',
|
||||||
|
'CREATE INDEX jobs_user ON jobs(user_id, status)',
|
||||||
|
`CREATE TABLE user_settings (
|
||||||
|
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||||
|
key TEXT NOT NULL,
|
||||||
|
value TEXT,
|
||||||
|
PRIMARY KEY (user_id, key)
|
||||||
|
)`,
|
||||||
|
{ sql: 'INSERT OR IGNORE INTO user_settings(user_id, key, value) SELECT u.id, s.key, s.value FROM settings s JOIN users u ON u.email = ?', params: ownerParams0 },
|
||||||
|
'DROP TABLE settings',
|
||||||
|
'DROP TABLE sessions',
|
||||||
|
`CREATE TABLE sessions (
|
||||||
|
id TEXT PRIMARY KEY,
|
||||||
|
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||||
|
created_at INTEGER NOT NULL, expires_at INTEGER NOT NULL
|
||||||
|
)`,
|
||||||
|
'CREATE INDEX sessions_user ON sessions(user_id)',
|
||||||
|
'DROP TABLE oauth_states',
|
||||||
|
`CREATE TABLE oauth_states (
|
||||||
|
state TEXT PRIMARY KEY, provider TEXT NOT NULL, verifier TEXT NOT NULL, nonce TEXT NOT NULL,
|
||||||
|
binding TEXT NOT NULL, -- empreinte du cookie qui lie le flux au navigateur d'origine
|
||||||
|
created_at INTEGER NOT NULL
|
||||||
|
)`,
|
||||||
|
],
|
||||||
|
mysql: [
|
||||||
|
`CREATE TABLE IF NOT EXISTS users (
|
||||||
|
id BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY,
|
||||||
|
email VARCHAR(255) NOT NULL,
|
||||||
|
name VARCHAR(255),
|
||||||
|
provider VARCHAR(20), -- google | apple (NULL = compte préparé par la migration, jamais connecté)
|
||||||
|
provider_sub VARCHAR(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin, -- identifiant (sub) chez le fournisseur
|
||||||
|
status VARCHAR(20) NOT NULL DEFAULT 'active',
|
||||||
|
is_admin TINYINT NOT NULL DEFAULT 0,
|
||||||
|
plan VARCHAR(20) NOT NULL DEFAULT 'free',
|
||||||
|
created_at BIGINT NOT NULL,
|
||||||
|
last_login_at BIGINT,
|
||||||
|
claude_link_json TEXT, -- liaison Claude (J3)
|
||||||
|
UNIQUE KEY users_email (email),
|
||||||
|
UNIQUE KEY users_provider (provider, provider_sub),
|
||||||
|
CONSTRAINT users_status CHECK (status IN ('active', 'suspended'))
|
||||||
|
) ${T}`,
|
||||||
|
{ sql: "INSERT IGNORE INTO users(email, status, is_admin, plan, created_at) VALUES(?, 'active', 1, 'free', ?)", params: ownerParams, when: hasLegacyData },
|
||||||
|
// projects : user_id, puis unicité de git_url par utilisateur
|
||||||
|
{ sql: 'ALTER TABLE projects ADD COLUMN user_id BIGINT NULL', when: colMissing('projects', 'user_id') },
|
||||||
|
{ sql: 'UPDATE projects SET user_id = (SELECT id FROM users WHERE email = ?) WHERE user_id IS NULL', params: ownerParams0 },
|
||||||
|
'ALTER TABLE projects MODIFY user_id BIGINT NOT NULL',
|
||||||
|
{ sql: 'ALTER TABLE projects ADD CONSTRAINT projects_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE', when: fkMissing('projects', 'projects_user') },
|
||||||
|
{ sql: 'ALTER TABLE projects DROP INDEX projects_git_url', when: idxExists('projects', 'projects_git_url') },
|
||||||
|
{ sql: 'ALTER TABLE projects ADD UNIQUE KEY projects_user_git_url (user_id, git_url)', when: idxMissing('projects', 'projects_user_git_url') },
|
||||||
|
// jobs : user_id dénormalisé (un job sans projet doit rester attribuable)
|
||||||
|
{ sql: 'ALTER TABLE jobs ADD COLUMN user_id BIGINT NULL', when: colMissing('jobs', 'user_id') },
|
||||||
|
'UPDATE jobs SET user_id = (SELECT user_id FROM projects WHERE projects.id = jobs.project_id) WHERE user_id IS NULL AND project_id IS NOT NULL',
|
||||||
|
{ sql: 'UPDATE jobs SET user_id = (SELECT id FROM users WHERE email = ?) WHERE user_id IS NULL', params: ownerParams0 },
|
||||||
|
'ALTER TABLE jobs MODIFY user_id BIGINT NOT NULL',
|
||||||
|
{ sql: 'ALTER TABLE jobs ADD CONSTRAINT jobs_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE', when: fkMissing('jobs', 'jobs_user') },
|
||||||
|
{ sql: 'ALTER TABLE jobs ADD KEY jobs_user_status (user_id, status)', when: idxMissing('jobs', 'jobs_user_status') },
|
||||||
|
// réglages : globaux → par utilisateur
|
||||||
|
`CREATE TABLE IF NOT EXISTS user_settings (
|
||||||
|
user_id BIGINT NOT NULL,
|
||||||
|
\`key\` VARCHAR(190) NOT NULL,
|
||||||
|
value TEXT,
|
||||||
|
PRIMARY KEY (user_id, \`key\`),
|
||||||
|
CONSTRAINT user_settings_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
|
||||||
|
) ${T}`,
|
||||||
|
{ sql: 'INSERT IGNORE INTO user_settings(user_id, `key`, value) SELECT u.id, s.`key`, s.value FROM settings s JOIN users u ON u.email = ?', params: ownerParams0, when: tableExists('settings') },
|
||||||
|
'DROP TABLE IF EXISTS settings',
|
||||||
|
'DROP TABLE IF EXISTS sessions',
|
||||||
|
`CREATE TABLE IF NOT EXISTS sessions (
|
||||||
|
id VARCHAR(128) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL PRIMARY KEY,
|
||||||
|
user_id BIGINT NOT NULL,
|
||||||
|
created_at BIGINT NOT NULL, expires_at BIGINT NOT NULL,
|
||||||
|
KEY sessions_user (user_id),
|
||||||
|
CONSTRAINT sessions_user_fk FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
|
||||||
|
) ${T}`,
|
||||||
|
'DROP TABLE IF EXISTS oauth_states',
|
||||||
|
`CREATE TABLE IF NOT EXISTS oauth_states (
|
||||||
|
state VARCHAR(128) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL PRIMARY KEY,
|
||||||
|
provider VARCHAR(20) NOT NULL,
|
||||||
|
verifier VARCHAR(255) NOT NULL, nonce VARCHAR(255) NOT NULL,
|
||||||
|
binding VARCHAR(128) NOT NULL, -- empreinte du cookie qui lie le flux au navigateur d'origine
|
||||||
|
created_at BIGINT NOT NULL
|
||||||
|
) ${T}`,
|
||||||
|
],
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
// ---------- Aides de la migration 2 ----------
|
||||||
|
|
||||||
|
function ownerParams(ctx) { return [ctx.ownerEmail, ctx.now]; }
|
||||||
|
function ownerParams0(ctx) { return [ctx.ownerEmail ?? null]; }
|
||||||
|
|
||||||
|
// Des données existent-elles (une instance déjà utilisée) ? Alors elles ont besoin d'un propriétaire.
|
||||||
|
async function hasLegacyData(q) {
|
||||||
|
for (const t of ['projects', 'settings', 'jobs']) {
|
||||||
|
if ((await q(`SELECT COUNT(*) n FROM ${t}`))[0].n > 0) return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function checkOwner(q, ctx) {
|
||||||
|
if (ctx.ownerEmail) return;
|
||||||
|
if (await hasLegacyData(q)) {
|
||||||
|
throw new Error('Migration comptes : des données existent, définis ADMIN_EMAILS (le premier email devient propriétaire de ces données).');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const infoSchema = (what) => `SELECT 1 x FROM information_schema.${what} WHERE table_schema = DATABASE() AND table_name = ?`;
|
||||||
|
function colMissing(t, c) {
|
||||||
|
return async (q) => !(await q(`${infoSchema('columns')} AND column_name = ?`, [t, c])).length;
|
||||||
|
}
|
||||||
|
function idxExists(t, i) {
|
||||||
|
return async (q) => (await q(`${infoSchema('statistics')} AND index_name = ?`, [t, i])).length > 0;
|
||||||
|
}
|
||||||
|
function idxMissing(t, i) {
|
||||||
|
return async (q) => !(await idxExists(t, i)(q));
|
||||||
|
}
|
||||||
|
function fkMissing(t, name) {
|
||||||
|
return async (q) => !(await q(`${infoSchema('table_constraints')} AND constraint_name = ? AND constraint_type = 'FOREIGN KEY'`, [t, name])).length;
|
||||||
|
}
|
||||||
|
function tableExists(t) {
|
||||||
|
return async (q) => (await q(infoSchema('tables'), [t])).length > 0;
|
||||||
|
}
|
||||||
|
|
@ -3,7 +3,8 @@ import { now, getSetting } from './db.js';
|
||||||
import { encryptJson, decryptJson, decrypt } from './crypto.js';
|
import { encryptJson, decryptJson, decrypt } from './crypto.js';
|
||||||
import { HttpError } from './http.js';
|
import { HttpError } from './http.js';
|
||||||
|
|
||||||
export const repoDir = (cfg, id) => join(cfg.dataDir, 'repos', String(id));
|
// Un dossier de clones par utilisateur : data/repos/<utilisateur>/<projet>
|
||||||
|
export const repoDir = (cfg, userId, id) => join(cfg.dataDir, 'repos', String(Number(userId)), String(Number(id)));
|
||||||
|
|
||||||
const parse = (s) => (s ? JSON.parse(s) : null);
|
const parse = (s) => (s ? JSON.parse(s) : null);
|
||||||
|
|
||||||
|
|
@ -14,11 +15,16 @@ function readSecret(key, payload, what) {
|
||||||
catch { console.warn(`[secrets] ${what} illisible (SECRET_KEY changée ?), à ressaisir`); return null; }
|
catch { console.warn(`[secrets] ${what} illisible (SECRET_KEY changée ?), à ressaisir`); return null; }
|
||||||
}
|
}
|
||||||
|
|
||||||
export function getProject(app, id, { secrets = false } = {}) {
|
/**
|
||||||
const p = app.db.prepare('SELECT * FROM projects WHERE id = ?').get(Number(id));
|
* Projet d'un utilisateur. `userId` est obligatoire : un projet d'un autre compte est introuvable (404),
|
||||||
|
* exactement comme un projet qui n'existe pas. Les tâches de fond passent le propriétaire lu en base.
|
||||||
|
*/
|
||||||
|
export async function getProject(app, id, { userId, secrets = false } = {}) {
|
||||||
|
if (!Number.isInteger(Number(userId)) || Number(userId) <= 0) throw new Error('getProject : userId requis');
|
||||||
|
const p = await app.db.prepare('SELECT * FROM projects WHERE id = ? AND user_id = ?').get(Number(id), Number(userId));
|
||||||
if (!p) throw new HttpError(404, 'Projet introuvable');
|
if (!p) throw new HttpError(404, 'Projet introuvable');
|
||||||
const out = {
|
const out = {
|
||||||
id: p.id, name: p.name, gitUrl: p.git_url,
|
id: p.id, userId: Number(p.user_id), name: p.name, gitUrl: p.git_url,
|
||||||
profile: parse(p.profile_json), profileCommit: p.profile_commit, profileAt: p.profile_at,
|
profile: parse(p.profile_json), profileCommit: p.profile_commit, profileAt: p.profile_at,
|
||||||
target: parse(p.target_json), targetValidated: !!p.target_validated,
|
target: parse(p.target_json), targetValidated: !!p.target_validated,
|
||||||
dailyMailCap: p.daily_mail_cap, createdAt: p.created_at,
|
dailyMailCap: p.daily_mail_cap, createdAt: p.created_at,
|
||||||
|
|
@ -35,22 +41,24 @@ export function getProject(app, id, { secrets = false } = {}) {
|
||||||
return out;
|
return out;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function listProjects(app) {
|
export async function listProjects(app, userId) {
|
||||||
return app.db.prepare('SELECT id FROM projects ORDER BY name COLLATE NOCASE').all().map((r) => getProject(app, r.id));
|
const rows = await app.db.prepare('SELECT id FROM projects WHERE user_id = ? ORDER BY LOWER(name)').all(Number(userId));
|
||||||
|
return Promise.all(rows.map((r) => getProject(app, r.id, { userId })));
|
||||||
}
|
}
|
||||||
|
|
||||||
export function createProject(app, { name, gitUrl }) {
|
export async function createProject(app, { userId, name, gitUrl }) {
|
||||||
const r = app.db.prepare('INSERT INTO projects(name, git_url, created_at) VALUES(?, ?, ?)').run(name, gitUrl, now());
|
const r = await app.db.prepare('INSERT INTO projects(user_id, name, git_url, created_at) VALUES(?, ?, ?, ?)').run(Number(userId), name, gitUrl, now());
|
||||||
return Number(r.lastInsertRowid);
|
return Number(r.lastInsertRowid);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Les secrets vides dans le formulaire = on garde l'ancien (le formulaire ne les réaffiche jamais)
|
// Les secrets vides dans le formulaire = on garde l'ancien (le formulaire ne les réaffiche jamais)
|
||||||
export function saveSecretConfig(app, id, column, incoming, secretField) {
|
export async function saveSecretConfig(app, id, column, incoming, secretField) {
|
||||||
if (!['smtp_enc', 'db_enc', 'imap_enc'].includes(column)) throw new Error('Colonne invalide');
|
if (!['smtp_enc', 'db_enc', 'imap_enc'].includes(column)) throw new Error('Colonne invalide');
|
||||||
const current = readSecret(app.cfg.secretKey, app.db.prepare(`SELECT ${column} c FROM projects WHERE id = ?`).get(id)?.c, column) || {};
|
const row = await app.db.prepare(`SELECT ${column} c FROM projects WHERE id = ?`).get(id);
|
||||||
|
const current = readSecret(app.cfg.secretKey, row?.c, column) || {};
|
||||||
const next = { ...current, ...incoming };
|
const next = { ...current, ...incoming };
|
||||||
if (!incoming[secretField]) next[secretField] = current[secretField];
|
if (!incoming[secretField]) next[secretField] = current[secretField];
|
||||||
app.db.prepare(`UPDATE projects SET ${column} = ? WHERE id = ?`).run(encryptJson(app.cfg.secretKey, next), id);
|
await app.db.prepare(`UPDATE projects SET ${column} = ? WHERE id = ?`).run(encryptJson(app.cfg.secretKey, next), id);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Version "affichable" d'une config secrète (sans mot de passe)
|
// Version "affichable" d'une config secrète (sans mot de passe)
|
||||||
|
|
@ -60,27 +68,30 @@ export function publicConfig(cfg, secretField) {
|
||||||
return { ...rest, [`${secretField}Set`]: !!_omit };
|
return { ...rest, [`${secretField}Set`]: !!_omit };
|
||||||
}
|
}
|
||||||
|
|
||||||
export function forgejoToken(app) {
|
export async function forgejoToken(app, userId) {
|
||||||
try { return decrypt(app.cfg.secretKey, getSetting(app.db, 'forgejo_token_enc')); }
|
try { return decrypt(app.cfg.secretKey, await getSetting(app.db, userId, 'forgejo_token_enc')); }
|
||||||
catch { console.warn('[secrets] token Forgejo illisible, à ressaisir'); return null; }
|
catch { console.warn('[secrets] token Forgejo illisible, à ressaisir'); return null; }
|
||||||
}
|
}
|
||||||
|
|
||||||
export function globalSmtp(app) {
|
export async function globalSmtp(app, userId) {
|
||||||
return readSecret(app.cfg.secretKey, getSetting(app.db, 'smtp_enc'), 'SMTP global');
|
return readSecret(app.cfg.secretKey, await getSetting(app.db, userId, 'smtp_enc'), 'SMTP global');
|
||||||
}
|
}
|
||||||
|
|
||||||
export function prospectStats(db, projectId) {
|
export async function prospectStats(db, projectId) {
|
||||||
const rows = db.prepare('SELECT status, COUNT(*) n FROM prospects WHERE project_id = ? GROUP BY status').all(projectId);
|
const rows = await db.prepare('SELECT status, COUNT(*) n FROM prospects WHERE project_id = ? GROUP BY status').all(projectId);
|
||||||
const out = { total: 0 };
|
const out = { total: 0 };
|
||||||
for (const r of rows) { out[r.status] = r.n; out.total += r.n; }
|
for (const r of rows) { out[r.status] = r.n; out.total += r.n; }
|
||||||
return out;
|
return out;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function sentSince(db, since, projectId = null) {
|
/** Envois réussis depuis `since` : tous les projets de l'utilisateur, ou un seul projet (déjà vérifié comme étant le sien). */
|
||||||
const sql = projectId == null
|
export async function sentSince(db, since, userId, projectId = null) {
|
||||||
? 'SELECT COUNT(*) n FROM mail_log WHERE sent_at > ? AND error IS NULL'
|
if (projectId == null) {
|
||||||
: 'SELECT COUNT(*) n FROM mail_log WHERE sent_at > ? AND error IS NULL AND project_id = ?';
|
return (await db.prepare(`SELECT COUNT(*) n FROM mail_log m JOIN projects p ON p.id = m.project_id
|
||||||
return (projectId == null ? db.prepare(sql).get(since) : db.prepare(sql).get(since, projectId)).n;
|
WHERE m.sent_at > ? AND m.error IS NULL AND p.user_id = ?`).get(since, Number(userId))).n;
|
||||||
|
}
|
||||||
|
return (await db.prepare(`SELECT COUNT(*) n FROM mail_log m JOIN projects p ON p.id = m.project_id
|
||||||
|
WHERE m.sent_at > ? AND m.error IS NULL AND p.user_id = ? AND m.project_id = ?`).get(since, Number(userId), projectId)).n;
|
||||||
}
|
}
|
||||||
|
|
||||||
// IMAP : utilisateur vide = mêmes identifiants que le SMTP du projet (cas le plus courant)
|
// IMAP : utilisateur vide = mêmes identifiants que le SMTP du projet (cas le plus courant)
|
||||||
|
|
@ -96,24 +107,24 @@ export function imapCredentials(imap, smtp) {
|
||||||
// ---------- Modèles de mail ----------
|
// ---------- Modèles de mail ----------
|
||||||
export const TEMPLATE_KINDS = ['initial', 'followup'];
|
export const TEMPLATE_KINDS = ['initial', 'followup'];
|
||||||
|
|
||||||
export function getTemplate(db, projectId, kind, { validatedOnly = false } = {}) {
|
export async function getTemplate(db, projectId, kind, { validatedOnly = false } = {}) {
|
||||||
const row = db.prepare('SELECT * FROM templates WHERE project_id = ? AND kind = ?').get(projectId, kind);
|
const row = await db.prepare('SELECT * FROM templates WHERE project_id = ? AND kind = ?').get(projectId, kind);
|
||||||
if (!row || (validatedOnly && row.status !== 'validated')) return null;
|
if (!row || (validatedOnly && row.status !== 'validated')) return null;
|
||||||
return row;
|
return row;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function saveTemplate(db, projectId, kind, { subject = '', subjectB = null, body, status = 'draft' }) {
|
export async function saveTemplate(db, projectId, kind, { subject = '', subjectB = null, body, status = 'draft' }) {
|
||||||
if (!TEMPLATE_KINDS.includes(kind)) throw new HttpError(400, 'Type de modèle inconnu');
|
if (!TEMPLATE_KINDS.includes(kind)) throw new HttpError(400, 'Type de modèle inconnu');
|
||||||
db.prepare(`INSERT INTO templates(project_id, kind, subject, subject_b, body, status, updated_at) VALUES(?, ?, ?, ?, ?, ?, ?)
|
await db.prepare(`INSERT INTO templates(project_id, kind, subject, subject_b, body, status, updated_at) VALUES(?, ?, ?, ?, ?, ?, ?)
|
||||||
ON CONFLICT(project_id, kind) DO UPDATE SET subject = excluded.subject, subject_b = excluded.subject_b,
|
ON CONFLICT(project_id, kind) DO UPDATE SET subject = excluded.subject, subject_b = excluded.subject_b,
|
||||||
body = excluded.body, status = excluded.status, updated_at = excluded.updated_at`)
|
body = excluded.body, status = excluded.status, updated_at = excluded.updated_at`)
|
||||||
.run(projectId, kind, subject, kind === 'initial' ? (subjectB || null) : null, body, status, now());
|
.run(projectId, kind, subject, kind === 'initial' ? (subjectB || null) : null, body, status, now());
|
||||||
}
|
}
|
||||||
|
|
||||||
// Objet A ou B : on équilibre les envois (B seulement si un objet B est défini)
|
// Objet A ou B : on équilibre les envois (B seulement si un objet B est défini)
|
||||||
export function pickVariant(db, projectId, template) {
|
export async function pickVariant(db, projectId, template) {
|
||||||
if (!template.subject_b) return 'A';
|
if (!template.subject_b) return 'A';
|
||||||
const rows = db.prepare(`SELECT variant, COUNT(*) n FROM mail_log
|
const rows = await db.prepare(`SELECT variant, COUNT(*) n FROM mail_log
|
||||||
WHERE project_id = ? AND kind = 'initial' AND error IS NULL AND variant IN ('A', 'B') GROUP BY variant`).all(projectId);
|
WHERE project_id = ? AND kind = 'initial' AND error IS NULL AND variant IN ('A', 'B') GROUP BY variant`).all(projectId);
|
||||||
const count = { A: 0, B: 0 };
|
const count = { A: 0, B: 0 };
|
||||||
for (const r of rows) count[r.variant] = r.n;
|
for (const r of rows) count[r.variant] = r.n;
|
||||||
|
|
@ -121,8 +132,8 @@ export function pickVariant(db, projectId, template) {
|
||||||
}
|
}
|
||||||
|
|
||||||
// Taux de réponse par objet (A/B) sur les premiers mails
|
// Taux de réponse par objet (A/B) sur les premiers mails
|
||||||
export function abStats(db, projectId) {
|
export async function abStats(db, projectId) {
|
||||||
const rows = db.prepare(`SELECT m.variant v, COUNT(*) sent, SUM(p.replied_at IS NOT NULL) replied
|
const rows = await db.prepare(`SELECT m.variant v, COUNT(*) sent, SUM(p.replied_at IS NOT NULL) replied
|
||||||
FROM mail_log m JOIN prospects p ON p.id = m.prospect_id
|
FROM mail_log m JOIN prospects p ON p.id = m.prospect_id
|
||||||
WHERE m.project_id = ? AND m.kind = 'initial' AND m.error IS NULL AND m.variant IS NOT NULL
|
WHERE m.project_id = ? AND m.kind = 'initial' AND m.error IS NULL AND m.variant IS NOT NULL
|
||||||
GROUP BY m.variant ORDER BY m.variant`).all(projectId);
|
GROUP BY m.variant ORDER BY m.variant`).all(projectId);
|
||||||
|
|
|
||||||
441
src/routes.js
441
src/routes.js
|
|
@ -1,8 +1,15 @@
|
||||||
import { now, getSetting, setSetting } from './db.js';
|
import { now, getSetting, setSetting } from './db.js';
|
||||||
import { encrypt, encryptJson, decryptJson, verifyUnsubToken } from './crypto.js';
|
import { encrypt, encryptJson, decryptJson, verifyUnsubToken } from './crypto.js';
|
||||||
import { html, json, redirect, readBody, HttpError } from './http.js';
|
import { html, json, redirect, readBody, HttpError } from './http.js';
|
||||||
import { startGoogleLogin, finishGoogleLogin, destroySession } from './auth.js';
|
import { startLogin, finishLogin, destroySession, getSession } from './auth.js';
|
||||||
import { loginPage, dashboardPage, settingsPage, unsubPage } from './views.js';
|
import { deleteUser, normalizeEmail } from './users.js';
|
||||||
|
import {
|
||||||
|
assertCanRunAi, getLinkState, linkApiKey, linkSubscriptionToken, linkServer, unlink, testLink, lastConsent,
|
||||||
|
MODES,
|
||||||
|
} from './claudelink.js';
|
||||||
|
import { loginPage } from './site/pages.js';
|
||||||
|
import { registerSiteRoutes } from './site/routes.js';
|
||||||
|
import { dashboardPage, settingsPage, unsubPage, accountPage, linkPage } from './views.js';
|
||||||
import { enqueue, latestJobs, cancelJob, usageSummary } from './services/jobs.js';
|
import { enqueue, latestJobs, cancelJob, usageSummary } from './services/jobs.js';
|
||||||
import { validateGitUrl, removeRepo } from './services/git.js';
|
import { validateGitUrl, removeRepo } from './services/git.js';
|
||||||
import { fetchRecap, clearRecapCache, validateSelect } from './services/recap.js';
|
import { fetchRecap, clearRecapCache, validateSelect } from './services/recap.js';
|
||||||
|
|
@ -31,174 +38,277 @@ const pid = (params) => Number(params.id);
|
||||||
|
|
||||||
export function registerRoutes(router, app) {
|
export function registerRoutes(router, app) {
|
||||||
const { db, cfg } = app;
|
const { db, cfg } = app;
|
||||||
|
const cliModeEnabled = cfg.cliModeEnabled !== false;
|
||||||
|
const aiOpts = { cliModeEnabled };
|
||||||
|
|
||||||
|
// Toute ressource métier est lue AVEC l'utilisateur courant : celle d'un autre compte est « introuvable » (404)
|
||||||
|
const project = (ctx, opts) => getProject(app, pid(ctx.params), { userId: ctx.session.userId, ...opts });
|
||||||
|
|
||||||
// ---------- Public ----------
|
// ---------- Public ----------
|
||||||
router.get('/login', ({ res, url }) => html(res, loginPage(url.searchParams.get('e'))), { public: true });
|
registerSiteRoutes(router, app);
|
||||||
router.get('/auth/google', ({ res }) => startGoogleLogin(db, cfg, res), { public: true });
|
// Déjà connecté : la page de connexion n'a rien à offrir, on va au tableau de bord
|
||||||
router.get('/auth/google/callback', async ({ res, url }) => {
|
router.get('/login', async ({ req, res, url }) => {
|
||||||
try { await finishGoogleLogin(db, cfg, url, res); }
|
if (await getSession(db, req)) return redirect(res, '/');
|
||||||
catch (e) { redirect(res, `/login?e=${encodeURIComponent(e.message)}`); }
|
html(res, loginPage({ appUrl: cfg.appUrl, error: url.searchParams.get('e'), apple: !!cfg.apple, bye: url.searchParams.has('bye') }));
|
||||||
|
}, { public: true });
|
||||||
|
// Erreur de connexion : message du serveur s'il est destiné à l'utilisateur, sinon générique (rien de technique à l'écran)
|
||||||
|
const loginFailed = (res, e) => {
|
||||||
|
if (!e.status || e.status >= 500) console.error('[connexion]', e);
|
||||||
|
redirect(res, `/login?e=${encodeURIComponent(e.status && e.status < 500 ? e.message : 'Connexion impossible, réessaie dans un instant')}`);
|
||||||
|
};
|
||||||
|
router.get('/auth/google', async ({ res }) => startLogin(app, 'google', res), { public: true });
|
||||||
|
router.get('/auth/google/callback', async ({ req, res, url }) => {
|
||||||
|
try { await finishLogin(app, 'google', url.searchParams, req, res); }
|
||||||
|
catch (e) { loginFailed(res, e); }
|
||||||
|
}, { public: true });
|
||||||
|
// Apple : le retour est un POST cross-site (response_mode=form_post), donc public et sans contrôle d'origine ;
|
||||||
|
// la protection repose sur state + nonce + cookie de liaison (voir auth.js)
|
||||||
|
router.get('/auth/apple', async ({ res }) => startLogin(app, 'apple', res), { public: true });
|
||||||
|
router.post('/auth/apple/callback', async ({ req, res }) => {
|
||||||
|
try { await finishLogin(app, 'apple', await readBody(req), req, res); }
|
||||||
|
catch (e) { loginFailed(res, e); }
|
||||||
}, { public: true });
|
}, { public: true });
|
||||||
|
|
||||||
// Désinscription (RGPD). GET = page de confirmation (évite les désinscriptions par les scanners de liens),
|
// Désinscription (RGPD). GET = page de confirmation (évite les désinscriptions par les scanners de liens),
|
||||||
// POST = désinscription effective, compatible "one-click" (RFC 8058).
|
// POST = désinscription effective, compatible "one-click" (RFC 8058).
|
||||||
router.get('/u/:email/:token', ({ res, params }) => {
|
router.get('/u/:email/:token', async ({ res, params }) => {
|
||||||
const valid = verifyUnsubToken(cfg.secretKey, params.email, params.token);
|
const valid = verifyUnsubToken(cfg.secretKey, params.email, params.token);
|
||||||
html(res, unsubPage({ email: params.email, valid, done: false }), valid ? 200 : 400);
|
html(res, unsubPage({ email: params.email, valid, done: false }), valid ? 200 : 400);
|
||||||
}, { public: true });
|
}, { public: true });
|
||||||
router.post('/u/:email/:token', ({ res, params }) => {
|
router.post('/u/:email/:token', async ({ res, params }) => {
|
||||||
const email = params.email.toLowerCase();
|
const email = params.email.toLowerCase();
|
||||||
const valid = verifyUnsubToken(cfg.secretKey, email, params.token);
|
const valid = verifyUnsubToken(cfg.secretKey, email, params.token);
|
||||||
if (valid) {
|
if (valid) {
|
||||||
db.prepare("INSERT OR IGNORE INTO blacklist(email, reason, created_at) VALUES(?, 'unsubscribe', ?)").run(email, now());
|
await db.prepare("INSERT OR IGNORE INTO blacklist(email, reason, created_at) VALUES(?, 'unsubscribe', ?)").run(email, now());
|
||||||
db.prepare("UPDATE prospects SET status = 'refused' WHERE email = ? AND status IN ('new','sent')").run(email);
|
await db.prepare("UPDATE prospects SET status = 'refused' WHERE email = ? AND status IN ('new','sent')").run(email);
|
||||||
}
|
}
|
||||||
html(res, unsubPage({ email, valid, done: valid }), valid ? 200 : 400);
|
html(res, unsubPage({ email, valid, done: valid }), valid ? 200 : 400);
|
||||||
}, { public: true });
|
}, { public: true });
|
||||||
|
|
||||||
// ---------- Privé ----------
|
// ---------- Privé ----------
|
||||||
router.post('/logout', ({ req, res }) => { destroySession(db, req, res); redirect(res, '/login'); });
|
router.post('/logout', async ({ req, res }) => { await destroySession(db, req, res); redirect(res, '/login'); });
|
||||||
|
|
||||||
router.get('/', ({ res, session }) => {
|
router.get('/', async ({ res, session }) => {
|
||||||
const projects = listProjects(app).map((p) => {
|
const userId = session.userId;
|
||||||
const full = getProject(app, p.id, { secrets: true });
|
const projects = [];
|
||||||
return { project: p, smtp: publicConfig(full.smtp, 'pass'), dbCfg: publicConfig(full.dbCfg, 'password'), imap: publicConfig(full.imapCfg, 'pass') };
|
for (const p of await listProjects(app, userId)) {
|
||||||
});
|
const full = await getProject(app, p.id, { userId, secrets: true });
|
||||||
html(res, dashboardPage({ email: session.email, projects, forgejoHost: getSetting(db, 'forgejo_host') }));
|
projects.push({ project: p, smtp: publicConfig(full.smtp, 'pass'), dbCfg: publicConfig(full.dbCfg, 'password'), imap: publicConfig(full.imapCfg, 'pass') });
|
||||||
|
}
|
||||||
|
html(res, dashboardPage({
|
||||||
|
email: session.email, projects, forgejoHost: await getSetting(db, userId, 'forgejo_host'),
|
||||||
|
}));
|
||||||
});
|
});
|
||||||
|
|
||||||
router.get('/settings', ({ res, session, url }) => {
|
router.get('/settings', async ({ res, session, url }) => {
|
||||||
|
const userId = session.userId;
|
||||||
|
const discord = await notifyConfig(app, userId);
|
||||||
const s = {
|
const s = {
|
||||||
notify_email: getSetting(db, 'notify_email', ''),
|
notify_email: await getSetting(db, userId, 'notify_email', ''),
|
||||||
forgejo_host: getSetting(db, 'forgejo_host', ''),
|
forgejo_host: await getSetting(db, userId, 'forgejo_host', ''),
|
||||||
forgejo_token_set: !!getSetting(db, 'forgejo_token_enc'),
|
forgejo_token_set: !!await getSetting(db, userId, 'forgejo_token_enc'),
|
||||||
smtp: publicConfig(globalSmtp(app), 'pass'),
|
smtp: publicConfig(await globalSmtp(app, userId), 'pass'),
|
||||||
global_daily_cap: getSetting(db, 'global_daily_cap', '100'),
|
global_daily_cap: await getSetting(db, userId, 'global_daily_cap', '100'),
|
||||||
send_delay_min: getSetting(db, 'send_delay_min', '20'),
|
send_delay_min: await getSetting(db, userId, 'send_delay_min', '20'),
|
||||||
send_delay_max: getSetting(db, 'send_delay_max', '60'),
|
send_delay_max: await getSetting(db, userId, 'send_delay_max', '60'),
|
||||||
prospect_model: getSetting(db, 'prospect_model', 'haiku'),
|
prospect_model: await getSetting(db, userId, 'prospect_model', 'haiku'),
|
||||||
analyze_model: getSetting(db, 'analyze_model', 'haiku'),
|
analyze_model: await getSetting(db, userId, 'analyze_model', 'haiku'),
|
||||||
blacklist_count: db.prepare('SELECT COUNT(*) n FROM blacklist').get().n,
|
// La liste d'opposition est commune à tous les comptes : on n'en montre que ce qui touche SES prospects
|
||||||
weekly_report: getSetting(db, 'weekly_report', '0') === '1',
|
blacklist_count: (await db.prepare(`SELECT COUNT(DISTINCT x.email) n FROM prospects x JOIN projects p ON p.id = x.project_id
|
||||||
budget_day_usd: getSetting(db, 'budget_day_usd', ''),
|
WHERE p.user_id = ? AND x.email IN (SELECT email FROM blacklist)`).get(userId)).n,
|
||||||
budget_month_usd: getSetting(db, 'budget_month_usd', ''),
|
weekly_report: await getSetting(db, userId, 'weekly_report', '0') === '1',
|
||||||
discord: { set: !!notifyConfig(app).url, events: notifyConfig(app).events, all: EVENTS },
|
budget_day_usd: await getSetting(db, userId, 'budget_day_usd', ''),
|
||||||
|
budget_month_usd: await getSetting(db, userId, 'budget_month_usd', ''),
|
||||||
|
discord: { set: !!discord.url, events: discord.events, all: EVENTS },
|
||||||
};
|
};
|
||||||
html(res, settingsPage({ email: session.email, s, saved: url.searchParams.has('ok') }));
|
html(res, settingsPage({ email: session.email, s, saved: url.searchParams.has('ok') }));
|
||||||
});
|
});
|
||||||
|
|
||||||
router.post('/settings', async ({ req, res }) => {
|
router.post('/settings', async ({ req, res, session }) => {
|
||||||
|
const userId = session.userId;
|
||||||
|
const set = (k, v) => setSetting(db, userId, k, v);
|
||||||
const b = await readBody(req);
|
const b = await readBody(req);
|
||||||
if (b.notify_email && !EMAIL_RE.test(b.notify_email)) throw new HttpError(400, 'Email de réception invalide');
|
if (b.notify_email && !EMAIL_RE.test(b.notify_email)) throw new HttpError(400, 'Email de réception invalide');
|
||||||
setSetting(db, 'notify_email', (b.notify_email || '').trim());
|
await set('notify_email', (b.notify_email || '').trim());
|
||||||
setSetting(db, 'forgejo_host', (b.forgejo_host || '').trim().replace(/^https?:\/\//, '').replace(/\/.*$/, ''));
|
await set('forgejo_host', (b.forgejo_host || '').trim().replace(/^https?:\/\//, '').replace(/\/.*$/, ''));
|
||||||
if (b.forgejo_token) setSetting(db, 'forgejo_token_enc', encrypt(cfg.secretKey, b.forgejo_token.trim()));
|
if (b.forgejo_token) await set('forgejo_token_enc', encrypt(cfg.secretKey, b.forgejo_token.trim()));
|
||||||
const cap = int(b.global_daily_cap, 1, 300, 100);
|
const cap = int(b.global_daily_cap, 1, 300, 100);
|
||||||
const dmin = int(b.send_delay_min, 5, 3600, 20);
|
const dmin = int(b.send_delay_min, 5, 3600, 20);
|
||||||
const dmax = Math.max(dmin, int(b.send_delay_max, 5, 3600, 60));
|
const dmax = Math.max(dmin, int(b.send_delay_max, 5, 3600, 60));
|
||||||
setSetting(db, 'global_daily_cap', String(cap));
|
await set('global_daily_cap', String(cap));
|
||||||
setSetting(db, 'send_delay_min', String(dmin));
|
await set('send_delay_min', String(dmin));
|
||||||
setSetting(db, 'send_delay_max', String(dmax));
|
await set('send_delay_max', String(dmax));
|
||||||
setSetting(db, 'prospect_model', b.prospect_model === 'sonnet' ? 'sonnet' : 'haiku');
|
await set('prospect_model', b.prospect_model === 'sonnet' ? 'sonnet' : 'haiku');
|
||||||
setSetting(db, 'analyze_model', b.analyze_model === 'sonnet' ? 'sonnet' : 'haiku');
|
await set('analyze_model', b.analyze_model === 'sonnet' ? 'sonnet' : 'haiku');
|
||||||
const money = (v) => { const n = Number(String(v || '').replace(',', '.')); return Number.isFinite(n) && n > 0 ? String(Math.round(n * 100) / 100) : ''; };
|
const money = (v) => { const n = Number(String(v || '').replace(',', '.')); return Number.isFinite(n) && n > 0 ? String(Math.round(n * 100) / 100) : ''; };
|
||||||
setSetting(db, 'weekly_report', b.weekly_report === 'on' ? '1' : '0');
|
await set('weekly_report', b.weekly_report === 'on' ? '1' : '0');
|
||||||
setSetting(db, 'budget_day_usd', money(b.budget_day_usd));
|
await set('budget_day_usd', money(b.budget_day_usd));
|
||||||
setSetting(db, 'budget_month_usd', money(b.budget_month_usd));
|
await set('budget_month_usd', money(b.budget_month_usd));
|
||||||
|
|
||||||
const hook = String(b.discord_webhook || '').trim();
|
const hook = String(b.discord_webhook || '').trim();
|
||||||
if (hook && !WEBHOOK_RE.test(hook)) throw new HttpError(400, 'URL de webhook Discord invalide (https://discord.com/api/webhooks/…)');
|
if (hook && !WEBHOOK_RE.test(hook)) throw new HttpError(400, 'URL de webhook Discord invalide (https://discord.com/api/webhooks/…)');
|
||||||
if (hook) setSetting(db, 'discord_webhook_enc', encrypt(cfg.secretKey, hook));
|
if (hook) await set('discord_webhook_enc', encrypt(cfg.secretKey, hook));
|
||||||
if (b.discord_remove === 'on') setSetting(db, 'discord_webhook_enc', null);
|
if (b.discord_remove === 'on') await set('discord_webhook_enc', null);
|
||||||
setSetting(db, 'discord_events', JSON.stringify(Object.keys(EVENTS).filter((k) => b[`ev_${k}`] === 'on')));
|
await set('discord_events', JSON.stringify(Object.keys(EVENTS).filter((k) => b[`ev_${k}`] === 'on')));
|
||||||
|
|
||||||
const prev = globalSmtp(app) || {};
|
const prev = await globalSmtp(app, userId) || {};
|
||||||
const smtp = { host: b.smtp_host, port: b.smtp_port, user: b.smtp_user, pass: b.smtp_pass || prev.pass, fromEmail: b.smtp_fromEmail };
|
const smtp = { host: b.smtp_host, port: b.smtp_port, user: b.smtp_user, pass: b.smtp_pass || prev.pass, fromEmail: b.smtp_fromEmail };
|
||||||
setSetting(db, 'smtp_enc', smtp.host ? encryptJson(cfg.secretKey, smtp) : null);
|
await set('smtp_enc', smtp.host ? encryptJson(cfg.secretKey, smtp) : null);
|
||||||
redirect(res, '/settings?ok');
|
redirect(res, '/settings?ok');
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// ---------- Liaison Claude ----------
|
||||||
|
// Page d'onboarding (bloquante tant qu'aucune liaison valide n'existe). Les secrets arrivent par POST, ne sont jamais
|
||||||
|
// relus ni réaffichés ; les erreurs ne contiennent que des messages fixes.
|
||||||
|
router.get('/link', async ({ res, session, url }) => {
|
||||||
|
html(res, linkPage({
|
||||||
|
user: session.user, link: await getLinkState(db, session.userId), cliModeEnabled, error: url.searchParams.get('e'),
|
||||||
|
}));
|
||||||
|
});
|
||||||
|
|
||||||
|
const wantsJson = (req) => !!req.headers.accept?.includes('json');
|
||||||
|
// Formulaire HTML : l'erreur revient sur la page de liaison ; appel JSON : code HTTP + { error }
|
||||||
|
const linkAction = (fn, okTo = '/') => async ({ req, res, session }) => {
|
||||||
|
const b = await readBody(req);
|
||||||
|
try {
|
||||||
|
const out = (await fn(b, session)) || {};
|
||||||
|
if (wantsJson(req)) return json(res, { ok: true, ...out });
|
||||||
|
redirect(res, okTo);
|
||||||
|
} catch (e) {
|
||||||
|
if (!(e instanceof HttpError) || wantsJson(req)) throw e;
|
||||||
|
redirect(res, `/link?e=${encodeURIComponent(e.message)}`);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
router.post('/link/api-key', linkAction((b, s) => linkApiKey(app, s.userId, b.apiKey)));
|
||||||
|
router.post('/link/subscription', linkAction((b, s) => linkSubscriptionToken(app, s.userId, { token: b.token, accept: b.accept })));
|
||||||
|
router.post('/link/server', linkAction((b, s) => linkServer(app, s.userId)));
|
||||||
|
router.post('/link/test', async ({ req, res, session }) => {
|
||||||
|
const r = await testLink(app, session.userId);
|
||||||
|
if (wantsJson(req)) return json(res, r);
|
||||||
|
redirect(res, `/account?t=${r.ok ? 'ok' : 'ko'}&m=${encodeURIComponent(r.message)}`);
|
||||||
|
});
|
||||||
|
router.post('/link/unlink', async ({ req, res, session }) => {
|
||||||
|
const cancelled = await unlink(app, session.userId);
|
||||||
|
if (wantsJson(req)) return json(res, { ok: true, cancelled });
|
||||||
|
redirect(res, '/account?t=unlinked');
|
||||||
|
});
|
||||||
|
|
||||||
|
// ---------- Mon compte ----------
|
||||||
|
router.get('/account', async ({ res, session, url }) => {
|
||||||
|
const t = url.searchParams.get('t');
|
||||||
|
html(res, accountPage({
|
||||||
|
user: session.user, error: url.searchParams.get('e'), link: await getLinkState(db, session.userId),
|
||||||
|
consent: await lastConsent(db, session.userId), cliModeEnabled,
|
||||||
|
notice: t === 'unlinked' ? { ok: true, text: 'Liaison supprimée : le secret a été effacé et tes jobs IA en attente ont été annulés.' }
|
||||||
|
: t === 'ok' || t === 'ko' ? { ok: t === 'ok', text: String(url.searchParams.get('m') || '').slice(0, 300) } : null,
|
||||||
|
}));
|
||||||
|
});
|
||||||
|
|
||||||
|
// Suppression du compte : confirmée en saisissant son email ; efface TOUTES les données de l'utilisateur
|
||||||
|
router.post('/account/delete', async ({ req, res, session }) => {
|
||||||
|
const b = await readBody(req);
|
||||||
|
if (normalizeEmail(b.confirm) !== normalizeEmail(session.user.email)) {
|
||||||
|
return redirect(res, `/account?e=${encodeURIComponent("L'email saisi ne correspond pas à celui du compte")}`);
|
||||||
|
}
|
||||||
|
app.worker?.abortUser(session.userId); // un job en cours pour ce compte s'arrête avant l'effacement
|
||||||
|
await deleteUser(app, session.userId);
|
||||||
|
await destroySession(db, req, res);
|
||||||
|
redirect(res, '/login?bye=1');
|
||||||
|
});
|
||||||
|
|
||||||
// ---------- API JSON ----------
|
// ---------- API JSON ----------
|
||||||
router.post('/api/report/send', async ({ res }) => {
|
router.post('/api/report/send', async ({ res, session }) => {
|
||||||
const r = await sendWeeklyReport(app);
|
const r = await sendWeeklyReport(app, session.userId);
|
||||||
if (!r.channels.length) throw new HttpError(400, 'Configure le SMTP global + l\'email de réception, ou un webhook Discord');
|
if (!r.channels.length) throw new HttpError(400, 'Configure le SMTP global + l\'email de réception, ou un webhook Discord');
|
||||||
json(res, { ok: true, channels: r.channels });
|
json(res, { ok: true, channels: r.channels });
|
||||||
});
|
});
|
||||||
|
|
||||||
router.post('/api/notify/test', async ({ res }) => {
|
router.post('/api/notify/test', async ({ res, session }) => {
|
||||||
if (!notifyConfig(app).url) throw new HttpError(400, 'Aucun webhook Discord configuré');
|
if (!(await notifyConfig(app, session.userId)).url) throw new HttpError(400, 'Aucun webhook Discord configuré');
|
||||||
const ok = await notify(app, 'test', { title: 'Notification de test', description: 'Les notifications AiTools arrivent bien ici.', level: 'ok' }, { force: true });
|
const ok = await notify(app, session.userId, 'test', { title: 'Notification de test', description: 'Les notifications AiTools arrivent bien ici.', level: 'ok' }, { force: true });
|
||||||
if (!ok) throw new HttpError(502, 'Discord a refusé la notification (webhook supprimé ?)');
|
if (!ok) throw new HttpError(502, 'Discord a refusé la notification (webhook supprimé ?)');
|
||||||
json(res, { ok: true });
|
json(res, { ok: true });
|
||||||
});
|
});
|
||||||
|
|
||||||
router.get('/api/system', ({ res }) => {
|
// Barre du haut : uniquement les jobs, l'usage et les quotas de l'utilisateur courant (la température du serveur, réservée aux admins)
|
||||||
const queue = db.prepare(`SELECT COUNT(*) n FROM jobs WHERE status = 'running'
|
router.get('/api/system', async ({ res, session }) => {
|
||||||
OR (status = 'queued' AND (run_after IS NULL OR run_after <= ?))`).get(now()).n;
|
const userId = session.userId;
|
||||||
const scheduled = db.prepare("SELECT COUNT(*) n FROM jobs WHERE status = 'queued' AND run_after > ?").get(now()).n;
|
const queue = (await db.prepare(`SELECT COUNT(*) n FROM jobs WHERE user_id = ? AND (status = 'running'
|
||||||
const rlRaw = getSetting(db, 'claude_rate_limit_json');
|
OR (status = 'queued' AND (run_after IS NULL OR run_after <= ?)))`).get(userId, now())).n;
|
||||||
|
const scheduled = (await db.prepare("SELECT COUNT(*) n FROM jobs WHERE user_id = ? AND status = 'queued' AND run_after > ?").get(userId, now())).n;
|
||||||
|
const link = await getLinkState(db, userId);
|
||||||
|
// Le quota d'abonnement n'existe qu'en mode abonnement ou serveur : jamais de barre en mode clé API
|
||||||
|
const rlRaw = link?.mode === MODES.api_key ? null : await getSetting(db, userId, 'claude_rate_limit_json');
|
||||||
// Détail pour le menu « jobs » de la barre du haut : en cours d'abord, puis la file, puis les programmés
|
// Détail pour le menu « jobs » de la barre du haut : en cours d'abord, puis la file, puis les programmés
|
||||||
const jobs = db.prepare(`SELECT j.id, j.type, j.status, j.progress_json, j.run_after, j.started_at, j.created_at, p.id pid, p.name project
|
const jobs = (await db.prepare(`SELECT j.id, j.type, j.status, j.progress_json, j.run_after, j.started_at, j.created_at, p.id pid, p.name project
|
||||||
FROM jobs j LEFT JOIN projects p ON p.id = j.project_id
|
FROM jobs j LEFT JOIN projects p ON p.id = j.project_id
|
||||||
WHERE j.status IN ('queued','running')
|
WHERE j.user_id = ? AND j.status IN ('queued','running')
|
||||||
ORDER BY j.status = 'running' DESC, COALESCE(j.run_after, 0), j.id LIMIT 20`).all().map((r) => ({
|
ORDER BY j.status = 'running' DESC, COALESCE(j.run_after, 0), j.id LIMIT 20`).all(userId)).map((r) => ({
|
||||||
id: r.id, type: r.type, status: r.status, projectId: r.pid, project: r.project,
|
id: r.id, type: r.type, status: r.status, projectId: r.pid, project: r.project,
|
||||||
progress: r.progress_json ? JSON.parse(r.progress_json) : null,
|
progress: r.progress_json ? JSON.parse(r.progress_json) : null,
|
||||||
runAfter: r.run_after, startedAt: r.started_at, createdAt: r.created_at,
|
runAfter: r.run_after, startedAt: r.started_at, createdAt: r.created_at,
|
||||||
}));
|
}));
|
||||||
json(res, {
|
json(res, {
|
||||||
temp: cpuTemp(), queue, scheduled, jobs, usage: usageSummary(db), budget: budgetState(db), thermalMax: cfg.thermalMax,
|
temp: session.user.isAdmin ? cpuTemp() : null, queue, scheduled, jobs, usage: await usageSummary(db, userId), budget: await budgetState(db, userId), thermalMax: cfg.thermalMax,
|
||||||
claudeRateLimit: rlRaw ? JSON.parse(rlRaw) : null,
|
claudeRateLimit: rlRaw ? JSON.parse(rlRaw) : null, linkMode: link?.mode ?? null,
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
router.post('/api/projects', async ({ req, res }) => {
|
router.post('/api/projects', async ({ req, res, session }) => {
|
||||||
|
const userId = session.userId;
|
||||||
const b = await readBody(req);
|
const b = await readBody(req);
|
||||||
const name = String(b.name || '').trim().slice(0, 80);
|
const name = String(b.name || '').trim().slice(0, 80);
|
||||||
if (!name) throw new HttpError(400, 'Nom requis');
|
if (!name) throw new HttpError(400, 'Nom requis');
|
||||||
const host = getSetting(db, 'forgejo_host');
|
const host = await getSetting(db, userId, 'forgejo_host');
|
||||||
if (!host) throw new HttpError(400, "Configure l'hôte Forgejo dans Réglages");
|
if (!host) throw new HttpError(400, "Configure l'hôte Forgejo dans Réglages");
|
||||||
let gitUrl;
|
let gitUrl;
|
||||||
try { gitUrl = validateGitUrl(String(b.gitUrl || '').trim(), host); }
|
try { gitUrl = validateGitUrl(String(b.gitUrl || '').trim(), host); }
|
||||||
catch (e) { throw new HttpError(400, e.message); }
|
catch (e) { throw new HttpError(400, e.message); }
|
||||||
if (db.prepare('SELECT 1 FROM projects WHERE git_url = ?').get(gitUrl)) throw new HttpError(409, 'Ce dépôt est déjà un projet');
|
// Un même dépôt peut être un projet pour deux comptes différents : l'unicité est par utilisateur
|
||||||
const id = createProject(app, { name, gitUrl });
|
const exists = () => db.prepare('SELECT 1 FROM projects WHERE user_id = ? AND git_url = ?').get(userId, gitUrl);
|
||||||
enqueue(db, { projectId: id, type: 'analyze' });
|
if (await exists()) throw new HttpError(409, 'Ce dépôt est déjà un projet');
|
||||||
|
let id;
|
||||||
|
try { id = await createProject(app, { userId, name, gitUrl }); }
|
||||||
|
catch (e) { if (await exists()) throw new HttpError(409, 'Ce dépôt est déjà un projet'); throw e; }
|
||||||
|
await enqueue(db, { userId, projectId: id, type: 'analyze' }, aiOpts);
|
||||||
json(res, { id });
|
json(res, { id });
|
||||||
});
|
});
|
||||||
|
|
||||||
router.post('/api/projects/:id/delete', ({ res, params }) => {
|
router.post('/api/projects/:id/delete', async (ctx) => {
|
||||||
const p = getProject(app, pid(params));
|
const p = await project(ctx);
|
||||||
db.prepare('DELETE FROM projects WHERE id = ?').run(p.id);
|
await db.prepare('DELETE FROM projects WHERE id = ? AND user_id = ?').run(p.id, ctx.session.userId);
|
||||||
removeRepo(repoDir(cfg, p.id));
|
removeRepo(repoDir(cfg, ctx.session.userId, p.id));
|
||||||
clearRecapCache(p.id);
|
clearRecapCache(p.id);
|
||||||
json(res, { ok: true });
|
json(ctx.res, { ok: true });
|
||||||
});
|
});
|
||||||
|
|
||||||
router.get('/api/projects/:id/status', ({ res, params }) => {
|
router.get('/api/projects/:id/status', async (ctx) => {
|
||||||
const p = getProject(app, pid(params));
|
const { res, session } = ctx;
|
||||||
const jobs = latestJobs(db, p.id);
|
const userId = session.userId;
|
||||||
|
const p = await project(ctx);
|
||||||
|
const jobs = await latestJobs(db, p.id);
|
||||||
// Rendu côté serveur (échappé) : le front n'injecte jamais le Markdown brut de Claude
|
// Rendu côté serveur (échappé) : le front n'injecte jamais le Markdown brut de Claude
|
||||||
if (jobs.evolution?.result?.markdown) jobs.evolution.result.html = evolutionHtml(jobs.evolution.result.markdown);
|
if (jobs.evolution?.result?.markdown) jobs.evolution.result.html = evolutionHtml(jobs.evolution.result.markdown);
|
||||||
const tplOut = (row) => (row ? { subject: row.subject, subjectB: row.subject_b, body: row.body, status: row.status, updated_at: row.updated_at } : null);
|
const tplOut = (row) => (row ? { subject: row.subject, subjectB: row.subject_b, body: row.body, status: row.status, updated_at: row.updated_at } : null);
|
||||||
const templates = { initial: tplOut(getTemplate(db, p.id, 'initial')), followup: tplOut(getTemplate(db, p.id, 'followup')) };
|
const templates = { initial: tplOut(await getTemplate(db, p.id, 'initial')), followup: tplOut(await getTemplate(db, p.id, 'followup')) };
|
||||||
const stats = prospectStats(db, p.id);
|
const stats = await prospectStats(db, p.id);
|
||||||
const day = now() - 86400;
|
const day = now() - 86400;
|
||||||
const sendMax = allowedToSend({
|
const sendMax = allowedToSend({
|
||||||
requested: 100, available: stats.new || 0,
|
requested: 100, available: stats.new || 0,
|
||||||
projectCap: p.dailyMailCap, sentTodayProject: sentSince(db, day, p.id),
|
projectCap: p.dailyMailCap, sentTodayProject: await sentSince(db, day, userId, p.id),
|
||||||
globalCap: Number(getSetting(db, 'global_daily_cap', '100')), sentTodayGlobal: sentSince(db, day),
|
globalCap: Number(await getSetting(db, userId, 'global_daily_cap', '100')), sentTodayGlobal: await sentSince(db, day, userId),
|
||||||
});
|
});
|
||||||
json(res, {
|
json(res, {
|
||||||
jobs, templates, stats, sendMax,
|
jobs, templates, stats, sendMax,
|
||||||
followup: { enabled: p.followupEnabled, days: p.followupDays, ...followupPlan(db, p) },
|
followup: { enabled: p.followupEnabled, days: p.followupDays, ...(await followupPlan(db, p)) },
|
||||||
targetValidated: p.targetValidated, hasProfile: !!p.profile, hasSmtp: p.hasSmtp,
|
targetValidated: p.targetValidated, hasProfile: !!p.profile, hasSmtp: p.hasSmtp,
|
||||||
hasImap: p.hasImap, inbox: p.inbox, ab: abStats(db, p.id),
|
hasImap: p.hasImap, inbox: p.inbox, ab: await abStats(db, p.id),
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
router.post('/api/projects/:id/target', async ({ req, res, params }) => {
|
router.post('/api/projects/:id/target', async (ctx) => {
|
||||||
const p = getProject(app, pid(params));
|
const { req, res } = ctx;
|
||||||
|
const p = await project(ctx);
|
||||||
const b = await readBody(req);
|
const b = await readBody(req);
|
||||||
const target = {
|
const target = {
|
||||||
description: String(b.description || '').slice(0, 300),
|
description: String(b.description || '').slice(0, 300),
|
||||||
|
|
@ -209,18 +319,21 @@ export function registerRoutes(router, app) {
|
||||||
requetes: lines(b.requetes),
|
requetes: lines(b.requetes),
|
||||||
};
|
};
|
||||||
if (!target.description || !target.secteurs.length) throw new HttpError(400, 'Description et au moins un secteur requis');
|
if (!target.description || !target.secteurs.length) throw new HttpError(400, 'Description et au moins un secteur requis');
|
||||||
db.prepare('UPDATE projects SET target_json = ?, target_validated = 1 WHERE id = ?').run(JSON.stringify(target), p.id);
|
await db.prepare('UPDATE projects SET target_json = ?, target_validated = 1 WHERE id = ?').run(JSON.stringify(target), p.id);
|
||||||
json(res, { ok: true });
|
json(res, { ok: true });
|
||||||
});
|
});
|
||||||
|
|
||||||
const jobRoute = (type, paramsOf = () => ({}), guard = () => {}) => async ({ req, res, params }) => {
|
const jobRoute = (type, paramsOf = () => ({}), guard = () => {}) => async (ctx) => {
|
||||||
const p = getProject(app, pid(params));
|
const { req, res, session } = ctx;
|
||||||
|
// Refus côté serveur AVANT toute autre vérification : pas de job IA sans liaison Claude valide (enqueue le revérifie)
|
||||||
|
if (AI_JOBS.has(type)) await assertCanRunAi(db, session.userId, aiOpts);
|
||||||
|
const p = await project(ctx);
|
||||||
const b = req.headers['content-type']?.includes('json') ? await readBody(req) : {};
|
const b = req.headers['content-type']?.includes('json') ? await readBody(req) : {};
|
||||||
guard(p, b);
|
await guard(p, b);
|
||||||
// "Cette nuit" : démarrage au prochain créneau 1h-6h (Pi au frais, quota Claude libre)
|
// "Cette nuit" : démarrage au prochain créneau 1h-6h (Pi au frais, quota Claude libre)
|
||||||
const runAfter = b.when === 'night' ? Math.floor(nextNightSlot().getTime() / 1000) : null;
|
const runAfter = b.when === 'night' ? Math.floor(nextNightSlot().getTime() / 1000) : null;
|
||||||
const r = enqueue(db, { projectId: p.id, type, params: paramsOf(b), runAfter });
|
const r = await enqueue(db, { userId: session.userId, projectId: p.id, type, params: paramsOf(b), runAfter }, aiOpts);
|
||||||
const budget = AI_JOBS.has(type) ? budgetState(db) : null;
|
const budget = AI_JOBS.has(type) ? await budgetState(db, session.userId) : null;
|
||||||
json(res, { ...r, budgetBlocked: budget?.blocked ? budget.reason : null });
|
json(res, { ...r, budgetBlocked: budget?.blocked ? budget.reason : null });
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
@ -231,11 +344,12 @@ export function registerRoutes(router, app) {
|
||||||
router.post('/api/projects/:id/followup_template', jobRoute('followup_template', () => ({}), (p) => {
|
router.post('/api/projects/:id/followup_template', jobRoute('followup_template', () => ({}), (p) => {
|
||||||
if (!p.profile) throw new HttpError(400, "Analyse le projet d'abord");
|
if (!p.profile) throw new HttpError(400, "Analyse le projet d'abord");
|
||||||
}));
|
}));
|
||||||
router.post('/api/projects/:id/followup', async ({ req, res, params }) => {
|
router.post('/api/projects/:id/followup', async (ctx) => {
|
||||||
const p = getProject(app, pid(params));
|
const { req, res } = ctx;
|
||||||
|
const p = await project(ctx);
|
||||||
const b = await readBody(req);
|
const b = await readBody(req);
|
||||||
const enabled = b.enabled === true || b.enabled === 'on';
|
const enabled = b.enabled === true || b.enabled === 'on';
|
||||||
db.prepare('UPDATE projects SET followup_enabled = ?, followup_days = ? WHERE id = ?').run(enabled ? 1 : 0, int(b.days, 2, 30, 7), p.id);
|
await db.prepare('UPDATE projects SET followup_enabled = ?, followup_days = ? WHERE id = ?').run(enabled ? 1 : 0, int(b.days, 2, 30, 7), p.id);
|
||||||
json(res, { ok: true });
|
json(res, { ok: true });
|
||||||
});
|
});
|
||||||
router.post('/api/projects/:id/prospect', jobRoute('prospect', (b) => ({ count: int(b.count, 1, 50, 10) }), (p) => {
|
router.post('/api/projects/:id/prospect', jobRoute('prospect', (b) => ({ count: int(b.count, 1, 50, 10) }), (p) => {
|
||||||
|
|
@ -245,14 +359,15 @@ export function registerRoutes(router, app) {
|
||||||
count: int(b.count, 1, 20, 5),
|
count: int(b.count, 1, 20, 5),
|
||||||
level: ['rapide', 'normal', 'approfondi'].includes(b.level) ? b.level : 'rapide',
|
level: ['rapide', 'normal', 'approfondi'].includes(b.level) ? b.level : 'rapide',
|
||||||
})));
|
})));
|
||||||
router.post('/api/projects/:id/send', jobRoute('send', (b) => ({ count: int(b.count, 1, 100, 10) }), (p, b) => {
|
router.post('/api/projects/:id/send', jobRoute('send', (b) => ({ count: int(b.count, 1, 100, 10) }), async (p, b) => {
|
||||||
if (!b.confirm) throw new HttpError(400, 'Confirmation requise');
|
if (!b.confirm) throw new HttpError(400, 'Confirmation requise');
|
||||||
const running = db.prepare("SELECT 1 FROM jobs WHERE project_id = ? AND type = 'prospect' AND status IN ('queued','running')").get(p.id);
|
const running = await db.prepare("SELECT 1 FROM jobs WHERE project_id = ? AND type = 'prospect' AND status IN ('queued','running')").get(p.id);
|
||||||
if (running) throw new HttpError(409, 'La recherche de prospects est encore en cours');
|
if (running) throw new HttpError(409, 'La recherche de prospects est encore en cours');
|
||||||
}));
|
}));
|
||||||
|
|
||||||
router.post('/api/projects/:id/template/save', async ({ req, res, params }) => {
|
router.post('/api/projects/:id/template/save', async (ctx) => {
|
||||||
const p = getProject(app, pid(params));
|
const { req, res } = ctx;
|
||||||
|
const p = await project(ctx);
|
||||||
const b = await readBody(req);
|
const b = await readBody(req);
|
||||||
const subject = String(b.subject || '').trim().slice(0, 200);
|
const subject = String(b.subject || '').trim().slice(0, 200);
|
||||||
const body = String(b.body || '').trim().slice(0, 5000);
|
const body = String(b.body || '').trim().slice(0, 5000);
|
||||||
|
|
@ -261,51 +376,55 @@ export function registerRoutes(router, app) {
|
||||||
// Relance : objet facultatif (vide = "Re: <objet du 1er mail>", même fil de discussion)
|
// Relance : objet facultatif (vide = "Re: <objet du 1er mail>", même fil de discussion)
|
||||||
if (!body || (kind === 'initial' && !subject)) throw new HttpError(400, kind === 'initial' ? 'Objet et corps requis' : 'Corps requis');
|
if (!body || (kind === 'initial' && !subject)) throw new HttpError(400, kind === 'initial' ? 'Objet et corps requis' : 'Corps requis');
|
||||||
const status = b.mode === 'validate' ? 'validated' : 'draft';
|
const status = b.mode === 'validate' ? 'validated' : 'draft';
|
||||||
saveTemplate(db, p.id, kind, { subject, subjectB, body, status });
|
await saveTemplate(db, p.id, kind, { subject, subjectB, body, status });
|
||||||
json(res, { ok: true, status });
|
json(res, { ok: true, status });
|
||||||
});
|
});
|
||||||
|
|
||||||
router.post('/api/projects/:id/smtp', async ({ req, res, params }) => {
|
router.post('/api/projects/:id/smtp', async (ctx) => {
|
||||||
const p = getProject(app, pid(params));
|
const { req, res } = ctx;
|
||||||
|
const p = await project(ctx);
|
||||||
const b = await readBody(req);
|
const b = await readBody(req);
|
||||||
if (b.fromEmail && !EMAIL_RE.test(b.fromEmail)) throw new HttpError(400, 'Email expéditeur invalide');
|
if (b.fromEmail && !EMAIL_RE.test(b.fromEmail)) throw new HttpError(400, 'Email expéditeur invalide');
|
||||||
saveSecretConfig(app, p.id, 'smtp_enc', {
|
await saveSecretConfig(app, p.id, 'smtp_enc', {
|
||||||
host: String(b.host || '').trim(), port: int(b.port, 1, 65535, 587), user: String(b.user || '').trim(),
|
host: String(b.host || '').trim(), port: int(b.port, 1, 65535, 587), user: String(b.user || '').trim(),
|
||||||
pass: b.pass || '', fromEmail: String(b.fromEmail || '').trim(), fromName: String(b.fromName || '').trim().slice(0, 80),
|
pass: b.pass || '', fromEmail: String(b.fromEmail || '').trim(), fromName: String(b.fromName || '').trim().slice(0, 80),
|
||||||
}, 'pass');
|
}, 'pass');
|
||||||
db.prepare('UPDATE projects SET daily_mail_cap = ? WHERE id = ?').run(int(b.dailyCap, 1, 200, 30), p.id);
|
await db.prepare('UPDATE projects SET daily_mail_cap = ? WHERE id = ?').run(int(b.dailyCap, 1, 200, 30), p.id);
|
||||||
json(res, { ok: true });
|
json(res, { ok: true });
|
||||||
});
|
});
|
||||||
|
|
||||||
// Boîte de réception : on enregistre puis on teste tout de suite la connexion
|
// Boîte de réception : on enregistre puis on teste tout de suite la connexion
|
||||||
router.post('/api/projects/:id/imap', async ({ req, res, params }) => {
|
router.post('/api/projects/:id/imap', async (ctx) => {
|
||||||
const p = getProject(app, pid(params));
|
const { req, res, session } = ctx;
|
||||||
|
const p = await project(ctx);
|
||||||
const b = await readBody(req);
|
const b = await readBody(req);
|
||||||
const host = String(b.host || '').trim();
|
const host = String(b.host || '').trim();
|
||||||
if (!host) {
|
if (!host) {
|
||||||
db.prepare('UPDATE projects SET imap_enc = NULL, inbox_json = NULL WHERE id = ?').run(p.id);
|
await db.prepare('UPDATE projects SET imap_enc = NULL, inbox_json = NULL WHERE id = ?').run(p.id);
|
||||||
return json(res, { ok: true, disabled: true });
|
return json(res, { ok: true, disabled: true });
|
||||||
}
|
}
|
||||||
saveSecretConfig(app, p.id, 'imap_enc', {
|
await saveSecretConfig(app, p.id, 'imap_enc', {
|
||||||
host, port: int(b.port, 1, 65535, 993), user: String(b.user || '').trim(), pass: b.pass || '',
|
host, port: int(b.port, 1, 65535, 993), user: String(b.user || '').trim(), pass: b.pass || '',
|
||||||
}, 'pass');
|
}, 'pass');
|
||||||
try { json(res, { ok: true, check: await checkInbox(app, p.id) }); }
|
try { json(res, { ok: true, check: await checkInbox(app, session.userId, p.id) }); }
|
||||||
catch (e) { json(res, { ok: false, error: e.message }); }
|
catch (e) { json(res, { ok: false, error: e.message }); }
|
||||||
});
|
});
|
||||||
|
|
||||||
router.post('/api/projects/:id/inbox/check', async ({ res, params }) => {
|
router.post('/api/projects/:id/inbox/check', async (ctx) => {
|
||||||
const p = getProject(app, pid(params));
|
const { res, session } = ctx;
|
||||||
try { json(res, { ok: true, check: await checkInbox(app, p.id) }); }
|
const p = await project(ctx);
|
||||||
|
try { json(res, { ok: true, check: await checkInbox(app, session.userId, p.id) }); }
|
||||||
catch (e) { throw new HttpError(502, e.message); }
|
catch (e) { throw new HttpError(502, e.message); }
|
||||||
});
|
});
|
||||||
|
|
||||||
router.post('/api/projects/:id/db', async ({ req, res, params }) => {
|
router.post('/api/projects/:id/db', async (ctx) => {
|
||||||
const p = getProject(app, pid(params));
|
const { req, res } = ctx;
|
||||||
|
const p = await project(ctx);
|
||||||
const b = await readBody(req);
|
const b = await readBody(req);
|
||||||
for (const k of ['sql_users', 'sql_clients', 'sql_revenue']) {
|
for (const k of ['sql_users', 'sql_clients', 'sql_revenue']) {
|
||||||
try { validateSelect(b[k]); } catch (e) { throw new HttpError(400, `${k} : ${e.message}`); }
|
try { validateSelect(b[k]); } catch (e) { throw new HttpError(400, `${k} : ${e.message}`); }
|
||||||
}
|
}
|
||||||
saveSecretConfig(app, p.id, 'db_enc', {
|
await saveSecretConfig(app, p.id, 'db_enc', {
|
||||||
type: b.type === 'pg' ? 'pg' : 'mysql', host: String(b.host || '').trim(), port: b.port ? int(b.port, 1, 65535, null) : null,
|
type: b.type === 'pg' ? 'pg' : 'mysql', host: String(b.host || '').trim(), port: b.port ? int(b.port, 1, 65535, null) : null,
|
||||||
database: String(b.database || '').trim(), user: String(b.user || '').trim(), password: b.password || '',
|
database: String(b.database || '').trim(), user: String(b.user || '').trim(), password: b.password || '',
|
||||||
ssl: b.ssl === 'on' || b.ssl === true,
|
ssl: b.ssl === 'on' || b.ssl === true,
|
||||||
|
|
@ -315,20 +434,22 @@ export function registerRoutes(router, app) {
|
||||||
json(res, { ok: true });
|
json(res, { ok: true });
|
||||||
});
|
});
|
||||||
|
|
||||||
router.get('/api/projects/:id/recap', async ({ res, params, url }) => {
|
router.get('/api/projects/:id/recap', async (ctx) => {
|
||||||
const p = getProject(app, pid(params), { secrets: true });
|
const { res, url } = ctx;
|
||||||
const stats = prospectStats(db, p.id);
|
const p = await project(ctx, { secrets: true });
|
||||||
const cost = db.prepare('SELECT COALESCE(SUM(cost_usd),0) c FROM jobs WHERE project_id = ?').get(p.id).c;
|
const stats = await prospectStats(db, p.id);
|
||||||
|
const cost = (await db.prepare('SELECT COALESCE(SUM(cost_usd),0) c FROM jobs WHERE project_id = ? AND user_id = ?').get(p.id, ctx.session.userId)).c;
|
||||||
let business = null, error = null;
|
let business = null, error = null;
|
||||||
try {
|
try {
|
||||||
business = await fetchRecap(p.id, p.dbCfg, { force: url.searchParams.has('force') });
|
business = await fetchRecap(p.id, p.dbCfg, { force: url.searchParams.has('force') });
|
||||||
saveSnapshot(db, p.id, business); // la consultation alimente aussi la courbe du jour
|
await saveSnapshot(db, p.id, business); // la consultation alimente aussi la courbe du jour
|
||||||
} catch (e) { error = e.message; }
|
} catch (e) { error = e.message; }
|
||||||
json(res, { business, error, stats, aiCostUsd: cost });
|
json(res, { business, error, stats, aiCostUsd: cost });
|
||||||
});
|
});
|
||||||
|
|
||||||
router.get('/api/projects/:id/prospects\\.csv', ({ res, params, url }) => {
|
router.get('/api/projects/:id/prospects\\.csv', async (ctx) => {
|
||||||
const p = getProject(app, pid(params));
|
const { res, url } = ctx;
|
||||||
|
const p = await project(ctx);
|
||||||
const slug = p.name.normalize('NFD').replace(/[^\w-]+/g, '-').replace(/^-|-$/g, '').toLowerCase() || 'projet';
|
const slug = p.name.normalize('NFD').replace(/[^\w-]+/g, '-').replace(/^-|-$/g, '').toLowerCase() || 'projet';
|
||||||
const date = new Date().toLocaleDateString('sv-SE', { timeZone: 'Europe/Paris' });
|
const date = new Date().toLocaleDateString('sv-SE', { timeZone: 'Europe/Paris' });
|
||||||
res.writeHead(200, {
|
res.writeHead(200, {
|
||||||
|
|
@ -336,62 +457,70 @@ export function registerRoutes(router, app) {
|
||||||
'Content-Disposition': `attachment; filename="prospects-${slug}-${date}.csv"`,
|
'Content-Disposition': `attachment; filename="prospects-${slug}-${date}.csv"`,
|
||||||
'Cache-Control': 'no-store',
|
'Cache-Control': 'no-store',
|
||||||
});
|
});
|
||||||
res.end(exportProspects(db, p.id, parseFilters(url.searchParams)));
|
res.end(await exportProspects(db, p.id, parseFilters(url.searchParams)));
|
||||||
});
|
});
|
||||||
|
|
||||||
router.post('/api/projects/:id/prospects/import', async ({ req, res, params }) => {
|
router.post('/api/projects/:id/prospects/import', async (ctx) => {
|
||||||
const p = getProject(app, pid(params));
|
const { req, res } = ctx;
|
||||||
|
const p = await project(ctx);
|
||||||
const b = await readBody(req, { max: 1024 * 1024 });
|
const b = await readBody(req, { max: 1024 * 1024 });
|
||||||
try { json(res, importProspects(db, p.id, String(b.csv || ''))); }
|
try { json(res, await importProspects(db, p.id, String(b.csv || ''))); }
|
||||||
catch (e) { throw new HttpError(400, e.message); }
|
catch (e) { throw new HttpError(400, e.message); }
|
||||||
});
|
});
|
||||||
|
|
||||||
router.get('/api/projects/:id/history', ({ res, params, url }) => {
|
router.get('/api/projects/:id/history', async (ctx) => {
|
||||||
const p = getProject(app, pid(params));
|
const { res, url } = ctx;
|
||||||
json(res, history(db, p.id, { days: url.searchParams.get('days') === '90' ? 90 : 30 }));
|
const p = await project(ctx);
|
||||||
|
json(res, await history(db, p.id, { days: url.searchParams.get('days') === '90' ? 90 : 30 }));
|
||||||
});
|
});
|
||||||
|
|
||||||
router.get('/api/projects/:id/prospects', ({ res, params, url }) => {
|
router.get('/api/projects/:id/prospects', async (ctx) => {
|
||||||
const p = getProject(app, pid(params));
|
const { res, url } = ctx;
|
||||||
json(res, listProspects(db, p.id, parseFilters(url.searchParams)));
|
const p = await project(ctx);
|
||||||
|
json(res, await listProspects(db, p.id, parseFilters(url.searchParams)));
|
||||||
});
|
});
|
||||||
|
|
||||||
const STATUSES = Object.keys(PROSPECT_STATUSES);
|
const STATUSES = Object.keys(PROSPECT_STATUSES);
|
||||||
router.post('/api/prospects/:id/status', async ({ req, res, params }) => {
|
// ---------- Fiche prospect ----------
|
||||||
|
// Un prospect n'est accessible que par le propriétaire de son projet ; sinon 404, comme s'il n'existait pas
|
||||||
|
const ownedProspect = async ({ params, session }) => {
|
||||||
|
const row = await db.prepare(`SELECT x.id, x.email FROM prospects x JOIN projects p ON p.id = x.project_id
|
||||||
|
WHERE x.id = ? AND p.user_id = ?`).get(Number(params.id), session.userId);
|
||||||
|
if (!row) throw new HttpError(404, 'Prospect introuvable');
|
||||||
|
return row;
|
||||||
|
};
|
||||||
|
router.post('/api/prospects/:id/status', async (ctx) => {
|
||||||
|
const { req, res } = ctx;
|
||||||
const b = await readBody(req);
|
const b = await readBody(req);
|
||||||
if (!STATUSES.includes(b.status)) throw new HttpError(400, 'Statut invalide');
|
if (!STATUSES.includes(b.status)) throw new HttpError(400, 'Statut invalide');
|
||||||
const r = db.prepare('UPDATE prospects SET status = ? WHERE id = ?').run(b.status, Number(params.id));
|
const row = await ownedProspect(ctx);
|
||||||
if (!r.changes) throw new HttpError(404, 'Prospect introuvable');
|
await db.prepare('UPDATE prospects SET status = ? WHERE id = ?').run(b.status, row.id);
|
||||||
if (b.status === 'refused') {
|
if (b.status === 'refused') {
|
||||||
const { email } = db.prepare('SELECT email FROM prospects WHERE id = ?').get(Number(params.id));
|
await db.prepare("INSERT OR IGNORE INTO blacklist(email, reason, created_at) VALUES(?, 'refused', ?)").run(row.email, now());
|
||||||
db.prepare("INSERT OR IGNORE INTO blacklist(email, reason, created_at) VALUES(?, 'refused', ?)").run(email, now());
|
|
||||||
}
|
}
|
||||||
json(res, { ok: true });
|
json(res, { ok: true });
|
||||||
});
|
});
|
||||||
|
|
||||||
// ---------- Fiche prospect ----------
|
router.get('/api/prospects/:id', async (ctx) => json(ctx.res, await prospectDetail(db, (await ownedProspect(ctx)).id)));
|
||||||
const prospectId = (params) => {
|
router.post('/api/prospects/:id/notes', async (ctx) => {
|
||||||
const id = Number(params.id);
|
const id = (await ownedProspect(ctx)).id;
|
||||||
if (!db.prepare('SELECT 1 FROM prospects WHERE id = ?').get(id)) throw new HttpError(404, 'Prospect introuvable');
|
const noteId = await addNote(db, id, (await readBody(ctx.req)).body);
|
||||||
return id;
|
|
||||||
};
|
|
||||||
router.get('/api/prospects/:id', ({ res, params }) => json(res, prospectDetail(db, prospectId(params))));
|
|
||||||
router.post('/api/prospects/:id/notes', async ({ req, res, params }) => {
|
|
||||||
const id = prospectId(params);
|
|
||||||
const noteId = addNote(db, id, (await readBody(req)).body);
|
|
||||||
if (!noteId) throw new HttpError(400, 'Note vide');
|
if (!noteId) throw new HttpError(400, 'Note vide');
|
||||||
json(res, { ok: true, id: noteId });
|
json(ctx.res, { ok: true, id: noteId });
|
||||||
});
|
});
|
||||||
router.post('/api/prospects/:id/notes/:nid/delete', ({ res, params }) => {
|
router.post('/api/prospects/:id/notes/:nid/delete', async (ctx) => {
|
||||||
if (!deleteNote(db, prospectId(params), Number(params.nid))) throw new HttpError(404, 'Note introuvable');
|
if (!await deleteNote(db, (await ownedProspect(ctx)).id, Number(ctx.params.nid))) throw new HttpError(404, 'Note introuvable');
|
||||||
json(res, { ok: true });
|
json(ctx.res, { ok: true });
|
||||||
});
|
});
|
||||||
router.post('/api/prospects/:id/next', async ({ req, res, params }) => {
|
router.post('/api/prospects/:id/next', async (ctx) => {
|
||||||
const id = prospectId(params);
|
const id = (await ownedProspect(ctx)).id;
|
||||||
const b = await readBody(req);
|
const b = await readBody(ctx.req);
|
||||||
try { json(res, { ok: true, at: setNextAction(db, id, b.action, b.day) }); }
|
try { json(ctx.res, { ok: true, at: await setNextAction(db, id, b.action, b.day) }); }
|
||||||
catch (e) { throw new HttpError(400, e.message); }
|
catch (e) { throw new HttpError(400, e.message); }
|
||||||
});
|
});
|
||||||
|
|
||||||
router.post('/api/jobs/:id/cancel', ({ res, params }) => { cancelJob(db, Number(params.id)); json(res, { ok: true }); });
|
router.post('/api/jobs/:id/cancel', async ({ res, params, session }) => {
|
||||||
|
await cancelJob(db, session.userId, Number(params.id));
|
||||||
|
json(res, { ok: true });
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
|
||||||
114
src/server.js
114
src/server.js
|
|
@ -1,11 +1,13 @@
|
||||||
import { createServer } from 'node:http';
|
import { createServer } from 'node:http';
|
||||||
import { readFileSync } from 'node:fs';
|
import { readFileSync } from 'node:fs';
|
||||||
|
import { createHash } from 'node:crypto';
|
||||||
import { join, dirname } from 'node:path';
|
import { join, dirname } from 'node:path';
|
||||||
import { fileURLToPath } from 'node:url';
|
import { fileURLToPath } from 'node:url';
|
||||||
import { loadConfig } from './config.js';
|
import { loadConfig } from './config.js';
|
||||||
import { openDb } from './db.js';
|
import { openDb } from './db.js';
|
||||||
import { Router, json, redirect, html, HttpError } from './http.js';
|
import { Router, json, redirect, html, HttpError } from './http.js';
|
||||||
import { getSession, checkOrigin, purgeExpired } from './auth.js';
|
import { getSession, checkOrigin, purgeExpired } from './auth.js';
|
||||||
|
import { syncAdmins } from './users.js';
|
||||||
import { registerRoutes } from './routes.js';
|
import { registerRoutes } from './routes.js';
|
||||||
import { Worker } from './services/jobs.js';
|
import { Worker } from './services/jobs.js';
|
||||||
import { makeHandlers } from './handlers.js';
|
import { makeHandlers } from './handlers.js';
|
||||||
|
|
@ -13,53 +15,83 @@ import { Scheduler } from './services/scheduler.js';
|
||||||
import { notify, notifyJob } from './services/notify.js';
|
import { notify, notifyJob } from './services/notify.js';
|
||||||
import { budgetState, AI_JOBS, quotaState, isQuotaSensitive } from './services/budget.js';
|
import { budgetState, AI_JOBS, quotaState, isQuotaSensitive } from './services/budget.js';
|
||||||
import { layout } from './views.js';
|
import { layout } from './views.js';
|
||||||
|
import { homePage, notFoundPage } from './site/pages.js';
|
||||||
|
import { securityHeaders, robotsHeaderFor } from './site/seo.js';
|
||||||
|
import { hasUsableLink, isLinkExempt, LINK_REQUIRED_MESSAGE } from './claudelink.js';
|
||||||
|
import { sandboxStartupMessages } from './services/sandbox.js';
|
||||||
|
|
||||||
const ROOT = join(dirname(fileURLToPath(import.meta.url)), '..');
|
const ROOT = join(dirname(fileURLToPath(import.meta.url)), '..');
|
||||||
|
|
||||||
// Fichiers statiques chargés une fois en mémoire (2 fichiers, quelques Ko)
|
// Fichiers statiques chargés une fois en mémoire (quelques Ko), avec ETag : un rechargement coûte un 304
|
||||||
|
function asset(file, type, maxAge) {
|
||||||
|
const body = readFileSync(join(ROOT, 'public', file));
|
||||||
|
const etag = '"' + createHash('sha1').update(body).digest('base64url').slice(0, 20) + '"';
|
||||||
|
return { type, body, etag, cache: `public, max-age=${maxAge}` };
|
||||||
|
}
|
||||||
const STATIC = {
|
const STATIC = {
|
||||||
'/static/app.css': ['text/css; charset=utf-8', readFileSync(join(ROOT, 'public/app.css'))],
|
'/static/app.css': asset('app.css', 'text/css; charset=utf-8', 3600),
|
||||||
'/static/app.js': ['text/javascript; charset=utf-8', readFileSync(join(ROOT, 'public/app.js'))],
|
'/static/site.css': asset('site.css', 'text/css; charset=utf-8', 3600),
|
||||||
|
'/static/app.js': asset('app.js', 'text/javascript; charset=utf-8', 3600),
|
||||||
|
'/static/favicon.svg': asset('favicon.svg', 'image/svg+xml', 86400),
|
||||||
};
|
};
|
||||||
|
|
||||||
const SECURITY_HEADERS = {
|
// `fetch`, `validateApiKey`, `validateToken`, `syncRepo` : points d'injection pour les tests (aucun appel réseau réel)
|
||||||
'X-Content-Type-Options': 'nosniff',
|
export async function createApp(cfg, { db, worker = true, createTransport, fetch, validateApiKey, validateToken, syncRepo } = {}) {
|
||||||
'X-Frame-Options': 'DENY',
|
db ??= await openDb(cfg.db, { adminEmails: cfg.adminEmails });
|
||||||
'Referrer-Policy': 'same-origin',
|
await syncAdmins(db, cfg.adminEmails || []); // ADMIN_EMAILS fait foi pour le rôle admin
|
||||||
'Content-Security-Policy': "default-src 'self'; style-src 'self'; script-src 'self'; img-src 'self' data:; form-action 'self' https://accounts.google.com; frame-ancestors 'none'",
|
const app = { db, cfg, createTransport, fetch, validateApiKey, validateToken, syncRepo };
|
||||||
'Strict-Transport-Security': 'max-age=31536000',
|
const secHeaders = securityHeaders(cfg.appUrl);
|
||||||
};
|
|
||||||
|
|
||||||
export function createApp(cfg, { db = openDb(cfg.dataDir), worker = true, createTransport } = {}) {
|
|
||||||
const app = { db, cfg, createTransport };
|
|
||||||
const router = new Router();
|
const router = new Router();
|
||||||
registerRoutes(router, app);
|
registerRoutes(router, app);
|
||||||
|
|
||||||
const server = createServer(async (req, res) => {
|
const server = createServer(async (req, res) => {
|
||||||
for (const [k, v] of Object.entries(SECURITY_HEADERS)) res.setHeader(k, v);
|
for (const [k, v] of Object.entries(secHeaders)) res.setHeader(k, v);
|
||||||
const url = new URL(req.url, cfg.appUrl);
|
const url = new URL(req.url, cfg.appUrl);
|
||||||
|
// Pages d'application, API, connexion, 404 : jamais indexées (seul le site public l'est)
|
||||||
|
const robots = robotsHeaderFor(url.pathname);
|
||||||
|
if (robots) res.setHeader('X-Robots-Tag', robots);
|
||||||
try {
|
try {
|
||||||
const st = STATIC[url.pathname];
|
const isRead = req.method === 'GET' || req.method === 'HEAD';
|
||||||
if (st && req.method === 'GET') {
|
const st = isRead ? STATIC[url.pathname] : null;
|
||||||
res.writeHead(200, { 'Content-Type': st[0], 'Cache-Control': 'public, max-age=3600' });
|
if (st) {
|
||||||
return res.end(st[1]);
|
const headers = { 'Content-Type': st.type, 'Cache-Control': st.cache, ETag: st.etag };
|
||||||
|
if (req.headers['if-none-match'] === st.etag) { res.writeHead(304, headers); return res.end(); }
|
||||||
|
res.writeHead(200, headers);
|
||||||
|
return res.end(st.body);
|
||||||
}
|
}
|
||||||
const route = router.match(req.method, url.pathname);
|
// HEAD répond comme GET (Node n'envoie pas le corps)
|
||||||
if (!route) throw new HttpError(404, 'Page introuvable');
|
const route = router.match(req.method === 'HEAD' ? 'GET' : req.method, url.pathname);
|
||||||
const session = route.public ? null : getSession(db, req);
|
if (!route) {
|
||||||
|
const wantsJson = url.pathname.startsWith('/api/') || req.headers.accept?.includes('json');
|
||||||
|
if (wantsJson || !isRead) throw new HttpError(404, 'Page introuvable');
|
||||||
|
return html(res, notFoundPage({ appUrl: cfg.appUrl }), 404);
|
||||||
|
}
|
||||||
|
const session = route.public ? null : await getSession(db, req);
|
||||||
if (!route.public) {
|
if (!route.public) {
|
||||||
if (!session) {
|
if (!session) {
|
||||||
|
// Visiteur sur la racine : le site public. Connecté, la même adresse mène au tableau de bord.
|
||||||
|
if (isRead && url.pathname === '/') {
|
||||||
|
res.setHeader('Vary', 'Cookie');
|
||||||
|
return html(res, homePage({ appUrl: cfg.appUrl, apple: !!cfg.apple }));
|
||||||
|
}
|
||||||
if (url.pathname.startsWith('/api/')) throw new HttpError(401, 'Non connecté');
|
if (url.pathname.startsWith('/api/')) throw new HttpError(401, 'Non connecté');
|
||||||
return redirect(res, '/login');
|
return redirect(res, '/login');
|
||||||
}
|
}
|
||||||
checkOrigin(req, cfg);
|
checkOrigin(req, cfg);
|
||||||
|
// Onboarding bloquant : sans liaison Claude valide, seules la liaison, Mon compte et la déconnexion répondent
|
||||||
|
if (!isLinkExempt(req.method, url.pathname) && !(await hasUsableLink(db, session.userId, { cliModeEnabled: cfg.cliModeEnabled !== false }))) {
|
||||||
|
if (url.pathname.startsWith('/api/') || req.headers.accept?.includes('json')) {
|
||||||
|
return json(res, { error: LINK_REQUIRED_MESSAGE, code: 'link_required' }, 403);
|
||||||
|
}
|
||||||
|
return redirect(res, '/link');
|
||||||
|
}
|
||||||
}
|
}
|
||||||
await route.handler({ req, res, url, params: route.params, session, app });
|
await route.handler({ req, res, url, params: route.params, session, app });
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
const status = e.status || 500;
|
const status = e.status || 500;
|
||||||
if (status >= 500) console.error(`[${req.method} ${url.pathname}]`, e);
|
if (status >= 500 && !e.expose) console.error(`[${req.method} ${url.pathname}]`, e);
|
||||||
if (res.headersSent) return res.end();
|
if (res.headersSent) return res.end();
|
||||||
const msg = status >= 500 ? 'Erreur interne' : e.message;
|
const msg = status >= 500 && !e.expose ? 'Erreur interne' : e.message;
|
||||||
if (url.pathname.startsWith('/api/') || req.headers.accept?.includes('json')) json(res, { error: msg }, status);
|
if (url.pathname.startsWith('/api/') || req.headers.accept?.includes('json')) json(res, { error: msg }, status);
|
||||||
else html(res, layout({ title: 'Erreur', body: `<section class="card"><h1>${status}</h1><p>${msg.replace(/</g, '<')}</p><a href="/">Retour</a></section>` }), status);
|
else html(res, layout({ title: 'Erreur', body: `<section class="card"><h1>${status}</h1><p>${msg.replace(/</g, '<')}</p><a href="/">Retour</a></section>` }), status);
|
||||||
}
|
}
|
||||||
|
|
@ -73,42 +105,56 @@ export function createApp(cfg, { db = openDb(cfg.dataDir), worker = true, create
|
||||||
let scheduler = null;
|
let scheduler = null;
|
||||||
if (worker) {
|
if (worker) {
|
||||||
w = new Worker(db, makeHandlers(app), {
|
w = new Worker(db, makeHandlers(app), {
|
||||||
thermalMax: cfg.thermalMax,
|
thermalMax: cfg.thermalMax, cliModeEnabled: cfg.cliModeEnabled !== false,
|
||||||
onFinish: (job, r) => notifyJob(app, job, r),
|
onFinish: (job, r) => notifyJob(app, job, r),
|
||||||
budget: () => budgetState(db),
|
budget: (userId) => budgetState(db, userId),
|
||||||
isAiJob: (type) => AI_JOBS.has(type),
|
isAiJob: (type) => AI_JOBS.has(type),
|
||||||
onBudget: (reason) => notify(app, 'budget', {
|
onBudget: (reason, userId) => notify(app, userId, 'budget', {
|
||||||
title: 'Budget IA atteint', level: 'warn',
|
title: 'Budget IA atteint', level: 'warn',
|
||||||
description: `${reason[0].toUpperCase()}${reason.slice(1)}. Les jobs IA attendent ; les envois et relances continuent.`,
|
description: `${reason[0].toUpperCase()}${reason.slice(1)}. Les jobs IA attendent ; les envois et relances continuent.`,
|
||||||
}),
|
}),
|
||||||
quota: () => quotaState(db),
|
quota: (userId) => quotaState(db, userId),
|
||||||
isQuotaSensitive,
|
isQuotaSensitive,
|
||||||
onQuotaHold: (reason) => notify(app, 'quota', {
|
onQuotaHold: (reason, userId) => notify(app, userId, 'quota', {
|
||||||
title: 'Job IA reporté (quota serré)', level: 'warn',
|
title: 'Job IA reporté (quota serré)', level: 'warn',
|
||||||
description: `${reason[0].toUpperCase()}${reason.slice(1)}. Analyse et évolutions attendent ; prospection et envois continuent.`,
|
description: `${reason[0].toUpperCase()}${reason.slice(1)}. Analyse et évolutions attendent ; prospection et envois continuent.`,
|
||||||
}),
|
}),
|
||||||
onThermal: (t) => notify(app, 'thermal', {
|
onThermal: (t, userId) => notify(app, userId, 'thermal', {
|
||||||
title: 'Pause thermique', level: 'warn',
|
title: 'Pause thermique', level: 'warn',
|
||||||
description: `CPU à ${t} °C : les jobs IA attendent que le Pi redescende sous ${cfg.thermalMax - 5} °C.`,
|
description: `CPU à ${t} °C : les jobs IA attendent que le Pi redescende sous ${cfg.thermalMax - 5} °C.`,
|
||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
w.start();
|
await w.start();
|
||||||
|
app.worker = w;
|
||||||
scheduler = new Scheduler(app);
|
scheduler = new Scheduler(app);
|
||||||
scheduler.start();
|
scheduler.start();
|
||||||
}
|
}
|
||||||
const purge = setInterval(() => purgeExpired(db), 3600_000);
|
let purging = null;
|
||||||
|
const purge = setInterval(() => {
|
||||||
|
purging = purgeExpired(db).catch((e) => console.error('[purge]', e.message));
|
||||||
|
}, 3600_000);
|
||||||
purge.unref();
|
purge.unref();
|
||||||
|
|
||||||
app.close = () => new Promise((r) => { w?.stop(); scheduler?.stop(); clearInterval(purge); server.close(() => { db.close(); r(); }); });
|
// Arrêt propre : plus de requêtes, puis fin du job en cours et des tâches de fond, enfin fermeture de la base
|
||||||
|
app.close = async () => {
|
||||||
|
clearInterval(purge);
|
||||||
|
await new Promise((r) => { server.close(r); server.closeIdleConnections?.(); });
|
||||||
|
await w?.stop();
|
||||||
|
await scheduler?.stop();
|
||||||
|
await purging;
|
||||||
|
await db.close();
|
||||||
|
};
|
||||||
app.server = server;
|
app.server = server;
|
||||||
return app;
|
return app;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (process.argv[1] === fileURLToPath(import.meta.url)) {
|
if (process.argv[1] === fileURLToPath(import.meta.url)) {
|
||||||
const cfg = loadConfig();
|
const cfg = loadConfig();
|
||||||
const app = createApp(cfg);
|
if (!cfg.adminEmails.length) console.warn('ADMIN_EMAILS est vide : aucun administrateur (personne ne pourra utiliser le mode « Claude du serveur »).');
|
||||||
|
for (const m of sandboxStartupMessages(cfg.sandbox)) console.warn(m);
|
||||||
|
const app = await createApp(cfg);
|
||||||
app.server.listen(cfg.port, cfg.host, () => console.log(`AiTools sur http://${cfg.host}:${cfg.port} (${cfg.appUrl})`));
|
app.server.listen(cfg.port, cfg.host, () => console.log(`AiTools sur http://${cfg.host}:${cfg.port} (${cfg.appUrl})`));
|
||||||
const shutdown = () => app.close().then(() => process.exit(0));
|
const shutdown = () => app.close().then(() => process.exit(0), (e) => { console.error(e); process.exit(1); });
|
||||||
process.on('SIGTERM', shutdown);
|
process.on('SIGTERM', shutdown);
|
||||||
process.on('SIGINT', shutdown);
|
process.on('SIGINT', shutdown);
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -7,20 +7,20 @@ export const AI_JOBS = new Set(['analyze', 'prospect', 'template', 'followup_tem
|
||||||
|
|
||||||
const usd = (n) => `${n.toFixed(2)} $`;
|
const usd = (n) => `${n.toFixed(2)} $`;
|
||||||
|
|
||||||
// La dépense compte au moment où le job s'est terminé (un job de nuit compte la nuit)
|
// La dépense compte au moment où le job s'est terminé (un job de nuit compte la nuit). Budget propre à chaque utilisateur.
|
||||||
function spentSince(db, since) {
|
async function spentSince(db, userId, since) {
|
||||||
return db.prepare('SELECT COALESCE(SUM(cost_usd), 0) c FROM jobs WHERE COALESCE(finished_at, created_at) > ?').get(since).c;
|
return (await db.prepare('SELECT COALESCE(SUM(cost_usd), 0) c FROM jobs WHERE user_id = ? AND COALESCE(finished_at, created_at) > ?').get(userId, since)).c;
|
||||||
}
|
}
|
||||||
|
|
||||||
function limit(db, key) {
|
async function limit(db, userId, key) {
|
||||||
const v = Number(getSetting(db, key, ''));
|
const v = Number(await getSetting(db, userId, key, ''));
|
||||||
return Number.isFinite(v) && v > 0 ? v : null;
|
return Number.isFinite(v) && v > 0 ? v : null;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @returns {{day: {used:number, limit:number|null}, month: {used:number, limit:number|null}, blocked: boolean, reason: string|null}} */
|
/** @returns {{day: {used:number, limit:number|null}, month: {used:number, limit:number|null}, blocked: boolean, reason: string|null}} */
|
||||||
export function budgetState(db, { at = now() } = {}) {
|
export async function budgetState(db, userId, { at = now() } = {}) {
|
||||||
const day = { used: spentSince(db, at - 86400), limit: limit(db, 'budget_day_usd') };
|
const day = { used: await spentSince(db, userId, at - 86400), limit: await limit(db, userId, 'budget_day_usd') };
|
||||||
const month = { used: spentSince(db, at - 30 * 86400), limit: limit(db, 'budget_month_usd') };
|
const month = { used: await spentSince(db, userId, at - 30 * 86400), limit: await limit(db, userId, 'budget_month_usd') };
|
||||||
const over = (x) => x.limit != null && x.used >= x.limit;
|
const over = (x) => x.limit != null && x.used >= x.limit;
|
||||||
const reason = over(day) ? `budget IA des dernières 24 h atteint (${usd(day.used)} / ${usd(day.limit)})`
|
const reason = over(day) ? `budget IA des dernières 24 h atteint (${usd(day.used)} / ${usd(day.limit)})`
|
||||||
: over(month) ? `budget IA des 30 derniers jours atteint (${usd(month.used)} / ${usd(month.limit)})`
|
: over(month) ? `budget IA des 30 derniers jours atteint (${usd(month.used)} / ${usd(month.limit)})`
|
||||||
|
|
@ -40,8 +40,8 @@ export const QUOTA_PAUSE_THRESHOLD = 0.85;
|
||||||
const WINDOW_LABELS = { fiveHour: 'session Claude (5 h)', sevenDay: 'semaine Claude' };
|
const WINDOW_LABELS = { fiveHour: 'session Claude (5 h)', sevenDay: 'semaine Claude' };
|
||||||
|
|
||||||
/** @returns {{blocked: boolean, reason: string|null}} */
|
/** @returns {{blocked: boolean, reason: string|null}} */
|
||||||
export function quotaState(db) {
|
export async function quotaState(db, userId) {
|
||||||
const raw = getSetting(db, 'claude_rate_limit_json');
|
const raw = await getSetting(db, userId, 'claude_rate_limit_json');
|
||||||
if (!raw) return { blocked: false, reason: null };
|
if (!raw) return { blocked: false, reason: null };
|
||||||
let rl;
|
let rl;
|
||||||
try { rl = JSON.parse(raw); } catch { return { blocked: false, reason: null }; }
|
try { rl = JSON.parse(raw); } catch { return { blocked: false, reason: null }; }
|
||||||
|
|
@ -58,10 +58,10 @@ export function quotaState(db) {
|
||||||
const ALERT_LEVELS = [0.95, 0.80];
|
const ALERT_LEVELS = [0.95, 0.80];
|
||||||
|
|
||||||
/** Renvoie les paliers nouvellement franchis et enregistre l'état pour ne pas re-notifier. */
|
/** Renvoie les paliers nouvellement franchis et enregistre l'état pour ne pas re-notifier. */
|
||||||
export function quotaAlerts(db, windows) {
|
export async function quotaAlerts(db, userId, windows) {
|
||||||
if (!windows) return [];
|
if (!windows) return [];
|
||||||
let prev = {};
|
let prev = {};
|
||||||
try { prev = JSON.parse(getSetting(db, 'claude_quota_notified_json', '{}') || '{}'); } catch { prev = {}; }
|
try { prev = JSON.parse((await getSetting(db, userId, 'claude_quota_notified_json', '{}')) || '{}'); } catch { prev = {}; }
|
||||||
const next = { ...prev };
|
const next = { ...prev };
|
||||||
const alerts = [];
|
const alerts = [];
|
||||||
for (const [key, label] of Object.entries(WINDOW_LABELS)) {
|
for (const [key, label] of Object.entries(WINDOW_LABELS)) {
|
||||||
|
|
@ -73,6 +73,6 @@ export function quotaAlerts(db, windows) {
|
||||||
if (crossed) alerts.push({ label, level: Math.round(crossed * 100), utilization: w.utilization });
|
if (crossed) alerts.push({ label, level: Math.round(crossed * 100), utilization: w.utilization });
|
||||||
next[key] = { resetsAt: w.resetsAt, level: crossed ? Math.round(crossed * 100) : state.level };
|
next[key] = { resetsAt: w.resetsAt, level: crossed ? Math.round(crossed * 100) : state.level };
|
||||||
}
|
}
|
||||||
setSetting(db, 'claude_quota_notified_json', JSON.stringify(next));
|
await setSetting(db, userId, 'claude_quota_notified_json', JSON.stringify(next));
|
||||||
return alerts;
|
return alerts;
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,7 @@
|
||||||
// Lance Claude Code en headless (`claude -p`) avec un périmètre d'outils restreint,
|
// Lance Claude Code en headless (`claude -p`) avec un périmètre d'outils restreint,
|
||||||
// et parse le flux stream-json pour remonter la progression en direct.
|
// et parse le flux stream-json pour remonter la progression en direct.
|
||||||
import { spawn } from 'node:child_process';
|
import { spawn } from 'node:child_process';
|
||||||
|
import { prepareLaunch } from './sandbox.js';
|
||||||
|
|
||||||
export const MODELS = { rapide: 'haiku', normal: 'sonnet', approfondi: 'opus' };
|
export const MODELS = { rapide: 'haiku', normal: 'sonnet', approfondi: 'opus' };
|
||||||
|
|
||||||
|
|
@ -17,6 +18,10 @@ export const MODELS = { rapide: 'haiku', normal: 'sonnet', approfondi: 'opus' };
|
||||||
* @param {AbortSignal} [o.signal]
|
* @param {AbortSignal} [o.signal]
|
||||||
* @param {number} [o.timeoutMs]
|
* @param {number} [o.timeoutMs]
|
||||||
* @param {string} [o.bin]
|
* @param {string} [o.bin]
|
||||||
|
* @param {object} o.sandbox cfg.sandbox (obligatoire : voir services/sandbox.js)
|
||||||
|
* @param {Record<string,string>} [o.secretEnv] secret de l'utilisateur du job (ANTHROPIC_API_KEY ou CLAUDE_CODE_OAUTH_TOKEN), transmis au seul processus enfant
|
||||||
|
* @param {boolean} [o.serverConfig] mode « Claude du serveur » (admins) : configuration CLI du serveur
|
||||||
|
* @param {string} [o.allowedRoot] dossier des clones de l'utilisateur : `cwd` doit s'y trouver
|
||||||
*/
|
*/
|
||||||
export function runClaude(o) {
|
export function runClaude(o) {
|
||||||
const args = [
|
const args = [
|
||||||
|
|
@ -29,10 +34,14 @@ export function runClaude(o) {
|
||||||
];
|
];
|
||||||
if (o.system) args.push('--append-system-prompt', o.system);
|
if (o.system) args.push('--append-system-prompt', o.system);
|
||||||
|
|
||||||
// nice : le serveur web reste réactif pendant qu'un job tourne
|
const launch = prepareLaunch({
|
||||||
const child = spawn('nice', ['-n', '10', o.bin || 'claude', ...args], {
|
bin: o.bin || 'claude', args, cwd: o.cwd, allowedRoot: o.allowedRoot,
|
||||||
cwd: o.cwd, env: process.env, stdio: ['ignore', 'pipe', 'pipe'],
|
secretEnv: o.secretEnv, serverConfig: o.serverConfig, sandbox: o.sandbox,
|
||||||
});
|
});
|
||||||
|
const secrets = Object.values(o.secretEnv || {}).filter((v) => v && v.length >= 8);
|
||||||
|
// Aucune trace du secret dans les erreurs, stderr ou textes remontés (journaux, base, réponses HTTP)
|
||||||
|
const redact = (t) => secrets.reduce((acc, s) => acc.split(s).join('***'), String(t ?? ''));
|
||||||
|
const child = spawn(launch.command, launch.args, { cwd: launch.cwd, env: launch.env, stdio: ['ignore', 'pipe', 'pipe'] });
|
||||||
|
|
||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
let buf = '';
|
let buf = '';
|
||||||
|
|
@ -55,6 +64,7 @@ export function runClaude(o) {
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
child.stderr.on('data', (c) => { stderr = (stderr + c).slice(-4000); });
|
child.stderr.on('data', (c) => { stderr = (stderr + c).slice(-4000); });
|
||||||
|
const done = () => { clearTimeout(timer); launch.cleanup(); };
|
||||||
|
|
||||||
function handle(line) {
|
function handle(line) {
|
||||||
let ev;
|
let ev;
|
||||||
|
|
@ -62,7 +72,7 @@ export function runClaude(o) {
|
||||||
if (ev.type === 'assistant') {
|
if (ev.type === 'assistant') {
|
||||||
o.onTurn?.(++turns);
|
o.onTurn?.(++turns);
|
||||||
for (const block of ev.message?.content || []) {
|
for (const block of ev.message?.content || []) {
|
||||||
if (block.type === 'text' && block.text) { texts.push(block.text); o.onText?.(block.text); }
|
if (block.type === 'text' && block.text) { texts.push(block.text); o.onText?.(redact(block.text)); }
|
||||||
}
|
}
|
||||||
} else if (ev.type === 'result') {
|
} else if (ev.type === 'result') {
|
||||||
result = ev;
|
result = ev;
|
||||||
|
|
@ -72,17 +82,17 @@ export function runClaude(o) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
child.on('error', (e) => { clearTimeout(timer); reject(new Error(`Impossible de lancer Claude : ${e.message}`)); });
|
child.on('error', (e) => { done(); reject(new Error(redact(`Impossible de lancer Claude : ${e.message}`))); });
|
||||||
child.on('close', (code) => {
|
child.on('close', (code) => {
|
||||||
clearTimeout(timer);
|
done();
|
||||||
if (buf.trim()) handle(buf.trim());
|
if (buf.trim()) handle(buf.trim());
|
||||||
if (!result) return reject(new Error(`Claude s'est arrêté sans résultat (code ${code}). ${stderr.trim()}`));
|
if (!result) return reject(new Error(redact(`Claude s'est arrêté sans résultat (code ${code}). ${stderr.trim()}`)));
|
||||||
const usage = result.usage || {};
|
const usage = result.usage || {};
|
||||||
resolve({
|
resolve({
|
||||||
ok: !result.is_error,
|
ok: !result.is_error,
|
||||||
subtype: result.subtype, // success | error_max_turns | ...
|
subtype: result.subtype, // success | error_max_turns | ...
|
||||||
text: result.result ?? texts.join('\n'),
|
text: redact(result.result ?? texts.join('\n')),
|
||||||
allText: texts.join('\n'),
|
allText: redact(texts.join('\n')),
|
||||||
costUsd: result.total_cost_usd ?? null,
|
costUsd: result.total_cost_usd ?? null,
|
||||||
tokensIn: (usage.input_tokens || 0) + (usage.cache_read_input_tokens || 0) + (usage.cache_creation_input_tokens || 0),
|
tokensIn: (usage.input_tokens || 0) + (usage.cache_read_input_tokens || 0) + (usage.cache_creation_input_tokens || 0),
|
||||||
tokensOut: usage.output_tokens || 0,
|
tokensOut: usage.output_tokens || 0,
|
||||||
|
|
|
||||||
|
|
@ -10,7 +10,7 @@ const SORTS = {
|
||||||
score: 'score DESC, id DESC',
|
score: 'score DESC, id DESC',
|
||||||
recent: 'created_at DESC, id DESC',
|
recent: 'created_at DESC, id DESC',
|
||||||
contacted: 'COALESCE(sent_at, 0) DESC, id DESC',
|
contacted: 'COALESCE(sent_at, 0) DESC, id DESC',
|
||||||
company: 'company COLLATE NOCASE, id',
|
company: 'LOWER(company), id',
|
||||||
};
|
};
|
||||||
|
|
||||||
const int = (v, min, max, def) => {
|
const int = (v, min, max, def) => {
|
||||||
|
|
@ -34,8 +34,9 @@ export function filterWhere(projectId, f) {
|
||||||
const where = ['project_id = ?'];
|
const where = ['project_id = ?'];
|
||||||
const args = [projectId];
|
const args = [projectId];
|
||||||
if (f.q) {
|
if (f.q) {
|
||||||
const like = `%${f.q.replace(/[\\%_]/g, (c) => `\\${c}`)}%`;
|
// '!' comme échappement : le backslash n'a pas le même sens dans un littéral SQLite et MySQL
|
||||||
where.push("(company LIKE ? ESCAPE '\\' OR email LIKE ? ESCAPE '\\' OR city LIKE ? ESCAPE '\\' OR sector LIKE ? ESCAPE '\\')");
|
const like = `%${f.q.replace(/[!%_]/g, (c) => `!${c}`)}%`;
|
||||||
|
where.push("(company LIKE ? ESCAPE '!' OR email LIKE ? ESCAPE '!' OR city LIKE ? ESCAPE '!' OR sector LIKE ? ESCAPE '!')");
|
||||||
args.push(like, like, like, like);
|
args.push(like, like, like, like);
|
||||||
}
|
}
|
||||||
if (f.status) { where.push('status = ?'); args.push(f.status); }
|
if (f.status) { where.push('status = ?'); args.push(f.status); }
|
||||||
|
|
@ -44,12 +45,12 @@ export function filterWhere(projectId, f) {
|
||||||
return { sql: where.join(' AND '), args, order: SORTS[f.sort] || SORTS.score };
|
return { sql: where.join(' AND '), args, order: SORTS[f.sort] || SORTS.score };
|
||||||
}
|
}
|
||||||
|
|
||||||
export function listProspects(db, projectId, f, { limit = 100 } = {}) {
|
export async function listProspects(db, projectId, f, { limit = 100 } = {}) {
|
||||||
const { sql, args, order } = filterWhere(projectId, f);
|
const { sql, args, order } = filterWhere(projectId, f);
|
||||||
const total = db.prepare(`SELECT COUNT(*) n FROM prospects WHERE ${sql}`).get(...args).n;
|
const total = (await db.prepare(`SELECT COUNT(*) n FROM prospects WHERE ${sql}`).get(...args)).n;
|
||||||
const pages = Math.max(1, Math.ceil(total / limit));
|
const pages = Math.max(1, Math.ceil(total / limit));
|
||||||
const page = Math.min(f.page, pages);
|
const page = Math.min(f.page, pages);
|
||||||
const rows = db.prepare(`SELECT id, company, email, website, city, sector, score, status, sent_at, followup_at, replied_at,
|
const rows = await db.prepare(`SELECT id, company, email, website, city, sector, score, status, sent_at, followup_at, replied_at,
|
||||||
next_action, next_action_at
|
next_action, next_action_at
|
||||||
FROM prospects WHERE ${sql} ORDER BY ${order} LIMIT ? OFFSET ?`).all(...args, limit, (page - 1) * limit);
|
FROM prospects WHERE ${sql} ORDER BY ${order} LIMIT ? OFFSET ?`).all(...args, limit, (page - 1) * limit);
|
||||||
return { total, page, pages, rows };
|
return { total, page, pages, rows };
|
||||||
|
|
@ -58,32 +59,35 @@ export function listProspects(db, projectId, f, { limit = 100 } = {}) {
|
||||||
// ---------- Fiche prospect ----------
|
// ---------- Fiche prospect ----------
|
||||||
|
|
||||||
/** Tout ce qu'on sait d'un prospect : infos, mails envoyés, réponse, notes. */
|
/** Tout ce qu'on sait d'un prospect : infos, mails envoyés, réponse, notes. */
|
||||||
export function prospectDetail(db, id) {
|
export async function prospectDetail(db, id) {
|
||||||
const p = db.prepare('SELECT * FROM prospects WHERE id = ?').get(id);
|
const p = await db.prepare('SELECT * FROM prospects WHERE id = ?').get(id);
|
||||||
if (!p) return null;
|
if (!p) return null;
|
||||||
const mails = db.prepare(`SELECT kind, subject, variant, sent_at, error FROM mail_log
|
const mails = await db.prepare(`SELECT kind, subject, variant, sent_at, error FROM mail_log
|
||||||
WHERE prospect_id = ? ORDER BY sent_at, id`).all(id);
|
WHERE prospect_id = ? ORDER BY sent_at, id`).all(id);
|
||||||
const notes = db.prepare('SELECT id, body, created_at FROM prospect_notes WHERE prospect_id = ? ORDER BY created_at DESC, id DESC').all(id);
|
const notes = await db.prepare('SELECT id, body, created_at FROM prospect_notes WHERE prospect_id = ? ORDER BY created_at DESC, id DESC').all(id);
|
||||||
const optOut = db.prepare('SELECT reason, created_at FROM blacklist WHERE email = ?').get(p.email) || null;
|
// La liste d'opposition est commune à tous les comptes : on n'en révèle que le strict nécessaire. Le motif d'un
|
||||||
|
// autre compte (refus, adresse invalide) n'est pas montré ; seule la désinscription, acte de la personne elle-même, l'est.
|
||||||
|
const row = await db.prepare('SELECT reason FROM blacklist WHERE email = ?').get(p.email);
|
||||||
|
const optOut = row ? { reason: row.reason === 'unsubscribe' ? 'unsubscribe' : p.status === 'bounced' ? 'bounce' : 'refused' } : null;
|
||||||
return { prospect: p, mails, notes, optOut };
|
return { prospect: p, mails, notes, optOut };
|
||||||
}
|
}
|
||||||
|
|
||||||
export function addNote(db, prospectId, body) {
|
export async function addNote(db, prospectId, body) {
|
||||||
const text = String(body || '').trim().slice(0, 2000);
|
const text = String(body || '').trim().slice(0, 2000);
|
||||||
if (!text) return null;
|
if (!text) return null;
|
||||||
return Number(db.prepare('INSERT INTO prospect_notes(prospect_id, body, created_at) VALUES(?, ?, ?)').run(prospectId, text, now()).lastInsertRowid);
|
return Number((await db.prepare('INSERT INTO prospect_notes(prospect_id, body, created_at) VALUES(?, ?, ?)').run(prospectId, text, now())).lastInsertRowid);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function deleteNote(db, prospectId, noteId) {
|
export async function deleteNote(db, prospectId, noteId) {
|
||||||
return db.prepare('DELETE FROM prospect_notes WHERE id = ? AND prospect_id = ?').run(noteId, prospectId).changes > 0;
|
return (await db.prepare('DELETE FROM prospect_notes WHERE id = ? AND prospect_id = ?').run(noteId, prospectId)).changes > 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Prochaine action : texte + jour (AAAA-MM-JJ, rappel à 9h heure de Paris). Vide = effacer. */
|
/** Prochaine action : texte + jour (AAAA-MM-JJ, rappel à 9h heure de Paris). Vide = effacer. */
|
||||||
export function setNextAction(db, prospectId, action, day) {
|
export async function setNextAction(db, prospectId, action, day) {
|
||||||
const text = String(action || '').trim().slice(0, 200);
|
const text = String(action || '').trim().slice(0, 200);
|
||||||
const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(String(day || ''));
|
const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(String(day || ''));
|
||||||
if (!text) {
|
if (!text) {
|
||||||
db.prepare('UPDATE prospects SET next_action = NULL, next_action_at = NULL WHERE id = ?').run(prospectId);
|
await db.prepare('UPDATE prospects SET next_action = NULL, next_action_at = NULL WHERE id = ?').run(prospectId);
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
if (!m) throw new Error('Date attendue au format AAAA-MM-JJ');
|
if (!m) throw new Error('Date attendue au format AAAA-MM-JJ');
|
||||||
|
|
@ -91,6 +95,6 @@ export function setNextAction(db, prospectId, action, day) {
|
||||||
// 2026-02-31 deviendrait le 3 mars sans prévenir : on refuse
|
// 2026-02-31 deviendrait le 3 mars sans prévenir : on refuse
|
||||||
if (parisParts(date).day !== +m[3]) throw new Error('Date invalide');
|
if (parisParts(date).day !== +m[3]) throw new Error('Date invalide');
|
||||||
const at = Math.floor(date.getTime() / 1000);
|
const at = Math.floor(date.getTime() / 1000);
|
||||||
db.prepare('UPDATE prospects SET next_action = ?, next_action_at = ? WHERE id = ?').run(text, at, prospectId);
|
await db.prepare('UPDATE prospects SET next_action = ?, next_action_at = ? WHERE id = ?').run(text, at, prospectId);
|
||||||
return at;
|
return at;
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -21,9 +21,9 @@ export function toCsv(header, rows) {
|
||||||
|
|
||||||
const day = (ts) => (ts ? new Date(ts * 1000).toLocaleString('sv-SE', { timeZone: 'Europe/Paris' }).slice(0, 16) : '');
|
const day = (ts) => (ts ? new Date(ts * 1000).toLocaleString('sv-SE', { timeZone: 'Europe/Paris' }).slice(0, 16) : '');
|
||||||
|
|
||||||
export function exportProspects(db, projectId, filters) {
|
export async function exportProspects(db, projectId, filters) {
|
||||||
const { sql, args, order } = filterWhere(projectId, filters);
|
const { sql, args, order } = filterWhere(projectId, filters);
|
||||||
const rows = db.prepare(`SELECT * FROM prospects WHERE ${sql} ORDER BY ${order} LIMIT 10000`).all(...args);
|
const rows = await db.prepare(`SELECT * FROM prospects WHERE ${sql} ORDER BY ${order} LIMIT 10000`).all(...args);
|
||||||
const header = ['Entreprise', 'Email', 'Site', 'Ville', 'Secteur', 'Score', 'Statut', 'Ajouté le', 'Contacté le', 'Objet',
|
const header = ['Entreprise', 'Email', 'Site', 'Ville', 'Secteur', 'Score', 'Statut', 'Ajouté le', 'Contacté le', 'Objet',
|
||||||
'Relancé le', 'Répondu le', 'Prochaine action', 'Échéance', 'Source', 'Accroche'];
|
'Relancé le', 'Répondu le', 'Prochaine action', 'Échéance', 'Source', 'Accroche'];
|
||||||
return toCsv(header, rows.map((p) => [
|
return toCsv(header, rows.map((p) => [
|
||||||
|
|
@ -75,7 +75,7 @@ const MAX_ROWS = 2000;
|
||||||
// Notre propre export préfixe les formules par ' : on l'enlève à la relecture
|
// Notre propre export préfixe les formules par ' : on l'enlève à la relecture
|
||||||
const unformula = (s) => (/^'[=+\-@]/.test(s) ? s.slice(1) : s);
|
const unformula = (s) => (/^'[=+\-@]/.test(s) ? s.slice(1) : s);
|
||||||
|
|
||||||
export function importProspects(db, projectId, text, { at = now() } = {}) {
|
export async function importProspects(db, projectId, text, { at = now() } = {}) {
|
||||||
const rows = parseCsv(text);
|
const rows = parseCsv(text);
|
||||||
if (rows.length < 2) throw new Error('Fichier vide ou sans en-tête');
|
if (rows.length < 2) throw new Error('Fichier vide ou sans en-tête');
|
||||||
const header = rows[0].map(norm);
|
const header = rows[0].map(norm);
|
||||||
|
|
@ -89,36 +89,32 @@ export function importProspects(db, projectId, text, { at = now() } = {}) {
|
||||||
if (data.length > MAX_ROWS) throw new Error(`Maximum ${MAX_ROWS} lignes par import (${data.length} dans le fichier)`);
|
if (data.length > MAX_ROWS) throw new Error(`Maximum ${MAX_ROWS} lignes par import (${data.length} dans le fichier)`);
|
||||||
|
|
||||||
const dateLabel = new Date(at * 1000).toLocaleDateString('fr-FR', { timeZone: 'Europe/Paris' });
|
const dateLabel = new Date(at * 1000).toLocaleDateString('fr-FR', { timeZone: 'Europe/Paris' });
|
||||||
const exists = db.prepare('SELECT 1 FROM prospects WHERE project_id = ? AND email = ?');
|
|
||||||
const optOut = db.prepare('SELECT 1 FROM blacklist WHERE email = ?');
|
|
||||||
const insert = db.prepare(`INSERT INTO prospects(project_id, company, email, website, city, sector, score, source, hook, created_at)
|
|
||||||
VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`);
|
|
||||||
const res = { total: data.length, imported: 0, duplicates: 0, blacklisted: 0, invalid: [] };
|
const res = { total: data.length, imported: 0, duplicates: 0, blacklisted: 0, invalid: [] };
|
||||||
const seen = new Set();
|
const seen = new Set();
|
||||||
const get = (r, k, max = 200) => (col[k] === undefined ? '' : unformula(String(r[col[k]] ?? '').trim()).slice(0, max));
|
const get = (r, k, max = 200) => (col[k] === undefined ? '' : unformula(String(r[col[k]] ?? '').trim()).slice(0, max));
|
||||||
|
|
||||||
db.exec('BEGIN');
|
// Tout ou rien : une ligne qui plante annule l'import entier
|
||||||
try {
|
await db.transaction(async (tx) => {
|
||||||
data.forEach((r, i) => {
|
const exists = tx.prepare('SELECT 1 FROM prospects WHERE project_id = ? AND email = ?');
|
||||||
|
const optOut = tx.prepare('SELECT 1 FROM blacklist WHERE email = ?');
|
||||||
|
const insert = tx.prepare(`INSERT INTO prospects(project_id, company, email, website, city, sector, score, source, hook, created_at)
|
||||||
|
VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`);
|
||||||
|
for (const [i, r] of data.entries()) {
|
||||||
const line = i + 2;
|
const line = i + 2;
|
||||||
const email = get(r, 'email').toLowerCase();
|
const email = get(r, 'email').toLowerCase();
|
||||||
if (!EMAIL_RE.test(email)) { if (res.invalid.length < 50) res.invalid.push({ line, reason: `email invalide : "${email || 'vide'}"` }); return; }
|
if (!EMAIL_RE.test(email)) { if (res.invalid.length < 50) res.invalid.push({ line, reason: `email invalide : "${email || 'vide'}"` }); continue; }
|
||||||
if (seen.has(email) || exists.get(projectId, email)) { res.duplicates++; return; }
|
if (seen.has(email) || await exists.get(projectId, email)) { res.duplicates++; continue; }
|
||||||
seen.add(email);
|
seen.add(email);
|
||||||
if (optOut.get(email)) { res.blacklisted++; return; }
|
if (await optOut.get(email)) { res.blacklisted++; continue; }
|
||||||
const s = Number(get(r, 'score'));
|
const s = Number(get(r, 'score'));
|
||||||
insert.run(
|
await insert.run(
|
||||||
projectId, get(r, 'company') || email.split('@')[1], email, httpUrl(get(r, 'website', 300)), get(r, 'city', 100) || null,
|
projectId, get(r, 'company') || email.split('@')[1], email, httpUrl(get(r, 'website', 300)), get(r, 'city', 100) || null,
|
||||||
get(r, 'sector', 100) || null, Number.isFinite(s) && s > 0 ? Math.max(1, Math.min(10, Math.round(s))) : null,
|
get(r, 'sector', 100) || null, Number.isFinite(s) && s > 0 ? Math.max(1, Math.min(10, Math.round(s))) : null,
|
||||||
// RGPD : on garde toujours l'origine de la donnée
|
// RGPD : on garde toujours l'origine de la donnée
|
||||||
httpUrl(get(r, 'source', 300)) || get(r, 'source', 300) || `Import CSV du ${dateLabel}`, get(r, 'hook', 400) || null, at,
|
httpUrl(get(r, 'source', 300)) || get(r, 'source', 300) || `Import CSV du ${dateLabel}`, get(r, 'hook', 400) || null, at,
|
||||||
);
|
);
|
||||||
res.imported++;
|
res.imported++;
|
||||||
});
|
}
|
||||||
db.exec('COMMIT');
|
});
|
||||||
} catch (e) {
|
|
||||||
db.exec('ROLLBACK');
|
|
||||||
throw e;
|
|
||||||
}
|
|
||||||
return res;
|
return res;
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -17,16 +17,16 @@ export function isBusinessHours(date = new Date(), timeZone = 'Europe/Paris') {
|
||||||
const CANDIDATES_SQL = `FROM prospects WHERE project_id = ? AND status = 'sent' AND followup_at IS NULL
|
const CANDIDATES_SQL = `FROM prospects WHERE project_id = ? AND status = 'sent' AND followup_at IS NULL
|
||||||
AND sent_at <= ? AND email NOT IN (SELECT email FROM blacklist)`;
|
AND sent_at <= ? AND email NOT IN (SELECT email FROM blacklist)`;
|
||||||
|
|
||||||
export function followupCandidates(db, project, { at = now(), limit = 100 } = {}) {
|
export async function followupCandidates(db, project, { at = now(), limit = 100 } = {}) {
|
||||||
const cutoff = at - project.followupDays * 86400;
|
const cutoff = at - project.followupDays * 86400;
|
||||||
return db.prepare(`SELECT * ${CANDIDATES_SQL} ORDER BY sent_at, id LIMIT ?`).all(project.id, cutoff, limit);
|
return db.prepare(`SELECT * ${CANDIDATES_SQL} ORDER BY sent_at, id LIMIT ?`).all(project.id, cutoff, limit);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** @returns {{due: number, blockers: string[], inHours: boolean, ready: boolean}} */
|
/** @returns {{due: number, blockers: string[], inHours: boolean, ready: boolean}} */
|
||||||
export function followupPlan(db, project, { at = now(), date = new Date(at * 1000) } = {}) {
|
export async function followupPlan(db, project, { at = now(), date = new Date(at * 1000) } = {}) {
|
||||||
const blockers = [];
|
const blockers = [];
|
||||||
if (!project.followupEnabled) blockers.push('relance désactivée');
|
if (!project.followupEnabled) blockers.push('relance désactivée');
|
||||||
if (!getTemplate(db, project.id, 'followup', { validatedOnly: true })) blockers.push('modèle de relance à valider');
|
if (!(await getTemplate(db, project.id, 'followup', { validatedOnly: true }))) blockers.push('modèle de relance à valider');
|
||||||
if (!project.hasSmtp) blockers.push('SMTP à configurer');
|
if (!project.hasSmtp) blockers.push('SMTP à configurer');
|
||||||
// Sans lecture de la boîte, on relancerait des gens qui ont déjà répondu
|
// Sans lecture de la boîte, on relancerait des gens qui ont déjà répondu
|
||||||
const inbox = project.inbox || {};
|
const inbox = project.inbox || {};
|
||||||
|
|
@ -34,7 +34,7 @@ export function followupPlan(db, project, { at = now(), date = new Date(at * 100
|
||||||
else if (inbox.lastError || !inbox.lastOk || at - inbox.lastOk > INBOX_MAX_AGE) blockers.push('boîte non vérifiée récemment');
|
else if (inbox.lastError || !inbox.lastOk || at - inbox.lastOk > INBOX_MAX_AGE) blockers.push('boîte non vérifiée récemment');
|
||||||
|
|
||||||
const cutoff = at - project.followupDays * 86400;
|
const cutoff = at - project.followupDays * 86400;
|
||||||
const due = db.prepare(`SELECT COUNT(*) n ${CANDIDATES_SQL}`).get(project.id, cutoff).n;
|
const due = (await db.prepare(`SELECT COUNT(*) n ${CANDIDATES_SQL}`).get(project.id, cutoff)).n;
|
||||||
const inHours = isBusinessHours(date);
|
const inHours = isBusinessHours(date);
|
||||||
return { due, blockers, inHours, ready: !blockers.length && inHours && due > 0 };
|
return { due, blockers, inHours, ready: !blockers.length && inHours && due > 0 };
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,11 +1,14 @@
|
||||||
// Clone / mise à jour des repos Forgejo. Clone superficiel (--depth 1) : léger sur le SSD.
|
// Clone / mise à jour des repos Forgejo. Clone superficiel (--depth 1) : léger sur le SSD.
|
||||||
// Le token passe par variables d'env GIT_CONFIG_* : jamais écrit dans .git/config, invisible dans `ps`.
|
// Le token passe par variables d'env GIT_CONFIG_* : jamais écrit dans .git/config, invisible dans `ps`.
|
||||||
import { execFile } from 'node:child_process';
|
// L'URL vient de l'utilisateur : https seulement, aucun hook ni sous-module, délai et taille bornés.
|
||||||
import { existsSync, rmSync, mkdirSync } from 'node:fs';
|
import { spawn } from 'node:child_process';
|
||||||
import { dirname } from 'node:path';
|
import { existsSync, readdirSync, rmSync, mkdirSync, statSync } from 'node:fs';
|
||||||
import { promisify } from 'node:util';
|
import { dirname, join } from 'node:path';
|
||||||
|
import { buildChildEnv } from './sandbox.js';
|
||||||
|
import { tmpdir } from 'node:os';
|
||||||
|
|
||||||
const run = promisify(execFile);
|
export const GIT_TIMEOUT_MS = 2 * 60_000;
|
||||||
|
export const GIT_MAX_BYTES = 300 * 1024 * 1024;
|
||||||
|
|
||||||
export function validateGitUrl(url, allowedHost) {
|
export function validateGitUrl(url, allowedHost) {
|
||||||
let u;
|
let u;
|
||||||
|
|
@ -17,8 +20,18 @@ export function validateGitUrl(url, allowedHost) {
|
||||||
return u.toString().replace(/\/$/, '');
|
return u.toString().replace(/\/$/, '');
|
||||||
}
|
}
|
||||||
|
|
||||||
function gitEnv(token) {
|
/**
|
||||||
const env = { ...process.env, GIT_TERMINAL_PROMPT: '0' };
|
* Environnement de git : liste blanche (aucun secret du serveur), https seulement, aucune configuration
|
||||||
|
* globale ou système lue, aucune invite.
|
||||||
|
*/
|
||||||
|
export function gitEnv(token, { parentEnv = process.env } = {}) {
|
||||||
|
const env = {
|
||||||
|
...buildChildEnv(parentEnv, { home: tmpdir() }),
|
||||||
|
GIT_TERMINAL_PROMPT: '0',
|
||||||
|
GIT_ALLOW_PROTOCOL: 'https',
|
||||||
|
GIT_CONFIG_NOSYSTEM: '1',
|
||||||
|
GIT_CONFIG_GLOBAL: process.platform === 'win32' ? 'NUL' : '/dev/null',
|
||||||
|
};
|
||||||
if (token) {
|
if (token) {
|
||||||
env.GIT_CONFIG_COUNT = '1';
|
env.GIT_CONFIG_COUNT = '1';
|
||||||
env.GIT_CONFIG_KEY_0 = 'http.extraHeader';
|
env.GIT_CONFIG_KEY_0 = 'http.extraHeader';
|
||||||
|
|
@ -27,20 +40,69 @@ function gitEnv(token) {
|
||||||
return env;
|
return env;
|
||||||
}
|
}
|
||||||
|
|
||||||
const opts = (token, cwd) => ({ env: gitEnv(token), cwd, timeout: 5 * 60_000, maxBuffer: 1024 * 1024 });
|
// Réglages passés à CHAQUE commande : pas de hooks (ni ceux du dépôt cloné), pas de sous-modules, https seul,
|
||||||
|
// pas de filtres ni de commandes externes déclenchées par le contenu du dépôt
|
||||||
|
export const GIT_HARDENING = [
|
||||||
|
'-c', 'protocol.allow=never', '-c', 'protocol.https.allow=always',
|
||||||
|
'-c', 'core.hooksPath=' + (process.platform === 'win32' ? 'NUL' : '/dev/null'),
|
||||||
|
'-c', 'core.fsmonitor=false', '-c', 'submodule.recurse=false', '-c', 'core.symlinks=false',
|
||||||
|
];
|
||||||
|
|
||||||
|
export const cloneArgs = (url, dir) => [...GIT_HARDENING, 'clone', '--depth', '1', '--single-branch', '--no-tags', '--no-recurse-submodules', url, dir];
|
||||||
|
export const fetchArgs = () => [...GIT_HARDENING, 'fetch', '--depth', '1', '--no-tags', '--no-recurse-submodules', 'origin', 'HEAD'];
|
||||||
|
|
||||||
|
/** Taille d'un dossier en octets (sans suivre les liens symboliques). Coupe court dès que `limit` est dépassé. */
|
||||||
|
export function dirSize(dir, limit = Infinity) {
|
||||||
|
let total = 0;
|
||||||
|
const stack = [dir];
|
||||||
|
while (stack.length && total <= limit) {
|
||||||
|
const d = stack.pop();
|
||||||
|
let entries;
|
||||||
|
try { entries = readdirSync(d, { withFileTypes: true }); } catch { continue; }
|
||||||
|
for (const e of entries) {
|
||||||
|
const p = join(d, e.name);
|
||||||
|
if (e.isDirectory()) stack.push(p);
|
||||||
|
else if (e.isFile()) { try { total += statSync(p).size; } catch { /* disparu */ } }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return total;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Lance git avec délai et taille bornés : au-delà, le processus est tué et le dossier surveillé effacé par l'appelant
|
||||||
|
function runGit(args, { token, cwd, watchDir, timeoutMs = GIT_TIMEOUT_MS, maxBytes = GIT_MAX_BYTES, gitBin = 'git' }) {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
const child = spawn(gitBin, args, { env: gitEnv(token), cwd, stdio: ['ignore', 'pipe', 'pipe'] });
|
||||||
|
let stdout = '', stderr = '', killed = null;
|
||||||
|
const kill = (why) => { killed = why; child.kill('SIGKILL'); };
|
||||||
|
const timer = setTimeout(() => kill('Délai dépassé'), timeoutMs);
|
||||||
|
const size = watchDir ? setInterval(() => { if (dirSize(watchDir, maxBytes) > maxBytes) kill('Dépôt trop volumineux'); }, 1500) : null;
|
||||||
|
child.stdout.on('data', (c) => { stdout = (stdout + c).slice(-8000); });
|
||||||
|
child.stderr.on('data', (c) => { stderr = (stderr + c).slice(-8000); });
|
||||||
|
child.on('error', (e) => { clearTimeout(timer); clearInterval(size); reject(Object.assign(e, { stderr })); });
|
||||||
|
child.on('close', (code) => {
|
||||||
|
clearTimeout(timer); clearInterval(size);
|
||||||
|
if (killed) return reject(Object.assign(new Error(killed), { stderr: killed }));
|
||||||
|
if (code !== 0) return reject(Object.assign(new Error(`git a échoué (code ${code})`), { stderr }));
|
||||||
|
resolve({ stdout });
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
// Clone ou met à jour. Retourne le hash du commit HEAD.
|
// Clone ou met à jour. Retourne le hash du commit HEAD.
|
||||||
export async function syncRepo(url, dir, token) {
|
export async function syncRepo(url, dir, token, opts = {}) {
|
||||||
try {
|
try {
|
||||||
|
// L'URL est relue en base : on revalide ici (pas de file://, ext::, ssh) quel que soit l'appelant
|
||||||
|
url = validateGitUrl(url);
|
||||||
if (existsSync(`${dir}/.git`)) {
|
if (existsSync(`${dir}/.git`)) {
|
||||||
await run('git', ['fetch', '--depth', '1', 'origin', 'HEAD'], opts(token, dir));
|
await runGit(fetchArgs(), { token, cwd: dir, watchDir: dir, ...opts });
|
||||||
await run('git', ['reset', '--hard', 'FETCH_HEAD'], opts(token, dir));
|
await runGit([...GIT_HARDENING, 'reset', '--hard', 'FETCH_HEAD'], { token, cwd: dir, ...opts });
|
||||||
} else {
|
} else {
|
||||||
rmSync(dir, { recursive: true, force: true });
|
rmSync(dir, { recursive: true, force: true });
|
||||||
mkdirSync(dirname(dir), { recursive: true });
|
mkdirSync(dirname(dir), { recursive: true });
|
||||||
await run('git', ['clone', '--depth', '1', '--single-branch', url, dir], opts(token));
|
try { await runGit(cloneArgs(url, dir), { token, watchDir: dir, ...opts }); }
|
||||||
|
catch (e) { rmSync(dir, { recursive: true, force: true }); throw e; }
|
||||||
}
|
}
|
||||||
const { stdout } = await run('git', ['rev-parse', 'HEAD'], opts(null, dir));
|
const { stdout } = await runGit([...GIT_HARDENING, 'rev-parse', 'HEAD'], { cwd: dir, ...opts });
|
||||||
return stdout.trim();
|
return stdout.trim();
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
// On ne remonte jamais stderr brut (pourrait contenir l'en-tête d'auth)
|
// On ne remonte jamais stderr brut (pourrait contenir l'en-tête d'auth)
|
||||||
|
|
|
||||||
|
|
@ -48,7 +48,7 @@ export function classify(msg) {
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Applique une liste de messages aux prospects du projet. Idempotent. */
|
/** Applique une liste de messages aux prospects du projet. Idempotent. */
|
||||||
export function applyMessages(db, projectId, messages, { at = now() } = {}) {
|
export async function applyMessages(db, projectId, messages, { at = now() } = {}) {
|
||||||
const res = { replies: 0, bounces: 0, ignored: 0 };
|
const res = { replies: 0, bounces: 0, ignored: 0 };
|
||||||
const byMsgId = db.prepare('SELECT prospect_id FROM mail_log WHERE project_id = ? AND message_id = ? AND prospect_id IS NOT NULL LIMIT 1');
|
const byMsgId = db.prepare('SELECT prospect_id FROM mail_log WHERE project_id = ? AND message_id = ? AND prospect_id IS NOT NULL LIMIT 1');
|
||||||
const byEmail = db.prepare('SELECT id FROM prospects WHERE project_id = ? AND email = ? LIMIT 1');
|
const byEmail = db.prepare('SELECT id FROM prospects WHERE project_id = ? AND email = ? LIMIT 1');
|
||||||
|
|
@ -57,30 +57,30 @@ export function applyMessages(db, projectId, messages, { at = now() } = {}) {
|
||||||
const markBounce = db.prepare("UPDATE prospects SET status = 'bounced' WHERE id = ? AND status = 'sent'");
|
const markBounce = db.prepare("UPDATE prospects SET status = 'bounced' WHERE id = ? AND status = 'sent'");
|
||||||
const blacklist = db.prepare("INSERT OR IGNORE INTO blacklist(email, reason, created_at) SELECT email, 'bounce', ? FROM prospects WHERE id = ?");
|
const blacklist = db.prepare("INSERT OR IGNORE INTO blacklist(email, reason, created_at) SELECT email, 'bounce', ? FROM prospects WHERE id = ?");
|
||||||
|
|
||||||
const fromIds = (list) => {
|
const fromIds = async (list) => {
|
||||||
for (const id of list) { const r = byMsgId.get(projectId, id); if (r) return r.prospect_id; }
|
for (const id of list) { const r = await byMsgId.get(projectId, id); if (r) return r.prospect_id; }
|
||||||
return null;
|
return null;
|
||||||
};
|
};
|
||||||
|
|
||||||
for (const msg of messages) {
|
for (const msg of messages) {
|
||||||
const c = classify(msg);
|
const c = classify(msg);
|
||||||
if (c.type === 'bounce') {
|
if (c.type === 'bounce') {
|
||||||
const pid = fromIds(c.ids);
|
const pid = await fromIds(c.ids);
|
||||||
if (pid && markBounce.run(pid).changes) { blacklist.run(at, pid); res.bounces++; } else res.ignored++;
|
if (pid && (await markBounce.run(pid)).changes) { await blacklist.run(at, pid); res.bounces++; } else res.ignored++;
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
if (c.type === 'auto') { res.ignored++; continue; }
|
if (c.type === 'auto') { res.ignored++; continue; }
|
||||||
|
|
||||||
// Réponse : 1) fil de discussion, 2) même adresse, 3) même domaine pro (un seul prospect en attente dessus)
|
// Réponse : 1) fil de discussion, 2) même adresse, 3) même domaine pro (un seul prospect en attente dessus)
|
||||||
let pid = fromIds(c.ids) ?? byEmail.get(projectId, c.from)?.id ?? null;
|
let pid = (await fromIds(c.ids)) ?? (await byEmail.get(projectId, c.from))?.id ?? null;
|
||||||
if (!pid) {
|
if (!pid) {
|
||||||
const domain = c.from.split('@')[1];
|
const domain = c.from.split('@')[1];
|
||||||
if (domain && !GENERIC_DOMAINS.has(domain)) {
|
if (domain && !GENERIC_DOMAINS.has(domain)) {
|
||||||
const rows = byDomain.all(projectId, domain);
|
const rows = await byDomain.all(projectId, domain);
|
||||||
if (rows.length === 1) pid = rows[0].id;
|
if (rows.length === 1) pid = rows[0].id;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (pid && markReply.run(at, String(msg.subject || '').slice(0, 300), pid).changes) res.replies++;
|
if (pid && (await markReply.run(at, String(msg.subject || '').slice(0, 300), pid)).changes) res.replies++;
|
||||||
else res.ignored++;
|
else res.ignored++;
|
||||||
}
|
}
|
||||||
return res;
|
return res;
|
||||||
|
|
@ -143,25 +143,25 @@ export async function fetchInbox(creds, state, { since, max = 500 }) {
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Vérifie la boîte d'un projet et mémorise l'état (dernier UID, erreurs, compteurs). */
|
/** Vérifie la boîte d'un projet et mémorise l'état (dernier UID, erreurs, compteurs). */
|
||||||
export async function checkInbox(app, projectId) {
|
export async function checkInbox(app, userId, projectId) {
|
||||||
const { db } = app;
|
const { db } = app;
|
||||||
const project = getProject(app, projectId, { secrets: true });
|
const project = await getProject(app, projectId, { userId, secrets: true });
|
||||||
if (!project.imap) throw new Error('Boîte IMAP non configurée');
|
if (!project.imap) throw new Error('Boîte IMAP non configurée');
|
||||||
const state = project.inbox || {};
|
const state = project.inbox || {};
|
||||||
const firstSent = db.prepare('SELECT MIN(sent_at) t FROM mail_log WHERE project_id = ?').get(project.id).t;
|
const firstSent = (await db.prepare('SELECT MIN(sent_at) t FROM mail_log WHERE project_id = ?').get(project.id)).t;
|
||||||
const since = new Date(((firstSent || now()) - 86400) * 1000);
|
const since = new Date(((firstSent || now()) - 86400) * 1000);
|
||||||
const at = now();
|
const at = now();
|
||||||
const save = (s) => db.prepare('UPDATE projects SET inbox_json = ? WHERE id = ?').run(JSON.stringify(s), project.id);
|
const save = (s) => db.prepare('UPDATE projects SET inbox_json = ? WHERE id = ?').run(JSON.stringify(s), project.id);
|
||||||
try {
|
try {
|
||||||
const r = await (app.fetchInbox || fetchInbox)(project.imap, state, { since });
|
const r = await (app.fetchInbox || fetchInbox)(project.imap, state, { since });
|
||||||
const res = applyMessages(db, project.id, r.messages, { at });
|
const res = await applyMessages(db, project.id, r.messages, { at });
|
||||||
save({
|
await save({
|
||||||
uidValidity: r.uidValidity, lastUid: r.lastUid, lastCheck: at, lastOk: at, lastError: null,
|
uidValidity: r.uidValidity, lastUid: r.lastUid, lastCheck: at, lastOk: at, lastError: null,
|
||||||
replies: (state.replies || 0) + res.replies, bounces: (state.bounces || 0) + res.bounces,
|
replies: (state.replies || 0) + res.replies, bounces: (state.bounces || 0) + res.bounces,
|
||||||
});
|
});
|
||||||
if (res.replies) {
|
if (res.replies) {
|
||||||
const who = db.prepare('SELECT company, email, reply_subject FROM prospects WHERE project_id = ? AND replied_at = ? LIMIT 10').all(project.id, at);
|
const who = await db.prepare('SELECT company, email, reply_subject FROM prospects WHERE project_id = ? AND replied_at = ? LIMIT 10').all(project.id, at);
|
||||||
await notify(app, 'reply', {
|
await notify(app, userId, 'reply', {
|
||||||
title: `${project.name} · ${res.replies} réponse(s) de prospect`, level: 'ok',
|
title: `${project.name} · ${res.replies} réponse(s) de prospect`, level: 'ok',
|
||||||
description: who.map((p) => `**${p.company}** (${p.email}) : ${p.reply_subject || 'sans objet'}`).join('\n'),
|
description: who.map((p) => `**${p.company}** (${p.email}) : ${p.reply_subject || 'sans objet'}`).join('\n'),
|
||||||
});
|
});
|
||||||
|
|
@ -169,7 +169,7 @@ export async function checkInbox(app, projectId) {
|
||||||
return res;
|
return res;
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
const msg = String(e.responseText || e.message || e).slice(0, 300);
|
const msg = String(e.responseText || e.message || e).slice(0, 300);
|
||||||
save({ ...state, lastCheck: at, lastError: msg });
|
await save({ ...state, lastCheck: at, lastError: msg });
|
||||||
throw new Error(`IMAP : ${msg}`);
|
throw new Error(`IMAP : ${msg}`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,30 +1,66 @@
|
||||||
// File de jobs dans SQLite, UN seul worker : un seul `claude` à la fois sur le Pi.
|
// File de jobs en base, UN seul worker : un seul `claude` à la fois.
|
||||||
import { now } from '../db.js';
|
import { now } from '../db.js';
|
||||||
|
import { HttpError } from '../http.js';
|
||||||
|
import { AI_JOBS } from './budget.js';
|
||||||
|
import { getUser } from '../users.js';
|
||||||
|
import { aiRefusal, assertCanRunAi } from '../claudelink.js';
|
||||||
import { waitCool } from './thermal.js';
|
import { waitCool } from './thermal.js';
|
||||||
|
|
||||||
export function enqueue(db, { projectId, type, params = {}, runAfter = null }) {
|
/**
|
||||||
const running = db.prepare(
|
* Met un job en file pour un utilisateur. Point de passage obligé de toutes les routes et tâches de fond :
|
||||||
"SELECT id FROM jobs WHERE project_id IS ? AND type = ? AND status IN ('queued','running')"
|
* - le projet doit appartenir à l'utilisateur (sinon 404) ;
|
||||||
).get(projectId ?? null, type);
|
* - un compte suspendu ne met rien en file ;
|
||||||
|
* - un job IA exige une liaison Claude valide de CET utilisateur.
|
||||||
|
* Sans projet, `userId` est obligatoire. `opts.cliModeEnabled` : drapeau CLAUDE_CLI_MODE_ENABLED (vrai par défaut).
|
||||||
|
*/
|
||||||
|
export async function enqueue(db, { userId, projectId, type, params = {}, runAfter = null }, opts = {}) {
|
||||||
|
if (projectId != null) {
|
||||||
|
const owner = await db.prepare('SELECT user_id FROM projects WHERE id = ?').get(projectId);
|
||||||
|
if (!owner || (userId != null && Number(owner.user_id) !== Number(userId))) throw new HttpError(404, 'Projet introuvable');
|
||||||
|
userId = Number(owner.user_id);
|
||||||
|
}
|
||||||
|
const user = userId == null ? null : await getUser(db, userId);
|
||||||
|
if (!user) throw new Error('enqueue : utilisateur requis');
|
||||||
|
if (user.status !== 'active') throw new HttpError(403, 'Compte suspendu');
|
||||||
|
if (AI_JOBS.has(type)) await assertCanRunAi(db, user.id, opts);
|
||||||
|
// Deux écritures de la même condition : "= ?" ne marche pas avec NULL, et "IS ?" n'existe pas en MySQL
|
||||||
|
const running = projectId == null
|
||||||
|
? await db.prepare("SELECT id FROM jobs WHERE user_id = ? AND project_id IS NULL AND type = ? AND status IN ('queued','running')").get(user.id, type)
|
||||||
|
: await db.prepare("SELECT id FROM jobs WHERE project_id = ? AND type = ? AND status IN ('queued','running')").get(projectId, type);
|
||||||
if (running) return { id: running.id, existing: true };
|
if (running) return { id: running.id, existing: true };
|
||||||
const r = db.prepare('INSERT INTO jobs(project_id, type, params_json, created_at, run_after) VALUES(?, ?, ?, ?, ?)')
|
const r = await db.prepare('INSERT INTO jobs(user_id, project_id, type, params_json, created_at, run_after) VALUES(?, ?, ?, ?, ?, ?)')
|
||||||
.run(projectId ?? null, type, JSON.stringify(params), now(), runAfter);
|
.run(user.id, projectId ?? null, type, JSON.stringify(params), now(), runAfter);
|
||||||
return { id: Number(r.lastInsertRowid), existing: false };
|
return { id: Number(r.lastInsertRowid), existing: false };
|
||||||
}
|
}
|
||||||
|
|
||||||
export function setProgress(db, jobId, progress) {
|
/**
|
||||||
db.prepare('UPDATE jobs SET progress_json = ? WHERE id = ?').run(JSON.stringify(progress), jobId);
|
* Un job peut-il s'exécuter ? Renvoie la raison du refus, ou null. Revérifié par le worker à chaque
|
||||||
|
* exécution (la file peut contenir un job mis en attente avant une suspension, un changement de rôle ou une déliaison).
|
||||||
|
*/
|
||||||
|
export async function jobRefusal(db, job, opts = {}) {
|
||||||
|
const user = await getUser(db, job.user_id);
|
||||||
|
if (!user) return 'Compte supprimé';
|
||||||
|
if (user.status !== 'active') return 'Compte suspendu';
|
||||||
|
if (AI_JOBS.has(job.type)) return aiRefusal(db, job.user_id, opts);
|
||||||
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function cancelJob(db, jobId) {
|
export async function setProgress(db, jobId, progress) {
|
||||||
db.prepare("UPDATE jobs SET status = 'cancelled', finished_at = ? WHERE id = ? AND status IN ('queued','running')")
|
await db.prepare('UPDATE jobs SET progress_json = ? WHERE id = ?').run(JSON.stringify(progress), jobId);
|
||||||
.run(now(), jobId);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export function latestJobs(db, projectId) {
|
/** Annule un job de l'utilisateur ; un job d'un autre compte est introuvable. */
|
||||||
const rows = db.prepare(`
|
export async function cancelJob(db, userId, jobId) {
|
||||||
|
const r = await db.prepare("UPDATE jobs SET status = 'cancelled', finished_at = ? WHERE id = ? AND user_id = ? AND status IN ('queued','running')")
|
||||||
|
.run(now(), jobId, userId);
|
||||||
|
if (!r.changes && !(await db.prepare('SELECT 1 FROM jobs WHERE id = ? AND user_id = ?').get(jobId, userId))) throw new HttpError(404, 'Job introuvable');
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Derniers jobs d'un projet (le projet doit déjà avoir été vérifié comme appartenant à l'utilisateur). */
|
||||||
|
export async function latestJobs(db, projectId) {
|
||||||
|
const rows = await db.prepare(`
|
||||||
SELECT j.* FROM jobs j
|
SELECT j.* FROM jobs j
|
||||||
JOIN (SELECT type, MAX(id) id FROM jobs WHERE project_id = ? GROUP BY type) last ON last.id = j.id
|
JOIN (SELECT type, MAX(id) id FROM jobs WHERE project_id = ? GROUP BY type) lj ON lj.id = j.id
|
||||||
`).all(projectId);
|
`).all(projectId);
|
||||||
const out = {};
|
const out = {};
|
||||||
for (const r of rows) {
|
for (const r of rows) {
|
||||||
|
|
@ -41,98 +77,146 @@ export function latestJobs(db, projectId) {
|
||||||
export class Worker {
|
export class Worker {
|
||||||
constructor(db, handlers, {
|
constructor(db, handlers, {
|
||||||
thermalMax = 75, pollMs = 3000, log = console, clock = now, onFinish, onThermal,
|
thermalMax = 75, pollMs = 3000, log = console, clock = now, onFinish, onThermal,
|
||||||
budget, isAiJob, onBudget, quota, isQuotaSensitive, onQuotaHold,
|
budget, isAiJob, onBudget, quota, isQuotaSensitive, onQuotaHold, cliModeEnabled = true,
|
||||||
} = {}) {
|
} = {}) {
|
||||||
|
this.cliModeEnabled = cliModeEnabled;
|
||||||
this.clock = clock;
|
this.clock = clock;
|
||||||
this.budget = budget; // () => {blocked, reason}
|
this.budget = budget; // async (userId) => {blocked, reason} : budget de CET utilisateur
|
||||||
this.isAiJob = isAiJob; // (type) => bool : jobs à mettre en attente si budget ($ équivalent) atteint
|
this.isAiJob = isAiJob; // (type) => bool : jobs à mettre en attente si budget ($ équivalent) atteint
|
||||||
this.onBudget = onBudget; // (reason) → une notif quand le blocage commence
|
this.onBudget = onBudget; // (reason, userId) → une notif quand le blocage commence
|
||||||
this.budgetBlocked = false;
|
this.budgetBlocked = new Set(); // utilisateurs dont les jobs IA attendent (budget)
|
||||||
this.quota = quota; // () => {blocked, reason} : quota du compte Claude lui-même (session/semaine)
|
this.quota = quota; // async (userId) => {blocked, reason} : quota du compte Claude lui-même (session/semaine)
|
||||||
this.isQuotaSensitive = isQuotaSensitive; // (type) => bool : jobs à reporter si le quota est serré (pas la prospection/l'envoi)
|
this.isQuotaSensitive = isQuotaSensitive; // (type) => bool : jobs à reporter si le quota est serré (pas la prospection/l'envoi)
|
||||||
this.onQuotaHold = onQuotaHold; // (reason) → une notif quand le report commence
|
this.onQuotaHold = onQuotaHold; // (reason, userId) → une notif quand le report commence
|
||||||
this.quotaBlocked = false;
|
this.quotaBlocked = new Set();
|
||||||
this.onFinish = onFinish; // (job, {status, result, error}) → notifications
|
this.onFinish = onFinish; // (job, {status, result, error}) → notifications
|
||||||
this.onThermal = onThermal; // (°C) → une fois par pause
|
this.onThermal = onThermal; // (°C, userId) → une fois par pause
|
||||||
this.db = db;
|
this.db = db;
|
||||||
this.handlers = handlers;
|
this.handlers = handlers;
|
||||||
this.thermalMax = thermalMax;
|
this.thermalMax = thermalMax;
|
||||||
this.pollMs = pollMs;
|
this.pollMs = pollMs;
|
||||||
this.log = log;
|
this.log = log;
|
||||||
this.current = null;
|
this.current = null;
|
||||||
|
this.currentJob = null;
|
||||||
this.stopped = false;
|
this.stopped = false;
|
||||||
|
this.pending = new Set(); // callbacks de notification en vol (attendus à l'arrêt)
|
||||||
|
this.loopDone = null;
|
||||||
|
this.wake = null;
|
||||||
}
|
}
|
||||||
|
|
||||||
start() {
|
async start() {
|
||||||
// Un job "running" au démarrage = crash/reboot pendant l'exécution
|
// Un job "running" au démarrage = crash/reboot pendant l'exécution
|
||||||
this.db.prepare("UPDATE jobs SET status = 'error', error = 'Interrompu (redémarrage)', finished_at = ? WHERE status = 'running'").run(now());
|
await this.db.prepare("UPDATE jobs SET status = 'error', error = 'Interrompu (redémarrage)', finished_at = ? WHERE status = 'running'").run(now());
|
||||||
this.loop();
|
this.loopDone = this.loop();
|
||||||
}
|
}
|
||||||
|
|
||||||
stop() { this.stopped = true; this.current?.abort(); }
|
/** Arrête la boucle et attend le job en cours ainsi que les notifications en vol. */
|
||||||
|
async stop() {
|
||||||
|
this.stopped = true;
|
||||||
|
this.current?.abort();
|
||||||
|
this.wake?.();
|
||||||
|
await this.loopDone;
|
||||||
|
await this.idle();
|
||||||
|
}
|
||||||
|
|
||||||
// Les callbacks ne doivent jamais bloquer ni faire tomber le worker
|
/** Interrompt le job en cours s'il appartient à cet utilisateur (suppression du compte). */
|
||||||
|
abortUser(userId) {
|
||||||
|
if (this.currentJob && Number(this.currentJob.user_id) === Number(userId)) this.current?.abort();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Interrompt le job en cours s'il est un job IA de cet utilisateur (déliaison de son accès Claude). */
|
||||||
|
abortUserAi(userId) {
|
||||||
|
if (this.currentJob && Number(this.currentJob.user_id) === Number(userId) && this.isAiJob?.(this.currentJob.type)) this.current?.abort();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Attend les callbacks (notifications) lancés par emit(). */
|
||||||
|
async idle() {
|
||||||
|
while (this.pending.size) await Promise.allSettled([...this.pending]);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Les callbacks ne doivent jamais bloquer ni faire tomber le worker : lancés sans attendre,
|
||||||
|
// mais suivis (idle/stop les attendent) et leurs erreurs journalisées.
|
||||||
emit(name, ...args) {
|
emit(name, ...args) {
|
||||||
try { Promise.resolve(this[name]?.(...args)).catch((e) => this.log.error(`[${name}]`, e.message)); }
|
let p;
|
||||||
catch (e) { this.log.error(`[${name}]`, e.message); }
|
try { p = Promise.resolve(this[name]?.(...args)); }
|
||||||
|
catch (e) { this.log.error(`[${name}]`, e.message); return; }
|
||||||
|
const tracked = p.catch((e) => this.log.error(`[${name}]`, e.message)).finally(() => this.pending.delete(tracked));
|
||||||
|
this.pending.add(tracked);
|
||||||
}
|
}
|
||||||
|
|
||||||
isCancelled(jobId) {
|
async isCancelled(jobId) {
|
||||||
return this.db.prepare('SELECT status FROM jobs WHERE id = ?').get(jobId)?.status === 'cancelled';
|
return (await this.db.prepare('SELECT status FROM jobs WHERE id = ?').get(jobId))?.status === 'cancelled';
|
||||||
}
|
}
|
||||||
|
|
||||||
async loop() {
|
async loop() {
|
||||||
while (!this.stopped) {
|
while (!this.stopped) {
|
||||||
const ran = await this.tick();
|
let ran = false;
|
||||||
if (!ran) await new Promise((r) => setTimeout(r, this.pollMs));
|
try { ran = await this.tick(); }
|
||||||
|
catch (e) { this.log.error('[worker]', e.message); } // base indisponible : on réessaie au prochain passage
|
||||||
|
if (!ran && !this.stopped) {
|
||||||
|
await new Promise((r) => { this.wake = r; setTimeout(r, this.pollMs).unref(); });
|
||||||
|
this.wake = null;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async tick() {
|
async tick() {
|
||||||
const due = this.db.prepare(`SELECT * FROM jobs WHERE status = 'queued'
|
const due = await this.db.prepare(`SELECT * FROM jobs WHERE status = 'queued'
|
||||||
AND (run_after IS NULL OR run_after <= ?) ORDER BY id`).all(this.clock());
|
AND (run_after IS NULL OR run_after <= ?) ORDER BY id`).all(this.clock());
|
||||||
if (!due.length) return false;
|
if (!due.length) return false;
|
||||||
|
|
||||||
// Budget $ atteint ou quota du compte Claude serré : les jobs concernés restent en file
|
// Budget $ atteint ou quota du compte Claude serré : les jobs concernés restent en file
|
||||||
// (pas perdus), les autres passent devant. Deux garde-fous indépendants, deux périmètres :
|
// (pas perdus), les autres passent devant. Deux garde-fous indépendants, deux périmètres :
|
||||||
// le budget met en pause TOUS les jobs IA, le quota ne retarde que les jobs non urgents
|
// le budget met en pause TOUS les jobs IA, le quota ne retarde que les jobs non urgents
|
||||||
// (analyse, évolutions) — la prospection et les envois continuent.
|
// (analyse, évolutions) — la prospection et les envois continuent. Chaque utilisateur a les siens.
|
||||||
const budget = this.budget?.() || { blocked: false };
|
const budgets = new Map(), quotas = new Map();
|
||||||
const quota = this.quota?.() || { blocked: false };
|
const perUser = async (cache, fn, userId) => {
|
||||||
const hold = (j, reason) => {
|
if (!cache.has(userId)) cache.set(userId, (await fn?.(userId)) || { blocked: false });
|
||||||
|
return cache.get(userId);
|
||||||
|
};
|
||||||
|
const hold = async (j, reason) => {
|
||||||
const msg = JSON.stringify({ message: `En attente : ${reason}` });
|
const msg = JSON.stringify({ message: `En attente : ${reason}` });
|
||||||
if (j.progress_json !== msg) this.db.prepare('UPDATE jobs SET progress_json = ? WHERE id = ?').run(msg, j.id);
|
if (j.progress_json !== msg) await this.db.prepare('UPDATE jobs SET progress_json = ? WHERE id = ?').run(msg, j.id);
|
||||||
};
|
};
|
||||||
let job = null;
|
let job = null;
|
||||||
let waiting = false, quotaWaiting = false;
|
const waiting = new Map(), quotaWaiting = new Map();
|
||||||
for (const j of due) {
|
for (const j of due) {
|
||||||
if (budget.blocked && this.isAiJob?.(j.type)) { waiting = true; hold(j, budget.reason); continue; }
|
// Compte suspendu ou supprimé, job IA sans liaison Claude valide : refusé sans exécution
|
||||||
if (quota.blocked && this.isQuotaSensitive?.(j.type)) { quotaWaiting = true; hold(j, quota.reason); continue; }
|
const refusal = await jobRefusal(this.db, j, { cliModeEnabled: this.cliModeEnabled });
|
||||||
|
if (refusal) {
|
||||||
|
await this.db.prepare("UPDATE jobs SET status = 'error', error = ?, finished_at = ? WHERE id = ? AND status = 'queued'").run(refusal, now(), j.id);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const budget = await perUser(budgets, this.budget, j.user_id);
|
||||||
|
if (budget.blocked && this.isAiJob?.(j.type)) { waiting.set(j.user_id, budget.reason); await hold(j, budget.reason); continue; }
|
||||||
|
const quota = await perUser(quotas, this.quota, j.user_id);
|
||||||
|
if (quota.blocked && this.isQuotaSensitive?.(j.type)) { quotaWaiting.set(j.user_id, quota.reason); await hold(j, quota.reason); continue; }
|
||||||
job = j;
|
job = j;
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
if (waiting && !this.budgetBlocked) this.emit('onBudget', budget.reason);
|
for (const [userId, reason] of waiting) if (!this.budgetBlocked.has(userId)) this.emit('onBudget', reason, userId);
|
||||||
this.budgetBlocked = waiting;
|
this.budgetBlocked = new Set(waiting.keys());
|
||||||
if (quotaWaiting && !this.quotaBlocked) this.emit('onQuotaHold', quota.reason);
|
for (const [userId, reason] of quotaWaiting) if (!this.quotaBlocked.has(userId)) this.emit('onQuotaHold', reason, userId);
|
||||||
this.quotaBlocked = quotaWaiting;
|
this.quotaBlocked = new Set(quotaWaiting.keys());
|
||||||
if (!job) return false;
|
if (!job) return false;
|
||||||
const handler = this.handlers[job.type];
|
const handler = this.handlers[job.type];
|
||||||
if (!handler) {
|
if (!handler) {
|
||||||
this.db.prepare("UPDATE jobs SET status='error', error=?, finished_at=? WHERE id=?").run(`Type inconnu : ${job.type}`, now(), job.id);
|
await this.db.prepare("UPDATE jobs SET status='error', error=?, finished_at=? WHERE id=?").run(`Type inconnu : ${job.type}`, now(), job.id);
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
let warned = false;
|
let warned = false;
|
||||||
await waitCool(this.thermalMax, {
|
await waitCool(this.thermalMax, {
|
||||||
onWait: (t) => {
|
onWait: async (t) => {
|
||||||
setProgress(this.db, job.id, { message: `Pause thermique (${t} °C)` });
|
await setProgress(this.db, job.id, { message: `Pause thermique (${t} °C)` });
|
||||||
if (!warned) { warned = true; this.emit('onThermal', t); }
|
if (!warned) { warned = true; this.emit('onThermal', t, job.user_id); }
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
this.db.prepare("UPDATE jobs SET status='running', started_at=? WHERE id=? AND status='queued'").run(now(), job.id);
|
await this.db.prepare("UPDATE jobs SET status='running', started_at=? WHERE id=? AND status='queued'").run(now(), job.id);
|
||||||
const ctrl = new AbortController();
|
const ctrl = new AbortController();
|
||||||
this.current = ctrl;
|
this.current = ctrl;
|
||||||
|
this.currentJob = job;
|
||||||
const ctx = {
|
const ctx = {
|
||||||
job,
|
job,
|
||||||
params: JSON.parse(job.params_json || '{}'),
|
params: JSON.parse(job.params_json || '{}'),
|
||||||
|
|
@ -141,26 +225,29 @@ export class Worker {
|
||||||
cancelled: () => this.isCancelled(job.id),
|
cancelled: () => this.isCancelled(job.id),
|
||||||
usage: { costUsd: 0, tokensIn: 0, tokensOut: 0 },
|
usage: { costUsd: 0, tokensIn: 0, tokensOut: 0 },
|
||||||
};
|
};
|
||||||
// Annulation depuis l'UI : on surveille la BDD
|
// Annulation depuis l'UI : on surveille la BDD (une erreur ici ne doit jamais faire tomber le process)
|
||||||
const watch = setInterval(() => { if (this.isCancelled(job.id)) ctrl.abort(); }, 2000);
|
const watch = setInterval(() => {
|
||||||
|
this.isCancelled(job.id).then((c) => { if (c) ctrl.abort(); }, () => {});
|
||||||
|
}, 2000);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const result = await handler(ctx);
|
const result = await handler(ctx);
|
||||||
if (!this.isCancelled(job.id)) {
|
if (!(await this.isCancelled(job.id))) {
|
||||||
this.db.prepare("UPDATE jobs SET status='done', result_json=?, finished_at=?, cost_usd=?, tokens_in=?, tokens_out=? WHERE id=?")
|
await this.db.prepare("UPDATE jobs SET status='done', result_json=?, finished_at=?, cost_usd=?, tokens_in=?, tokens_out=? WHERE id=?")
|
||||||
.run(JSON.stringify(result ?? null), now(), ctx.usage.costUsd, ctx.usage.tokensIn, ctx.usage.tokensOut, job.id);
|
.run(JSON.stringify(result ?? null), now(), ctx.usage.costUsd, ctx.usage.tokensIn, ctx.usage.tokensOut, job.id);
|
||||||
this.emit('onFinish', job, { status: 'done', result });
|
this.emit('onFinish', job, { status: 'done', result });
|
||||||
}
|
}
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
this.log.error(`[job ${job.id} ${job.type}]`, e.message);
|
this.log.error(`[job ${job.id} ${job.type}]`, e.message);
|
||||||
if (!this.isCancelled(job.id)) {
|
if (!(await this.isCancelled(job.id))) {
|
||||||
this.db.prepare("UPDATE jobs SET status='error', error=?, finished_at=?, cost_usd=?, tokens_in=?, tokens_out=? WHERE id=?")
|
await this.db.prepare("UPDATE jobs SET status='error', error=?, finished_at=?, cost_usd=?, tokens_in=?, tokens_out=? WHERE id=?")
|
||||||
.run(String(e.message).slice(0, 2000), now(), ctx.usage.costUsd, ctx.usage.tokensIn, ctx.usage.tokensOut, job.id);
|
.run(String(e.message).slice(0, 2000), now(), ctx.usage.costUsd, ctx.usage.tokensIn, ctx.usage.tokensOut, job.id);
|
||||||
this.emit('onFinish', job, { status: 'error', error: e.message });
|
this.emit('onFinish', job, { status: 'error', error: e.message });
|
||||||
}
|
}
|
||||||
} finally {
|
} finally {
|
||||||
clearInterval(watch);
|
clearInterval(watch);
|
||||||
this.current = null;
|
this.current = null;
|
||||||
|
this.currentJob = null;
|
||||||
}
|
}
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
@ -174,10 +261,10 @@ export function addUsage(ctx, r) {
|
||||||
}
|
}
|
||||||
|
|
||||||
// Conso des 30 derniers jours, pour la jauge (comptée à la fin du job, comme le budget)
|
// Conso des 30 derniers jours, pour la jauge (comptée à la fin du job, comme le budget)
|
||||||
export function usageSummary(db) {
|
export async function usageSummary(db, userId) {
|
||||||
const since = now() - 30 * 86400;
|
const since = now() - 30 * 86400;
|
||||||
const day = now() - 86400;
|
const day = now() - 86400;
|
||||||
const q = (s) => db.prepare(`SELECT COALESCE(SUM(cost_usd),0) cost, COALESCE(SUM(tokens_in),0) tin, COALESCE(SUM(tokens_out),0) tout, COUNT(*) n
|
const q = (s) => db.prepare(`SELECT COALESCE(SUM(cost_usd),0) cost, COALESCE(SUM(tokens_in),0) tin, COALESCE(SUM(tokens_out),0) tout, COUNT(*) n
|
||||||
FROM jobs WHERE COALESCE(finished_at, created_at) > ?`).get(s);
|
FROM jobs WHERE user_id = ? AND COALESCE(finished_at, created_at) > ?`).get(userId, s);
|
||||||
return { month: q(since), day: q(day) };
|
return { month: await q(since), day: await q(day) };
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -9,8 +9,8 @@ const pad = (n) => String(n).padStart(2, '0');
|
||||||
export const parisDay = (date = new Date()) => { const p = parisParts(date); return `${p.year}-${pad(p.month)}-${pad(p.day)}`; };
|
export const parisDay = (date = new Date()) => { const p = parisParts(date); return `${p.year}-${pad(p.month)}-${pad(p.day)}`; };
|
||||||
const num = (v) => (typeof v === 'number' && Number.isFinite(v) ? v : null);
|
const num = (v) => (typeof v === 'number' && Number.isFinite(v) ? v : null);
|
||||||
|
|
||||||
export function saveSnapshot(db, projectId, business, { date = new Date() } = {}) {
|
export async function saveSnapshot(db, projectId, business, { date = new Date() } = {}) {
|
||||||
db.prepare(`INSERT INTO metrics_daily(project_id, day, users, clients, revenue) VALUES(?, ?, ?, ?, ?)
|
await db.prepare(`INSERT INTO metrics_daily(project_id, day, users, clients, revenue) VALUES(?, ?, ?, ?, ?)
|
||||||
ON CONFLICT(project_id, day) DO UPDATE SET users = excluded.users, clients = excluded.clients, revenue = excluded.revenue`)
|
ON CONFLICT(project_id, day) DO UPDATE SET users = excluded.users, clients = excluded.clients, revenue = excluded.revenue`)
|
||||||
.run(projectId, parisDay(date), num(business.users), num(business.clients), num(business.revenue));
|
.run(projectId, parisDay(date), num(business.users), num(business.clients), num(business.revenue));
|
||||||
}
|
}
|
||||||
|
|
@ -18,13 +18,14 @@ export function saveSnapshot(db, projectId, business, { date = new Date() } = {}
|
||||||
/** Une photo par projet et par jour, appelée par le planificateur (toutes les 15 min, ne fait rien si déjà prise). */
|
/** Une photo par projet et par jour, appelée par le planificateur (toutes les 15 min, ne fait rien si déjà prise). */
|
||||||
export async function snapshotAll(app, { date = new Date(), log = console } = {}) {
|
export async function snapshotAll(app, { date = new Date(), log = console } = {}) {
|
||||||
const day = parisDay(date);
|
const day = parisDay(date);
|
||||||
const todo = app.db.prepare(`SELECT id FROM projects WHERE db_enc IS NOT NULL
|
const todo = await app.db.prepare(`SELECT p.id, p.user_id FROM projects p JOIN users u ON u.id = p.user_id
|
||||||
AND id NOT IN (SELECT project_id FROM metrics_daily WHERE day = ?)`).all(day);
|
WHERE p.db_enc IS NOT NULL AND u.status = 'active'
|
||||||
|
AND p.id NOT IN (SELECT project_id FROM metrics_daily WHERE day = ?)`).all(day);
|
||||||
let n = 0;
|
let n = 0;
|
||||||
for (const { id } of todo) {
|
for (const { id, user_id: userId } of todo) {
|
||||||
try {
|
try {
|
||||||
const p = getProject(app, id, { secrets: true });
|
const p = await getProject(app, id, { userId, secrets: true });
|
||||||
saveSnapshot(app.db, id, await (app.fetchRecap || fetchRecap)(id, p.dbCfg, { force: true }), { date });
|
await saveSnapshot(app.db, id, await (app.fetchRecap || fetchRecap)(id, p.dbCfg, { force: true }), { date });
|
||||||
n++;
|
n++;
|
||||||
} catch (e) { log.error(`[métriques ${id}]`, e.message); }
|
} catch (e) { log.error(`[métriques ${id}]`, e.message); }
|
||||||
}
|
}
|
||||||
|
|
@ -40,9 +41,9 @@ function weekStart(date) {
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Séries pour les graphiques : jours (KPI business) et semaines (envois / réponses). */
|
/** Séries pour les graphiques : jours (KPI business) et semaines (envois / réponses). */
|
||||||
export function history(db, projectId, { days = 30, at = now() } = {}) {
|
export async function history(db, projectId, { days = 30, at = now() } = {}) {
|
||||||
const fromDay = parisDay(new Date((at - (days - 1) * 86400) * 1000));
|
const fromDay = parisDay(new Date((at - (days - 1) * 86400) * 1000));
|
||||||
const daily = db.prepare('SELECT day, users, clients, revenue FROM metrics_daily WHERE project_id = ? AND day >= ? ORDER BY day')
|
const daily = await db.prepare('SELECT day, users, clients, revenue FROM metrics_daily WHERE project_id = ? AND day >= ? ORDER BY day')
|
||||||
.all(projectId, fromDay);
|
.all(projectId, fromDay);
|
||||||
|
|
||||||
const nWeeks = Math.ceil(days / 7);
|
const nWeeks = Math.ceil(days / 7);
|
||||||
|
|
@ -55,10 +56,10 @@ export function history(db, projectId, { days = 30, at = now() } = {}) {
|
||||||
const first = weeks[0].start.split('-').map(Number);
|
const first = weeks[0].start.split('-').map(Number);
|
||||||
const since = Math.floor(parisTime(first[0], first[1], first[2], 0).getTime() / 1000);
|
const since = Math.floor(parisTime(first[0], first[1], first[2], 0).getTime() / 1000);
|
||||||
const bucket = (ts) => weeks.find((w) => w.start === weekStart(new Date(ts * 1000)));
|
const bucket = (ts) => weeks.find((w) => w.start === weekStart(new Date(ts * 1000)));
|
||||||
for (const r of db.prepare("SELECT sent_at FROM mail_log WHERE project_id = ? AND kind = 'initial' AND error IS NULL AND sent_at >= ?").all(projectId, since)) {
|
for (const r of await db.prepare("SELECT sent_at FROM mail_log WHERE project_id = ? AND kind = 'initial' AND error IS NULL AND sent_at >= ?").all(projectId, since)) {
|
||||||
const w = bucket(r.sent_at); if (w) w.sent++;
|
const w = bucket(r.sent_at); if (w) w.sent++;
|
||||||
}
|
}
|
||||||
for (const r of db.prepare('SELECT replied_at FROM prospects WHERE project_id = ? AND replied_at >= ?').all(projectId, since)) {
|
for (const r of await db.prepare('SELECT replied_at FROM prospects WHERE project_id = ? AND replied_at >= ?').all(projectId, since)) {
|
||||||
const w = bucket(r.replied_at); if (w) w.replies++;
|
const w = bucket(r.replied_at); if (w) w.replies++;
|
||||||
}
|
}
|
||||||
return { daily, weeks };
|
return { daily, weeks };
|
||||||
|
|
|
||||||
|
|
@ -31,18 +31,18 @@ export function bar(done, total, width = 12) {
|
||||||
return `${'▰'.repeat(full)}${'▱'.repeat(width - full)} ${Math.round(r * 100)} %`;
|
return `${'▰'.repeat(full)}${'▱'.repeat(width - full)} ${Math.round(r * 100)} %`;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function notifyConfig(app) {
|
export async function notifyConfig(app, userId) {
|
||||||
let url = null;
|
let url = null;
|
||||||
try { url = decrypt(app.cfg.secretKey, getSetting(app.db, 'discord_webhook_enc')); }
|
try { url = decrypt(app.cfg.secretKey, await getSetting(app.db, userId, 'discord_webhook_enc')); }
|
||||||
catch { url = null; }
|
catch { url = null; }
|
||||||
const raw = getSetting(app.db, 'discord_events');
|
const raw = await getSetting(app.db, userId, 'discord_events');
|
||||||
const events = raw ? JSON.parse(raw) : Object.keys(EVENTS);
|
const events = raw ? JSON.parse(raw) : Object.keys(EVENTS);
|
||||||
return { url, events };
|
return { url, events };
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Envoie une notif si le webhook est configuré et l'événement activé. Ne lève jamais d'erreur. */
|
/** Envoie une notif si le webhook est configuré et l'événement activé. Ne lève jamais d'erreur. */
|
||||||
export async function notify(app, event, { title, description = '', level = 'info', fields = [], footer }, { force = false } = {}) {
|
export async function notify(app, userId, event, { title, description = '', level = 'info', fields = [], footer }, { force = false } = {}) {
|
||||||
const { url, events } = notifyConfig(app);
|
const { url, events } = await notifyConfig(app, userId);
|
||||||
if (!url || (!force && !events.includes(event))) return false;
|
if (!url || (!force && !events.includes(event))) return false;
|
||||||
const body = {
|
const body = {
|
||||||
username: 'AiTools',
|
username: 'AiTools',
|
||||||
|
|
@ -109,36 +109,36 @@ const DONE = {
|
||||||
const LABEL = { analyze: 'Analyse', prospect: 'Recherche', template: 'Modèle de mail', followup_template: 'Modèle de relance', send: 'Envoi', followup: 'Relances', evolution: 'Évolutions' };
|
const LABEL = { analyze: 'Analyse', prospect: 'Recherche', template: 'Modèle de mail', followup_template: 'Modèle de relance', send: 'Envoi', followup: 'Relances', evolution: 'Évolutions' };
|
||||||
|
|
||||||
// Durée et coût réels, relus en base une fois le job clos (absents dans les tests unitaires)
|
// Durée et coût réels, relus en base une fois le job clos (absents dans les tests unitaires)
|
||||||
function jobMeta(app, job) {
|
async function jobMeta(app, job) {
|
||||||
if (!job.id) return [];
|
if (!job.id) return [];
|
||||||
const row = app.db.prepare('SELECT started_at, finished_at, cost_usd FROM jobs WHERE id = ?').get(job.id);
|
const row = await app.db.prepare('SELECT started_at, finished_at, cost_usd FROM jobs WHERE id = ? AND user_id = ?').get(job.id, job.user_id);
|
||||||
const out = [];
|
const out = [];
|
||||||
if (row?.started_at && row?.finished_at) out.push({ name: '⏱️ Durée', value: duration(row.finished_at - row.started_at) });
|
if (row?.started_at && row?.finished_at) out.push({ name: '⏱️ Durée', value: duration(row.finished_at - row.started_at) });
|
||||||
if (row?.cost_usd) out.push({ name: '💳 Coût IA', value: `${row.cost_usd.toFixed(2)} $` });
|
if (row?.cost_usd) out.push({ name: '💳 Coût IA', value: `${row.cost_usd.toFixed(2)} $` });
|
||||||
return out;
|
return out;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function notifyJob(app, job, { status, result, error }) {
|
export async function notifyJob(app, job, { status, result, error }) {
|
||||||
const project = job.project_id ? app.db.prepare('SELECT name FROM projects WHERE id = ?').get(job.project_id)?.name : null;
|
const project = job.project_id ? (await app.db.prepare('SELECT name FROM projects WHERE id = ? AND user_id = ?').get(job.project_id, job.user_id))?.name : null;
|
||||||
const prefix = project ? `${project} · ` : '';
|
const prefix = project ? `${project} · ` : '';
|
||||||
const footer = project ? `${project} · ${LABEL[job.type] || job.type}` : undefined;
|
const footer = project ? `${project} · ${LABEL[job.type] || job.type}` : undefined;
|
||||||
if (status === 'error') {
|
if (status === 'error') {
|
||||||
return notify(app, 'job_error', {
|
return notify(app, job.user_id, 'job_error', {
|
||||||
title: `${prefix}${LABEL[job.type] || job.type} en échec`, level: 'error', footer,
|
title: `${prefix}${LABEL[job.type] || job.type} en échec`, level: 'error', footer,
|
||||||
description: `\`\`\`\n${String(error || 'Erreur inconnue').slice(0, 900).replace(/```/g, "'''")}\n\`\`\``,
|
description: `\`\`\`\n${String(error || 'Erreur inconnue').slice(0, 900).replace(/```/g, "'''")}\n\`\`\``,
|
||||||
fields: jobMeta(app, job),
|
fields: await jobMeta(app, job),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
if (status !== 'done') return Promise.resolve(false);
|
if (status !== 'done') return false;
|
||||||
if (job.type === 'followup') {
|
if (job.type === 'followup') {
|
||||||
if (!result?.sent) return Promise.resolve(false);
|
if (!result?.sent) return false;
|
||||||
return notify(app, 'followup', {
|
return notify(app, job.user_id, 'followup', {
|
||||||
title: `${prefix}Relances envoyées`, level: 'info', footer,
|
title: `${prefix}Relances envoyées`, level: 'info', footer,
|
||||||
description: `${result.sent} relance(s), ${result.failed} échec(s).\n${bar(result.sent, result.total || result.sent)}`,
|
description: `${result.sent} relance(s), ${result.failed} échec(s).\n${bar(result.sent, result.total || result.sent)}`,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
const make = DONE[job.type];
|
const make = DONE[job.type];
|
||||||
if (!make) return Promise.resolve(false);
|
if (!make) return false;
|
||||||
const n = make(result);
|
const n = make(result);
|
||||||
return notify(app, 'job_done', { ...n, title: `${prefix}${n.title}`, footer, fields: [...(n.fields || []), ...jobMeta(app, job)] });
|
return notify(app, job.user_id, 'job_done', { ...n, title: `${prefix}${n.title}`, footer, fields: [...(n.fields || []), ...(await jobMeta(app, job))] });
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -10,26 +10,27 @@ const pct = (a, b) => (b ? `${Math.round((a / b) * 100)} %` : '-');
|
||||||
const usd = (n) => `${n.toFixed(2)} $`;
|
const usd = (n) => `${n.toFixed(2)} $`;
|
||||||
const day = (ts) => new Date(ts * 1000).toLocaleDateString('fr-FR', { day: '2-digit', month: '2-digit', timeZone: 'Europe/Paris' });
|
const day = (ts) => new Date(ts * 1000).toLocaleDateString('fr-FR', { day: '2-digit', month: '2-digit', timeZone: 'Europe/Paris' });
|
||||||
|
|
||||||
export function weeklyStats(db, { at = now() } = {}) {
|
export async function weeklyStats(db, userId, { at = now() } = {}) {
|
||||||
const from = at - 7 * 86400;
|
const from = at - 7 * 86400;
|
||||||
const one = (sql, ...a) => db.prepare(sql).get(...a).n;
|
const one = async (sql, ...a) => (await db.prepare(sql).get(...a)).n;
|
||||||
const projects = db.prepare('SELECT id, name FROM projects ORDER BY name COLLATE NOCASE').all().map((p) => {
|
const projects = [];
|
||||||
const sent = one("SELECT COUNT(*) n FROM mail_log WHERE project_id = ? AND kind = 'initial' AND error IS NULL AND sent_at > ?", p.id, from);
|
for (const p of await db.prepare('SELECT id, name FROM projects WHERE user_id = ? ORDER BY LOWER(name)').all(userId)) {
|
||||||
const ab = abStats(db, p.id);
|
const sent = await one("SELECT COUNT(*) n FROM mail_log WHERE project_id = ? AND kind = 'initial' AND error IS NULL AND sent_at > ?", p.id, from);
|
||||||
return {
|
const ab = await abStats(db, p.id);
|
||||||
|
projects.push({
|
||||||
name: p.name,
|
name: p.name,
|
||||||
found: one('SELECT COUNT(*) n FROM prospects WHERE project_id = ? AND created_at > ?', p.id, from),
|
found: await one('SELECT COUNT(*) n FROM prospects WHERE project_id = ? AND created_at > ?', p.id, from),
|
||||||
sent,
|
sent,
|
||||||
followups: one("SELECT COUNT(*) n FROM mail_log WHERE project_id = ? AND kind = 'followup' AND error IS NULL AND sent_at > ?", p.id, from),
|
followups: await one("SELECT COUNT(*) n FROM mail_log WHERE project_id = ? AND kind = 'followup' AND error IS NULL AND sent_at > ?", p.id, from),
|
||||||
replies: one('SELECT COUNT(*) n FROM prospects WHERE project_id = ? AND replied_at > ?', p.id, from),
|
replies: await one('SELECT COUNT(*) n FROM prospects WHERE project_id = ? AND replied_at > ?', p.id, from),
|
||||||
clients: one("SELECT COUNT(*) n FROM prospects WHERE project_id = ? AND status = 'client'", p.id),
|
clients: await one("SELECT COUNT(*) n FROM prospects WHERE project_id = ? AND status = 'client'", p.id),
|
||||||
bounces: one(`SELECT COUNT(*) n FROM blacklist b JOIN prospects x ON x.email = b.email
|
bounces: await one(`SELECT COUNT(*) n FROM blacklist b JOIN prospects x ON x.email = b.email
|
||||||
WHERE x.project_id = ? AND b.reason = 'bounce' AND b.created_at > ?`, p.id, from),
|
WHERE x.project_id = ? AND b.reason = 'bounce' AND b.created_at > ?`, p.id, from),
|
||||||
cost: db.prepare('SELECT COALESCE(SUM(cost_usd), 0) c FROM jobs WHERE project_id = ? AND COALESCE(finished_at, created_at) > ?').get(p.id, from).c,
|
cost: (await db.prepare('SELECT COALESCE(SUM(cost_usd), 0) c FROM jobs WHERE project_id = ? AND COALESCE(finished_at, created_at) > ?').get(p.id, from)).c,
|
||||||
bestSubject: ab.length > 1 && ab.every((v) => v.sent >= 10) ? [...ab].sort((a, b) => b.rate - a.rate)[0] : null,
|
bestSubject: ab.length > 1 && ab.every((v) => v.sent >= 10) ? [...ab].sort((a, b) => b.rate - a.rate)[0] : null,
|
||||||
};
|
});
|
||||||
});
|
}
|
||||||
const cost = db.prepare('SELECT COALESCE(SUM(cost_usd), 0) c FROM jobs WHERE COALESCE(finished_at, created_at) > ?').get(from).c;
|
const cost = (await db.prepare('SELECT COALESCE(SUM(cost_usd), 0) c FROM jobs WHERE user_id = ? AND COALESCE(finished_at, created_at) > ?').get(userId, from)).c;
|
||||||
const sum = (k) => projects.reduce((t, p) => t + p[k], 0);
|
const sum = (k) => projects.reduce((t, p) => t + p[k], 0);
|
||||||
return { from, to: at, projects, totals: { found: sum('found'), sent: sum('sent'), followups: sum('followups'), replies: sum('replies'), cost } };
|
return { from, to: at, projects, totals: { found: sum('found'), sent: sum('sent'), followups: sum('followups'), replies: sum('replies'), cost } };
|
||||||
}
|
}
|
||||||
|
|
@ -54,12 +55,12 @@ export function weeklyText(st) {
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Envoie le rapport (mail si SMTP global + adresse, Discord si webhook). Retourne les canaux utilisés. */
|
/** Envoie le rapport (mail si SMTP global + adresse, Discord si webhook). Retourne les canaux utilisés. */
|
||||||
export async function sendWeeklyReport(app, { at = now() } = {}) {
|
export async function sendWeeklyReport(app, userId, { at = now() } = {}) {
|
||||||
const st = weeklyStats(app.db, { at });
|
const st = await weeklyStats(app.db, userId, { at });
|
||||||
const text = weeklyText(st);
|
const text = weeklyText(st);
|
||||||
const channels = [];
|
const channels = [];
|
||||||
const to = getSetting(app.db, 'notify_email');
|
const to = await getSetting(app.db, userId, 'notify_email');
|
||||||
const smtp = globalSmtp(app);
|
const smtp = await globalSmtp(app, userId);
|
||||||
if (to && smtp) {
|
if (to && smtp) {
|
||||||
const transport = (app.createTransport || createTransport)(smtp);
|
const transport = (app.createTransport || createTransport)(smtp);
|
||||||
try {
|
try {
|
||||||
|
|
@ -72,7 +73,7 @@ export async function sendWeeklyReport(app, { at = now() } = {}) {
|
||||||
}
|
}
|
||||||
const t = st.totals;
|
const t = st.totals;
|
||||||
const active = st.projects.filter((p) => p.sent || p.found || p.replies);
|
const active = st.projects.filter((p) => p.sent || p.found || p.replies);
|
||||||
const ok = await notify(app, 'weekly', {
|
const ok = await notify(app, userId, 'weekly', {
|
||||||
title: `Rapport hebdo · ${day(st.from)} → ${day(st.to)}`, level: 'info',
|
title: `Rapport hebdo · ${day(st.from)} → ${day(st.to)}`, level: 'info',
|
||||||
description: active.length
|
description: active.length
|
||||||
? `**${t.sent}** mails · **${t.replies}** réponses (${pct(t.replies, t.sent)}) · **${t.found}** prospects trouvés`
|
? `**${t.sent}** mails · **${t.replies}** réponses (${pct(t.replies, t.sent)}) · **${t.found}** prospects trouvés`
|
||||||
|
|
@ -92,15 +93,15 @@ export async function sendWeeklyReport(app, { at = now() } = {}) {
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Appelé toutes les 15 min : envoie une fois par semaine, le lundi à partir de 8h (Paris). */
|
/** Appelé toutes les 15 min : envoie une fois par semaine, le lundi à partir de 8h (Paris). */
|
||||||
export async function maybeSendWeekly(app, { date = new Date() } = {}) {
|
export async function maybeSendWeekly(app, userId, { date = new Date() } = {}) {
|
||||||
if (getSetting(app.db, 'weekly_report', '0') !== '1') return null;
|
if ((await getSetting(app.db, userId, 'weekly_report', '0')) !== '1') return null;
|
||||||
const p = parisParts(date);
|
const p = parisParts(date);
|
||||||
if (p.weekday !== 'Mon' || p.hour < 8) return null;
|
if (p.weekday !== 'Mon' || p.hour < 8) return null;
|
||||||
const mondayAt8 = Math.floor(parisTime(p.year, p.month, p.day, 8).getTime() / 1000);
|
const mondayAt8 = Math.floor(parisTime(p.year, p.month, p.day, 8).getTime() / 1000);
|
||||||
if (Number(getSetting(app.db, 'weekly_report_last', '0')) >= mondayAt8) return null;
|
if (Number(await getSetting(app.db, userId, 'weekly_report_last', '0')) >= mondayAt8) return null;
|
||||||
const at = Math.floor(date.getTime() / 1000);
|
const at = Math.floor(date.getTime() / 1000);
|
||||||
const r = await sendWeeklyReport(app, { at });
|
const r = await sendWeeklyReport(app, userId, { at });
|
||||||
// Rien de configuré : on ne marque pas, il partira dès qu'un canal existera
|
// Rien de configuré : on ne marque pas, il partira dès qu'un canal existera
|
||||||
if (r.channels.length) setSetting(app.db, 'weekly_report_last', String(at));
|
if (r.channels.length) await setSetting(app.db, userId, 'weekly_report_last', String(at));
|
||||||
return r;
|
return r;
|
||||||
}
|
}
|
||||||
|
|
|
||||||
156
src/services/sandbox.js
Normal file
156
src/services/sandbox.js
Normal file
|
|
@ -0,0 +1,156 @@
|
||||||
|
// Exécution isolée de Claude : bac à sable bubblewrap + environnement du processus enfant assaini.
|
||||||
|
// Chaque lancement a son propre HOME jetable ; seul le répertoire de travail de l'utilisateur est monté.
|
||||||
|
import { spawnSync } from 'node:child_process';
|
||||||
|
import { accessSync, constants, mkdtempSync, realpathSync, rmSync } from 'node:fs';
|
||||||
|
import { tmpdir } from 'node:os';
|
||||||
|
import { delimiter, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
|
||||||
|
|
||||||
|
export const SANDBOX_HOME = '/home/sandbox';
|
||||||
|
|
||||||
|
// Seules variables héritées du serveur. Rien d'autre : ni SECRET_KEY, ni DB_*, ni GOOGLE_*, ni APPLE_*.
|
||||||
|
const INHERITED = ['PATH', 'LANG'];
|
||||||
|
// Développement sous Windows : sans elles Node ne démarre pas correctement (aucune n'est un secret)
|
||||||
|
const INHERITED_WINDOWS = ['SystemRoot', 'PATHEXT', 'TEMP', 'TMP', 'COMSPEC'];
|
||||||
|
// Les deux seuls secrets qu'un processus enfant peut recevoir, et toujours ceux de l'utilisateur du job
|
||||||
|
export const SECRET_ENV_NAMES = new Set(['ANTHROPIC_API_KEY', 'CLAUDE_CODE_OAUTH_TOKEN']);
|
||||||
|
|
||||||
|
/** Environnement du processus enfant : liste blanche stricte + le secret de l'utilisateur concerné. */
|
||||||
|
export function buildChildEnv(parent, { secretEnv = {}, home }) {
|
||||||
|
const env = {};
|
||||||
|
for (const k of [...INHERITED, ...(process.platform === 'win32' ? INHERITED_WINDOWS : [])]) {
|
||||||
|
if (parent[k] !== undefined) env[k] = parent[k];
|
||||||
|
}
|
||||||
|
env.LANG ||= 'C.UTF-8';
|
||||||
|
env.HOME = home;
|
||||||
|
for (const [k, v] of Object.entries(secretEnv)) {
|
||||||
|
if (!SECRET_ENV_NAMES.has(k)) throw new Error(`Variable d'environnement non autorisée pour le processus enfant : ${k}`);
|
||||||
|
if (v) env[k] = v;
|
||||||
|
}
|
||||||
|
return env;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Chemin réel de l'exécutable (suit les liens symboliques) ; null s'il est introuvable. */
|
||||||
|
export function resolveBin(bin, pathEnv = process.env.PATH || '') {
|
||||||
|
const candidates = bin.includes('/') || bin.includes(sep)
|
||||||
|
? [resolve(bin)]
|
||||||
|
: pathEnv.split(delimiter).filter(Boolean).map((d) => join(d, bin));
|
||||||
|
for (const c of candidates) {
|
||||||
|
try { accessSync(c, constants.X_OK); return realpathSync(c); } catch { /* suivant */ }
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Le chemin est-il à l'intérieur de `root` (ou égal) ? Sert à n'accepter que le dossier de CET utilisateur. */
|
||||||
|
export function isInside(root, path) {
|
||||||
|
const rel = relative(resolve(root), resolve(path));
|
||||||
|
return rel === '' || (!rel.startsWith('..') && !isAbsolute(rel));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Ligne de commande bubblewrap (sans le binaire `bwrap` lui-même). Fonction pure, testée unitairement.
|
||||||
|
* - racine reconstruite en lecture seule (/usr, /etc, bibliothèques) : ni /home, ni /root, ni /var, ni le dossier de l'application ;
|
||||||
|
* - /tmp et HOME en tmpfs vides, propres à chaque exécution ;
|
||||||
|
* - seul `workDir` (clone du projet de l'utilisateur) est monté, en lecture seule ;
|
||||||
|
* - PID, IPC et UTS isolés, le réseau est conservé ;
|
||||||
|
* - aucun secret dans cette ligne (visible dans `ps`) : le secret passe par l'environnement du processus.
|
||||||
|
* @param {object} o
|
||||||
|
* @param {string|null} o.workDir clone du projet (absolu), ou null
|
||||||
|
* @param {string[]} o.command commande à exécuter dans le bac à sable
|
||||||
|
* @param {string[]} [o.roBinds] dossiers supplémentaires en lecture seule (binaire Claude, Node…)
|
||||||
|
* @param {{home:string}|null} [o.serverConfig] mode « Claude du serveur » seulement : monte la configuration du CLI du serveur
|
||||||
|
*/
|
||||||
|
export function buildBwrapArgs({ workDir = null, command, roBinds = [], serverConfig = null }) {
|
||||||
|
if (!Array.isArray(command) || !command.length) throw new Error('Commande vide');
|
||||||
|
if (workDir !== null && !isAbsolute(workDir)) throw new Error('Le répertoire de travail doit être absolu');
|
||||||
|
const args = [
|
||||||
|
'--die-with-parent', '--new-session',
|
||||||
|
'--unshare-pid', '--unshare-ipc', '--unshare-uts',
|
||||||
|
'--cap-drop', 'ALL',
|
||||||
|
'--ro-bind', '/usr', '/usr',
|
||||||
|
'--ro-bind-try', '/bin', '/bin',
|
||||||
|
'--ro-bind-try', '/sbin', '/sbin',
|
||||||
|
'--ro-bind-try', '/lib', '/lib',
|
||||||
|
'--ro-bind-try', '/lib64', '/lib64',
|
||||||
|
'--ro-bind', '/etc', '/etc',
|
||||||
|
'--ro-bind-try', '/run/systemd/resolve', '/run/systemd/resolve', // resolv.conf pointe souvent ici
|
||||||
|
'--proc', '/proc', '--dev', '/dev',
|
||||||
|
'--tmpfs', '/tmp',
|
||||||
|
'--tmpfs', SANDBOX_HOME,
|
||||||
|
];
|
||||||
|
for (const p of roBinds) args.push('--ro-bind', p, p);
|
||||||
|
if (workDir) args.push('--ro-bind', workDir, workDir);
|
||||||
|
if (serverConfig) {
|
||||||
|
args.push('--bind-try', join(serverConfig.home, '.claude'), `${SANDBOX_HOME}/.claude`);
|
||||||
|
args.push('--bind-try', join(serverConfig.home, '.claude.json'), `${SANDBOX_HOME}/.claude.json`);
|
||||||
|
}
|
||||||
|
args.push('--chdir', workDir || SANDBOX_HOME, '--', ...command);
|
||||||
|
return args;
|
||||||
|
}
|
||||||
|
|
||||||
|
const bwrapOk = new Map();
|
||||||
|
/** bwrap est-il installé et capable de créer un bac à sable (espaces de noms utilisateur) ? */
|
||||||
|
export function bwrapAvailable(bin = 'bwrap') {
|
||||||
|
if (bwrapOk.get(bin)) return true;
|
||||||
|
const r = spawnSync(bin, ['--version'], { stdio: 'ignore', timeout: 5000 });
|
||||||
|
const ok = !r.error && r.status === 0;
|
||||||
|
if (ok) bwrapOk.set(bin, true);
|
||||||
|
return ok;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Prépare un lancement : commande, arguments, environnement assaini, nettoyage.
|
||||||
|
* @param {object} o
|
||||||
|
* @param {string} o.bin exécutable Claude
|
||||||
|
* @param {string[]} o.args arguments du CLI
|
||||||
|
* @param {string} [o.cwd] clone du projet ; doit être dans `allowedRoot`
|
||||||
|
* @param {string} [o.allowedRoot] dossier des clones de CET utilisateur
|
||||||
|
* @param {Record<string,string>} [o.secretEnv] le secret de l'utilisateur (clé API ou jeton)
|
||||||
|
* @param {boolean} [o.serverConfig] mode « Claude du serveur » : monte la configuration du CLI du serveur
|
||||||
|
* @param {object} o.sandbox cfg.sandbox : { enabled, production, bwrapBin, roBinds, serverHome }
|
||||||
|
* @param {object} [deps] { parentEnv, hasBwrap, resolveBin } (tests)
|
||||||
|
*/
|
||||||
|
export function prepareLaunch(o, deps = {}) {
|
||||||
|
const sb = o.sandbox;
|
||||||
|
if (!sb) throw new Error('Configuration du bac à sable requise');
|
||||||
|
const parentEnv = deps.parentEnv || process.env;
|
||||||
|
const cwd = o.cwd ? resolve(o.cwd) : null;
|
||||||
|
if (cwd && o.allowedRoot && !isInside(o.allowedRoot, cwd)) {
|
||||||
|
throw new Error("Répertoire de travail hors du dossier de l'utilisateur : exécution refusée");
|
||||||
|
}
|
||||||
|
// Production : le bac à sable n'est jamais optionnel, même si la configuration dit le contraire
|
||||||
|
if (sb.production && !sb.enabled) throw new Error('Bac à sable obligatoire en production : exécution refusée');
|
||||||
|
const nice = ['nice', '-n', '10']; // le serveur web reste réactif pendant qu'un job tourne
|
||||||
|
|
||||||
|
if (!sb.enabled) {
|
||||||
|
// Développement uniquement (SANDBOX=off). HOME jetable, sauf pour le mode serveur (sa configuration CLI, comme avant).
|
||||||
|
const home = o.serverConfig ? sb.serverHome : mkdtempSync(join(tmpdir(), 'aitools-home-'));
|
||||||
|
return {
|
||||||
|
command: nice[0], args: [...nice.slice(1), o.bin, ...o.args], cwd: cwd || undefined, sandboxed: false,
|
||||||
|
env: buildChildEnv(parentEnv, { secretEnv: o.secretEnv, home }),
|
||||||
|
cleanup: () => { if (!o.serverConfig) rmSync(home, { recursive: true, force: true }); },
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!(deps.hasBwrap || bwrapAvailable)(sb.bwrapBin)) {
|
||||||
|
throw new Error('Bac à sable (bwrap) indisponible : exécution refusée');
|
||||||
|
}
|
||||||
|
const real = (deps.resolveBin || resolveBin)(o.bin, parentEnv.PATH);
|
||||||
|
if (!real) throw new Error(`Exécutable Claude introuvable : ${o.bin}`);
|
||||||
|
const roBinds = [...new Set([...(sb.roBinds || []), ...(real.startsWith('/usr/') ? [] : [dirname(real)])])];
|
||||||
|
const bwrap = buildBwrapArgs({
|
||||||
|
workDir: cwd, roBinds, command: [real, ...o.args],
|
||||||
|
serverConfig: o.serverConfig ? { home: sb.serverHome } : null,
|
||||||
|
});
|
||||||
|
return {
|
||||||
|
command: nice[0], args: [...nice.slice(1), sb.bwrapBin, ...bwrap], cwd: tmpdir(), sandboxed: true,
|
||||||
|
// Le secret n'est jamais dans argv : bwrap transmet son propre environnement au processus du bac à sable
|
||||||
|
env: buildChildEnv(parentEnv, { secretEnv: o.secretEnv, home: SANDBOX_HOME }),
|
||||||
|
cleanup: () => {},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export const sandboxStartupMessages = (sb) => [
|
||||||
|
...(sb.offIgnored ? ['SANDBOX=off est ignoré en production : le bac à sable reste obligatoire.'] : []),
|
||||||
|
...(!sb.enabled ? ['SANDBOX=off : les jobs IA tournent SANS bac à sable (développement uniquement).'] : []),
|
||||||
|
...(sb.enabled && !bwrapAvailable(sb.bwrapBin) ? [`${sb.bwrapBin} introuvable ou inutilisable : les jobs IA seront refusés (installe bubblewrap).`] : []),
|
||||||
|
];
|
||||||
|
|
@ -16,40 +16,57 @@ export class Scheduler {
|
||||||
this.everyMs = everyMs;
|
this.everyMs = everyMs;
|
||||||
this.log = log;
|
this.log = log;
|
||||||
this.running = false;
|
this.running = false;
|
||||||
|
this.inflight = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Passage lancé par un minuteur : suivi (stop() l'attend) et jamais d'erreur non gérée
|
||||||
|
run() {
|
||||||
|
this.inflight = this.tick().catch((e) => this.log.error('[planificateur]', e.message));
|
||||||
}
|
}
|
||||||
|
|
||||||
start() {
|
start() {
|
||||||
this.timer = setInterval(() => this.tick(), this.everyMs);
|
this.timer = setInterval(() => this.run(), this.everyMs);
|
||||||
this.timer.unref();
|
this.timer.unref();
|
||||||
// Premier passage peu après le démarrage
|
// Premier passage peu après le démarrage
|
||||||
this.first = setTimeout(() => this.tick(), 60_000);
|
this.first = setTimeout(() => this.run(), 60_000);
|
||||||
this.first.unref();
|
this.first.unref();
|
||||||
}
|
}
|
||||||
|
|
||||||
stop() { clearInterval(this.timer); clearTimeout(this.first); }
|
async stop() {
|
||||||
|
clearInterval(this.timer);
|
||||||
|
clearTimeout(this.first);
|
||||||
|
await this.inflight;
|
||||||
|
}
|
||||||
|
|
||||||
async tick() {
|
async tick() {
|
||||||
if (this.running) return;
|
if (this.running) return;
|
||||||
this.running = true;
|
this.running = true;
|
||||||
try {
|
try {
|
||||||
const projects = this.app.db.prepare('SELECT id FROM projects WHERE imap_enc IS NOT NULL').all();
|
// Les tâches de fond ne travaillent que pour les comptes actifs, projet par projet avec son propriétaire
|
||||||
for (const { id } of projects) {
|
const projects = await this.app.db.prepare(`SELECT p.id, p.user_id FROM projects p JOIN users u ON u.id = p.user_id
|
||||||
try { await checkInbox(this.app, id); }
|
WHERE p.imap_enc IS NOT NULL AND u.status = 'active'`).all();
|
||||||
|
for (const { id, user_id: userId } of projects) {
|
||||||
|
try { await checkInbox(this.app, userId, id); }
|
||||||
catch (e) { this.log.error(`[inbox ${id}]`, e.message); }
|
catch (e) { this.log.error(`[inbox ${id}]`, e.message); }
|
||||||
}
|
}
|
||||||
this.queueFollowups();
|
await this.queueFollowups();
|
||||||
try { await maybeSendWeekly(this.app); }
|
const users = await this.app.db.prepare(`SELECT s.user_id FROM user_settings s JOIN users u ON u.id = s.user_id
|
||||||
catch (e) { this.log.error('[rapport hebdo]', e.message); }
|
WHERE s.\`key\` = 'weekly_report' AND s.value = '1' AND u.status = 'active'`).all();
|
||||||
|
for (const { user_id: userId } of users) {
|
||||||
|
try { await maybeSendWeekly(this.app, userId); }
|
||||||
|
catch (e) { this.log.error('[rapport hebdo]', e.message); }
|
||||||
|
}
|
||||||
await snapshotAll(this.app, { log: this.log });
|
await snapshotAll(this.app, { log: this.log });
|
||||||
} finally { this.running = false; }
|
} finally { this.running = false; }
|
||||||
}
|
}
|
||||||
|
|
||||||
queueFollowups(opts) {
|
async queueFollowups(opts) {
|
||||||
const { db } = this.app;
|
const { db } = this.app;
|
||||||
const queued = [];
|
const queued = [];
|
||||||
for (const { id } of db.prepare('SELECT id FROM projects WHERE followup_enabled = 1').all()) {
|
for (const { id, user_id: userId } of await db.prepare(`SELECT p.id, p.user_id FROM projects p JOIN users u ON u.id = p.user_id
|
||||||
const plan = followupPlan(db, getProject(this.app, id), opts);
|
WHERE p.followup_enabled = 1 AND u.status = 'active'`).all()) {
|
||||||
if (plan.ready) queued.push({ id, ...enqueue(db, { projectId: id, type: 'followup', params: { count: plan.due } }) });
|
const plan = await followupPlan(db, await getProject(this.app, id, { userId }), opts);
|
||||||
|
if (plan.ready) queued.push({ id, ...await enqueue(db, { userId, projectId: id, type: 'followup', params: { count: plan.due } }) });
|
||||||
}
|
}
|
||||||
return queued;
|
return queued;
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -11,7 +11,7 @@ export async function waitCool(max, { read = cpuTemp, sleep = (ms) => new Promis
|
||||||
let t = read();
|
let t = read();
|
||||||
if (t === null || t < max) return;
|
if (t === null || t < max) return;
|
||||||
while (t !== null && t >= max - 5) {
|
while (t !== null && t >= max - 5) {
|
||||||
onWait?.(t);
|
await onWait?.(t);
|
||||||
await sleep(30_000);
|
await sleep(30_000);
|
||||||
t = read();
|
t = read();
|
||||||
}
|
}
|
||||||
|
|
|
||||||
103
src/site/layout.js
Normal file
103
src/site/layout.js
Normal file
|
|
@ -0,0 +1,103 @@
|
||||||
|
// Gabarit du site public : balisage sémantique, métadonnées (title, description, canonical, Open Graph), liens
|
||||||
|
// d'évitement, navigation. Aucune ressource externe (CSS et favicon servis par l'application, pas de script).
|
||||||
|
import { esc } from '../http.js';
|
||||||
|
|
||||||
|
export const SITE_NAME = 'AiTools';
|
||||||
|
export const CONTACT_EMAIL = 'contact@tony-averty.dev';
|
||||||
|
|
||||||
|
const NAV = [
|
||||||
|
['/fonctionnement', 'Fonctionnement'],
|
||||||
|
['/tarifs', 'Tarifs'],
|
||||||
|
];
|
||||||
|
|
||||||
|
const LEGAL_NAV = [
|
||||||
|
['/mentions-legales', 'Mentions légales'],
|
||||||
|
['/confidentialite', 'Confidentialité'],
|
||||||
|
['/cgu', 'CGU'],
|
||||||
|
];
|
||||||
|
|
||||||
|
/** URL absolue d'une page du site (canonical, Open Graph, sitemap). */
|
||||||
|
export function absoluteUrl(appUrl, path) {
|
||||||
|
return `${String(appUrl).replace(/\/$/, '')}${path}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @param {object} o
|
||||||
|
* @param {string} o.appUrl URL publique de l'application (config)
|
||||||
|
* @param {string} o.path chemin de la page (ex. /tarifs) : sert au canonical et à la navigation
|
||||||
|
* @param {string} o.title <title> complet (60 caractères environ)
|
||||||
|
* @param {string} o.description meta description (160 caractères environ)
|
||||||
|
* @param {string} o.body contenu de <main>, déjà échappé
|
||||||
|
* @param {boolean} [o.noindex] page à ne pas indexer (connexion, 404)
|
||||||
|
* @param {object} [o.jsonLd] données structurées (bloc de données, non exécuté : compatible avec la CSP)
|
||||||
|
*/
|
||||||
|
export function siteLayout({ appUrl, path, title, description, body, noindex = false, jsonLd = null }) {
|
||||||
|
const url = absoluteUrl(appUrl, path === '/' ? '/' : path);
|
||||||
|
const year = new Date().getFullYear();
|
||||||
|
const link = ([href, label]) => `<li><a href="${href}"${href === path ? ' aria-current="page"' : ''}>${esc(label)}</a></li>`;
|
||||||
|
return `<!doctype html>
|
||||||
|
<html lang="fr">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
|
<title>${esc(title)}</title>
|
||||||
|
<meta name="description" content="${esc(description)}">
|
||||||
|
<meta name="robots" content="${noindex ? 'noindex, follow' : 'index, follow'}">
|
||||||
|
${noindex ? '' : `<link rel="canonical" href="${esc(url)}">\n`}<meta name="color-scheme" content="light dark">
|
||||||
|
<meta name="theme-color" content="#f4f5f7" media="(prefers-color-scheme: light)">
|
||||||
|
<meta name="theme-color" content="#111317" media="(prefers-color-scheme: dark)">
|
||||||
|
<meta property="og:type" content="website">
|
||||||
|
<meta property="og:site_name" content="${SITE_NAME}">
|
||||||
|
<meta property="og:locale" content="fr_FR">
|
||||||
|
<meta property="og:title" content="${esc(title)}">
|
||||||
|
<meta property="og:description" content="${esc(description)}">
|
||||||
|
<meta property="og:url" content="${esc(url)}">
|
||||||
|
<meta name="twitter:card" content="summary">
|
||||||
|
<link rel="icon" type="image/svg+xml" href="/static/favicon.svg">
|
||||||
|
<link rel="stylesheet" href="/static/app.css">
|
||||||
|
<link rel="stylesheet" href="/static/site.css">
|
||||||
|
${jsonLd ? `<script type="application/ld+json">${JSON.stringify(jsonLd).replace(/</g, '\\u003c')}</script>\n` : ''}</head>
|
||||||
|
<body class="site">
|
||||||
|
<a class="skip" href="#contenu">Aller au contenu</a>
|
||||||
|
<header class="site-head">
|
||||||
|
<div class="wrap head-in">
|
||||||
|
<a class="brand" href="/" aria-label="${SITE_NAME}, accueil"><span class="mark" aria-hidden="true"></span>${SITE_NAME}</a>
|
||||||
|
<nav class="site-nav" aria-label="Navigation principale">
|
||||||
|
<ul>
|
||||||
|
${NAV.map(link).join('\n ')}
|
||||||
|
<li><a href="/login"${path === '/login' ? ' aria-current="page"' : ''}>Connexion</a></li>
|
||||||
|
<li><a class="btn primary" href="/login">Créer mon compte</a></li>
|
||||||
|
</ul>
|
||||||
|
</nav>
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
<main id="contenu" tabindex="-1">
|
||||||
|
${body}
|
||||||
|
</main>
|
||||||
|
<footer class="site-foot">
|
||||||
|
<div class="wrap foot-in">
|
||||||
|
<div>
|
||||||
|
<a class="brand" href="/"><span class="mark" aria-hidden="true"></span>${SITE_NAME}</a>
|
||||||
|
<p>Un panel qui pilote Claude Code pour prospecter par mail, avec ton propre accès Claude.</p>
|
||||||
|
<p class="fine">Édité par Tony AVERTY, entrepreneur individuel. © ${year}</p>
|
||||||
|
</div>
|
||||||
|
<nav aria-label="Pages du site">
|
||||||
|
<h2>Le site</h2>
|
||||||
|
<ul>
|
||||||
|
<li><a href="/">Accueil</a></li>
|
||||||
|
${NAV.map(link).join('\n ')}
|
||||||
|
<li><a href="/login">Connexion</a></li>
|
||||||
|
</ul>
|
||||||
|
</nav>
|
||||||
|
<nav aria-label="Informations légales">
|
||||||
|
<h2>Légal et contact</h2>
|
||||||
|
<ul>
|
||||||
|
${LEGAL_NAV.map(link).join('\n ')}
|
||||||
|
<li><a href="mailto:${CONTACT_EMAIL}">${CONTACT_EMAIL}</a></li>
|
||||||
|
</ul>
|
||||||
|
</nav>
|
||||||
|
</div>
|
||||||
|
</footer>
|
||||||
|
</body>
|
||||||
|
</html>`;
|
||||||
|
}
|
||||||
315
src/site/legal.js
Normal file
315
src/site/legal.js
Normal file
|
|
@ -0,0 +1,315 @@
|
||||||
|
// Pages légales : mentions légales, politique de confidentialité, conditions d'utilisation.
|
||||||
|
// Textes rédigés d'après le code (données réellement collectées, cookies réellement posés) pour l'entrepreneur
|
||||||
|
// individuel Tony AVERTY. Ce sont des modèles sérieux, pas un avis juridique : voir docs/JOURNAL.md pour ce qui reste
|
||||||
|
// à compléter (marqueurs visibles) et à faire relire.
|
||||||
|
import { siteLayout, CONTACT_EMAIL } from './layout.js';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Marqueurs visibles tant que l'information n'est pas fournie ou validée. Leur liste est aussi dans docs/JOURNAL.md
|
||||||
|
* (section « Marqueurs à compléter ») ; un test compare les deux pour qu'aucun ne soit oublié.
|
||||||
|
*/
|
||||||
|
export const MARKERS = {
|
||||||
|
address: '[À COMPLÉTER : adresse du siège]',
|
||||||
|
host: '[À COMPLÉTER : hébergeur]',
|
||||||
|
phone: '[À COMPLÉTER : téléphone]',
|
||||||
|
retention: '[À VALIDER : durées de conservation]',
|
||||||
|
transfers: '[À VALIDER : transferts hors UE]',
|
||||||
|
processing: '[À VALIDER : cadre de sous-traitance]',
|
||||||
|
liability: '[À VALIDER : limitation de responsabilité]',
|
||||||
|
};
|
||||||
|
export const LEGAL_MARKERS = Object.values(MARKERS);
|
||||||
|
const todo = (key) => `<mark class="todo">${MARKERS[key]}</mark>`;
|
||||||
|
|
||||||
|
export const LEGAL_UPDATED = '22 octobre 2026';
|
||||||
|
|
||||||
|
/** Gabarit commun : titre, sommaire, sections numérotées par ancre. */
|
||||||
|
function legalPage({ appUrl, path, title, description, h1, lead, sections }) {
|
||||||
|
const toc = sections.map((s) => `<li><a href="#${s.id}">${s.title}</a></li>`).join('');
|
||||||
|
const body = sections.map((s) => `<h2 id="${s.id}">${s.title}</h2>\n${s.html}`).join('\n');
|
||||||
|
return siteLayout({
|
||||||
|
appUrl, path, title, description,
|
||||||
|
body: `<div class="wrap page-head">
|
||||||
|
<p class="eyebrow"><span class="mark" aria-hidden="true"></span>Informations légales</p>
|
||||||
|
<h1>${h1}</h1>
|
||||||
|
<p class="lead">${lead}</p>
|
||||||
|
<p class="updated">Dernière mise à jour : ${LEGAL_UPDATED}</p>
|
||||||
|
</div>
|
||||||
|
<div class="wrap prose-wrap">
|
||||||
|
<nav class="toc" aria-label="Sommaire"><h2>Sommaire</h2><ol>${toc}</ol></nav>
|
||||||
|
<div class="prose">
|
||||||
|
${body}
|
||||||
|
</div>
|
||||||
|
</div>`,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- Mentions légales ----------
|
||||||
|
export function mentionsPage({ appUrl }) {
|
||||||
|
return legalPage({
|
||||||
|
appUrl, path: '/mentions-legales',
|
||||||
|
title: 'Mentions légales · AiTools',
|
||||||
|
description: "Éditeur, directeur de la publication, hébergeur et contact du site AiTools, édité par Tony AVERTY, entrepreneur individuel.",
|
||||||
|
h1: 'Mentions légales',
|
||||||
|
lead: "Qui édite AiTools, qui l'héberge et comment nous joindre.",
|
||||||
|
sections: [
|
||||||
|
{
|
||||||
|
id: 'editeur', title: 'Éditeur du site',
|
||||||
|
html: `<dl>
|
||||||
|
<dt>Nom</dt><dd>Tony AVERTY, entrepreneur individuel (micro-entreprise)</dd>
|
||||||
|
<dt>SIRET</dt><dd>100 142 819 00018</dd>
|
||||||
|
<dt>Code APE</dt><dd>62.01Z (programmation informatique)</dd>
|
||||||
|
<dt>Siège</dt><dd>${todo('address')}</dd>
|
||||||
|
<dt>Email</dt><dd><a href="mailto:${CONTACT_EMAIL}">${CONTACT_EMAIL}</a></dd>
|
||||||
|
<dt>Téléphone</dt><dd>${todo('phone')}</dd>
|
||||||
|
<dt>TVA</dt><dd>TVA non applicable, art. 293 B du CGI</dd>
|
||||||
|
<dt>Directeur de la publication</dt><dd>Tony AVERTY</dd>
|
||||||
|
</dl>`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'hebergeur', title: 'Hébergeur',
|
||||||
|
html: `<p>Le site et le service sont hébergés par : ${todo('host')}</p>`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'propriete', title: 'Propriété intellectuelle',
|
||||||
|
html: `<p>Le site, son code, ses textes et son identité visuelle sont la propriété de leur éditeur. Toute reproduction sans accord écrit est interdite, hors citation courte avec mention de la source.</p>
|
||||||
|
<p>Les contenus que tu saisis dans AiTools (projets, prospects, modèles de mail) restent les tiens. Claude et Anthropic sont des marques d'Anthropic ; Google et Apple sont des marques de leurs propriétaires. Ils sont cités pour décrire le fonctionnement du service, sans lien d'affiliation.</p>`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'responsabilite', title: 'Responsabilité et liens externes',
|
||||||
|
html: `<p>L'éditeur s'efforce de publier des informations exactes mais ne peut garantir qu'elles soient exemptes d'erreur. Le site contient quelques liens vers des sites tiers, dont l'éditeur ne maîtrise pas le contenu.</p>
|
||||||
|
<p>Les conditions d'usage du service sont dans les <a href="/cgu">conditions générales d'utilisation</a>.</p>`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'donnees', title: 'Données personnelles et cookies',
|
||||||
|
html: `<p>Le traitement des données personnelles et l'usage des cookies sont décrits dans la <a href="/confidentialite">politique de confidentialité</a>. Le site ne pose que des cookies strictement nécessaires à son fonctionnement.</p>`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'signalement', title: 'Contact et signalement',
|
||||||
|
html: `<p>Pour toute question, ou pour signaler un contenu illicite ou un mail reçu à tort depuis AiTools : <a href="mailto:${CONTACT_EMAIL}">${CONTACT_EMAIL}</a>.</p>
|
||||||
|
<p>Droit applicable : le droit français.</p>`,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- Politique de confidentialité ----------
|
||||||
|
// Paragraphe reCAPTCHA prêt, à insérer dans la section « destinataires » et à relier à la section « cookies » le jour où
|
||||||
|
// le CAPTCHA est activé (jalon anti-abus). Le texte suppose le chargement du script Google APRÈS un choix de l'utilisateur.
|
||||||
|
//
|
||||||
|
// <li><strong>Google reCAPTCHA</strong> (Google Ireland Limited, Google LLC) : protège les pages de connexion contre les
|
||||||
|
// envois automatisés. Il est chargé uniquement si tu l'acceptes, car il dépose des cookies et transmet à Google ton
|
||||||
|
// adresse IP, des données sur ton navigateur et ton comportement sur la page. Base légale : ton consentement. Si tu le
|
||||||
|
// refuses, tu peux te connecter autrement [à définir selon la solution retenue]. Voir la politique de confidentialité de Google.</li>
|
||||||
|
//
|
||||||
|
// En l'activant, penser aussi à : afficher un choix « Accepter » / « Refuser » aussi simple l'un que l'autre, mettre à jour
|
||||||
|
// la CSP (script-src, frame-src), le tableau des cookies, la section « transferts » et la date de mise à jour.
|
||||||
|
|
||||||
|
export function privacyPage({ appUrl, apple = false }) {
|
||||||
|
return legalPage({
|
||||||
|
appUrl, path: '/confidentialite',
|
||||||
|
title: 'Politique de confidentialité · AiTools',
|
||||||
|
description: "Quelles données AiTools collecte, pourquoi, combien de temps, qui les reçoit et comment exercer tes droits. Rôles : responsable de traitement et sous-traitant.",
|
||||||
|
h1: 'Politique de confidentialité',
|
||||||
|
lead: "Ce que le service collecte, ce qu'il en fait, et comment reprendre la main. Écrit pour être lu.",
|
||||||
|
sections: [
|
||||||
|
{
|
||||||
|
id: 'roles', title: 'Qui est responsable de quoi',
|
||||||
|
html: `<p>AiTools est édité par Tony AVERTY, entrepreneur individuel (SIRET 100 142 819 00018), siège : ${todo('address')}. Contact : <a href="mailto:${CONTACT_EMAIL}">${CONTACT_EMAIL}</a>. Il n'y a pas de délégué à la protection des données.</p>
|
||||||
|
<ul>
|
||||||
|
<li><strong>Pour ton compte</strong> (identité, connexion, liaison Claude, réglages), AiTools est <strong>responsable de traitement</strong>.</li>
|
||||||
|
<li><strong>Pour les données de tes prospects</strong> (entreprises et adresses professionnelles que tu recherches, importes ou contactes), c'est <strong>toi le responsable de traitement</strong> : tu décides à qui tu écris et pourquoi. AiTools agit comme <strong>sous-traitant</strong> : il les traite uniquement pour faire fonctionner le service que tu utilises, sur tes instructions, avec les garanties de sécurité décrites plus bas, et les supprime avec ton compte. ${todo('processing')}</li>
|
||||||
|
</ul>`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'donnees', title: 'Les données collectées',
|
||||||
|
html: `<div class="table-wrap"><table>
|
||||||
|
<caption>Données réellement enregistrées par AiTools</caption>
|
||||||
|
<thead><tr><th scope="col">Catégorie</th><th scope="col">Contenu</th><th scope="col">Pourquoi et sur quelle base</th></tr></thead>
|
||||||
|
<tbody>
|
||||||
|
<tr><th scope="row">Compte</th><td>Email et nom fournis par ${apple ? 'Google ou Apple' : 'Google'}, fournisseur de connexion et identifiant chez lui, plan, dates de création et de dernière connexion.</td><td>Créer ton compte et te connecter. Exécution du contrat.</td></tr>
|
||||||
|
<tr><th scope="row">Session</th><td>Un identifiant de session aléatoire (cookie), un cookie de liaison pendant la connexion.</td><td>Te garder connecté et sécuriser la connexion. Exécution du contrat, intérêt légitime.</td></tr>
|
||||||
|
<tr><th scope="row">Liaison Claude</th><td>Ta clé API ou ton jeton d'abonnement, chiffrés. Les 4 derniers caractères d'une clé API, les dates de liaison et de test, la date et la version du texte d'avertissement accepté pour le mode abonnement.</td><td>Lancer tes jobs avec ton accès, garder la preuve de ton acceptation. Exécution du contrat, intérêt légitime.</td></tr>
|
||||||
|
<tr><th scope="row">Projets</th><td>Nom, adresse du dépôt Git, fiche projet, cible, modèles de mail, copie du dépôt sur le serveur.</td><td>Fournir le service. Exécution du contrat.</td></tr>
|
||||||
|
<tr><th scope="row">Configuration</th><td>Identifiants SMTP et IMAP, accès à la base de données de ton projet (récapitulatif), jeton Forgejo, adresse du webhook Discord, plafonds et budgets. Les mots de passe, jetons et adresses de webhook sont chiffrés.</td><td>Envoyer, lire les réponses, notifier. Exécution du contrat.</td></tr>
|
||||||
|
<tr><th scope="row">Prospects</th><td>Entreprise, adresse professionnelle, site, ville, secteur, phrase d'accroche, page source, score, statut, notes, prochaine action, historique d'envoi, objet et date d'une réponse.</td><td>Fournir le service pour ton compte (voir « rôles »). La base légale du démarchage est la tienne, en B2B en règle générale l'intérêt légitime.</td></tr>
|
||||||
|
<tr><th scope="row">Activité</th><td>Type, état, durée, coût et nombre de tokens de chaque job IA, résultat du job. Chaque jour, trois nombres lus dans la base de ton projet si tu l'as reliée (utilisateurs, clients, revenu).</td><td>Fournir le service, appliquer tes budgets et plafonds. Exécution du contrat.</td></tr>
|
||||||
|
<tr><th scope="row">Liste d'opposition</th><td>Adresse email, motif (désinscription, refus, mail rejeté) et date.</td><td>Ne plus jamais contacter une personne qui s'y est opposée, pour tous les comptes. Obligation légale, intérêt légitime.</td></tr>
|
||||||
|
</tbody>
|
||||||
|
</table></div>
|
||||||
|
<p>AiTools ne collecte ni statistiques de visite, ni identifiant publicitaire, et ne charge aucun pixel de suivi.</p>`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'durees', title: 'Combien de temps',
|
||||||
|
html: `<div class="table-wrap"><table>
|
||||||
|
<caption>Durées de conservation ${todo('retention')}</caption>
|
||||||
|
<thead><tr><th scope="col">Donnée</th><th scope="col">Durée</th></tr></thead>
|
||||||
|
<tbody>
|
||||||
|
<tr><th scope="row">Compte et toutes ses données</th><td>Tant que le compte existe. Effacés quand tu supprimes ton compte depuis Mon compte, copie du code comprise.</td></tr>
|
||||||
|
<tr><th scope="row">Compte inactif</th><td>Suppression prévue après 24 mois sans connexion. Cette suppression automatique n'est pas encore en place.</td></tr>
|
||||||
|
<tr><th scope="row">Session</th><td>30 jours au plus, effacée à la déconnexion. Les états de connexion durent 10 minutes.</td></tr>
|
||||||
|
<tr><th scope="row">Clé API ou jeton Claude</th><td>Jusqu'à ce que tu le délies ou supprimes ton compte.</td></tr>
|
||||||
|
<tr><th scope="row">Prospects, notes et journaux d'envoi</th><td>Jusqu'à la suppression du projet ou du compte. En tant que responsable de traitement, ne garde pas une fiche plus de 3 ans après le dernier contact.</td></tr>
|
||||||
|
<tr><th scope="row">Liste d'opposition</th><td>Conservée après la suppression d'un compte, tant qu'il faut respecter l'opposition de la personne.</td></tr>
|
||||||
|
<tr><th scope="row">Sauvegardes</th><td>Environ 14 jours : une donnée effacée disparaît des sauvegardes à leur expiration.</td></tr>
|
||||||
|
<tr><th scope="row">Journaux d'accès du serveur web</th><td>12 mois au plus (adresse IP, date, page demandée), pour la sécurité.</td></tr>
|
||||||
|
</tbody>
|
||||||
|
</table></div>`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'destinataires', title: 'Qui reçoit les données',
|
||||||
|
html: `<p>Aucune donnée n'est vendue ni cédée. Elles sont accessibles aux seuls prestataires nécessaires au service :</p>
|
||||||
|
<ul>
|
||||||
|
<li><strong>Google</strong> pour la connexion : il nous transmet ton email, ton nom et un identifiant. <a href="https://policies.google.com/privacy" rel="noopener noreferrer">Politique de Google</a>.</li>
|
||||||
|
${apple ? '<li><strong>Apple</strong> pour la connexion avec Apple : même principe, avec la possibilité de masquer ton email. <a href="https://www.apple.com/legal/privacy/fr-fr/" rel="noopener noreferrer">Politique d\'Apple</a>.</li>' : ''}
|
||||||
|
<li><strong>Anthropic</strong>, par l'intermédiaire de <em>ton</em> accès Claude : le code de ton projet lu par Claude, la fiche et la cible, les domaines des prospects déjà connus pour éviter les doublons, et ce que Claude trouve sur le web transitent par ton compte Anthropic, selon les conditions que tu as acceptées avec lui. <a href="https://www.anthropic.com/legal/privacy" rel="noopener noreferrer">Politique d'Anthropic</a>.</li>
|
||||||
|
<li><strong>L'hébergeur</strong> du serveur : ${todo('host')}</li>
|
||||||
|
<li><strong>Tes propres services</strong>, quand tu les configures : serveur SMTP et IMAP de ta messagerie, Forgejo, base de données de ton projet, Discord. AiTools s'y connecte avec tes identifiants.</li>
|
||||||
|
</ul>
|
||||||
|
<p>Les adresses de tes prospects ne sont pas transmises à d'autres utilisateurs. Chaque compte est cloisonné : une ressource d'un autre compte répond « introuvable ».</p>`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'transferts', title: 'Transferts hors de l\'Union européenne',
|
||||||
|
html: `<p>${apple ? 'Google, Apple et Anthropic' : 'Google et Anthropic'} peuvent traiter des données aux États-Unis. Ils s'appuient pour cela sur les mécanismes prévus par le RGPD (clauses contractuelles types, cadre de protection des données UE-États-Unis) décrits dans leurs politiques. ${todo('transfers')}</p>
|
||||||
|
<p>Le reste du service (base de données, application) est hébergé selon les indications de la section « hébergeur ».</p>`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'cookies', title: 'Cookies et traceurs',
|
||||||
|
html: `<p>AiTools ne pose que des cookies <strong>strictement nécessaires</strong> au service. Ils sont exemptés de consentement : c'est pourquoi aucun bandeau ne s'affiche. Pas d'analyse d'audience, pas de publicité, pas de police ni de script chargés depuis un autre site.</p>
|
||||||
|
<div class="table-wrap"><table>
|
||||||
|
<caption>Cookies posés par AiTools</caption>
|
||||||
|
<thead><tr><th scope="col">Nom</th><th scope="col">Rôle</th><th scope="col">Durée</th></tr></thead>
|
||||||
|
<tbody>
|
||||||
|
<tr><th scope="row"><code>sid</code></th><td>Te garder connecté (identifiant de session aléatoire). Sécurisé : HttpOnly, Secure, SameSite=Lax.</td><td>30 jours au plus</td></tr>
|
||||||
|
<tr><th scope="row"><code>oauth_b</code></th><td>Relier une tentative de connexion à ton navigateur, pour empêcher qu'un tiers la détourne. Limité aux adresses de connexion.</td><td>10 minutes</td></tr>
|
||||||
|
</tbody>
|
||||||
|
</table></div>
|
||||||
|
<p>Le tableau de bord retient aussi, dans la mémoire de session de ton navigateur, le projet que tu as ouvert en dernier ; cette mémoire est effacée à la fermeture de l'onglet et rien n'est envoyé au serveur.</p>
|
||||||
|
<p>Si un traceur non essentiel devait un jour être ajouté, un choix « Accepter » ou « Refuser » apparaîtrait avant tout dépôt, et cette page serait mise à jour.</p>`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'droits', title: 'Tes droits',
|
||||||
|
html: `<p>Tu peux demander l'accès à tes données, leur rectification, leur effacement, la limitation ou l'opposition à leur traitement, et leur portabilité.</p>
|
||||||
|
<ul>
|
||||||
|
<li><strong>Suppression :</strong> directement dans Mon compte. Elle efface ton compte et ses données, immédiatement.</li>
|
||||||
|
<li><strong>Export :</strong> tes prospects s'exportent en CSV depuis le tableau de bord. Pour le reste de tes données, écris-nous.</li>
|
||||||
|
<li><strong>Autres demandes :</strong> par email à <a href="mailto:${CONTACT_EMAIL}">${CONTACT_EMAIL}</a>. Réponse sous un mois au plus. Nous pouvons demander une preuve que la demande vient bien de toi.</li>
|
||||||
|
</ul>
|
||||||
|
<p>Tu peux aussi saisir la CNIL : <a href="https://www.cnil.fr/fr/plaintes" rel="noopener noreferrer">cnil.fr/fr/plaintes</a>.</p>`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'prospects', title: 'Tu as reçu un mail envoyé avec AiTools ?',
|
||||||
|
html: `<p>L'expéditeur est un utilisateur d'AiTools : c'est lui le responsable du traitement de ton adresse professionnelle. Le pied du mail indique la page publique où elle a été trouvée.</p>
|
||||||
|
<ul>
|
||||||
|
<li><strong>Ne plus recevoir de messages :</strong> clique sur le lien de désinscription du mail. Ton adresse entre dans une liste d'opposition respectée par tous les utilisateurs d'AiTools.</li>
|
||||||
|
<li><strong>Accès, effacement, opposition :</strong> adresse-toi à l'expéditeur. Tu peux aussi écrire à <a href="mailto:${CONTACT_EMAIL}">${CONTACT_EMAIL}</a> : nous inscrivons ton adresse en liste d'opposition et transmettons ta demande.</li>
|
||||||
|
</ul>`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'securite', title: 'Sécurité',
|
||||||
|
html: `<ul>
|
||||||
|
<li>Connexions chiffrées (HTTPS) et cookies sécurisés.</li>
|
||||||
|
<li>Aucun mot de passe : la connexion passe par ${apple ? 'Google ou Apple' : 'Google'}.</li>
|
||||||
|
<li>Clés, jetons et mots de passe de services enregistrés chiffrés (AES-256-GCM), jamais réaffichés, jamais écrits dans les journaux.</li>
|
||||||
|
<li>Comptes cloisonnés : chaque requête est filtrée par utilisateur.</li>
|
||||||
|
<li>Les jobs IA s'exécutent dans un environnement isolé qui ne voit que le clone du projet de leur propriétaire.</li>
|
||||||
|
</ul>
|
||||||
|
<p>En cas de violation de données susceptible de te porter préjudice, tu seras prévenu, et la CNIL le sera dans les 72 heures lorsque la loi l'exige.</p>`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'public', title: 'Public concerné et mises à jour',
|
||||||
|
html: `<p>Le service s'adresse à des professionnels majeurs. Cette page peut évoluer ; la date de mise à jour figure en haut, et un changement important sera signalé aux utilisateurs.</p>`,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- Conditions générales d'utilisation ----------
|
||||||
|
export function termsPage({ appUrl, apple = false }) {
|
||||||
|
return legalPage({
|
||||||
|
appUrl, path: '/cgu',
|
||||||
|
title: "Conditions générales d'utilisation · AiTools",
|
||||||
|
description: "Les règles d'usage d'AiTools : compte, plan gratuit, liaison de ton accès Claude (y compris le risque de l'abonnement), usages interdits, responsabilités, résiliation.",
|
||||||
|
h1: "Conditions générales d'utilisation",
|
||||||
|
lead: "Les règles du jeu entre toi et AiTools. À lire avant de relier ton accès Claude.",
|
||||||
|
sections: [
|
||||||
|
{
|
||||||
|
id: 'objet', title: 'Objet et éditeur',
|
||||||
|
html: `<p>AiTools est un service en ligne édité par Tony AVERTY, entrepreneur individuel (voir les <a href="/mentions-legales">mentions légales</a>). Il pilote Claude Code, avec ton propre accès Claude, pour analyser un projet, rechercher des prospects professionnels, rédiger et envoyer des mails de prospection, relancer et suivre les réponses.</p>
|
||||||
|
<p>Utiliser le service, c'est accepter ces conditions. Si tu ne les acceptes pas, ne crée pas de compte.</p>`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'acces', title: 'Accès et public',
|
||||||
|
html: `<p>Le service est réservé aux personnes majeures qui l'utilisent pour leurs besoins professionnels. Il n'est pas destiné aux consommateurs.</p>`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'compte', title: 'Ton compte',
|
||||||
|
html: `<p>Le compte est créé à la première connexion avec ${apple ? 'Google ou Apple' : 'Google'}. Un compte correspond à une personne. Tu es responsable de la sécurité de l'accès à ton compte de connexion, et de tout ce qui est fait depuis ton compte AiTools. Préviens-nous sans attendre si tu penses qu'un tiers y a accès.</p>`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'claude', title: 'Ton accès Claude',
|
||||||
|
html: `<p>Pour lancer un job, tu relies ton propre accès à Claude. AiTools ne fournit ni crédits ni abonnement.</p>
|
||||||
|
<ul>
|
||||||
|
<li><strong>Clé API Anthropic :</strong> Anthropic te facture directement, selon ses tarifs. Tu es responsable de cette dépense. Les budgets réglables dans AiTools sont des garde-fous, pas une garantie.</li>
|
||||||
|
<li><strong>Abonnement Claude (jeton) :</strong> les conditions d'Anthropic peuvent ne pas autoriser l'usage d'un abonnement via une application tierce. Si tu choisis ce mode, <strong>ton compte Claude peut être limité, suspendu ou fermé</strong> par Anthropic. L'éditeur d'AiTools n'a aucun contrôle sur cette décision et n'en est pas responsable, dans la mesure permise par la loi. Avant la liaison, une fenêtre d'avertissement te demande de cocher « J'ai compris et j'accepte ce risque ». Cette acceptation est enregistrée avec sa date et la version du texte. Ce mode peut être désactivé à tout moment.</li>
|
||||||
|
</ul>
|
||||||
|
<p>Tu peux délier ton accès à tout moment depuis Mon compte : le secret est alors effacé et tes jobs IA en attente sont annulés.</p>`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'plans', title: 'Plan gratuit et plans payants',
|
||||||
|
html: `<p>Le plan gratuit comprend 1 projet, 50 prospects, 100 mails et 5 jobs IA par mois. Ces limites peuvent évoluer, avec information préalable. Un plan payant est prévu mais n'est pas ouvert : aucun paiement n'est demandé aujourd'hui. Ses conditions et son prix seront publiés avant toute facturation, et ne s'appliqueront qu'avec ton accord.</p>`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'envois', title: 'Tes envois',
|
||||||
|
html: `<p>Tu es seul responsable des mails envoyés depuis ton compte, de leur contenu, de tes destinataires et de la manière dont tu as obtenu leurs adresses. En particulier :</p>
|
||||||
|
<ul>
|
||||||
|
<li>tu ne prospectes que des professionnels, à propos de leur activité professionnelle ;</li>
|
||||||
|
<li>tu laisses en place le lien de désinscription et la mention de la source, ajoutés automatiquement ;</li>
|
||||||
|
<li>tu ne recontactes pas une personne qui s'est opposée, et tu respectes les demandes d'effacement qu'elle t'adresse ;</li>
|
||||||
|
<li>tu relis ce que Claude propose avant d'envoyer : il peut se tromper.</li>
|
||||||
|
</ul>
|
||||||
|
<p>Tu configures toi-même ton serveur d'envoi. La réputation de ton domaine (SPF, DKIM, DMARC, volume) t'appartient.</p>`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'interdits', title: 'Usages interdits',
|
||||||
|
html: `<ul>
|
||||||
|
<li>Envoyer du spam, ou des mails sans base légale.</li>
|
||||||
|
<li>Démarcher des particuliers sans leur consentement préalable (prospection « B2C »).</li>
|
||||||
|
<li>Utiliser des adresses devinées, achetées sans garantie de conformité, ou collectées de façon déloyale.</li>
|
||||||
|
<li>Tromper les destinataires : fausse identité, objet mensonger, usurpation.</li>
|
||||||
|
<li>Envoyer des contenus illicites, haineux, frauduleux, ou des logiciels malveillants.</li>
|
||||||
|
<li>Contourner les limites du service, le surcharger, tenter d'accéder aux données d'un autre compte ou d'attaquer le service.</li>
|
||||||
|
<li>Partager ton compte, ou revendre l'accès au service.</li>
|
||||||
|
</ul>`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'donnees', title: 'Données personnelles',
|
||||||
|
html: `<p>Les rôles de chacun sont décrits dans la <a href="/confidentialite">politique de confidentialité</a> : tu es responsable de traitement pour les données de tes prospects, AiTools est ton sous-traitant. Tu t'engages à n'enregistrer que des données que tu as le droit de traiter, et à informer les personnes concernées comme la loi l'exige. ${todo('processing')}</p>`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'garanties', title: 'Disponibilité et résultats',
|
||||||
|
html: `<p>Le service est fourni en l'état. Il peut être interrompu pour maintenance ou en cas d'incident, et l'éditeur ne garantit pas une disponibilité continue. Aucun résultat n'est garanti : ni nombre de réponses, ni clients obtenus. Les textes et analyses produits par Claude peuvent contenir des erreurs ; tu les vérifies avant de les utiliser.</p>`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'propriete', title: 'Propriété intellectuelle',
|
||||||
|
html: `<p>Tes contenus (projets, prospects, modèles de mail) restent à toi. Tu donnes à l'éditeur l'autorisation de les traiter uniquement pour faire fonctionner le service pour toi. Le service lui-même (code, textes, identité visuelle) reste la propriété de l'éditeur ; tu reçois un droit d'usage personnel, non exclusif et non transférable, le temps de ton compte.</p>`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'responsabilite', title: 'Responsabilité',
|
||||||
|
html: `<p>L'éditeur répond des dommages directs qui lui sont imputables. Dans la mesure permise par la loi, il n'est pas responsable des dommages indirects, de la suspension ou de la fermeture de ton compte Claude, des frais facturés par Anthropic ou tes autres prestataires, de la réputation de ton domaine d'envoi, ni de l'usage que tu fais du service en violation de ces conditions. Rien ici n'exclut la responsabilité en cas de faute lourde ou de dol, ni celle que la loi interdit de limiter. ${todo('liability')}</p>`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'suspension', title: 'Suspension et résiliation',
|
||||||
|
html: `<p><strong>Par toi :</strong> tu peux supprimer ton compte à tout moment depuis Mon compte. Tes données sont alors effacées, sauf la liste d'opposition.</p>
|
||||||
|
<p><strong>Par l'éditeur :</strong> en cas de manquement à ces conditions, d'abus, de plaintes de destinataires, de risque pour la sécurité ou la réputation du service, ton compte peut être suspendu, puis supprimé. Nous t'en informons quand c'est possible. Une suspension peut être immédiate quand l'urgence l'exige.</p>`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'modifications', title: 'Modification des conditions',
|
||||||
|
html: `<p>Ces conditions peuvent évoluer. Un changement important est annoncé aux utilisateurs avant son entrée en vigueur ; continuer à utiliser le service après cette date vaut acceptation. Si tu refuses, supprime ton compte.</p>`,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'droit', title: 'Droit applicable et litiges',
|
||||||
|
html: `<p>Ces conditions sont soumises au droit français. En cas de difficulté, écris d'abord à <a href="mailto:${CONTACT_EMAIL}">${CONTACT_EMAIL}</a> : nous cherchons une solution amiable. À défaut, les tribunaux français sont compétents.</p>`,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
}
|
||||||
366
src/site/pages.js
Normal file
366
src/site/pages.js
Normal file
|
|
@ -0,0 +1,366 @@
|
||||||
|
// Pages publiques du site (rendu serveur, sans script). Les textes sont écrits pour être lus tels quels :
|
||||||
|
// rien ici ne promet un résultat, rien n'est chiffré au-delà de ce que le code fait réellement.
|
||||||
|
import { esc } from '../http.js';
|
||||||
|
import { siteLayout } from './layout.js';
|
||||||
|
|
||||||
|
/** « Google » ou « Google ou Apple » selon la configuration réelle de la connexion. */
|
||||||
|
export const providersText = (apple) => (apple ? 'Google ou Apple' : 'Google');
|
||||||
|
|
||||||
|
// ---------- Connexion ----------
|
||||||
|
export function loginPage({ appUrl, error = null, apple = false, bye = false }) {
|
||||||
|
return siteLayout({
|
||||||
|
appUrl, path: '/login', noindex: true,
|
||||||
|
title: 'Connexion · AiTools',
|
||||||
|
description: `Connecte-toi à AiTools avec ton compte ${providersText(apple)}. Ton compte est créé à la première connexion, sans mot de passe.`,
|
||||||
|
body: `<div class="wrap auth">
|
||||||
|
<div>
|
||||||
|
<p class="eyebrow"><span class="mark" aria-hidden="true"></span>Connexion</p>
|
||||||
|
<h1>Entre dans ton espace</h1>
|
||||||
|
<p class="lead">Ton compte est créé à la première connexion, sans mot de passe. Juste après, tu relies ton accès Claude : sans lui, aucun job ne se lance.</p>
|
||||||
|
<p class="fine">Tu n'as pas encore de compte ? C'est le même bouton. Le plan gratuit ne demande pas de carte bancaire.</p>
|
||||||
|
</div>
|
||||||
|
<section class="card" aria-labelledby="connexion-titre">
|
||||||
|
<h2 id="connexion-titre">Continuer avec</h2>
|
||||||
|
${bye ? '<p class="ok" role="status">Ton compte et toutes ses données ont été supprimés.</p>' : ''}
|
||||||
|
${error ? `<p class="error" role="alert">${esc(error)}</p>` : ''}
|
||||||
|
<div class="login-btns">
|
||||||
|
<a class="btn primary" href="/auth/google">Se connecter avec Google</a>
|
||||||
|
${apple ? '<a class="btn apple" href="/auth/apple">Se connecter avec Apple</a>' : ''}
|
||||||
|
</div>
|
||||||
|
<p class="fine">En te connectant, tu acceptes les <a href="/cgu">conditions d'utilisation</a> et tu reconnais avoir pris connaissance de la <a href="/confidentialite">politique de confidentialité</a>.</p>
|
||||||
|
</section>
|
||||||
|
</div>`,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- 404 ----------
|
||||||
|
export function notFoundPage({ appUrl }) {
|
||||||
|
return siteLayout({
|
||||||
|
appUrl, path: '/404', noindex: true,
|
||||||
|
title: 'Page introuvable · AiTools',
|
||||||
|
description: "Cette page n'existe pas ou a changé d'adresse.",
|
||||||
|
body: `<div class="wrap page-head">
|
||||||
|
<p class="eyebrow"><span class="mark" aria-hidden="true"></span>Erreur 404</p>
|
||||||
|
<h1>Cette page n'existe pas</h1>
|
||||||
|
<p class="lead">L'adresse est peut-être mal saisie, ou la page a changé de place. Voici où aller ensuite.</p>
|
||||||
|
<div class="cta-row">
|
||||||
|
<a class="btn primary" href="/">Retour à l'accueil</a>
|
||||||
|
<a class="textlink" href="/fonctionnement">Voir le fonctionnement</a>
|
||||||
|
<a class="textlink" href="/tarifs">Voir les tarifs</a>
|
||||||
|
</div>
|
||||||
|
</div>`,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- Accueil ----------
|
||||||
|
const HOME_JSON_LD = (appUrl) => ({
|
||||||
|
'@context': 'https://schema.org',
|
||||||
|
'@type': 'SoftwareApplication',
|
||||||
|
name: 'AiTools',
|
||||||
|
url: `${appUrl}/`,
|
||||||
|
applicationCategory: 'BusinessApplication',
|
||||||
|
operatingSystem: 'Web',
|
||||||
|
inLanguage: 'fr',
|
||||||
|
description: 'Panel qui pilote Claude Code pour analyser un projet, trouver des prospects, rédiger et envoyer des mails de prospection, relancer et suivre les réponses.',
|
||||||
|
offers: { '@type': 'Offer', price: '0', priceCurrency: 'EUR', description: 'Plan gratuit : 1 projet, 50 prospects, 100 mails et 5 jobs IA par mois' },
|
||||||
|
publisher: { '@type': 'Person', name: 'Tony AVERTY' },
|
||||||
|
});
|
||||||
|
|
||||||
|
// Maquette du tableau de bord : les vrais composants (.card, .badge, .running, .bar, table), des données d'exemple
|
||||||
|
const MOCKUP = `<figure class="shot">
|
||||||
|
<div class="mock" role="img" aria-label="Aperçu du tableau de bord : un projet dont la cible est validée, une recherche de prospects en cours et trois prospects avec leur statut">
|
||||||
|
<div class="mock-top"><span class="brand"><span class="mark"></span>AiTools</span><span class="push">Mon compte · Réglages</span></div>
|
||||||
|
<div class="card">
|
||||||
|
<div class="mock-name"><span>Atelier Exemple</span><span class="badge ok">cible validée</span></div>
|
||||||
|
<p class="mock-sub">Fiche projet générée depuis le dépôt Git</p>
|
||||||
|
<div class="running"><div>
|
||||||
|
<div class="run-head"><span>Recherche de prospects</span><span class="jpct">6 / 10</span></div>
|
||||||
|
<p class="mock-sub">Dernier trouvé : Menuiserie Exemple</p>
|
||||||
|
<div class="bar"><span class="w-60"></span></div>
|
||||||
|
</div></div>
|
||||||
|
</div>
|
||||||
|
<div class="card">
|
||||||
|
<div class="table-wrap"><table>
|
||||||
|
<thead><tr><th>Entreprise</th><th class="col-city">Ville</th><th>Score</th><th>Statut</th></tr></thead>
|
||||||
|
<tbody>
|
||||||
|
<tr><td>Menuiserie Exemple</td><td class="col-city">Lyon</td><td>8</td><td class="st-new">À contacter</td></tr>
|
||||||
|
<tr><td>Garage Exemple</td><td class="col-city">Nantes</td><td>7</td><td class="st-replied">A répondu</td></tr>
|
||||||
|
<tr><td>Cabinet Exemple</td><td class="col-city">Lille</td><td>6</td><td>Contacté</td></tr>
|
||||||
|
</tbody>
|
||||||
|
</table></div>
|
||||||
|
</div>
|
||||||
|
<span class="btn small primary">Lancer la recherche</span> <span class="btn small">Modèle de mail</span>
|
||||||
|
</div>
|
||||||
|
<figcaption class="fine">Le tableau de bord, avec des données d'exemple.</figcaption>
|
||||||
|
</figure>`;
|
||||||
|
|
||||||
|
export function homePage({ appUrl, apple = false }) {
|
||||||
|
return siteLayout({
|
||||||
|
appUrl, path: '/',
|
||||||
|
title: 'AiTools : prospection par mail avec ton propre Claude',
|
||||||
|
description: 'Un panel qui pilote Claude Code pour analyser ton projet, trouver des prospects, rédiger et envoyer tes mails de prospection, relancer et suivre les réponses.',
|
||||||
|
jsonLd: HOME_JSON_LD(appUrl),
|
||||||
|
body: `<section class="wrap hero" aria-labelledby="titre-accueil">
|
||||||
|
<div class="hero-text">
|
||||||
|
<p class="eyebrow"><span class="mark" aria-hidden="true"></span>Prospection B2B par mail</p>
|
||||||
|
<h1 id="titre-accueil">Un panel pour prospecter par mail, avec ton propre accès Claude</h1>
|
||||||
|
<p class="lead">AiTools lit ton projet, cherche des entreprises qui pourraient en avoir besoin, rédige les mails, les envoie depuis ta boîte et suit les réponses. Tu valides la cible, tu relis le modèle, tu choisis combien de mails partent.</p>
|
||||||
|
<div class="cta-row">
|
||||||
|
<a class="btn primary" href="/login">Créer mon compte</a>
|
||||||
|
<a class="textlink" href="/fonctionnement">Voir comment ça marche</a>
|
||||||
|
</div>
|
||||||
|
<p class="fine">Gratuit pour commencer, sans carte bancaire. Connexion avec ${providersText(apple)}, sans mot de passe.</p>
|
||||||
|
</div>
|
||||||
|
${MOCKUP}
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<div class="rule" aria-hidden="true"></div>
|
||||||
|
|
||||||
|
<section class="wrap block" aria-labelledby="titre-regles">
|
||||||
|
<div class="split">
|
||||||
|
<div class="sticky">
|
||||||
|
<h2 id="titre-regles">Ton accès, ta boîte mail, tes règles</h2>
|
||||||
|
<p>AiTools orchestre le travail. L'accès à Claude et la boîte d'envoi restent les tiens.</p>
|
||||||
|
</div>
|
||||||
|
<ul class="facts">
|
||||||
|
<li>
|
||||||
|
<h3>Ton accès Claude</h3>
|
||||||
|
<p>Les analyses et les rédactions tournent avec ta clé API Anthropic, facturée par Anthropic selon ton usage, ou avec ton abonnement Claude, au risque expliqué sur la page <a href="/tarifs#acces-claude">Tarifs</a>. AiTools ne revend pas de crédits.</p>
|
||||||
|
</li>
|
||||||
|
<li>
|
||||||
|
<h3>Ta boîte d'envoi</h3>
|
||||||
|
<p>Les mails partent de ton serveur SMTP, depuis ton adresse. Les réponses sont lues dans ta boîte, en IMAP.</p>
|
||||||
|
</li>
|
||||||
|
<li>
|
||||||
|
<h3>Tes envois, ta responsabilité</h3>
|
||||||
|
<p>Prospection entre professionnels uniquement, lien de désinscription dans chaque mail, liste d'opposition respectée. Tu restes responsable de ce que tu envoies.</p>
|
||||||
|
</li>
|
||||||
|
<li>
|
||||||
|
<h3>Tes données</h3>
|
||||||
|
<p>Chaque compte est cloisonné. Depuis Mon compte, tu supprimes ton compte et tout ce qu'il contient.</p>
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="wrap block" aria-labelledby="titre-etapes">
|
||||||
|
<h2 id="titre-etapes">Du dépôt Git à la réponse</h2>
|
||||||
|
<ol class="steps compact">
|
||||||
|
<li><h3>Il lit ton projet</h3><p>Claude parcourt ton dépôt en lecture seule et écrit une fiche : ce que fait le produit, pour qui, avec quels arguments.</p></li>
|
||||||
|
<li><h3>Tu valides la cible</h3><p>Secteurs, zone, taille, décideur. Aucune recherche ne démarre tant que tu n'as pas validé.</p></li>
|
||||||
|
<li><h3>Il cherche des prospects</h3><p>Des adresses professionnelles publiées sur le web, avec la page source et un score de pertinence.</p></li>
|
||||||
|
<li><h3>Il rédige</h3><p>Un modèle de mail, un objet B pour un test A/B, une relance. Tu modifies, tu valides.</p></li>
|
||||||
|
<li><h3>Il envoie, sans se presser</h3><p>Des lots de la taille que tu choisis, avec des plafonds par jour et un délai aléatoire entre deux mails.</p></li>
|
||||||
|
<li><h3>Il suit les réponses</h3><p>Réponses, adresses invalides et relance unique dans le même fil, puis un CRM pour garder la trace.</p></li>
|
||||||
|
</ol>
|
||||||
|
<p><a class="textlink" href="/fonctionnement">Le détail, étape par étape</a></p>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="wrap block" aria-labelledby="titre-limites">
|
||||||
|
<h2 id="titre-limites">Ce qu'AiTools ne fait pas</h2>
|
||||||
|
<div class="statement">
|
||||||
|
<p>Il ne promet aucune réponse : un mail bien écrit reste un mail envoyé à quelqu'un qui n'a rien demandé.</p>
|
||||||
|
<p>Il demande à Claude de ne retenir que des adresses professionnelles publiées publiquement, jamais devinées. Claude peut quand même se tromper : relis les fiches avant d'envoyer.</p>
|
||||||
|
<p>Il ne contacte pas de particuliers, et il n'envoie rien dans ton dos. Les premiers mails partent quand tu confirmes un envoi, la relance automatique quand tu l'actives.</p>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<div class="rule" aria-hidden="true"></div>
|
||||||
|
|
||||||
|
<section class="wrap block" aria-labelledby="titre-fin">
|
||||||
|
<div class="closing">
|
||||||
|
<div>
|
||||||
|
<h2 id="titre-fin">Commence avec le plan gratuit</h2>
|
||||||
|
<p>1 projet, 50 prospects, 100 mails et 5 jobs IA par mois. Le plan payant n'est pas ouvert : <a href="/tarifs">le détail est sur la page Tarifs</a>.</p>
|
||||||
|
</div>
|
||||||
|
<a class="btn primary" href="/login">Créer mon compte</a>
|
||||||
|
</div>
|
||||||
|
</section>`,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- Fonctionnement ----------
|
||||||
|
export function howPage({ appUrl, apple = false }) {
|
||||||
|
return siteLayout({
|
||||||
|
appUrl, path: '/fonctionnement',
|
||||||
|
title: 'Fonctionnement : du dépôt Git aux réponses · AiTools',
|
||||||
|
description: "Comment AiTools analyse ton projet, cherche des prospects, rédige et envoie les mails, relance et suit les réponses, étape par étape et avec ses limites.",
|
||||||
|
body: `<div class="wrap page-head">
|
||||||
|
<p class="eyebrow"><span class="mark" aria-hidden="true"></span>Fonctionnement</p>
|
||||||
|
<h1>Comment ça marche, vraiment</h1>
|
||||||
|
<p class="lead">Sept étapes, dans cet ordre. Pour chacune : ce que fait l'outil, ce que tu décides, et ce qu'il ne sait pas faire.</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="rule" aria-hidden="true"></div>
|
||||||
|
|
||||||
|
<section class="wrap block" aria-label="Les étapes">
|
||||||
|
<ol class="steps">
|
||||||
|
<li>
|
||||||
|
<h2>Tu relies ton accès Claude</h2>
|
||||||
|
<p>Après la connexion (${providersText(apple)}), AiTools te demande ton propre accès à Claude. Sans lui, la seule chose possible est de gérer ton compte : aucun job ne se lance.</p>
|
||||||
|
<ul>
|
||||||
|
<li>Une clé API Anthropic : elle est vérifiée sans consommer de tokens, chiffrée, et seuls ses 4 derniers caractères restent affichés.</li>
|
||||||
|
<li>Ou un jeton d'abonnement Claude, après un avertissement et une case à cocher. Les risques sont détaillés sur la page <a href="/tarifs#acces-claude">Tarifs</a>.</li>
|
||||||
|
</ul>
|
||||||
|
</li>
|
||||||
|
<li>
|
||||||
|
<h2>Tu ajoutes un projet</h2>
|
||||||
|
<p>Un projet, c'est un dépôt Git en https sur le Forgejo que tu déclares dans les réglages, avec un jeton en lecture seule si le dépôt est privé. AiTools le clone sur le serveur et Claude le lit : README, manifestes, pages principales, une quinzaine de fichiers au plus.</p>
|
||||||
|
<p>L'analyse produit une fiche : ce que fait le produit, la proposition de valeur, les arguments de vente, une cible suggérée. Elle ne tourne qu'une fois, puis à ta demande. En production, chaque job IA s'exécute dans un environnement isolé qui ne voit que le clone de ton projet.</p>
|
||||||
|
</li>
|
||||||
|
<li>
|
||||||
|
<h2>Tu valides la cible</h2>
|
||||||
|
<p>La fiche propose une cible : description, secteurs, zone, taille, décideur, requêtes de recherche. Tu corriges ce qui ne va pas. Tant que tu n'as pas cliqué sur « Valider la cible », la recherche de prospects reste verrouillée.</p>
|
||||||
|
</li>
|
||||||
|
<li>
|
||||||
|
<h2>Il cherche des prospects</h2>
|
||||||
|
<p>Tu demandes de 1 à 50 prospects, maintenant ou « cette nuit » (entre 1 h et 6 h, heure de Paris). Claude cherche sur le web. Il lui est demandé de ne garder que des adresses professionnelles publiées publiquement, jamais devinées, et de donner l'adresse exacte de la page où il les a vues.</p>
|
||||||
|
<p>Chaque fiche contient l'entreprise, l'email, le site, la ville, le secteur, une phrase d'accroche écrite d'après leur site, la source et un score de 1 à 10. Les adresses déjà dans la liste d'opposition sont écartées. Tu peux aussi importer un CSV (2 000 lignes au plus).</p>
|
||||||
|
<p><strong>Limite :</strong> Claude peut se tromper d'adresse ou juger mal une entreprise. Relis les fiches.</p>
|
||||||
|
</li>
|
||||||
|
<li>
|
||||||
|
<h2>Il rédige les mails</h2>
|
||||||
|
<p>Claude propose un premier mail court, un objet B pour un test A/B (les envois alternent entre les deux objets) et un mail de relance. Tu modifies, tu enregistres, puis tu valides le modèle. Les variables <code>{{entreprise}}</code>, <code>{{ville}}</code> et <code>{{accroche}}</code> personnalisent chaque envoi.</p>
|
||||||
|
<p>Le lien de désinscription et la mention de la source de l'adresse sont ajoutés automatiquement à chaque mail.</p>
|
||||||
|
</li>
|
||||||
|
<li>
|
||||||
|
<h2>Il envoie, sans se presser</h2>
|
||||||
|
<p>Tu choisis la taille de chaque lot (100 mails au plus) et tu confirmes. Les mails partent depuis ton serveur SMTP, avec un délai aléatoire entre deux envois (20 à 60 secondes par défaut). Des plafonds sur 24 heures s'appliquent par projet (réglable, 200 au plus) et pour l'ensemble de ton compte (réglable, 300 au plus). Un prospect n'est contacté qu'une fois.</p>
|
||||||
|
<p><strong>Limite :</strong> la réputation de ton domaine d'envoi dépend de toi. SPF, DKIM et DMARC doivent être en place, et il vaut mieux commencer petit.</p>
|
||||||
|
</li>
|
||||||
|
<li>
|
||||||
|
<h2>Il suit les réponses et relance une fois</h2>
|
||||||
|
<p>Si tu renseignes ta boîte de réception, AiTools la lit en IMAP toutes les 15 minutes. Une réponse fait passer le prospect en « A répondu ». Les absences et réponses automatiques sont ignorées. Un mail rejeté passe le prospect en « Rejeté » et l'adresse en liste d'opposition.</p>
|
||||||
|
<p>La relance est facultative : tu l'actives, et il n'y en a qu'une, après le nombre de jours que tu fixes (7 par défaut), dans le même fil. Elle ne part qu'en heures ouvrées (du lundi au vendredi, de 9 h à 18 h, heure de Paris), si ta boîte a été lue dans les deux dernières heures, et dans la limite des plafonds.</p>
|
||||||
|
<p>Chaque prospect a une fiche : l'historique des mails, une prochaine action datée, des notes. Tu filtres, tu exportes en CSV. Le récapitulatif affiche tes envois et tes réponses par semaine ; si tu donnes un accès en lecture seule à la base de données de ton projet, il suit aussi tes utilisateurs, tes clients et ton revenu.</p>
|
||||||
|
</li>
|
||||||
|
</ol>
|
||||||
|
<p class="fine">En plus : un rapport hebdomadaire par mail, des notifications Discord, et un bouton « Évolution » qui t'envoie par mail des idées de fonctionnalités tirées de ton propre code.</p>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<div class="rule" aria-hidden="true"></div>
|
||||||
|
|
||||||
|
<section class="wrap block" aria-labelledby="titre-garde-fous">
|
||||||
|
<div class="split">
|
||||||
|
<div class="sticky">
|
||||||
|
<h2 id="titre-garde-fous">Garde-fous pour ton compte Claude</h2>
|
||||||
|
</div>
|
||||||
|
<ul class="facts">
|
||||||
|
<li>
|
||||||
|
<h3>Un budget que tu fixes</h3>
|
||||||
|
<p>Tu peux plafonner la dépense IA sur 24 heures et sur 30 jours. Une fois le plafond atteint, les jobs IA attendent sans être perdus, et les envois continuent. Un job déjà commencé n'est jamais coupé : le plafond peut être dépassé d'un job.</p>
|
||||||
|
</li>
|
||||||
|
<li>
|
||||||
|
<h3>Un œil sur ton quota</h3>
|
||||||
|
<p>Avec un abonnement, la barre du haut affiche le quota remonté par Claude lui-même. Au-delà de 85 %, l'analyse et les idées d'évolution sont reportées pour garder de la marge à la prospection.</p>
|
||||||
|
</li>
|
||||||
|
<li>
|
||||||
|
<h3>Des modèles économes par défaut</h3>
|
||||||
|
<p>La prospection et l'analyse utilisent Haiku par défaut. Tu passes à Sonnet dans les réglages si les fiches manquent de précision.</p>
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="wrap block" aria-labelledby="titre-suite">
|
||||||
|
<div class="closing">
|
||||||
|
<div>
|
||||||
|
<h2 id="titre-suite">Prêt à essayer ?</h2>
|
||||||
|
<p>Le plan gratuit suffit pour un premier projet. Les limites sont sur la page <a href="/tarifs">Tarifs</a>.</p>
|
||||||
|
</div>
|
||||||
|
<a class="btn primary" href="/login">Créer mon compte</a>
|
||||||
|
</div>
|
||||||
|
</section>`,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- Tarifs ----------
|
||||||
|
export function pricingPage({ appUrl }) {
|
||||||
|
return siteLayout({
|
||||||
|
appUrl, path: '/tarifs',
|
||||||
|
title: 'Tarifs : plan gratuit et accès Claude à ta charge · AiTools',
|
||||||
|
description: "Le plan gratuit d'AiTools : 1 projet, 50 prospects, 100 mails et 5 jobs IA par mois. Le plan payant n'est pas ouvert. Ton accès Claude est facturé à part, par Anthropic.",
|
||||||
|
body: `<div class="wrap page-head">
|
||||||
|
<p class="eyebrow"><span class="mark" aria-hidden="true"></span>Tarifs</p>
|
||||||
|
<h1>Gratuit pour commencer, payant plus tard</h1>
|
||||||
|
<p class="lead">Aujourd'hui, un seul plan existe, et il est gratuit. Ton accès Claude est un coût à part, qui ne passe pas par AiTools.</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<section class="wrap" aria-label="Plans">
|
||||||
|
<div class="plans">
|
||||||
|
<article class="card plan" aria-labelledby="plan-gratuit">
|
||||||
|
<h2 id="plan-gratuit">Gratuit</h2>
|
||||||
|
<p class="price">0 € <small>sans carte bancaire</small></p>
|
||||||
|
<ul class="limits">
|
||||||
|
<li><span>Projets</span><strong>1</strong></li>
|
||||||
|
<li><span>Prospects</span><strong>50</strong></li>
|
||||||
|
<li><span>Mails par mois</span><strong>100</strong></li>
|
||||||
|
<li><span>Jobs IA par mois</span><strong>5</strong></li>
|
||||||
|
</ul>
|
||||||
|
<p class="fine">Ces plafonds sont annoncés dès maintenant. L'outil ne les applique pas encore automatiquement : cette vérification technique arrive prochainement.</p>
|
||||||
|
<a class="btn primary" href="/login">Créer mon compte</a>
|
||||||
|
</article>
|
||||||
|
<article class="card plan soon" aria-labelledby="plan-payant">
|
||||||
|
<h2 id="plan-payant">Plan payant <span class="badge warn">Bientôt</span></h2>
|
||||||
|
<p>Plus de projets, plus de prospects, plus de mails. Le contenu exact et le prix ne sont pas arrêtés.</p>
|
||||||
|
<p>Ils seront publiés sur cette page avant toute ouverture des paiements. Rien n'est facturé aujourd'hui.</p>
|
||||||
|
</article>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="wrap block" id="acces-claude" aria-labelledby="titre-claude">
|
||||||
|
<div class="split">
|
||||||
|
<div class="sticky">
|
||||||
|
<h2 id="titre-claude">Ton accès Claude : deux façons, deux coûts</h2>
|
||||||
|
<p>AiTools n'achète pas de Claude pour toi. Chaque job IA utilise ton accès, et rien que le tien.</p>
|
||||||
|
</div>
|
||||||
|
<ul class="facts">
|
||||||
|
<li>
|
||||||
|
<h3>Clé API Anthropic (recommandé)</h3>
|
||||||
|
<p>Tu crées une clé sur console.anthropic.com. Anthropic te facture à l'usage, selon ses propres tarifs, sur ton compte. C'est l'option prévue pour brancher un outil tiers. Tu peux plafonner la dépense par jour et par mois dans les réglages d'AiTools.</p>
|
||||||
|
</li>
|
||||||
|
<li>
|
||||||
|
<h3>Abonnement Claude (Pro, Max), avec un risque</h3>
|
||||||
|
<p>Tu génères un jeton avec <code>claude setup-token</code> et tu le colles dans AiTools. Pas de facture en plus, mais les conditions d'Anthropic peuvent ne pas autoriser l'usage d'un abonnement à travers une application tierce. Ton compte Claude pourrait être limité, suspendu ou fermé.</p>
|
||||||
|
<p>AiTools ne peut pas l'empêcher et n'en est pas responsable. Une fenêtre d'avertissement et une case à cocher te le rappellent avant toute liaison, et l'acceptation est enregistrée avec sa date. Lis les <a href="https://www.anthropic.com/legal/consumer-terms" rel="noopener noreferrer">conditions d'Anthropic</a> avant de choisir. Ce mode peut aussi être désactivé sur le service.</p>
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="wrap block" id="envois" aria-labelledby="titre-envois">
|
||||||
|
<div class="split">
|
||||||
|
<div class="sticky">
|
||||||
|
<h2 id="titre-envois">Tu es responsable de tes envois</h2>
|
||||||
|
<p>AiTools aide à rester dans les clous. Il ne remplace pas ta responsabilité d'expéditeur.</p>
|
||||||
|
</div>
|
||||||
|
<ul class="facts">
|
||||||
|
<li>
|
||||||
|
<h3>Entre professionnels, pas aux particuliers</h3>
|
||||||
|
<p>La prospection par mail vers un professionnel est possible, en règle générale, sans son accord préalable, à condition que le message ait un rapport avec son activité et qu'il puisse s'y opposer simplement. Vers un particulier, il faut son consentement : n'utilise pas AiTools pour cela.</p>
|
||||||
|
</li>
|
||||||
|
<li>
|
||||||
|
<h3>Désinscription et liste d'opposition</h3>
|
||||||
|
<p>Chaque mail contient un lien de désinscription en un clic. Une adresse qui se désinscrit, refuse ou rejette un mail entre dans une liste d'opposition qu'AiTools respecte pour tous les comptes.</p>
|
||||||
|
</li>
|
||||||
|
<li>
|
||||||
|
<h3>Source et transparence</h3>
|
||||||
|
<p>Chaque mail rappelle où l'adresse du destinataire a été trouvée. Pour les données de tes prospects, c'est toi le responsable de traitement : la <a href="/confidentialite">politique de confidentialité</a> et les <a href="/cgu">conditions d'utilisation</a> détaillent les rôles.</p>
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="wrap block" aria-labelledby="titre-questions">
|
||||||
|
<h2 id="titre-questions">Questions fréquentes</h2>
|
||||||
|
<div class="statement">
|
||||||
|
<h3>Faut-il une carte bancaire ?</h3>
|
||||||
|
<p>Non. Le plan gratuit n'en demande pas, et le paiement n'existe pas encore dans l'outil.</p>
|
||||||
|
<h3>Puis-je supprimer mon compte ?</h3>
|
||||||
|
<p>Oui, à tout moment, depuis Mon compte. Cela efface tes projets, tes prospects, tes modèles, tes réglages et le clone de ton code. Seule la liste d'opposition, qui protège les personnes désinscrites, est conservée.</p>
|
||||||
|
<h3>Combien me coûtera Claude ?</h3>
|
||||||
|
<p>Cela dépend de ton usage et de ton contrat avec Anthropic. AiTools ne peut pas le prévoir à ta place, mais tu peux fixer un budget maximum.</p>
|
||||||
|
</div>
|
||||||
|
</section>`,
|
||||||
|
});
|
||||||
|
}
|
||||||
26
src/site/routes.js
Normal file
26
src/site/routes.js
Normal file
|
|
@ -0,0 +1,26 @@
|
||||||
|
// Routes du site public : toutes accessibles sans compte.
|
||||||
|
import { html, send } from '../http.js';
|
||||||
|
import { homePage, howPage, pricingPage } from './pages.js';
|
||||||
|
import { mentionsPage, privacyPage, termsPage } from './legal.js';
|
||||||
|
import { robotsTxt, sitemapXml } from './seo.js';
|
||||||
|
|
||||||
|
export function registerSiteRoutes(router, { cfg }) {
|
||||||
|
const apple = !!cfg.apple;
|
||||||
|
const ctx = { appUrl: cfg.appUrl, apple };
|
||||||
|
const open = { public: true };
|
||||||
|
|
||||||
|
router.get('/fonctionnement', async ({ res }) => html(res, howPage(ctx)), open);
|
||||||
|
router.get('/tarifs', async ({ res }) => html(res, pricingPage(ctx)), open);
|
||||||
|
router.get('/mentions-legales', async ({ res }) => html(res, mentionsPage(ctx)), open);
|
||||||
|
router.get('/confidentialite', async ({ res }) => html(res, privacyPage(ctx)), open);
|
||||||
|
router.get('/cgu', async ({ res }) => html(res, termsPage(ctx)), open);
|
||||||
|
|
||||||
|
router.get('/robots.txt', async ({ res }) => {
|
||||||
|
res.setHeader('Cache-Control', 'public, max-age=3600');
|
||||||
|
send(res, 200, robotsTxt(cfg.appUrl), 'text/plain; charset=utf-8');
|
||||||
|
}, open);
|
||||||
|
router.get('/sitemap.xml', async ({ res }) => {
|
||||||
|
res.setHeader('Cache-Control', 'public, max-age=3600');
|
||||||
|
send(res, 200, sitemapXml(cfg.appUrl), 'application/xml; charset=utf-8');
|
||||||
|
}, open);
|
||||||
|
}
|
||||||
63
src/site/seo.js
Normal file
63
src/site/seo.js
Normal file
|
|
@ -0,0 +1,63 @@
|
||||||
|
// Référencement technique et en-têtes de sécurité du site : robots.txt, sitemap.xml, CSP et compagnie.
|
||||||
|
import { absoluteUrl } from './layout.js';
|
||||||
|
|
||||||
|
/** Pages publiques à indexer (et seulement elles) : alimentent le sitemap et l'exception du noindex. */
|
||||||
|
export const INDEXABLE_PATHS = ['/', '/fonctionnement', '/tarifs', '/mentions-legales', '/confidentialite', '/cgu'];
|
||||||
|
|
||||||
|
// Pages d'application : jamais explorées (le noindex des pages est posé en plus, par en-tête et par balise)
|
||||||
|
export const DISALLOWED_PATHS = ['/account', '/settings', '/link', '/api/', '/auth/', '/u/', '/logout'];
|
||||||
|
|
||||||
|
export function robotsTxt(appUrl) {
|
||||||
|
return [
|
||||||
|
'User-agent: *',
|
||||||
|
'Allow: /',
|
||||||
|
...DISALLOWED_PATHS.map((p) => `Disallow: ${p}`),
|
||||||
|
'',
|
||||||
|
`Sitemap: ${absoluteUrl(appUrl, '/sitemap.xml')}`,
|
||||||
|
'',
|
||||||
|
].join('\n');
|
||||||
|
}
|
||||||
|
|
||||||
|
export function sitemapXml(appUrl) {
|
||||||
|
const urls = INDEXABLE_PATHS.map((p) => ` <url><loc>${absoluteUrl(appUrl, p)}</loc></url>`).join('\n');
|
||||||
|
return `<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
|
||||||
|
${urls}
|
||||||
|
</urlset>
|
||||||
|
`;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Tout vient de l'application elle-même : ni script, ni style, ni police, ni image d'un autre domaine.
|
||||||
|
// Pas de style en ligne : les largeurs, couleurs et animations passent par des classes de public/*.css.
|
||||||
|
// form-action liste les fournisseurs de connexion (un formulaire ne les vise pas aujourd'hui, la redirection oui).
|
||||||
|
const CSP = [
|
||||||
|
"default-src 'self'",
|
||||||
|
"script-src 'self'",
|
||||||
|
"style-src 'self'",
|
||||||
|
"img-src 'self' data:",
|
||||||
|
"font-src 'self'",
|
||||||
|
"connect-src 'self'",
|
||||||
|
"object-src 'none'",
|
||||||
|
"base-uri 'self'",
|
||||||
|
"form-action 'self' https://accounts.google.com https://appleid.apple.com",
|
||||||
|
"frame-ancestors 'none'",
|
||||||
|
].join('; ');
|
||||||
|
|
||||||
|
/** En-têtes posés sur toutes les réponses. HSTS seulement si le site est servi en https. */
|
||||||
|
export function securityHeaders(appUrl) {
|
||||||
|
const headers = {
|
||||||
|
'X-Content-Type-Options': 'nosniff',
|
||||||
|
'X-Frame-Options': 'DENY',
|
||||||
|
'Referrer-Policy': 'same-origin',
|
||||||
|
'Permissions-Policy': 'camera=(), microphone=(), geolocation=(), payment=(), usb=(), interest-cohort=()',
|
||||||
|
'Cross-Origin-Opener-Policy': 'same-origin',
|
||||||
|
'Content-Security-Policy': CSP,
|
||||||
|
};
|
||||||
|
if (/^https:\/\//i.test(String(appUrl))) headers['Strict-Transport-Security'] = 'max-age=31536000';
|
||||||
|
return headers;
|
||||||
|
}
|
||||||
|
|
||||||
|
const INDEXABLE = new Set([...INDEXABLE_PATHS, '/robots.txt', '/sitemap.xml']);
|
||||||
|
|
||||||
|
/** En-tête X-Robots-Tag : noindex partout sauf sur les pages publiques à référencer. */
|
||||||
|
export const robotsHeaderFor = (pathname) => (INDEXABLE.has(pathname.replace(/(.)\/$/, '$1')) ? null : 'noindex, nofollow');
|
||||||
95
src/users.js
Normal file
95
src/users.js
Normal file
|
|
@ -0,0 +1,95 @@
|
||||||
|
// Comptes : création à la première connexion, rôle admin (ADMIN_EMAILS), suspension, suppression.
|
||||||
|
import { rmSync } from 'node:fs';
|
||||||
|
import { join } from 'node:path';
|
||||||
|
import { now } from './db.js';
|
||||||
|
import { HttpError } from './http.js';
|
||||||
|
import { clearRecapCache } from './services/recap.js';
|
||||||
|
|
||||||
|
export const PROVIDER_LABELS = { google: 'Google', apple: 'Apple' };
|
||||||
|
|
||||||
|
export const normalizeEmail = (e) => String(e ?? '').trim().toLowerCase();
|
||||||
|
const EMAIL_SHAPE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
||||||
|
|
||||||
|
const COLUMNS = 'id, email, name, provider, provider_sub, status, is_admin, plan, created_at, last_login_at';
|
||||||
|
|
||||||
|
// Forme exposée au reste de l'application (booléens, jamais claude_link_json)
|
||||||
|
function publicUser(r) {
|
||||||
|
if (!r) return null;
|
||||||
|
return {
|
||||||
|
id: Number(r.id), email: r.email, name: r.name, provider: r.provider, providerSub: r.provider_sub,
|
||||||
|
status: r.status, isAdmin: !!r.is_admin, plan: r.plan, createdAt: r.created_at, lastLoginAt: r.last_login_at,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getUser(db, id) {
|
||||||
|
return publicUser(await db.prepare(`SELECT ${COLUMNS} FROM users WHERE id = ?`).get(Number(id)));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** ADMIN_EMAILS fait foi : les admins sont exactement ces adresses (au démarrage et à chaque connexion). */
|
||||||
|
export async function syncAdmins(db, adminEmails) {
|
||||||
|
const list = adminEmails.map(normalizeEmail).filter(Boolean);
|
||||||
|
if (!list.length) { await db.prepare('UPDATE users SET is_admin = 0').run(); return; }
|
||||||
|
await db.prepare(`UPDATE users SET is_admin = CASE WHEN email IN (${list.map(() => '?').join(', ')}) THEN 1 ELSE 0 END`).run(...list);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Trouve ou crée le compte d'une identité vérifiée par le fournisseur.
|
||||||
|
* 1. (fournisseur, sub) connu → ce compte ;
|
||||||
|
* 2. sinon même email : compte préparé par la migration (sans fournisseur) → rattaché à cette identité ;
|
||||||
|
* compte déjà lié à un autre fournisseur → refus (pas de fusion automatique de comptes) ;
|
||||||
|
* 3. sinon inscription automatique (plan gratuit). Le compte suspendu est refusé.
|
||||||
|
*/
|
||||||
|
export async function loginIdentity(db, cfg, { provider, sub, email, name }) {
|
||||||
|
email = normalizeEmail(email);
|
||||||
|
sub = String(sub || '');
|
||||||
|
if (!sub) throw new HttpError(401, 'Identité fournisseur invalide');
|
||||||
|
if (!EMAIL_SHAPE.test(email) || email.length > 255) throw new HttpError(401, 'Email invalide');
|
||||||
|
const cleanName = name ? String(name).trim().slice(0, 200) || null : null;
|
||||||
|
const t = now();
|
||||||
|
|
||||||
|
let row = await db.prepare(`SELECT ${COLUMNS} FROM users WHERE provider = ? AND provider_sub = ?`).get(provider, sub);
|
||||||
|
if (!row) {
|
||||||
|
const byEmail = await db.prepare(`SELECT ${COLUMNS} FROM users WHERE email = ?`).get(email);
|
||||||
|
if (byEmail) {
|
||||||
|
if (byEmail.provider) {
|
||||||
|
throw new HttpError(409, `Cet email est déjà associé à un compte ${PROVIDER_LABELS[byEmail.provider] || byEmail.provider} : connecte-toi avec ce fournisseur.`);
|
||||||
|
}
|
||||||
|
await db.prepare('UPDATE users SET provider = ?, provider_sub = ? WHERE id = ? AND provider IS NULL').run(provider, sub, byEmail.id);
|
||||||
|
row = { ...byEmail, provider, provider_sub: sub };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!row) {
|
||||||
|
try {
|
||||||
|
const r = await db.prepare(`INSERT INTO users(email, name, provider, provider_sub, status, is_admin, plan, created_at, last_login_at)
|
||||||
|
VALUES(?, ?, ?, ?, 'active', ?, 'free', ?, ?)`).run(email, cleanName, provider, sub, cfg.adminEmails.includes(email) ? 1 : 0, t, t);
|
||||||
|
row = await db.prepare(`SELECT ${COLUMNS} FROM users WHERE id = ?`).get(Number(r.lastInsertRowid));
|
||||||
|
} catch (e) {
|
||||||
|
// Deux premières connexions simultanées du même compte : la seconde retrouve la ligne de la première
|
||||||
|
row = await db.prepare(`SELECT ${COLUMNS} FROM users WHERE provider = ? AND provider_sub = ?`).get(provider, sub);
|
||||||
|
if (!row) throw e;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (row.status !== 'active') throw new HttpError(403, 'Compte suspendu');
|
||||||
|
// L'identité est le (fournisseur, sub) ; le rôle suit ADMIN_EMAILS, relu à chaque connexion
|
||||||
|
await db.prepare('UPDATE users SET last_login_at = ?, is_admin = ?, name = COALESCE(?, name) WHERE id = ?')
|
||||||
|
.run(t, cfg.adminEmails.includes(normalizeEmail(row.email)) ? 1 : 0, cleanName, row.id);
|
||||||
|
return getUser(db, row.id);
|
||||||
|
}
|
||||||
|
|
||||||
|
export const userRepoRoot = (cfg, userId) => join(cfg.dataDir, 'repos', String(Number(userId)));
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Supprime le compte et TOUTES ses données : projets, prospects, notes, modèles, journaux d'envoi, jobs,
|
||||||
|
* métriques, réglages et sessions (cascade des clés étrangères), puis les clones git du disque.
|
||||||
|
* La liste d'opposition (blacklist) est volontairement conservée : c'est un registre d'adresses qui ont refusé
|
||||||
|
* d'être contactées, pas une donnée du compte.
|
||||||
|
*/
|
||||||
|
export async function deleteUser(app, userId) {
|
||||||
|
const { db, cfg } = app;
|
||||||
|
const user = await getUser(db, userId);
|
||||||
|
if (!user) throw new HttpError(404, 'Compte introuvable');
|
||||||
|
const projects = await db.prepare('SELECT id FROM projects WHERE user_id = ?').all(user.id);
|
||||||
|
await db.prepare('DELETE FROM users WHERE id = ?').run(user.id);
|
||||||
|
for (const p of projects) clearRecapCache(p.id);
|
||||||
|
rmSync(userRepoRoot(cfg, user.id), { recursive: true, force: true });
|
||||||
|
}
|
||||||
110
src/views.js
110
src/views.js
|
|
@ -1,5 +1,6 @@
|
||||||
import { esc } from './http.js';
|
import { esc } from './http.js';
|
||||||
import { STATUSES } from './services/crm.js';
|
import { STATUSES } from './services/crm.js';
|
||||||
|
import { MODE_LABELS, CONSENT_TEXT, CONSENT_CHECKBOX, CONSENT_VERSION } from './claudelink.js';
|
||||||
|
|
||||||
const fmtDate = (ts) => (ts ? new Date(ts * 1000).toLocaleString('fr-FR', { dateStyle: 'short', timeStyle: 'short', timeZone: 'Europe/Paris' }) : '—');
|
const fmtDate = (ts) => (ts ? new Date(ts * 1000).toLocaleString('fr-FR', { dateStyle: 'short', timeStyle: 'short', timeZone: 'Europe/Paris' }) : '—');
|
||||||
|
|
||||||
|
|
@ -48,7 +49,7 @@ ${email ? `<header class="top">
|
||||||
<div data-jobs-list></div>
|
<div data-jobs-list></div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<nav><a href="/settings">Réglages</a>
|
<nav><a href="/account">Mon compte</a><a href="/settings">Réglages</a>
|
||||||
<form method="post" action="/logout"><button class="link">Déconnexion</button></form></nav>
|
<form method="post" action="/logout"><button class="link">Déconnexion</button></form></nav>
|
||||||
</header>` : ''}
|
</header>` : ''}
|
||||||
<main>${body}</main>
|
<main>${body}</main>
|
||||||
|
|
@ -56,18 +57,111 @@ ${email ? `<header class="top">
|
||||||
</html>`;
|
</html>`;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function loginPage(error) {
|
const PROVIDER_NAMES = { google: 'Google', apple: 'Apple' };
|
||||||
|
|
||||||
|
// Section « Liaison Claude » de Mon compte : état, test, changement de mode, déliaison. Jamais le secret, ni même un masque
|
||||||
|
// plus long que les 4 derniers caractères de la clé API.
|
||||||
|
function linkSection(link, consent) {
|
||||||
|
if (!link) {
|
||||||
|
return `<section class="card">
|
||||||
|
<h4>Liaison Claude</h4>
|
||||||
|
<p class="muted">Aucun accès Claude n'est relié : l'application reste bloquée sur la page de liaison.</p>
|
||||||
|
<a class="btn primary" href="/link">Relier Claude</a>
|
||||||
|
</section>`;
|
||||||
|
}
|
||||||
|
return `<section class="card">
|
||||||
|
<h4>Liaison Claude</h4>
|
||||||
|
<dl class="account">
|
||||||
|
<dt>Mode</dt><dd>${esc(link.label)}</dd>
|
||||||
|
<dt>État</dt><dd>${link.valid ? '<span class="ok">Valide</span>' : '<span class="error">À revalider (teste ou relie de nouveau)</span>'}</dd>
|
||||||
|
${link.last4 ? `<dt>Clé API</dt><dd>sk-ant-…${esc(link.last4)}</dd>` : ''}
|
||||||
|
<dt>Reliée le</dt><dd>${fmtDate(link.linkedAt)}</dd>
|
||||||
|
<dt>Dernier test</dt><dd>${fmtDate(link.lastTestAt)}</dd>
|
||||||
|
${link.consentAt ? `<dt>Risque accepté</dt><dd>${fmtDate(link.consentAt)} (texte ${esc(link.consentVersion)})</dd>` : ''}
|
||||||
|
</dl>
|
||||||
|
<div class="row-actions">
|
||||||
|
<form method="post" action="/link/test"><button class="btn">Tester</button></form>
|
||||||
|
<a class="btn" href="/link?change=1">Changer de mode</a>
|
||||||
|
<form method="post" action="/link/unlink"><button class="btn danger">Délier</button></form>
|
||||||
|
</div>
|
||||||
|
<p class="muted small">Délier efface le secret chiffré et annule tes jobs IA en attente ou en cours.${consent && !link.consentAt ? ` Dernier consentement au mode abonnement : ${fmtDate(consent.at)}.` : ''}</p>
|
||||||
|
</section>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function accountPage({ user, error, link = null, consent = null, notice = null }) {
|
||||||
return layout({
|
return layout({
|
||||||
title: 'Connexion',
|
title: 'Mon compte', email: user.email,
|
||||||
body: `<section class="login card">
|
body: `<h1>Mon compte</h1>
|
||||||
<h1>AiTools</h1>
|
<section class="card">
|
||||||
<p class="muted">Accès réservé.</p>
|
<dl class="account">
|
||||||
|
<dt>Email</dt><dd>${esc(user.email)}</dd>
|
||||||
|
<dt>Connexion</dt><dd>${esc(PROVIDER_NAMES[user.provider] || '—')}</dd>
|
||||||
|
</dl>
|
||||||
|
</section>
|
||||||
|
${notice ? `<p class="${notice.ok ? 'ok' : 'error'}">${esc(notice.text)}</p>` : ''}
|
||||||
|
${linkSection(link, consent)}
|
||||||
|
<section class="card">
|
||||||
|
<h4>Supprimer mon compte</h4>
|
||||||
|
<p class="muted small">Efface définitivement ton compte et toutes tes données : projets, prospects, notes, modèles de mail, journaux d'envoi, jobs, réglages et clones du code. Les adresses qui ont demandé à ne plus être contactées restent dans la liste d'opposition commune. Cette action est irréversible.</p>
|
||||||
${error ? `<p class="error">${esc(error)}</p>` : ''}
|
${error ? `<p class="error">${esc(error)}</p>` : ''}
|
||||||
<a class="btn primary" href="/auth/google">Se connecter avec Google</a>
|
<form method="post" action="/account/delete" class="cfg">
|
||||||
|
<label>Pour confirmer, saisis ton email (${esc(user.email)})<input name="confirm" type="email" required autocomplete="off"></label>
|
||||||
|
<button class="btn danger">Supprimer mon compte et mes données</button>
|
||||||
|
</form>
|
||||||
</section>`,
|
</section>`,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Page « Relier Claude » : onboarding bloquant. Les trois modes sont des formulaires HTML classiques (POST) ;
|
||||||
|
* la fenêtre d'avertissement du mode abonnement est un <dialog> ouvert par public/app.js.
|
||||||
|
*/
|
||||||
|
export function linkPage({ user, link, cliModeEnabled, error }) {
|
||||||
|
const intro = link
|
||||||
|
? `<p class="muted">Accès actuel : <strong>${esc(link.label)}</strong>${link.valid ? '' : ' (à revalider)'}. Relier un autre accès remplace le précédent, dont le secret est effacé.</p>`
|
||||||
|
: '<p class="muted">Pour utiliser AiTools, relie ton propre accès Claude. Les analyses, recherches et rédactions s\'exécutent avec TON accès, jamais celui d\'un autre utilisateur.</p>';
|
||||||
|
const subscription = cliModeEnabled ? `
|
||||||
|
<section class="card">
|
||||||
|
<h4>Connexion avec Claude (abonnement)</h4>
|
||||||
|
<p class="muted small">Utilise ton abonnement Claude (Pro, Max) au lieu d'une clé API. Cette option comporte un risque pour ton compte Claude : une fenêtre d'avertissement s'affiche avant de continuer.</p>
|
||||||
|
<button type="button" class="btn" data-open-dialog="consent-dialog">Connexion avec Claude (abonnement)</button>
|
||||||
|
</section>
|
||||||
|
<dialog class="prospect-dialog" id="consent-dialog" aria-labelledby="consent-title">
|
||||||
|
<form method="post" action="/link/subscription" class="cfg">
|
||||||
|
<h2 id="consent-title">Avant de continuer</h2>
|
||||||
|
<div class="notice card">${CONSENT_TEXT.map((t) => `<p>${esc(t)}</p>`).join('')}</div>
|
||||||
|
<label class="check"><input type="checkbox" name="accept" id="consent-accept" required> ${esc(CONSENT_CHECKBOX)}</label>
|
||||||
|
<p class="muted small">Sur ta propre machine, lance la commande <code>claude setup-token</code>, connecte-toi à ton compte Claude quand le navigateur s'ouvre, puis copie le jeton affiché et colle-le ci-dessous. Le jeton est chiffré, utilisé uniquement pour tes jobs, et n'est jamais réaffiché.</p>
|
||||||
|
<label>Jeton d'abonnement<input name="token" type="password" autocomplete="new-password" spellcheck="false" required></label>
|
||||||
|
<p class="muted small">La vérification lance un appel minimal du CLI : quelques tokens sont décomptés de ton abonnement. Texte d'avertissement version ${esc(CONSENT_VERSION)}.</p>
|
||||||
|
<div class="row-actions">
|
||||||
|
<button type="button" class="btn" data-close-dialog>Annuler</button>
|
||||||
|
<button class="btn primary" id="consent-submit" disabled>Relier avec mon abonnement</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</dialog>` : '';
|
||||||
|
const server = user.isAdmin ? `
|
||||||
|
<section class="card">
|
||||||
|
<h4>Claude du serveur (administrateurs)</h4>
|
||||||
|
<p class="muted small">Utilise la configuration du CLI Claude déjà connectée sur la machine qui héberge AiTools.</p>
|
||||||
|
<form method="post" action="/link/server"><button class="btn">Utiliser Claude du serveur</button></form>
|
||||||
|
</section>` : '';
|
||||||
|
return layout({
|
||||||
|
title: 'Relier Claude', email: user.email,
|
||||||
|
body: `<h1>Relier Claude</h1>
|
||||||
|
${intro}
|
||||||
|
${error ? `<p class="error">${esc(error)}</p>` : ''}
|
||||||
|
<section class="card">
|
||||||
|
<h4>Clé API Anthropic (recommandé)</h4>
|
||||||
|
<p class="muted small">Crée une clé sur console.anthropic.com puis colle-la ici. Elle est vérifiée sans consommer de tokens, chiffrée, et ne sera plus jamais affichée (seuls ses 4 derniers caractères le seront).</p>
|
||||||
|
<form method="post" action="/link/api-key" class="cfg">
|
||||||
|
<label>Clé API<input name="apiKey" type="password" autocomplete="new-password" spellcheck="false" required placeholder="sk-ant-…"></label>
|
||||||
|
<button class="btn primary">Vérifier et relier</button>
|
||||||
|
</form>
|
||||||
|
</section>${subscription}${server}`,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
function targetForm(p) {
|
function targetForm(p) {
|
||||||
const t = p.target || {};
|
const t = p.target || {};
|
||||||
const list = (a) => esc((a || []).join('\n'));
|
const list = (a) => esc((a || []).join('\n'));
|
||||||
|
|
@ -329,7 +423,7 @@ ${saved ? '<p class="ok">Enregistré.</p>' : ''}
|
||||||
|
|
||||||
<section class="card">
|
<section class="card">
|
||||||
<h4>Liste d'opposition</h4>
|
<h4>Liste d'opposition</h4>
|
||||||
<p class="muted small">${s.blacklist_count} adresse(s) désinscrite(s). Elles ne seront plus jamais contactées, tous projets confondus.</p>
|
<p class="muted small">${s.blacklist_count} de tes prospects ont demandé à ne plus être contactés. La liste d'opposition est commune à tous les comptes : une adresse désinscrite n'est plus jamais contactée, quel que soit le projet.</p>
|
||||||
</section>`,
|
</section>`,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
|
||||||
127
test/account.test.js
Normal file
127
test/account.test.js
Normal file
|
|
@ -0,0 +1,127 @@
|
||||||
|
import { test, before, after } from 'node:test';
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import { existsSync, mkdirSync, writeFileSync } from 'node:fs';
|
||||||
|
import { join } from 'node:path';
|
||||||
|
import { now, setSetting } from '../src/db.js';
|
||||||
|
import { repoDir } from '../src/projects.js';
|
||||||
|
import { deleteUser } from '../src/users.js';
|
||||||
|
import { startApp } from './helpers/server.js';
|
||||||
|
|
||||||
|
let s, A, B;
|
||||||
|
const clone = {};
|
||||||
|
|
||||||
|
// Toutes les tables qui portent des données d'un utilisateur, et comment les compter pour lui
|
||||||
|
const OWN_PROJECTS = 'SELECT id FROM projects WHERE user_id = ?';
|
||||||
|
const COUNTS = {
|
||||||
|
users: 'SELECT COUNT(*) n FROM users WHERE id = ?',
|
||||||
|
sessions: 'SELECT COUNT(*) n FROM sessions WHERE user_id = ?',
|
||||||
|
user_settings: 'SELECT COUNT(*) n FROM user_settings WHERE user_id = ?',
|
||||||
|
projects: 'SELECT COUNT(*) n FROM projects WHERE user_id = ?',
|
||||||
|
jobs: 'SELECT COUNT(*) n FROM jobs WHERE user_id = ?',
|
||||||
|
templates: `SELECT COUNT(*) n FROM templates WHERE project_id IN (${OWN_PROJECTS})`,
|
||||||
|
prospects: `SELECT COUNT(*) n FROM prospects WHERE project_id IN (${OWN_PROJECTS})`,
|
||||||
|
prospect_notes: `SELECT COUNT(*) n FROM prospect_notes WHERE prospect_id IN (SELECT id FROM prospects WHERE project_id IN (${OWN_PROJECTS}))`,
|
||||||
|
mail_log: `SELECT COUNT(*) n FROM mail_log WHERE project_id IN (${OWN_PROJECTS})`,
|
||||||
|
metrics_daily: `SELECT COUNT(*) n FROM metrics_daily WHERE project_id IN (${OWN_PROJECTS})`,
|
||||||
|
};
|
||||||
|
const counts = async (uid) => {
|
||||||
|
const out = {};
|
||||||
|
for (const [t, sql] of Object.entries(COUNTS)) out[t] = (await s.db.prepare(sql).get(uid)).n;
|
||||||
|
return out;
|
||||||
|
};
|
||||||
|
|
||||||
|
async function seed(u, tag) {
|
||||||
|
const t = now();
|
||||||
|
const p = Number((await s.db.prepare('INSERT INTO projects(user_id, name, git_url, created_at) VALUES(?, ?, ?, ?)').run(u.id, `Projet ${tag}`, `https://git.test/${tag}/p.git`, t)).lastInsertRowid);
|
||||||
|
const pr = Number((await s.db.prepare('INSERT INTO prospects(project_id, company, email, created_at) VALUES(?, ?, ?, ?)').run(p, `Ent ${tag}`, `c@${tag}.fr`, t)).lastInsertRowid);
|
||||||
|
await s.db.prepare("INSERT INTO prospect_notes(prospect_id, body, created_at) VALUES(?, 'n', ?)").run(pr, t);
|
||||||
|
await s.db.prepare("INSERT INTO templates(project_id, kind, subject, body, updated_at) VALUES(?, 'initial', 's', 'b', ?)").run(p, t);
|
||||||
|
await s.db.prepare('INSERT INTO mail_log(project_id, prospect_id, email, sent_at) VALUES(?, ?, ?, ?)').run(p, pr, `c@${tag}.fr`, t);
|
||||||
|
await s.db.prepare("INSERT INTO metrics_daily(project_id, day, users) VALUES(?, '2026-10-21', 1)").run(p);
|
||||||
|
await s.db.prepare("INSERT INTO jobs(user_id, project_id, type, status, created_at) VALUES(?, ?, 'send', 'done', ?)").run(u.id, p, t);
|
||||||
|
await s.db.prepare("INSERT INTO jobs(user_id, type, status, created_at) VALUES(?, 'send', 'done', ?)").run(u.id, t); // job sans projet
|
||||||
|
await setSetting(s.db, u.id, 'notify_email', `${tag}@x.fr`);
|
||||||
|
const dir = repoDir(s.app.cfg, u.id, p);
|
||||||
|
mkdirSync(dir, { recursive: true });
|
||||||
|
writeFileSync(join(dir, 'README.md'), tag);
|
||||||
|
clone[tag] = dir;
|
||||||
|
}
|
||||||
|
|
||||||
|
before(async () => {
|
||||||
|
s = await startApp();
|
||||||
|
A = await s.newUser({ email: 'a@x.fr' });
|
||||||
|
B = await s.newUser({ email: 'b@x.fr' });
|
||||||
|
await seed(A, 'a');
|
||||||
|
await seed(B, 'b');
|
||||||
|
await s.db.prepare("INSERT INTO blacklist(email, reason, created_at) VALUES('c@a.fr', 'refused', ?)").run(now());
|
||||||
|
});
|
||||||
|
after(() => s.close());
|
||||||
|
|
||||||
|
test('« Mon compte » : email et fournisseur, formulaire de suppression', async () => {
|
||||||
|
const page = await (await A.get('/account')).text();
|
||||||
|
assert.match(page, /a@x\.fr/);
|
||||||
|
assert.match(page, /Google/);
|
||||||
|
assert.match(page, /action="\/account\/delete"/);
|
||||||
|
assert.doesNotMatch(page, /b@x\.fr/);
|
||||||
|
assert.equal((await s.anon.get('/account')).status, 303, 'connexion requise');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('suppression : refusée si l\'email saisi ne correspond pas, ou sans origine valide', async () => {
|
||||||
|
const before = await counts(A.id);
|
||||||
|
let r = await A.post('/account/delete', { confirm: 'autre@x.fr' }, { form: true });
|
||||||
|
assert.equal(r.status, 303);
|
||||||
|
assert.match(decodeURIComponent(r.headers.get('location')), /^\/account\?e=.*ne correspond pas/);
|
||||||
|
r = await A.post('/account/delete', { confirm: '' }, { form: true });
|
||||||
|
assert.match(decodeURIComponent(r.headers.get('location')), /ne correspond pas/);
|
||||||
|
r = await A.post('/account/delete', { confirm: 'a@x.fr' }, { form: true, origin: 'https://evil.com' });
|
||||||
|
assert.equal(r.status, 403, 'anti-CSRF');
|
||||||
|
r = await s.anon.post('/account/delete', { confirm: 'a@x.fr' }, { form: true });
|
||||||
|
assert.equal(r.status, 303);
|
||||||
|
assert.equal(r.headers.get('location'), '/login');
|
||||||
|
assert.deepEqual(await counts(A.id), before, 'rien n\'a été supprimé');
|
||||||
|
assert.ok(existsSync(clone.a));
|
||||||
|
});
|
||||||
|
|
||||||
|
test('suppression : efface toutes les données de l\'utilisateur, détruit la session, laisse les autres comptes intacts', async () => {
|
||||||
|
const mine = await counts(A.id);
|
||||||
|
assert.ok(Object.values(mine).every((n) => n >= 1), `données de départ : ${JSON.stringify(mine)}`);
|
||||||
|
const theirs = await counts(B.id);
|
||||||
|
|
||||||
|
const r = await A.post('/account/delete', { confirm: ' A@X.fr ' }, { form: true });
|
||||||
|
assert.equal(r.status, 303);
|
||||||
|
assert.equal(r.headers.get('location'), '/login?bye=1');
|
||||||
|
assert.match(r.headers.getSetCookie().find((c) => c.startsWith('sid=')), /Max-Age=0/, 'cookie de session effacé');
|
||||||
|
|
||||||
|
const after = await counts(A.id);
|
||||||
|
for (const [t, n] of Object.entries(after)) assert.equal(n, 0, `${t} doit être vide`);
|
||||||
|
assert.equal(existsSync(clone.a), false, 'clones git supprimés');
|
||||||
|
assert.deepEqual(await counts(B.id), theirs, 'les données de B sont intactes');
|
||||||
|
assert.ok(existsSync(clone.b));
|
||||||
|
assert.equal((await s.db.prepare('SELECT COUNT(*) n FROM blacklist').get()).n, 1, 'la liste d\'opposition est conservée');
|
||||||
|
|
||||||
|
// La session d'avant ne marche plus, la page de connexion confirme
|
||||||
|
assert.equal((await A.get('/api/system')).status, 401);
|
||||||
|
const login = await (await s.anon.get('/login?bye=1')).text();
|
||||||
|
assert.match(login, /supprimés/);
|
||||||
|
assert.equal((await A.post('/account/delete', { confirm: 'a@x.fr' }, { form: true })).status, 303);
|
||||||
|
assert.equal((await s.db.prepare("SELECT COUNT(*) n FROM users WHERE email = 'a@x.fr'").get()).n, 0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('suppression : un job en cours pour le compte est interrompu avant l\'effacement', async () => {
|
||||||
|
const U = await s.newUser({ email: 'run@x.fr' });
|
||||||
|
await seed(U, 'run');
|
||||||
|
const aborted = [];
|
||||||
|
s.app.worker = { abortUser: (id) => aborted.push(id) };
|
||||||
|
const r = await U.post('/account/delete', { confirm: 'run@x.fr' }, { form: true });
|
||||||
|
assert.equal(r.headers.get('location'), '/login?bye=1');
|
||||||
|
assert.deepEqual(aborted, [U.id]);
|
||||||
|
delete s.app.worker;
|
||||||
|
});
|
||||||
|
|
||||||
|
test('deleteUser (service) : compte inconnu → 404, et le nouvel inscrit du même email repart de zéro', async () => {
|
||||||
|
await assert.rejects(deleteUser(s.app, 999999), { status: 404 });
|
||||||
|
const N = await s.newUser({ email: 'a@x.fr' }); // même email que le compte supprimé
|
||||||
|
const c = await counts(N.id);
|
||||||
|
assert.equal(c.users, 1);
|
||||||
|
for (const t of Object.keys(c).filter((k) => !['users', 'sessions'].includes(k))) assert.equal(c[t], 0, `${t} : aucune donnée de l'ancien compte`);
|
||||||
|
});
|
||||||
125
test/accounts-migration.test.js
Normal file
125
test/accounts-migration.test.js
Normal file
|
|
@ -0,0 +1,125 @@
|
||||||
|
import { test } from 'node:test';
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import { now } from '../src/db.js';
|
||||||
|
import { MIGRATIONS } from '../src/migrations.js';
|
||||||
|
import { loginIdentity } from '../src/users.js';
|
||||||
|
import { testDb, USING_MYSQL } from './helpers/db.js';
|
||||||
|
|
||||||
|
// Migration 2 (comptes et multi-tenant) : une instance existante, mono-utilisateur, passe au schéma multi-utilisateur
|
||||||
|
// et ses données sont rattachées à l'utilisateur propriétaire (première adresse de ADMIN_EMAILS), sans perte.
|
||||||
|
|
||||||
|
const TABLES = ['projects', 'templates', 'prospects', 'prospect_notes', 'mail_log', 'metrics_daily', 'jobs', 'blacklist'];
|
||||||
|
|
||||||
|
/** Base à la version 1 avec des données « d'avant les comptes ». */
|
||||||
|
async function legacy() {
|
||||||
|
const db = await testDb({ upTo: 1 });
|
||||||
|
const t = now();
|
||||||
|
await db.prepare('INSERT INTO projects(id, name, git_url, smtp_enc, daily_mail_cap, created_at) VALUES(?, ?, ?, ?, ?, ?)').run(7, 'Café Été', 'https://git.x/a.git', 'v1:smtp:chiffré', 12, t);
|
||||||
|
await db.prepare('INSERT INTO projects(id, name, git_url, created_at) VALUES(?, ?, ?, ?)').run(42, 'Autre', 'https://git.x/b.git', t);
|
||||||
|
await db.prepare('INSERT INTO prospects(id, project_id, company, email, created_at) VALUES(?, ?, ?, ?, ?)').run(1001, 7, 'Léa', 'lea@x.fr', t);
|
||||||
|
await db.prepare('INSERT INTO prospect_notes(id, prospect_id, body, created_at) VALUES(?, ?, ?, ?)').run(5, 1001, 'à rappeler', t);
|
||||||
|
await db.prepare('INSERT INTO templates(project_id, kind, subject, body, updated_at) VALUES(?, ?, ?, ?, ?)').run(7, 'initial', 'Objet', 'Corps', t);
|
||||||
|
await db.prepare('INSERT INTO mail_log(id, project_id, prospect_id, email, sent_at) VALUES(?, ?, ?, ?, ?)').run(9, 7, 1001, 'lea@x.fr', t);
|
||||||
|
await db.prepare('INSERT INTO metrics_daily(project_id, day, users) VALUES(?, ?, ?)').run(7, '2026-10-21', 10);
|
||||||
|
await db.prepare('INSERT INTO jobs(id, project_id, type, status, cost_usd, created_at) VALUES(?, ?, ?, ?, ?, ?)').run(300, 7, 'analyze', 'done', 0.5, t);
|
||||||
|
await db.prepare('INSERT INTO jobs(id, project_id, type, status, created_at) VALUES(?, NULL, ?, ?, ?)').run(301, 'send', 'done', t); // job sans projet
|
||||||
|
await db.prepare('INSERT INTO blacklist(email, reason, created_at) VALUES(?, ?, ?)').run('no@x.fr', 'unsubscribe', t);
|
||||||
|
await db.prepare('INSERT INTO settings(`key`, value) VALUES(?, ?)').run('notify_email', 'tony@x.fr');
|
||||||
|
await db.prepare('INSERT INTO settings(`key`, value) VALUES(?, ?)').run('budget_day_usd', '3');
|
||||||
|
await db.prepare('INSERT INTO sessions(id, email, created_at, expires_at) VALUES(?, ?, ?, ?)').run('ancienne', 'tony@x.fr', t, t + 100);
|
||||||
|
return db;
|
||||||
|
}
|
||||||
|
|
||||||
|
const count = async (db, t) => (await db.prepare(`SELECT COUNT(*) n FROM \`${t}\``).get()).n;
|
||||||
|
|
||||||
|
test('rattachement : toutes les données au propriétaire (1re adresse de ADMIN_EMAILS), sans perte', async () => {
|
||||||
|
const db = await legacy();
|
||||||
|
const before = Object.fromEntries(await Promise.all(TABLES.map(async (t) => [t, await count(db, t)])));
|
||||||
|
await db.migrate({ adminEmails: ' Tony@X.fr , autre@x.fr' });
|
||||||
|
|
||||||
|
const users = await db.prepare('SELECT * FROM users').all();
|
||||||
|
assert.equal(users.length, 1, 'un seul compte créé : le propriétaire');
|
||||||
|
const owner = users[0];
|
||||||
|
assert.deepEqual({ email: owner.email, admin: owner.is_admin, status: owner.status, plan: owner.plan, provider: owner.provider, sub: owner.provider_sub },
|
||||||
|
{ email: 'tony@x.fr', admin: 1, status: 'active', plan: 'free', provider: null, sub: null });
|
||||||
|
assert.equal(owner.claude_link_json, null);
|
||||||
|
|
||||||
|
for (const t of TABLES) assert.equal(await count(db, t), before[t], `${t} : aucune ligne perdue`);
|
||||||
|
assert.deepEqual((await db.prepare('SELECT id, name, user_id, daily_mail_cap, smtp_enc FROM projects ORDER BY id').all()).map((p) => [p.id, p.name, Number(p.user_id), p.daily_mail_cap, p.smtp_enc]),
|
||||||
|
[[7, 'Café Été', owner.id, 12, 'v1:smtp:chiffré'], [42, 'Autre', owner.id, 30, null]]);
|
||||||
|
assert.equal((await db.prepare('SELECT COUNT(*) n FROM jobs WHERE user_id = ?').get(owner.id)).n, 2, 'tous les jobs, y compris celui sans projet');
|
||||||
|
assert.equal((await db.prepare('SELECT project_id FROM jobs WHERE id = 301').get()).project_id, null);
|
||||||
|
assert.equal((await db.prepare('SELECT cost_usd FROM jobs WHERE id = 300').get()).cost_usd, 0.5);
|
||||||
|
assert.equal((await db.prepare('SELECT body FROM prospect_notes WHERE id = 5').get()).body, 'à rappeler');
|
||||||
|
|
||||||
|
// réglages globaux → réglages du propriétaire ; ancienne table supprimée ; sessions éphémères repartent de zéro
|
||||||
|
assert.deepEqual((await db.prepare('SELECT `key`, value FROM user_settings WHERE user_id = ? ORDER BY `key`').all(owner.id)).map((r) => [r.key, r.value]),
|
||||||
|
[['budget_day_usd', '3'], ['notify_email', 'tony@x.fr']]);
|
||||||
|
await assert.rejects(db.prepare('SELECT 1 FROM settings').get(), /settings/);
|
||||||
|
assert.equal(await count(db, 'sessions'), 0);
|
||||||
|
await db.prepare('INSERT INTO sessions(id, user_id, created_at, expires_at) VALUES(?, ?, ?, ?)').run('nouvelle', owner.id, now(), now() + 10); // le nouveau format lie la session à un compte
|
||||||
|
assert.equal((await db.prepare('SELECT MAX(version) v, COUNT(*) n FROM schema_migrations').get()).v, MIGRATIONS.length);
|
||||||
|
|
||||||
|
// contraintes du nouveau schéma : unicité du dépôt PAR utilisateur, cascade depuis l'utilisateur
|
||||||
|
const other = Number((await db.prepare("INSERT INTO users(email, status, is_admin, plan, created_at) VALUES('b@x.fr', 'active', 0, 'free', ?)").run(now())).lastInsertRowid);
|
||||||
|
await assert.rejects(db.prepare('INSERT INTO projects(user_id, name, git_url, created_at) VALUES(?, ?, ?, ?)').run(owner.id, 'Doublon', 'https://git.x/a.git', now()));
|
||||||
|
await db.prepare('INSERT INTO projects(user_id, name, git_url, created_at) VALUES(?, ?, ?, ?)').run(other, 'Même dépôt', 'https://git.x/a.git', now());
|
||||||
|
await assert.rejects(db.prepare('INSERT INTO projects(user_id, name, git_url, created_at) VALUES(?, ?, ?, ?)').run(999, 'Orphelin', 'https://git.x/z.git', now()), 'user_id doit exister');
|
||||||
|
await assert.rejects(db.prepare('INSERT INTO projects(name, git_url, created_at) VALUES(?, ?, ?)').run('Sans propriétaire', 'https://git.x/y.git', now()), 'user_id obligatoire');
|
||||||
|
await assert.rejects(db.prepare('INSERT INTO jobs(type, created_at) VALUES(?, ?)').run('send', now()), 'jobs.user_id obligatoire');
|
||||||
|
|
||||||
|
if (db.dialect === 'sqlite') {
|
||||||
|
assert.deepEqual(await db.query('PRAGMA foreign_key_check'), [], 'aucune clé étrangère violée');
|
||||||
|
assert.equal((await db.prepare('PRAGMA foreign_keys').get()).foreign_keys, 1, 'clés étrangères réactivées après la migration');
|
||||||
|
}
|
||||||
|
await db.prepare('DELETE FROM users WHERE id = ?').run(owner.id);
|
||||||
|
for (const t of ['projects', 'templates', 'prospects', 'prospect_notes', 'mail_log', 'metrics_daily', 'user_settings']) {
|
||||||
|
const n = await count(db, t);
|
||||||
|
assert.equal(n, t === 'projects' ? 1 : 0, `${t} : supprimé avec le propriétaire (reste le projet de l'autre compte)`);
|
||||||
|
}
|
||||||
|
assert.equal(await count(db, 'jobs'), 0);
|
||||||
|
assert.equal(await count(db, 'blacklist'), 1, 'la liste d\'opposition ne dépend d\'aucun compte');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('rattachement : le propriétaire se connecte et retrouve ses données par son email', async () => {
|
||||||
|
const db = await legacy();
|
||||||
|
await db.migrate({ adminEmails: ['tony@x.fr'] });
|
||||||
|
const prepared = (await db.prepare('SELECT id FROM users').get()).id;
|
||||||
|
const user = await loginIdentity(db, { adminEmails: ['tony@x.fr'] }, { provider: 'google', sub: 'g-tony', email: 'Tony@X.fr', name: 'Tony' });
|
||||||
|
assert.equal(user.id, Number(prepared), 'même compte : pas de doublon');
|
||||||
|
assert.equal(user.isAdmin, true);
|
||||||
|
assert.equal(user.provider, 'google');
|
||||||
|
assert.equal((await db.prepare('SELECT COUNT(*) n FROM projects WHERE user_id = ?').get(user.id)).n, 2);
|
||||||
|
assert.equal((await db.prepare('SELECT COUNT(*) n FROM users').get()).n, 1);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('rattachement : refusé sans ADMIN_EMAILS quand des données existent (la base reste en version 1)', async () => {
|
||||||
|
const db = await legacy();
|
||||||
|
await assert.rejects(db.migrate({}), /ADMIN_EMAILS/);
|
||||||
|
await assert.rejects(db.migrate({ adminEmails: ' , ' }), /ADMIN_EMAILS/);
|
||||||
|
assert.equal((await db.prepare('SELECT MAX(version) v FROM schema_migrations').get()).v, 1);
|
||||||
|
assert.equal(await count(db, 'projects'), 2, 'rien n\'a été touché');
|
||||||
|
if (!USING_MYSQL) await assert.rejects(db.prepare('SELECT 1 FROM users').get(), /users/);
|
||||||
|
// une fois ADMIN_EMAILS défini, la migration passe
|
||||||
|
await db.migrate({ adminEmails: 'tony@x.fr' });
|
||||||
|
assert.equal((await db.prepare('SELECT MAX(version) v FROM schema_migrations').get()).v, MIGRATIONS.length);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('rattachement : base vide sans ADMIN_EMAILS → migration sans propriétaire, premier admin créé à sa connexion', async () => {
|
||||||
|
const db = await testDb({ upTo: 1 });
|
||||||
|
await db.migrate({});
|
||||||
|
assert.equal(await count(db, 'users'), 0);
|
||||||
|
const admin = await loginIdentity(db, { adminEmails: ['tony@x.fr'] }, { provider: 'google', sub: 'g1', email: 'tony@x.fr' });
|
||||||
|
assert.equal(admin.isAdmin, true);
|
||||||
|
const user = await loginIdentity(db, { adminEmails: ['tony@x.fr'] }, { provider: 'apple', sub: 'a1', email: 'visiteur@x.fr' });
|
||||||
|
assert.equal(user.isAdmin, false);
|
||||||
|
assert.equal(user.plan, 'free');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('rattachement : la migration rejouée ne change rien (déjà appliquée)', async () => {
|
||||||
|
const db = await legacy();
|
||||||
|
await db.migrate({ adminEmails: 'tony@x.fr' });
|
||||||
|
await db.migrate({ adminEmails: 'tony@x.fr' });
|
||||||
|
assert.equal(await count(db, 'users'), 1);
|
||||||
|
assert.equal(await count(db, 'projects'), 2);
|
||||||
|
});
|
||||||
363
test/auth.test.js
Normal file
363
test/auth.test.js
Normal file
|
|
@ -0,0 +1,363 @@
|
||||||
|
import { test, before, after } from 'node:test';
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import { createPublicKey, verify } from 'node:crypto';
|
||||||
|
import { now } from '../src/db.js';
|
||||||
|
import { loadConfig } from '../src/config.js';
|
||||||
|
import { PROVIDERS, appleClientSecret } from '../src/auth.js';
|
||||||
|
import { startApp, APP_URL } from './helpers/server.js';
|
||||||
|
import { makeProvider } from './helpers/oidc.js';
|
||||||
|
import { addUser } from './helpers/users.js';
|
||||||
|
|
||||||
|
// Flux Google et Apple avec des fournisseurs simulés : aucun appel réseau, tout passe par app.fetch.
|
||||||
|
const prov = makeProvider();
|
||||||
|
const PEM_HEAD = '-----BEGIN ' + 'PRIVATE KEY-----', PEM_FOOT = '-----END ' + 'PRIVATE KEY-----'; // faux contenu de .p8
|
||||||
|
let s, base, issue, calls;
|
||||||
|
|
||||||
|
before(async () => {
|
||||||
|
s = await startApp({ cfg: { apple: prov.apple, adminEmails: ['admin@x.fr'] } });
|
||||||
|
base = s.base;
|
||||||
|
s.app.fetch = async (url, opts = {}) => {
|
||||||
|
calls.push({ url, body: opts.body ? Object.fromEntries(new URLSearchParams(opts.body)) : null });
|
||||||
|
if (url === PROVIDERS.google.jwksUrl || url === PROVIDERS.apple.jwksUrl) return { ok: true, status: 200, json: async () => ({ keys: [prov.jwk] }) };
|
||||||
|
if (url === PROVIDERS.google.tokenUrl || url === PROVIDERS.apple.tokenUrl) {
|
||||||
|
return issue ? { ok: true, status: 200, json: async () => ({ id_token: issue(url) }) } : { ok: false, status: 400, json: async () => ({}) };
|
||||||
|
}
|
||||||
|
return { ok: false, status: 404, json: async () => ({}) };
|
||||||
|
};
|
||||||
|
});
|
||||||
|
after(() => s.close());
|
||||||
|
|
||||||
|
const GOOGLE_CLAIMS = (nonce, o = {}) => ({
|
||||||
|
iss: 'https://accounts.google.com', aud: 'gid', sub: 'g-100', exp: now() + 600, iat: now(),
|
||||||
|
nonce, email: 'Ada@Example.com', email_verified: true, name: 'Ada L.', ...o,
|
||||||
|
});
|
||||||
|
const APPLE_CLAIMS = (nonce, o = {}) => ({
|
||||||
|
iss: 'https://appleid.apple.com', aud: prov.apple.clientId, sub: '001234.abcd.5678', exp: now() + 600, iat: now(),
|
||||||
|
nonce, email: 'bob@privaterelay.appleid.com', email_verified: 'true', ...o,
|
||||||
|
});
|
||||||
|
|
||||||
|
const cookieOf = (r, name) => r.headers.getSetCookie().find((c) => c.startsWith(`${name}=`));
|
||||||
|
|
||||||
|
/** Démarre une connexion : state, nonce et cookie de liaison du « navigateur ». */
|
||||||
|
async function start(provider) {
|
||||||
|
calls = [];
|
||||||
|
const r = await fetch(`${base}/auth/${provider}`, { redirect: 'manual' });
|
||||||
|
assert.equal(r.status, 303);
|
||||||
|
const loc = new URL(r.headers.get('location'));
|
||||||
|
const set = cookieOf(r, 'oauth_b');
|
||||||
|
return { loc, set, state: loc.searchParams.get('state'), nonce: loc.searchParams.get('nonce'), bind: set?.split(';')[0] };
|
||||||
|
}
|
||||||
|
|
||||||
|
const google = ({ state, bind, code = 'code-1' }) => fetch(`${base}/auth/google/callback?${new URLSearchParams({ code, state })}`,
|
||||||
|
{ redirect: 'manual', headers: bind ? { cookie: bind } : {} });
|
||||||
|
// Retour d'Apple : POST cross-site (form_post), l'origine est celle d'Apple
|
||||||
|
const apple = ({ state, bind, code = 'code-1', user, error }) => fetch(`${base}/auth/apple/callback`, {
|
||||||
|
method: 'POST', redirect: 'manual',
|
||||||
|
headers: { 'content-type': 'application/x-www-form-urlencoded', origin: 'https://appleid.apple.com', ...(bind ? { cookie: bind } : {}) },
|
||||||
|
body: new URLSearchParams({ ...(code ? { code } : {}), state, ...(user ? { user } : {}), ...(error ? { error } : {}) }).toString(),
|
||||||
|
});
|
||||||
|
|
||||||
|
const failure = (r) => decodeURIComponent(new URL(r.headers.get('location'), base).searchParams.get('e') || '');
|
||||||
|
const sessions = async () => (await s.db.prepare('SELECT COUNT(*) n FROM sessions').get()).n;
|
||||||
|
const userByEmail = (email) => s.db.prepare('SELECT * FROM users WHERE email = ?').get(email);
|
||||||
|
|
||||||
|
test('Google : inscription automatique à la première connexion, session, PKCE et secret client', async () => {
|
||||||
|
const st = await start('google');
|
||||||
|
assert.equal(st.loc.host, 'accounts.google.com');
|
||||||
|
assert.equal(st.loc.searchParams.get('code_challenge_method'), 'S256');
|
||||||
|
assert.equal(st.loc.searchParams.get('scope'), 'openid email profile');
|
||||||
|
assert.match(st.set, /SameSite=None/);
|
||||||
|
assert.match(st.set, /Secure/);
|
||||||
|
assert.match(st.set, /HttpOnly/);
|
||||||
|
assert.match(st.set, /Path=\/auth/);
|
||||||
|
|
||||||
|
issue = () => prov.idToken(GOOGLE_CLAIMS(st.nonce));
|
||||||
|
const before = await sessions();
|
||||||
|
const r = await google(st);
|
||||||
|
assert.equal(r.status, 303);
|
||||||
|
assert.equal(r.headers.get('location'), '/');
|
||||||
|
const sid = cookieOf(r, 'sid');
|
||||||
|
assert.ok(sid, 'cookie de session');
|
||||||
|
assert.equal(await sessions(), before + 1);
|
||||||
|
|
||||||
|
const exchange = calls.find((c) => c.url === PROVIDERS.google.tokenUrl).body;
|
||||||
|
assert.equal(exchange.client_secret, 'gsecret');
|
||||||
|
assert.ok(exchange.code_verifier, 'PKCE');
|
||||||
|
assert.equal(exchange.redirect_uri, `${APP_URL}/auth/google/callback`);
|
||||||
|
|
||||||
|
const u = await userByEmail('ada@example.com');
|
||||||
|
assert.equal(u.provider, 'google');
|
||||||
|
assert.equal(u.provider_sub, 'g-100');
|
||||||
|
assert.equal(u.name, 'Ada L.');
|
||||||
|
assert.equal(u.status, 'active');
|
||||||
|
assert.equal(u.is_admin, 0);
|
||||||
|
assert.equal(u.plan, 'free');
|
||||||
|
assert.ok(u.last_login_at);
|
||||||
|
assert.equal(u.claude_link_json, null);
|
||||||
|
|
||||||
|
const home = await s.client(sid.split(';')[0]).get('/', { headers: { accept: 'text/html' } });
|
||||||
|
// Nouveau compte sans liaison Claude : l'onboarding bloquant renvoie vers la page de liaison
|
||||||
|
assert.equal(home.status, 303);
|
||||||
|
assert.equal(home.headers.get('location'), '/link');
|
||||||
|
assert.equal((await s.client(sid.split(';')[0]).get('/link')).status, 200, 'la session ouvre la page de liaison');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('Google : seconde connexion = même compte, pas de doublon', async () => {
|
||||||
|
const st = await start('google');
|
||||||
|
issue = () => prov.idToken(GOOGLE_CLAIMS(st.nonce, { email: 'ada@example.com' }));
|
||||||
|
const r = await google(st);
|
||||||
|
assert.equal(r.headers.get('location'), '/');
|
||||||
|
assert.equal((await s.db.prepare("SELECT COUNT(*) n FROM users WHERE email = 'ada@example.com'").get()).n, 1);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('Google : id_token invalide refusé (signature, alg, kid, émetteur, audience, expiration, nonce, email)', async () => {
|
||||||
|
const cases = {
|
||||||
|
'signature forgée (clé du faussaire)': [(n) => prov.idToken(GOOGLE_CLAIMS(n, { sub: 'evil' }), { key: prov.forgerKey }), /Signature/],
|
||||||
|
'alg none': [(n) => prov.idToken(GOOGLE_CLAIMS(n), { alg: 'none' }), /Algorithme/],
|
||||||
|
'alg HS256 (confusion de clé)': [(n) => prov.idToken(GOOGLE_CLAIMS(n), { alg: 'HS256' }), /Algorithme/],
|
||||||
|
'kid inconnu': [(n) => prov.idToken(GOOGLE_CLAIMS(n), { kid: 'autre' }), /Clé de signature/],
|
||||||
|
'émetteur': [(n) => prov.idToken(GOOGLE_CLAIMS(n, { iss: 'https://evil.example' })), /Émetteur/],
|
||||||
|
'audience': [(n) => prov.idToken(GOOGLE_CLAIMS(n, { aud: 'autre-client' })), /Audience/],
|
||||||
|
'expiré': [(n) => prov.idToken(GOOGLE_CLAIMS(n, { exp: now() - 10 })), /expiré/],
|
||||||
|
'nonce': [() => prov.idToken(GOOGLE_CLAIMS('autre-nonce')), /Nonce/],
|
||||||
|
'email non vérifié': [(n) => prov.idToken(GOOGLE_CLAIMS(n, { email_verified: false })), /vérifié/],
|
||||||
|
'sans sub': [(n) => prov.idToken(GOOGLE_CLAIMS(n, { sub: undefined })), /Identifiant/],
|
||||||
|
'jeton mal formé': [() => 'pas.un.jwt', /invalide/],
|
||||||
|
};
|
||||||
|
const known = (await s.db.prepare('SELECT COUNT(*) n FROM users').get()).n;
|
||||||
|
for (const [name, [make, re]] of Object.entries(cases)) {
|
||||||
|
const st = await start('google');
|
||||||
|
issue = () => make(st.nonce);
|
||||||
|
const sessionsBefore = await sessions();
|
||||||
|
const r = await google(st);
|
||||||
|
assert.equal(r.status, 303, name);
|
||||||
|
assert.match(failure(r), re, name);
|
||||||
|
assert.equal(cookieOf(r, 'sid'), undefined, `${name} : aucune session`);
|
||||||
|
assert.equal(await sessions(), sessionsBefore, name);
|
||||||
|
}
|
||||||
|
assert.equal((await s.db.prepare('SELECT COUNT(*) n FROM users').get()).n, known, 'aucun compte créé par un jeton invalide');
|
||||||
|
assert.equal(await userByEmail('evil@x.fr'), undefined);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('state, nonce et liaison au navigateur : inconnus, rejoués, expirés ou d\'un autre navigateur → refusés', async () => {
|
||||||
|
issue = null;
|
||||||
|
// state inconnu
|
||||||
|
let r = await google({ state: 'forge', bind: 'oauth_b=x' });
|
||||||
|
assert.match(failure(r), /State OAuth invalide/);
|
||||||
|
// paramètres manquants
|
||||||
|
r = await fetch(`${base}/auth/google/callback`, { redirect: 'manual' });
|
||||||
|
assert.match(failure(r), /manquants/);
|
||||||
|
|
||||||
|
// cookie absent (le flux n'a pas été démarré dans ce navigateur : login CSRF)
|
||||||
|
let st = await start('google');
|
||||||
|
issue = () => prov.idToken(GOOGLE_CLAIMS(st.nonce, { sub: 'g-csrf', email: 'csrf@x.fr' }));
|
||||||
|
r = await google({ state: st.state, bind: null });
|
||||||
|
assert.match(failure(r), /autre navigateur/);
|
||||||
|
assert.equal(await userByEmail('csrf@x.fr'), undefined);
|
||||||
|
|
||||||
|
// mauvais cookie
|
||||||
|
st = await start('google');
|
||||||
|
r = await google({ state: st.state, bind: 'oauth_b=pas-le-bon' });
|
||||||
|
assert.match(failure(r), /autre navigateur/);
|
||||||
|
|
||||||
|
// state à usage unique
|
||||||
|
st = await start('google');
|
||||||
|
issue = () => prov.idToken(GOOGLE_CLAIMS(st.nonce));
|
||||||
|
assert.equal((await google(st)).headers.get('location'), '/');
|
||||||
|
r = await google(st);
|
||||||
|
assert.match(failure(r), /State OAuth invalide/, 'rejeu refusé');
|
||||||
|
|
||||||
|
// state expiré
|
||||||
|
st = await start('google');
|
||||||
|
await s.db.prepare('UPDATE oauth_states SET created_at = ? WHERE state = ?').run(now() - 3600, st.state);
|
||||||
|
r = await google(st);
|
||||||
|
assert.match(failure(r), /State OAuth invalide/);
|
||||||
|
|
||||||
|
// state Google présenté sur le callback Apple
|
||||||
|
st = await start('google');
|
||||||
|
r = await apple({ state: st.state, bind: st.bind });
|
||||||
|
assert.match(failure(r), /State OAuth invalide/);
|
||||||
|
// le fournisseur refuse (code invalide) : échec propre, rien n'est créé
|
||||||
|
st = await start('google');
|
||||||
|
issue = null;
|
||||||
|
r = await google(st);
|
||||||
|
assert.match(failure(r), /refusé/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('Apple : redirection form_post avec state + nonce, cookie de liaison SameSite=None', async () => {
|
||||||
|
const st = await start('apple');
|
||||||
|
assert.equal(st.loc.origin + st.loc.pathname, PROVIDERS.apple.authUrl);
|
||||||
|
assert.equal(st.loc.searchParams.get('response_mode'), 'form_post');
|
||||||
|
assert.equal(st.loc.searchParams.get('response_type'), 'code');
|
||||||
|
assert.equal(st.loc.searchParams.get('scope'), 'name email');
|
||||||
|
assert.equal(st.loc.searchParams.get('client_id'), prov.apple.clientId);
|
||||||
|
assert.equal(st.loc.searchParams.get('redirect_uri'), `${APP_URL}/auth/apple/callback`);
|
||||||
|
assert.ok(st.state && st.nonce);
|
||||||
|
assert.match(st.set, /SameSite=None/);
|
||||||
|
assert.match(st.set, /Secure/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('Apple : POST cross-site accepté (state + nonce + cookie), nom reçu à la première connexion, secret client ES256 valide', async () => {
|
||||||
|
const st = await start('apple');
|
||||||
|
issue = () => prov.idToken(APPLE_CLAIMS(st.nonce));
|
||||||
|
const r = await apple({ ...st, user: JSON.stringify({ name: { firstName: 'Bob', lastName: 'Martin' }, email: 'bob@privaterelay.appleid.com' }) });
|
||||||
|
assert.equal(r.status, 303);
|
||||||
|
assert.equal(r.headers.get('location'), '/');
|
||||||
|
assert.ok(cookieOf(r, 'sid'));
|
||||||
|
const u = await userByEmail('bob@privaterelay.appleid.com');
|
||||||
|
assert.equal(u.provider, 'apple');
|
||||||
|
assert.equal(u.provider_sub, '001234.abcd.5678');
|
||||||
|
assert.equal(u.name, 'Bob Martin');
|
||||||
|
|
||||||
|
// Le secret client envoyé à Apple est un JWT ES256 signé avec la clé privée du compte développeur
|
||||||
|
const secret = calls.find((c) => c.url === PROVIDERS.apple.tokenUrl).body.client_secret;
|
||||||
|
const [h, p, sig] = secret.split('.');
|
||||||
|
const head = JSON.parse(Buffer.from(h, 'base64url'));
|
||||||
|
const claims = JSON.parse(Buffer.from(p, 'base64url'));
|
||||||
|
assert.deepEqual({ alg: head.alg, kid: head.kid }, { alg: 'ES256', kid: prov.apple.keyId });
|
||||||
|
assert.equal(claims.iss, prov.apple.teamId);
|
||||||
|
assert.equal(claims.sub, prov.apple.clientId);
|
||||||
|
assert.equal(claims.aud, 'https://appleid.apple.com');
|
||||||
|
assert.ok(claims.exp > claims.iat && claims.exp - claims.iat <= 600);
|
||||||
|
assert.equal(Buffer.from(sig, 'base64url').length, 64, 'signature brute r||s');
|
||||||
|
assert.ok(verify('sha256', Buffer.from(`${h}.${p}`), { key: prov.apple.publicKey, dsaEncoding: 'ieee-p1363' }, Buffer.from(sig, 'base64url')));
|
||||||
|
assert.equal(calls.find((c) => c.url === PROVIDERS.apple.tokenUrl).body.client_id, prov.apple.clientId);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('Apple : id_token forgé, mauvais nonce / audience / émetteur, POST sans cookie → refusés', async () => {
|
||||||
|
const cases = {
|
||||||
|
'signature forgée': [(n) => prov.idToken(APPLE_CLAIMS(n, { sub: 'evil' }), { key: prov.forgerKey }), /Signature/],
|
||||||
|
'nonce': [() => prov.idToken(APPLE_CLAIMS('autre')), /Nonce/],
|
||||||
|
'audience': [(n) => prov.idToken(APPLE_CLAIMS(n, { aud: 'dev.autre.app' })), /Audience/],
|
||||||
|
'émetteur': [(n) => prov.idToken(APPLE_CLAIMS(n, { iss: 'https://accounts.google.com' })), /Émetteur/],
|
||||||
|
'expiré': [(n) => prov.idToken(APPLE_CLAIMS(n, { exp: now() - 1 })), /expiré/],
|
||||||
|
'email non vérifié': [(n) => prov.idToken(APPLE_CLAIMS(n, { email_verified: 'false' })), /vérifié/],
|
||||||
|
};
|
||||||
|
for (const [name, [make, re]] of Object.entries(cases)) {
|
||||||
|
const st = await start('apple');
|
||||||
|
issue = () => make(st.nonce);
|
||||||
|
const r = await apple(st);
|
||||||
|
assert.match(failure(r), re, name);
|
||||||
|
assert.equal(cookieOf(r, 'sid'), undefined, name);
|
||||||
|
}
|
||||||
|
// Login CSRF : un POST d'un site tiers avec un state connu mais sans le cookie de ce navigateur
|
||||||
|
const st = await start('apple');
|
||||||
|
issue = () => prov.idToken(APPLE_CLAIMS(st.nonce, { sub: 'attacker', email: 'attacker@x.fr' }));
|
||||||
|
const r = await apple({ state: st.state, bind: null });
|
||||||
|
assert.match(failure(r), /autre navigateur/);
|
||||||
|
assert.equal(await userByEmail('attacker@x.fr'), undefined);
|
||||||
|
// refus de l'utilisateur côté Apple
|
||||||
|
const st2 = await start('apple');
|
||||||
|
assert.match(failure(await apple({ state: st2.state, bind: st2.bind, code: null, error: 'user_cancelled_authorize' })), /annulée/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('page de connexion : bouton Apple seulement si Apple est configuré', async () => {
|
||||||
|
let r = await s.anon.get('/login');
|
||||||
|
let page = await r.text();
|
||||||
|
assert.match(page, /Se connecter avec Google/);
|
||||||
|
assert.match(page, /Se connecter avec Apple/);
|
||||||
|
|
||||||
|
const bare = await startApp();
|
||||||
|
try {
|
||||||
|
page = await (await bare.anon.get('/login')).text();
|
||||||
|
assert.match(page, /Se connecter avec Google/);
|
||||||
|
assert.doesNotMatch(page, /Apple/);
|
||||||
|
assert.equal((await bare.anon.get('/auth/apple')).status, 404, 'route Apple inexistante sans configuration');
|
||||||
|
assert.equal((await bare.anon.post('/auth/apple/callback', {}, { origin: null })).status, 303, 'le retour Apple échoue proprement');
|
||||||
|
} finally { await bare.close(); }
|
||||||
|
});
|
||||||
|
|
||||||
|
test('configuration : variables Apple toutes présentes ou toutes absentes, ADMIN_EMAILS, plus de ALLOWED_EMAILS', () => {
|
||||||
|
const keep = { ...process.env };
|
||||||
|
try {
|
||||||
|
Object.assign(process.env, {
|
||||||
|
SECRET_KEY: '00'.repeat(32), APP_URL: 'https://x.test/', GOOGLE_CLIENT_ID: 'a', GOOGLE_CLIENT_SECRET: 'b',
|
||||||
|
DB_HOST: 'h', DB_USER: 'u', DB_NAME: 'n', ADMIN_EMAILS: ' Tony@X.fr, b@x.fr ,',
|
||||||
|
});
|
||||||
|
for (const k of ['APPLE_TEAM_ID', 'APPLE_KEY_ID', 'APPLE_CLIENT_ID', 'APPLE_PRIVATE_KEY', 'ALLOWED_EMAILS']) delete process.env[k];
|
||||||
|
let cfg = loadConfig();
|
||||||
|
assert.equal(cfg.apple, null);
|
||||||
|
assert.deepEqual(cfg.adminEmails, ['tony@x.fr', 'b@x.fr']);
|
||||||
|
assert.equal('allowedEmails' in cfg, false);
|
||||||
|
|
||||||
|
Object.assign(process.env, { APPLE_TEAM_ID: 'T', APPLE_KEY_ID: 'K' });
|
||||||
|
assert.throws(() => loadConfig(), /Apple.*APPLE_CLIENT_ID, APPLE_PRIVATE_KEY/);
|
||||||
|
|
||||||
|
Object.assign(process.env, { APPLE_CLIENT_ID: 'C', APPLE_PRIVATE_KEY: `${PEM_HEAD}\\nABC\\n${PEM_FOOT}` });
|
||||||
|
cfg = loadConfig();
|
||||||
|
assert.deepEqual({ ...cfg.apple, privateKey: undefined }, { teamId: 'T', keyId: 'K', clientId: 'C', privateKey: undefined });
|
||||||
|
assert.equal(cfg.apple.privateKey, `${PEM_HEAD}\nABC\n${PEM_FOOT}`,'les \\n littéraux du .env redeviennent des retours à la ligne');
|
||||||
|
// la clé fournie par prov.apple se relit telle quelle
|
||||||
|
assert.ok(appleClientSecret(prov.apple).split('.').length === 3);
|
||||||
|
} finally {
|
||||||
|
for (const k of Object.keys(process.env)) if (!(k in keep)) delete process.env[k];
|
||||||
|
Object.assign(process.env, keep);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test('ADMIN_EMAILS désigne les admins ; le compte préparé par la migration est retrouvé par son email', async () => {
|
||||||
|
// Compte propriétaire préparé (sans fournisseur) avec ses données
|
||||||
|
const prepared = await addUser(s.db, { email: 'admin@x.fr', provider: null, sub: null, admin: false });
|
||||||
|
await s.db.prepare('UPDATE users SET provider = NULL, provider_sub = NULL WHERE id = ?').run(prepared);
|
||||||
|
await s.db.prepare('INSERT INTO projects(user_id, name, git_url, created_at) VALUES(?, ?, ?, ?)').run(prepared, 'Existant', 'https://git.test/e.git', now());
|
||||||
|
|
||||||
|
const st = await start('google');
|
||||||
|
issue = () => prov.idToken(GOOGLE_CLAIMS(st.nonce, { sub: 'g-admin', email: 'ADMIN@x.fr' }));
|
||||||
|
assert.equal((await google(st)).headers.get('location'), '/');
|
||||||
|
const u = await userByEmail('admin@x.fr');
|
||||||
|
assert.equal(Number(u.id), prepared, 'même compte, pas de doublon');
|
||||||
|
assert.equal(u.provider, 'google');
|
||||||
|
assert.equal(u.provider_sub, 'g-admin');
|
||||||
|
assert.equal(u.is_admin, 1);
|
||||||
|
assert.equal((await s.db.prepare('SELECT COUNT(*) n FROM projects WHERE user_id = ?').get(prepared)).n, 1, 'ses données sont toujours là');
|
||||||
|
|
||||||
|
// un non-admin n'est pas promu, et ADMIN_EMAILS fait foi au démarrage
|
||||||
|
assert.equal((await userByEmail('ada@example.com')).is_admin, 0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('un email déjà lié à un autre fournisseur n\'est pas fusionné automatiquement', async () => {
|
||||||
|
const st = await start('apple');
|
||||||
|
issue = () => prov.idToken(APPLE_CLAIMS(st.nonce, { sub: 'apple-ada', email: 'ada@example.com' }));
|
||||||
|
const r = await apple(st);
|
||||||
|
assert.match(failure(r), /déjà associé à un compte Google/);
|
||||||
|
assert.equal(cookieOf(r, 'sid'), undefined);
|
||||||
|
assert.equal((await s.db.prepare("SELECT COUNT(*) n FROM users WHERE email = 'ada@example.com'").get()).n, 1);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('compte suspendu : connexion refusée, session existante inutilisable et supprimée', async () => {
|
||||||
|
const u = await s.newUser({ email: 'susp@x.fr' });
|
||||||
|
assert.equal((await u.get('/api/system')).status, 200);
|
||||||
|
await s.db.prepare("UPDATE users SET status = 'suspended' WHERE id = ?").run(u.id);
|
||||||
|
|
||||||
|
let r = await u.get('/api/system');
|
||||||
|
assert.equal(r.status, 401, 'la session existante ne marche plus');
|
||||||
|
r = await u.get('/account');
|
||||||
|
assert.equal(r.status, 303);
|
||||||
|
assert.equal(r.headers.get('location'), '/login');
|
||||||
|
assert.equal((await s.db.prepare('SELECT COUNT(*) n FROM sessions WHERE user_id = ?').get(u.id)).n, 0, 'sessions supprimées');
|
||||||
|
r = await u.post('/api/projects', { name: 'x', gitUrl: 'https://a/b/c.git' });
|
||||||
|
assert.equal(r.status, 401);
|
||||||
|
|
||||||
|
// et il ne peut pas se reconnecter
|
||||||
|
await s.db.prepare('UPDATE users SET provider = ?, provider_sub = ? WHERE id = ?').run('google', 'g-susp', u.id);
|
||||||
|
const st = await start('google');
|
||||||
|
issue = () => prov.idToken(GOOGLE_CLAIMS(st.nonce, { sub: 'g-susp', email: 'susp@x.fr' }));
|
||||||
|
const login = await google(st);
|
||||||
|
assert.match(failure(login), /suspendu/);
|
||||||
|
assert.equal(cookieOf(login, 'sid'), undefined);
|
||||||
|
assert.equal((await s.db.prepare('SELECT COUNT(*) n FROM sessions WHERE user_id = ?').get(u.id)).n, 0);
|
||||||
|
|
||||||
|
// réactivé : tout refonctionne
|
||||||
|
await s.db.prepare("UPDATE users SET status = 'active' WHERE id = ?").run(u.id);
|
||||||
|
const st2 = await start('google');
|
||||||
|
issue = () => prov.idToken(GOOGLE_CLAIMS(st2.nonce, { sub: 'g-susp', email: 'susp@x.fr' }));
|
||||||
|
assert.equal((await google(st2)).headers.get('location'), '/');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('déconnexion : la session est détruite côté serveur', async () => {
|
||||||
|
const u = await s.newUser();
|
||||||
|
assert.equal((await u.get('/api/system')).status, 200);
|
||||||
|
const r = await u.post('/logout', {}, { form: true });
|
||||||
|
assert.equal(r.status, 303);
|
||||||
|
assert.equal((await u.get('/api/system')).status, 401);
|
||||||
|
});
|
||||||
|
|
@ -1,38 +1,41 @@
|
||||||
import { test } from 'node:test';
|
import { test } from 'node:test';
|
||||||
import assert from 'node:assert/strict';
|
import assert from 'node:assert/strict';
|
||||||
import { openDb, now, setSetting } from '../src/db.js';
|
import { now, setSetting } from '../src/db.js';
|
||||||
|
import { testDb } from './helpers/db.js';
|
||||||
|
import { addUser } from './helpers/users.js';
|
||||||
import { budgetState, AI_JOBS, quotaState, isQuotaSensitive, quotaAlerts } from '../src/services/budget.js';
|
import { budgetState, AI_JOBS, quotaState, isQuotaSensitive, quotaAlerts } from '../src/services/budget.js';
|
||||||
import { Worker, enqueue, latestJobs } from '../src/services/jobs.js';
|
import { Worker, enqueue, latestJobs } from '../src/services/jobs.js';
|
||||||
|
|
||||||
function setup() {
|
async function setup() {
|
||||||
const db = openDb(':memory:');
|
const db = await testDb();
|
||||||
db.prepare("INSERT INTO projects(name, git_url, created_at) VALUES('p', 'u', ?)").run(now());
|
const u = await addUser(db);
|
||||||
const spend = (usd, finishedAgo) => db.prepare("INSERT INTO jobs(project_id, type, status, cost_usd, created_at, finished_at) VALUES(1, 'prospect', 'done', ?, ?, ?)")
|
await db.prepare("INSERT INTO projects(user_id, name, git_url, created_at) VALUES(?, 'p', 'u', ?)").run(u, now());
|
||||||
.run(usd, now() - finishedAgo - 60, now() - finishedAgo);
|
const spend = (usd, finishedAgo, user = u) => db.prepare("INSERT INTO jobs(user_id, project_id, type, status, cost_usd, created_at, finished_at) VALUES(?, 1, 'prospect', 'done', ?, ?, ?)")
|
||||||
return { db, spend };
|
.run(user, usd, now() - finishedAgo - 60, now() - finishedAgo);
|
||||||
|
return { db, spend, u };
|
||||||
}
|
}
|
||||||
|
|
||||||
test('budget : pas de limite par défaut, puis plafonds 24 h et 30 j glissants', () => {
|
test('budget : pas de limite par défaut, puis plafonds 24 h et 30 j glissants', async () => {
|
||||||
const s = setup();
|
const s = await setup();
|
||||||
s.spend(1.5, 3600); // il y a 1 h
|
await s.spend(1.5, 3600); // il y a 1 h
|
||||||
s.spend(10, 5 * 86400); // il y a 5 jours
|
await s.spend(10, 5 * 86400); // il y a 5 jours
|
||||||
s.spend(99, 40 * 86400); // hors fenêtre
|
await s.spend(99, 40 * 86400); // hors fenêtre
|
||||||
let b = budgetState(s.db);
|
let b = await budgetState(s.db, s.u);
|
||||||
assert.equal(b.blocked, false);
|
assert.equal(b.blocked, false);
|
||||||
assert.equal(b.day.used, 1.5);
|
assert.equal(b.day.used, 1.5);
|
||||||
assert.equal(b.month.used, 11.5);
|
assert.equal(b.month.used, 11.5);
|
||||||
|
|
||||||
setSetting(s.db, 'budget_day_usd', '2');
|
await setSetting(s.db, s.u, 'budget_day_usd', '2');
|
||||||
assert.equal(budgetState(s.db).blocked, false);
|
assert.equal((await budgetState(s.db, s.u)).blocked, false);
|
||||||
setSetting(s.db, 'budget_day_usd', '1.5');
|
await setSetting(s.db, s.u, 'budget_day_usd', '1.5');
|
||||||
b = budgetState(s.db);
|
b = await budgetState(s.db, s.u);
|
||||||
assert.equal(b.blocked, true);
|
assert.equal(b.blocked, true);
|
||||||
assert.equal(b.reason, 'budget IA des dernières 24 h atteint (1.50 $ / 1.50 $)');
|
assert.equal(b.reason, 'budget IA des dernières 24 h atteint (1.50 $ / 1.50 $)');
|
||||||
|
|
||||||
setSetting(s.db, 'budget_day_usd', '');
|
await setSetting(s.db, s.u, 'budget_day_usd', '');
|
||||||
setSetting(s.db, 'budget_month_usd', '10');
|
await setSetting(s.db, s.u, 'budget_month_usd', '10');
|
||||||
assert.match(budgetState(s.db).reason, /30 derniers jours atteint \(11\.50 \$ \/ 10\.00 \$\)/);
|
assert.match((await budgetState(s.db, s.u)).reason, /30 derniers jours atteint \(11\.50 \$ \/ 10\.00 \$\)/);
|
||||||
assert.equal(budgetState(s.db, { at: now() + 30 * 86400 }).blocked, false, 'la fenêtre glisse');
|
assert.equal((await budgetState(s.db, s.u, { at: now() + 30 * 86400 })).blocked, false, 'la fenêtre glisse');
|
||||||
});
|
});
|
||||||
|
|
||||||
test('les envois et relances ne consomment pas d\'IA', () => {
|
test('les envois et relances ne consomment pas d\'IA', () => {
|
||||||
|
|
@ -41,35 +44,35 @@ test('les envois et relances ne consomment pas d\'IA', () => {
|
||||||
});
|
});
|
||||||
|
|
||||||
test('budget atteint : les jobs IA attendent (pas perdus), les envois passent, une seule notif', async () => {
|
test('budget atteint : les jobs IA attendent (pas perdus), les envois passent, une seule notif', async () => {
|
||||||
const s = setup();
|
const s = await setup();
|
||||||
s.spend(5, 600);
|
await s.spend(5, 600);
|
||||||
setSetting(s.db, 'budget_day_usd', '3');
|
await setSetting(s.db, s.u, 'budget_day_usd', '3');
|
||||||
const ran = [];
|
const ran = [];
|
||||||
const alerts = [];
|
const alerts = [];
|
||||||
const h = (name) => async () => { ran.push(name); };
|
const h = (name) => async () => { ran.push(name); };
|
||||||
const w = new Worker(s.db, { prospect: h('prospect'), evolution: h('evolution'), send: h('send') }, {
|
const w = new Worker(s.db, { prospect: h('prospect'), evolution: h('evolution'), send: h('send') }, {
|
||||||
thermalMax: 999, log: { error() {} },
|
thermalMax: 999, log: { error() {} },
|
||||||
budget: () => budgetState(s.db), isAiJob: (t) => AI_JOBS.has(t), onBudget: (r) => alerts.push(r),
|
budget: (u) => budgetState(s.db, u), isAiJob: (t) => AI_JOBS.has(t), onBudget: (r) => alerts.push(r),
|
||||||
});
|
});
|
||||||
enqueue(s.db, { projectId: 1, type: 'prospect' });
|
await enqueue(s.db, { userId: s.u, projectId: 1, type: 'prospect' });
|
||||||
enqueue(s.db, { projectId: 1, type: 'send' });
|
await enqueue(s.db, { userId: s.u, projectId: 1, type: 'send' });
|
||||||
enqueue(s.db, { projectId: 1, type: 'evolution' });
|
await enqueue(s.db, { userId: s.u, projectId: 1, type: 'evolution' });
|
||||||
|
|
||||||
assert.equal(await w.tick(), true);
|
assert.equal(await w.tick(), true);
|
||||||
assert.deepEqual(ran, ['send'], 'l\'envoi passe devant les jobs IA bloqués');
|
assert.deepEqual(ran, ['send'], 'l\'envoi passe devant les jobs IA bloqués');
|
||||||
assert.equal(await w.tick(), false);
|
assert.equal(await w.tick(), false);
|
||||||
assert.equal(await w.tick(), false);
|
assert.equal(await w.tick(), false);
|
||||||
assert.equal(alerts.length, 1, 'une seule notif, pas une toutes les 3 s');
|
assert.equal(alerts.length, 1, 'une seule notif, pas une toutes les 3 s');
|
||||||
const jobs = latestJobs(s.db, 1);
|
const jobs = await latestJobs(s.db, 1);
|
||||||
assert.equal(jobs.prospect.status, 'queued');
|
assert.equal(jobs.prospect.status, 'queued');
|
||||||
assert.match(jobs.prospect.progress.message, /^En attente : budget IA des dernières 24 h atteint/);
|
assert.match(jobs.prospect.progress.message, /^En attente : budget IA des dernières 24 h atteint/);
|
||||||
|
|
||||||
setSetting(s.db, 'budget_day_usd', '20'); // ou la fenêtre de 24 h qui glisse
|
await setSetting(s.db, s.u, 'budget_day_usd', '20'); // ou la fenêtre de 24 h qui glisse
|
||||||
await w.tick(); await w.tick();
|
await w.tick(); await w.tick();
|
||||||
assert.deepEqual(ran, ['send', 'prospect', 'evolution'], 'les jobs repartent tout seuls, dans l\'ordre');
|
assert.deepEqual(ran, ['send', 'prospect', 'evolution'], 'les jobs repartent tout seuls, dans l\'ordre');
|
||||||
|
|
||||||
setSetting(s.db, 'budget_day_usd', '1');
|
await setSetting(s.db, s.u, 'budget_day_usd', '1');
|
||||||
enqueue(s.db, { projectId: 1, type: 'prospect' });
|
await enqueue(s.db, { userId: s.u, projectId: 1, type: 'prospect' });
|
||||||
await w.tick();
|
await w.tick();
|
||||||
assert.equal(alerts.length, 2, 'nouvelle notif pour un nouveau blocage');
|
assert.equal(alerts.length, 2, 'nouvelle notif pour un nouveau blocage');
|
||||||
});
|
});
|
||||||
|
|
@ -79,64 +82,64 @@ test('analyse et évolutions sont "non urgents", pas la prospection ni l\'envoi'
|
||||||
for (const t of ['prospect', 'template', 'followup_template', 'send', 'followup']) assert.equal(isQuotaSensitive(t), false);
|
for (const t of ['prospect', 'template', 'followup_template', 'send', 'followup']) assert.equal(isQuotaSensitive(t), false);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('quotaState : pas mesuré, en dessous du seuil, puis bloqué à 85 %', () => {
|
test('quotaState : pas mesuré, en dessous du seuil, puis bloqué à 85 %', async () => {
|
||||||
const s = setup();
|
const s = await setup();
|
||||||
assert.deepEqual(quotaState(s.db), { blocked: false, reason: null });
|
assert.deepEqual(await quotaState(s.db, s.u), { blocked: false, reason: null });
|
||||||
setSetting(s.db, 'claude_rate_limit_json', JSON.stringify({ fiveHour: { utilization: 0.5 }, sevenDay: { utilization: 0.6 } }));
|
await setSetting(s.db, s.u, 'claude_rate_limit_json', JSON.stringify({ fiveHour: { utilization: 0.5 }, sevenDay: { utilization: 0.6 } }));
|
||||||
assert.equal(quotaState(s.db).blocked, false);
|
assert.equal((await quotaState(s.db, s.u)).blocked, false);
|
||||||
setSetting(s.db, 'claude_rate_limit_json', JSON.stringify({ fiveHour: { utilization: 0.9 }, sevenDay: { utilization: 0.6 } }));
|
await setSetting(s.db, s.u, 'claude_rate_limit_json', JSON.stringify({ fiveHour: { utilization: 0.9 }, sevenDay: { utilization: 0.6 } }));
|
||||||
let q = quotaState(s.db);
|
let q = await quotaState(s.db, s.u);
|
||||||
assert.equal(q.blocked, true);
|
assert.equal(q.blocked, true);
|
||||||
assert.equal(q.reason, 'quota de la session Claude (5 h) à 90 %');
|
assert.equal(q.reason, 'quota de la session Claude (5 h) à 90 %');
|
||||||
setSetting(s.db, 'claude_rate_limit_json', JSON.stringify({ fiveHour: { utilization: 0.1 }, sevenDay: { utilization: 0.99 } }));
|
await setSetting(s.db, s.u, 'claude_rate_limit_json', JSON.stringify({ fiveHour: { utilization: 0.1 }, sevenDay: { utilization: 0.99 } }));
|
||||||
q = quotaState(s.db);
|
q = await quotaState(s.db, s.u);
|
||||||
assert.equal(q.reason, 'quota de la semaine Claude à 99 %');
|
assert.equal(q.reason, 'quota de la semaine Claude à 99 %');
|
||||||
setSetting(s.db, 'claude_rate_limit_json', 'pas du json');
|
await setSetting(s.db, s.u, 'claude_rate_limit_json', 'pas du json');
|
||||||
assert.deepEqual(quotaState(s.db), { blocked: false, reason: null }, 'jamais planter sur une valeur corrompue');
|
assert.deepEqual(await quotaState(s.db, s.u), { blocked: false, reason: null }, 'jamais planter sur une valeur corrompue');
|
||||||
});
|
});
|
||||||
|
|
||||||
test('quota serré : analyse/évolution attendent, la prospection et l\'envoi continuent', async () => {
|
test('quota serré : analyse/évolution attendent, la prospection et l\'envoi continuent', async () => {
|
||||||
const s = setup();
|
const s = await setup();
|
||||||
setSetting(s.db, 'claude_rate_limit_json', JSON.stringify({ fiveHour: { utilization: 0.9 } }));
|
await setSetting(s.db, s.u, 'claude_rate_limit_json', JSON.stringify({ fiveHour: { utilization: 0.9 } }));
|
||||||
const ran = [];
|
const ran = [];
|
||||||
const alerts = [];
|
const alerts = [];
|
||||||
const h = (name) => async () => { ran.push(name); };
|
const h = (name) => async () => { ran.push(name); };
|
||||||
const w = new Worker(s.db, { prospect: h('prospect'), evolution: h('evolution'), analyze: h('analyze') }, {
|
const w = new Worker(s.db, { prospect: h('prospect'), evolution: h('evolution'), analyze: h('analyze') }, {
|
||||||
thermalMax: 999, log: { error() {} },
|
thermalMax: 999, log: { error() {} },
|
||||||
quota: () => quotaState(s.db), isQuotaSensitive, onQuotaHold: (r) => alerts.push(r),
|
quota: (u) => quotaState(s.db, u), isQuotaSensitive, onQuotaHold: (r) => alerts.push(r),
|
||||||
});
|
});
|
||||||
enqueue(s.db, { projectId: 1, type: 'evolution' });
|
await enqueue(s.db, { userId: s.u, projectId: 1, type: 'evolution' });
|
||||||
enqueue(s.db, { projectId: 1, type: 'analyze' });
|
await enqueue(s.db, { userId: s.u, projectId: 1, type: 'analyze' });
|
||||||
enqueue(s.db, { projectId: 1, type: 'prospect' });
|
await enqueue(s.db, { userId: s.u, projectId: 1, type: 'prospect' });
|
||||||
|
|
||||||
assert.equal(await w.tick(), true);
|
assert.equal(await w.tick(), true);
|
||||||
assert.deepEqual(ran, ['prospect'], 'la prospection passe devant les jobs reportés');
|
assert.deepEqual(ran, ['prospect'], 'la prospection passe devant les jobs reportés');
|
||||||
assert.equal(alerts.length, 1);
|
assert.equal(alerts.length, 1);
|
||||||
assert.match(alerts[0], /quota de la session Claude \(5 h\) à 90 %/);
|
assert.match(alerts[0], /quota de la session Claude \(5 h\) à 90 %/);
|
||||||
const jobs = latestJobs(s.db, 1);
|
const jobs = await latestJobs(s.db, 1);
|
||||||
assert.match(jobs.evolution.progress.message, /^En attente : quota de la session/);
|
assert.match(jobs.evolution.progress.message, /^En attente : quota de la session/);
|
||||||
|
|
||||||
setSetting(s.db, 'claude_rate_limit_json', JSON.stringify({ fiveHour: { utilization: 0.1 } }));
|
await setSetting(s.db, s.u, 'claude_rate_limit_json', JSON.stringify({ fiveHour: { utilization: 0.1 } }));
|
||||||
await w.tick(); await w.tick();
|
await w.tick(); await w.tick();
|
||||||
assert.deepEqual(ran, ['prospect', 'evolution', 'analyze'], 'repartent tout seuls une fois le quota libéré');
|
assert.deepEqual(ran, ['prospect', 'evolution', 'analyze'], 'repartent tout seuls une fois le quota libéré');
|
||||||
});
|
});
|
||||||
|
|
||||||
test('quotaAlerts : un palier (80 %, 95 %) une seule fois, re-sonne si la fenêtre a tourné', () => {
|
test('quotaAlerts : un palier (80 %, 95 %) une seule fois, re-sonne si la fenêtre a tourné', async () => {
|
||||||
const s = setup();
|
const s = await setup();
|
||||||
let a = quotaAlerts(s.db, { fiveHour: { utilization: 0.5, resetsAt: 100 } });
|
let a = await quotaAlerts(s.db, s.u, { fiveHour: { utilization: 0.5, resetsAt: 100 } });
|
||||||
assert.deepEqual(a, []);
|
assert.deepEqual(a, []);
|
||||||
a = quotaAlerts(s.db, { fiveHour: { utilization: 0.82, resetsAt: 100 } });
|
a = await quotaAlerts(s.db, s.u, { fiveHour: { utilization: 0.82, resetsAt: 100 } });
|
||||||
assert.deepEqual(a, [{ label: 'session Claude (5 h)', level: 80, utilization: 0.82 }]);
|
assert.deepEqual(a, [{ label: 'session Claude (5 h)', level: 80, utilization: 0.82 }]);
|
||||||
// toujours au-dessus de 80 %, même fenêtre : pas de redite
|
// toujours au-dessus de 80 %, même fenêtre : pas de redite
|
||||||
a = quotaAlerts(s.db, { fiveHour: { utilization: 0.88, resetsAt: 100 } });
|
a = await quotaAlerts(s.db, s.u, { fiveHour: { utilization: 0.88, resetsAt: 100 } });
|
||||||
assert.deepEqual(a, []);
|
assert.deepEqual(a, []);
|
||||||
// passe 95 % : nouveau palier
|
// passe 95 % : nouveau palier
|
||||||
a = quotaAlerts(s.db, { fiveHour: { utilization: 0.97, resetsAt: 100 } });
|
a = await quotaAlerts(s.db, s.u, { fiveHour: { utilization: 0.97, resetsAt: 100 } });
|
||||||
assert.deepEqual(a, [{ label: 'session Claude (5 h)', level: 95, utilization: 0.97 }]);
|
assert.deepEqual(a, [{ label: 'session Claude (5 h)', level: 95, utilization: 0.97 }]);
|
||||||
// la fenêtre a tourné (nouveau resetsAt) : 80 % re-sonne
|
// la fenêtre a tourné (nouveau resetsAt) : 80 % re-sonne
|
||||||
a = quotaAlerts(s.db, { fiveHour: { utilization: 0.81, resetsAt: 200 } });
|
a = await quotaAlerts(s.db, s.u, { fiveHour: { utilization: 0.81, resetsAt: 200 } });
|
||||||
assert.deepEqual(a, [{ label: 'session Claude (5 h)', level: 80, utilization: 0.81 }]);
|
assert.deepEqual(a, [{ label: 'session Claude (5 h)', level: 80, utilization: 0.81 }]);
|
||||||
// saut direct à 95 % : un seul palier notifié, pas 80 puis 95
|
// saut direct à 95 % : un seul palier notifié, pas 80 puis 95
|
||||||
a = quotaAlerts(s.db, { sevenDay: { utilization: 0.97, resetsAt: 300 } });
|
a = await quotaAlerts(s.db, s.u, { sevenDay: { utilization: 0.97, resetsAt: 300 } });
|
||||||
assert.deepEqual(a, [{ label: 'semaine Claude', level: 95, utilization: 0.97 }]);
|
assert.deepEqual(a, [{ label: 'semaine Claude', level: 95, utilization: 0.97 }]);
|
||||||
});
|
});
|
||||||
|
|
|
||||||
445
test/claude-link.test.js
Normal file
445
test/claude-link.test.js
Normal file
|
|
@ -0,0 +1,445 @@
|
||||||
|
import { test, before, after } from 'node:test';
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import { mkdtempSync, rmSync } from 'node:fs';
|
||||||
|
import { tmpdir } from 'node:os';
|
||||||
|
import { join } from 'node:path';
|
||||||
|
import { now, getSetting, setSetting } from '../src/db.js';
|
||||||
|
import { decrypt } from '../src/crypto.js';
|
||||||
|
import { enqueue, Worker, jobRefusal } from '../src/services/jobs.js';
|
||||||
|
import { AI_JOBS } from '../src/services/budget.js';
|
||||||
|
import { makeClaude } from '../src/handlers.js';
|
||||||
|
import {
|
||||||
|
LINK_REQUIRED_MESSAGE, CONSENT_VERSION, CONSENT_CHECKBOX, aiRefusal, validateApiKey, getLinkState,
|
||||||
|
} from '../src/claudelink.js';
|
||||||
|
import { startApp } from './helpers/server.js';
|
||||||
|
import { makeClaudeBin } from './helpers/claude-bin.js';
|
||||||
|
|
||||||
|
// Liaison Claude : clé API, jeton d'abonnement avec consentement, mode serveur, onboarding bloquant, déliaison.
|
||||||
|
// Aucun appel réseau ni CLI réel : fetch injecté, CLI simulé par les fixtures.
|
||||||
|
let s, binDir;
|
||||||
|
const KEY_A = `sk-ant-api03-${'A'.repeat(40)}ZZ12`;
|
||||||
|
const KEY_B = `sk-ant-api03-${'B'.repeat(40)}QQ34`;
|
||||||
|
const TOKEN = `sk-ant-oat01-${'T'.repeat(48)}`;
|
||||||
|
const AI_ROUTES = ['analyze', 'template', 'followup_template', 'prospect', 'evolution'];
|
||||||
|
const logs = [];
|
||||||
|
const realConsole = { log: console.log, warn: console.warn, error: console.error };
|
||||||
|
|
||||||
|
// Réponses de « api.anthropic.com » : 200 par défaut, modifiable par test
|
||||||
|
let apiStatus = 200, apiThrows = false;
|
||||||
|
const apiCalls = [];
|
||||||
|
|
||||||
|
before(async () => {
|
||||||
|
binDir = mkdtempSync(join(tmpdir(), 'aitools-bin-'));
|
||||||
|
s = await startApp({ cfg: { claudeBin: makeClaudeBin(binDir) } });
|
||||||
|
s.app.fetch = async (url, opts) => {
|
||||||
|
apiCalls.push({ url, headers: opts?.headers });
|
||||||
|
if (apiThrows) throw new Error('ECONNRESET');
|
||||||
|
return { status: apiStatus, ok: apiStatus >= 200 && apiStatus < 300 };
|
||||||
|
};
|
||||||
|
for (const k of Object.keys(realConsole)) console[k] = (...a) => { logs.push(a.map(String).join(' ')); };
|
||||||
|
});
|
||||||
|
after(async () => {
|
||||||
|
Object.assign(console, realConsole);
|
||||||
|
await s.close();
|
||||||
|
rmSync(binDir, { recursive: true, force: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
const row = (id) => s.db.prepare('SELECT claude_link_json FROM users WHERE id = ?').get(id);
|
||||||
|
const dump = async () => JSON.stringify([
|
||||||
|
await s.db.prepare('SELECT * FROM users').all(), await s.db.prepare('SELECT * FROM user_settings').all(),
|
||||||
|
await s.db.prepare('SELECT * FROM jobs').all(), await s.db.prepare('SELECT * FROM sessions').all(),
|
||||||
|
]);
|
||||||
|
const project = async (u) => Number((await s.db.prepare(`INSERT INTO projects(user_id, name, git_url, profile_json, target_json, target_validated, created_at)
|
||||||
|
VALUES(?, 'P', ?, ?, ?, 1, ?)`).run(u.id, `https://git.test/u${u.id}/p.git`, JSON.stringify({ resume: 'x' }), JSON.stringify({ description: 'd', secteurs: ['s'] }), now())).lastInsertRowid);
|
||||||
|
|
||||||
|
test('clé API : validée sans coût (GET /v1/models), chiffrée, jamais réaffichée', async () => {
|
||||||
|
const u = await s.newUser({ admin: false });
|
||||||
|
apiCalls.length = 0; apiStatus = 200;
|
||||||
|
const r = await u.post('/link/api-key', { apiKey: KEY_A });
|
||||||
|
assert.equal(r.status, 200);
|
||||||
|
assert.equal(apiCalls.length, 1);
|
||||||
|
assert.equal(apiCalls[0].url, 'https://api.anthropic.com/v1/models');
|
||||||
|
assert.equal(apiCalls[0].headers['x-api-key'], KEY_A);
|
||||||
|
assert.equal(apiCalls[0].headers['anthropic-version'], '2023-06-01');
|
||||||
|
|
||||||
|
const stored = (await row(u.id)).claude_link_json;
|
||||||
|
assert.ok(!stored.includes(KEY_A), 'pas en clair en base');
|
||||||
|
const link = JSON.parse(stored);
|
||||||
|
assert.equal(link.mode, 'api_key');
|
||||||
|
assert.equal(link.last4, 'ZZ12');
|
||||||
|
assert.equal(decrypt(s.app.cfg.secretKey, link.secret_enc), KEY_A, 'chiffré avec SECRET_KEY, relisible');
|
||||||
|
assert.ok(!(await dump()).includes(KEY_A));
|
||||||
|
|
||||||
|
for (const path of ['/link', '/account', '/api/system']) {
|
||||||
|
const body = await (await u.get(path, { headers: { accept: 'text/html' } })).text();
|
||||||
|
assert.ok(!body.includes(KEY_A), `${path} ne renvoie jamais la clé`);
|
||||||
|
assert.ok(!body.includes('A'.repeat(20)), `${path} ne renvoie pas de morceau de la clé`);
|
||||||
|
}
|
||||||
|
const account = await (await u.get('/account', { headers: { accept: 'text/html' } })).text();
|
||||||
|
assert.match(account, /sk-ant-…ZZ12/);
|
||||||
|
assert.ok(!logs.some((l) => l.includes(KEY_A)), 'aucune trace de la clé dans les journaux');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('clé API : refus 401/403 et erreur réseau distincts, rien n\'est stocké', async () => {
|
||||||
|
const u = await s.newUser({ admin: false });
|
||||||
|
apiStatus = 401;
|
||||||
|
let r = await u.post('/link/api-key', { apiKey: KEY_B });
|
||||||
|
assert.equal(r.status, 400);
|
||||||
|
const refused = (await r.json()).error;
|
||||||
|
assert.match(refused, /refusée/);
|
||||||
|
apiStatus = 403;
|
||||||
|
assert.equal((await u.post('/link/api-key', { apiKey: KEY_B })).status, 400);
|
||||||
|
apiStatus = 200; apiThrows = true;
|
||||||
|
r = await u.post('/link/api-key', { apiKey: KEY_B });
|
||||||
|
apiThrows = false;
|
||||||
|
assert.equal(r.status, 502);
|
||||||
|
const network = (await r.json()).error;
|
||||||
|
assert.match(network, /réseau/);
|
||||||
|
assert.notEqual(network, refused);
|
||||||
|
assert.ok(!JSON.stringify(network).includes(KEY_B));
|
||||||
|
apiStatus = 500;
|
||||||
|
assert.equal((await u.post('/link/api-key', { apiKey: KEY_B })).status, 502);
|
||||||
|
apiStatus = 200;
|
||||||
|
assert.equal((await row(u.id)).claude_link_json, null, 'aucune liaison enregistrée');
|
||||||
|
assert.equal((await u.post('/link/api-key', { apiKey: 'pas-une-cle' })).status, 400);
|
||||||
|
assert.equal((await u.post('/link/api-key', {})).status, 400);
|
||||||
|
assert.ok(!logs.some((l) => l.includes(KEY_B)));
|
||||||
|
});
|
||||||
|
|
||||||
|
test('validateApiKey : fetch injectable, 401/403 refusé, réseau distinct', async () => {
|
||||||
|
await assert.rejects(validateApiKey(KEY_A, async () => ({ status: 401, ok: false })), { status: 400 });
|
||||||
|
await assert.rejects(validateApiKey(KEY_A, async () => ({ status: 403, ok: false })), { status: 400 });
|
||||||
|
await assert.rejects(validateApiKey(KEY_A, async () => { throw new Error('boom'); }), { status: 502 });
|
||||||
|
await validateApiKey(KEY_A, async () => ({ status: 200, ok: true }));
|
||||||
|
});
|
||||||
|
|
||||||
|
test('mode abonnement : sans la case, 400 et rien n\'est stocké ni validé', async () => {
|
||||||
|
const u = await s.newUser({ admin: false });
|
||||||
|
let validated = 0;
|
||||||
|
s.app.validateToken = async () => { validated++; };
|
||||||
|
try {
|
||||||
|
for (const body of [{ token: TOKEN }, { token: TOKEN, accept: '' }, { token: TOKEN, accept: 'off' }, { token: TOKEN, accept: false }]) {
|
||||||
|
const r = await u.post('/link/subscription', body);
|
||||||
|
assert.equal(r.status, 400);
|
||||||
|
assert.match((await r.json()).error, new RegExp(CONSENT_CHECKBOX));
|
||||||
|
}
|
||||||
|
assert.equal(validated, 0, 'le jeton n\'est même pas vérifié sans consentement');
|
||||||
|
assert.equal((await row(u.id)).claude_link_json, null);
|
||||||
|
assert.equal(await getSetting(s.db, u.id, 'claude_cli_consent_json'), null);
|
||||||
|
assert.ok(!(await dump()).includes(TOKEN));
|
||||||
|
} finally { delete s.app.validateToken; }
|
||||||
|
});
|
||||||
|
|
||||||
|
test('mode abonnement : case cochée, consentement horodaté avec la version du texte, jeton chiffré', async () => {
|
||||||
|
const u = await s.newUser({ admin: false });
|
||||||
|
s.app.validateToken = async () => {};
|
||||||
|
const before = now();
|
||||||
|
try {
|
||||||
|
const r = await u.post('/link/subscription', { token: TOKEN, accept: true });
|
||||||
|
assert.equal(r.status, 200);
|
||||||
|
} finally { delete s.app.validateToken; }
|
||||||
|
const stored = (await row(u.id)).claude_link_json;
|
||||||
|
assert.ok(!stored.includes(TOKEN));
|
||||||
|
const link = JSON.parse(stored);
|
||||||
|
assert.equal(link.mode, 'subscription_token');
|
||||||
|
assert.ok(link.consent.at >= before && link.consent.at <= now());
|
||||||
|
assert.equal(link.consent.version, CONSENT_VERSION);
|
||||||
|
assert.equal(decrypt(s.app.cfg.secretKey, link.secret_enc), TOKEN);
|
||||||
|
assert.ok(!(await dump()).includes(TOKEN));
|
||||||
|
const account = await (await u.get('/account', { headers: { accept: 'text/html' } })).text();
|
||||||
|
assert.ok(!account.includes(TOKEN));
|
||||||
|
assert.match(account, new RegExp(CONSENT_VERSION.replace(/\./g, '\\.')));
|
||||||
|
assert.doesNotMatch(account, /sk-ant-…/, 'pas de 4 derniers caractères pour un jeton');
|
||||||
|
assert.ok(!logs.some((l) => l.includes(TOKEN)));
|
||||||
|
});
|
||||||
|
|
||||||
|
test('mode abonnement via le CLI simulé : jeton révoqué refusé, jeton valide accepté, jamais dans les erreurs', async () => {
|
||||||
|
const u = await s.newUser({ admin: false });
|
||||||
|
const revoked = `${TOKEN}REVOKED`;
|
||||||
|
const r = await u.post('/link/subscription', { token: revoked, accept: true });
|
||||||
|
assert.equal(r.status, 400);
|
||||||
|
assert.ok(!JSON.stringify(await r.json()).includes(revoked));
|
||||||
|
assert.equal((await row(u.id)).claude_link_json, null);
|
||||||
|
assert.equal((await u.post('/link/subscription', { token: TOKEN, accept: 'on' })).status, 200);
|
||||||
|
assert.equal((await getLinkState(s.db, u.id)).mode, 'subscription_token');
|
||||||
|
// une clé API collée dans le champ jeton est signalée
|
||||||
|
assert.equal((await u.post('/link/subscription', { token: KEY_A, accept: true })).status, 400);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('formulaire HTML : l\'erreur revient sur /link, la page affiche la fenêtre d\'avertissement avec la case', async () => {
|
||||||
|
const u = await s.newUser({ admin: false });
|
||||||
|
const r = await u.post('/link/subscription', { token: TOKEN }, { form: true });
|
||||||
|
assert.equal(r.status, 400, 'ce client demande du JSON');
|
||||||
|
const form = await fetch(`${s.base}/link/subscription`, {
|
||||||
|
method: 'POST', redirect: 'manual',
|
||||||
|
headers: { cookie: u.cookie, origin: 'https://ai.tony-averty.dev', 'content-type': 'application/x-www-form-urlencoded' },
|
||||||
|
body: new URLSearchParams({ token: TOKEN }).toString(),
|
||||||
|
});
|
||||||
|
assert.equal(form.status, 303);
|
||||||
|
assert.match(decodeURIComponent(form.headers.get('location')), /^\/link\?e=.*cocher/);
|
||||||
|
const page = (await (await u.get('/link', { headers: { accept: 'text/html' } })).text()).replace(/'/g, "'");
|
||||||
|
assert.match(page, /<dialog[^>]*id="consent-dialog"/);
|
||||||
|
assert.match(page, /contrevenir aux conditions d'utilisation d'Anthropic/);
|
||||||
|
assert.match(page, /suspension/);
|
||||||
|
assert.match(page, /ne peut en être tenu responsable/);
|
||||||
|
assert.match(page, /<input type="checkbox" name="accept" id="consent-accept" required>/);
|
||||||
|
assert.match(page, /id="consent-submit" disabled/);
|
||||||
|
assert.match(page, /claude setup-token/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('drapeau CLAUDE_CLI_MODE_ENABLED=false : mode abonnement masqué et refusé côté serveur', async () => {
|
||||||
|
const off = await startApp({ cfg: { claudeBin: 'inexistant', cliModeEnabled: false } });
|
||||||
|
try {
|
||||||
|
const u = await off.newUser({ admin: false });
|
||||||
|
let validated = 0;
|
||||||
|
off.app.validateToken = async () => { validated++; };
|
||||||
|
const r = await u.post('/link/subscription', { token: TOKEN, accept: true });
|
||||||
|
assert.equal(r.status, 403);
|
||||||
|
assert.equal(validated, 0);
|
||||||
|
assert.equal((await off.db.prepare('SELECT claude_link_json FROM users WHERE id = ?').get(u.id)).claude_link_json, null);
|
||||||
|
const page = await (await u.get('/link', { headers: { accept: 'text/html' } })).text();
|
||||||
|
assert.doesNotMatch(page, /consent-dialog|setup-token|abonnement/);
|
||||||
|
assert.match(page, /Clé API Anthropic/);
|
||||||
|
// une liaison abonnement déjà en base ne permet plus de lancer de job
|
||||||
|
const linked = await off.newUser({ admin: false, link: { v: 1, mode: 'subscription_token', valid: true, secret_enc: 'x' } });
|
||||||
|
assert.match(await aiRefusal(off.db, linked.id, { cliModeEnabled: false }), /désactivé/);
|
||||||
|
assert.equal(await aiRefusal(off.db, linked.id, { cliModeEnabled: true }), null);
|
||||||
|
} finally { await off.close(); }
|
||||||
|
});
|
||||||
|
|
||||||
|
test('mode « Claude du serveur » : réservé aux admins (liaison et exécution)', async () => {
|
||||||
|
const user = await s.newUser({ admin: false });
|
||||||
|
assert.equal((await user.post('/link/server', {})).status, 403);
|
||||||
|
assert.equal((await row(user.id)).claude_link_json, null);
|
||||||
|
assert.ok(!(await (await user.get('/link', { headers: { accept: 'text/html' } })).text()).includes('/link/server'));
|
||||||
|
const admin = await s.newUser({ admin: true, link: null });
|
||||||
|
assert.match(await (await admin.get('/link', { headers: { accept: 'text/html' } })).text(), /action="\/link\/server"/);
|
||||||
|
assert.equal((await admin.post('/link/server', {})).status, 200);
|
||||||
|
assert.equal((await getLinkState(s.db, admin.id)).mode, 'server');
|
||||||
|
assert.equal(await aiRefusal(s.db, admin.id), null);
|
||||||
|
// un admin rétrogradé (ADMIN_EMAILS) perd le mode serveur
|
||||||
|
await s.db.prepare('UPDATE users SET is_admin = 0 WHERE id = ?').run(admin.id);
|
||||||
|
assert.match(await aiRefusal(s.db, admin.id), /réservé aux administrateurs/);
|
||||||
|
await s.db.prepare('UPDATE users SET is_admin = 1 WHERE id = ?').run(admin.id);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('onboarding bloquant : sans liaison, tout est refusé côté serveur sauf liaison, compte, déconnexion', async () => {
|
||||||
|
const u = await s.newUser({ admin: false });
|
||||||
|
const html = { headers: { accept: 'text/html' } };
|
||||||
|
let r = await u.get('/', html);
|
||||||
|
assert.equal(r.status, 303);
|
||||||
|
assert.equal(r.headers.get('location'), '/link');
|
||||||
|
assert.equal((await u.get('/settings', html)).headers.get('location'), '/link');
|
||||||
|
|
||||||
|
const p = await project(u);
|
||||||
|
const blocked = [
|
||||||
|
['get', '/api/system'], ['get', `/api/projects/${p}/status`], ['get', `/api/projects/${p}/prospects`],
|
||||||
|
['get', `/api/projects/${p}/prospects.csv`], ['get', `/api/projects/${p}/recap`], ['get', `/api/projects/${p}/history`],
|
||||||
|
['post', '/api/projects', { name: 'x', gitUrl: 'https://git.test/u/x.git' }],
|
||||||
|
['post', `/api/projects/${p}/send`, { count: 1, confirm: true }],
|
||||||
|
['post', `/api/projects/${p}/target`, {}], ['post', `/api/projects/${p}/delete`, {}],
|
||||||
|
['post', `/api/projects/${p}/prospects/import`, { csv: 'a' }], ['post', '/api/report/send', {}],
|
||||||
|
['post', '/api/notify/test', {}], ['post', '/settings', {}], ['post', '/api/jobs/1/cancel', {}],
|
||||||
|
...AI_ROUTES.map((t) => ['post', `/api/projects/${p}/${t}`, {}]),
|
||||||
|
];
|
||||||
|
for (const [method, path, body] of blocked) {
|
||||||
|
r = method === 'get' ? await u.get(path) : await u.post(path, body ?? {});
|
||||||
|
assert.equal(r.status, 403, `${method} ${path}`);
|
||||||
|
const j = await r.json();
|
||||||
|
assert.equal(j.code, 'link_required');
|
||||||
|
assert.equal(j.error, LINK_REQUIRED_MESSAGE);
|
||||||
|
}
|
||||||
|
assert.equal((await s.db.prepare('SELECT COUNT(*) n FROM jobs WHERE user_id = ?').get(u.id)).n, 0);
|
||||||
|
|
||||||
|
// Ce qui reste accessible
|
||||||
|
for (const path of ['/link', '/account']) assert.equal((await u.get(path, html)).status, 200, path);
|
||||||
|
assert.equal((await u.post('/logout', {})).status, 303);
|
||||||
|
assert.equal((await s.client(u.cookie).get('/link', html)).status, 303, 'la session est détruite par la déconnexion');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('onboarding : une fois relié, l\'application est accessible', async () => {
|
||||||
|
const u = await s.newUser({ admin: false });
|
||||||
|
const html = { headers: { accept: 'text/html' } };
|
||||||
|
assert.equal((await u.get('/', html)).status, 303);
|
||||||
|
await u.post('/link/api-key', { apiKey: KEY_A });
|
||||||
|
assert.equal((await u.get('/', html)).status, 200);
|
||||||
|
assert.equal((await u.get('/api/system')).status, 200);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('garde « compte relié » à chaque couche : route, enqueue, worker, wrapper', async () => {
|
||||||
|
const linked = await s.newUser({ admin: false });
|
||||||
|
await linked.post('/link/api-key', { apiKey: KEY_A });
|
||||||
|
const bare = await s.newUser({ admin: false });
|
||||||
|
const pBare = await project(bare);
|
||||||
|
const pLinked = await project(linked);
|
||||||
|
// enqueue
|
||||||
|
for (const type of AI_JOBS) {
|
||||||
|
await assert.rejects(enqueue(s.db, { userId: bare.id, projectId: pBare, type }), { status: 403, message: LINK_REQUIRED_MESSAGE }, type);
|
||||||
|
}
|
||||||
|
assert.equal((await enqueue(s.db, { userId: bare.id, projectId: pBare, type: 'send', params: { count: 1 } })).existing, false, 'un envoi n\'utilise pas Claude');
|
||||||
|
await s.db.prepare("UPDATE jobs SET status = 'cancelled' WHERE user_id = ?").run(bare.id);
|
||||||
|
assert.equal((await enqueue(s.db, { userId: linked.id, projectId: pLinked, type: 'analyze' })).existing, false);
|
||||||
|
await s.db.prepare("UPDATE jobs SET status = 'cancelled' WHERE user_id = ?").run(linked.id);
|
||||||
|
|
||||||
|
// worker : un job IA déjà en base d'un compte non relié ne s'exécute pas
|
||||||
|
const ran = [];
|
||||||
|
const w = new Worker(s.db, Object.fromEntries([...AI_JOBS, 'send'].map((t) => [t, async () => { ran.push(t); return {}; }])), { thermalMax: 999, log: { error() {} } });
|
||||||
|
for (const type of [...AI_JOBS, 'send']) await s.db.prepare("INSERT INTO jobs(user_id, project_id, type, status, created_at) VALUES(?, ?, ?, 'queued', ?)").run(bare.id, pBare, type, now());
|
||||||
|
while (await w.tick()) { /* vide la file */ }
|
||||||
|
assert.deepEqual(ran, ['send']);
|
||||||
|
assert.equal(await jobRefusal(s.db, { user_id: bare.id, type: 'analyze' }), LINK_REQUIRED_MESSAGE);
|
||||||
|
assert.equal(await jobRefusal(s.db, { user_id: bare.id, type: 'send' }), null);
|
||||||
|
|
||||||
|
// wrapper d'exécution : dernier garde-fou, avant tout lancement de processus
|
||||||
|
const claude = makeClaude({ ...s.app, cfg: { ...s.app.cfg, claudeBin: '/inexistant/claude' } });
|
||||||
|
await assert.rejects(claude(bare.id, { prompt: 'x' }), { status: 403, message: LINK_REQUIRED_MESSAGE });
|
||||||
|
await assert.rejects(claude(999999, { prompt: 'x' }), { status: 403, message: 'Compte supprimé' });
|
||||||
|
});
|
||||||
|
|
||||||
|
test('liaison invalide ou compte suspendu : aucun job IA', async () => {
|
||||||
|
const u = await s.newUser({ admin: false });
|
||||||
|
await u.post('/link/api-key', { apiKey: KEY_A });
|
||||||
|
assert.equal(await aiRefusal(s.db, u.id), null);
|
||||||
|
await s.db.prepare("UPDATE users SET status = 'suspended' WHERE id = ?").run(u.id);
|
||||||
|
assert.equal(await aiRefusal(s.db, u.id), 'Compte suspendu');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('Mon compte : Tester — succès, refus (liaison invalidée, onboarding de retour), réseau (liaison inchangée)', async () => {
|
||||||
|
const u = await s.newUser({ admin: false });
|
||||||
|
await u.post('/link/api-key', { apiKey: KEY_A });
|
||||||
|
apiStatus = 200;
|
||||||
|
let j = await (await u.post('/link/test', {})).json();
|
||||||
|
assert.deepEqual({ ok: j.ok }, { ok: true });
|
||||||
|
const t1 = (await getLinkState(s.db, u.id)).lastTestAt;
|
||||||
|
assert.ok(t1);
|
||||||
|
|
||||||
|
apiThrows = true;
|
||||||
|
j = await (await u.post('/link/test', {})).json();
|
||||||
|
apiThrows = false;
|
||||||
|
assert.equal(j.ok, false);
|
||||||
|
assert.match(j.message, /réseau/);
|
||||||
|
assert.equal((await getLinkState(s.db, u.id)).valid, true, 'une panne réseau n\'invalide pas la liaison');
|
||||||
|
|
||||||
|
apiStatus = 401;
|
||||||
|
j = await (await u.post('/link/test', {})).json();
|
||||||
|
apiStatus = 200;
|
||||||
|
assert.equal(j.ok, false);
|
||||||
|
const state = await getLinkState(s.db, u.id);
|
||||||
|
assert.equal(state.valid, false);
|
||||||
|
assert.equal((await u.get('/', { headers: { accept: 'text/html' } })).headers.get('location'), '/link', 'liaison invalide : retour à l\'onboarding');
|
||||||
|
const account = await (await u.get('/account', { headers: { accept: 'text/html' } })).text();
|
||||||
|
assert.match(account, /À revalider/);
|
||||||
|
// Re-relier avec une clé valide rétablit l'accès
|
||||||
|
assert.equal((await u.post('/link/api-key', { apiKey: KEY_B })).status, 200);
|
||||||
|
assert.equal((await getLinkState(s.db, u.id)).last4, 'QQ34');
|
||||||
|
assert.equal(await aiRefusal(s.db, u.id), null);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('Mon compte : état de la liaison, boutons Tester, Changer de mode, Délier', async () => {
|
||||||
|
const u = await s.newUser({ admin: false });
|
||||||
|
await u.post('/link/api-key', { apiKey: KEY_A });
|
||||||
|
const page = await (await u.get('/account', { headers: { accept: 'text/html' } })).text();
|
||||||
|
assert.match(page, /Clé API Anthropic/);
|
||||||
|
assert.match(page, /Valide/);
|
||||||
|
assert.match(page, /action="\/link\/test"/);
|
||||||
|
assert.match(page, /href="\/link\?change=1"/);
|
||||||
|
assert.match(page, /action="\/link\/unlink"/);
|
||||||
|
// changer de mode : la page de liaison reste accessible et le nouvel accès remplace l'ancien
|
||||||
|
s.app.validateToken = async () => {};
|
||||||
|
try { assert.equal((await u.post('/link/subscription', { token: TOKEN, accept: true })).status, 200); } finally { delete s.app.validateToken; }
|
||||||
|
const link = JSON.parse((await row(u.id)).claude_link_json);
|
||||||
|
assert.equal(link.mode, 'subscription_token');
|
||||||
|
assert.equal(link.last4, undefined, 'plus de trace de la clé API');
|
||||||
|
assert.ok(!(await dump()).includes(KEY_A));
|
||||||
|
});
|
||||||
|
|
||||||
|
test('délier : secret effacé, jobs IA en file annulés, autres jobs et autres comptes intacts, onboarding de retour', async () => {
|
||||||
|
const a = await s.newUser({ admin: false });
|
||||||
|
const b = await s.newUser({ admin: false });
|
||||||
|
await a.post('/link/api-key', { apiKey: KEY_A });
|
||||||
|
await b.post('/link/api-key', { apiKey: KEY_B });
|
||||||
|
const pa = await project(a), pb = await project(b);
|
||||||
|
await enqueue(s.db, { userId: a.id, projectId: pa, type: 'analyze' });
|
||||||
|
await enqueue(s.db, { userId: a.id, projectId: pa, type: 'prospect' });
|
||||||
|
await enqueue(s.db, { userId: a.id, projectId: pa, type: 'send', params: { count: 1 } });
|
||||||
|
await enqueue(s.db, { userId: b.id, projectId: pb, type: 'analyze' });
|
||||||
|
await setSetting(s.db, a.id, 'claude_rate_limit_json', JSON.stringify({ fiveHour: { utilization: 0.9 } }));
|
||||||
|
|
||||||
|
const r = await a.post('/link/unlink', {});
|
||||||
|
assert.equal(r.status, 200);
|
||||||
|
assert.equal((await r.json()).cancelled, 2);
|
||||||
|
assert.equal((await row(a.id)).claude_link_json, null);
|
||||||
|
assert.ok(!(await dump()).includes(KEY_A), 'le secret chiffré est supprimé');
|
||||||
|
const status = async (u, type) => (await s.db.prepare('SELECT status FROM jobs WHERE user_id = ? AND type = ?').get(u.id, type)).status;
|
||||||
|
assert.equal(await status(a, 'analyze'), 'cancelled');
|
||||||
|
assert.equal(await status(a, 'prospect'), 'cancelled');
|
||||||
|
assert.equal(await status(a, 'send'), 'queued', 'un envoi n\'utilise pas Claude');
|
||||||
|
assert.equal(await status(b, 'analyze'), 'queued', 'les jobs d\'un autre compte ne bougent pas');
|
||||||
|
assert.equal((await getLinkState(s.db, b.id)).mode, 'api_key');
|
||||||
|
assert.equal(await getSetting(s.db, a.id, 'claude_rate_limit_json'), null, 'le quota de l\'ancien accès ne subsiste pas');
|
||||||
|
assert.equal((await a.get('/', { headers: { accept: 'text/html' } })).headers.get('location'), '/link');
|
||||||
|
assert.equal(await aiRefusal(s.db, a.id), LINK_REQUIRED_MESSAGE);
|
||||||
|
// Mon compte reste accessible et propose de relier
|
||||||
|
assert.match(await (await a.get('/account', { headers: { accept: 'text/html' } })).text(), /Relier Claude/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('délier un job IA en cours : il est interrompu', async () => {
|
||||||
|
const u = await s.newUser({ admin: false });
|
||||||
|
await u.post('/link/api-key', { apiKey: KEY_A });
|
||||||
|
const p = await project(u);
|
||||||
|
let aborted = false;
|
||||||
|
await s.db.prepare("UPDATE jobs SET status = 'cancelled' WHERE status = 'queued'").run(); // jobs des tests précédents
|
||||||
|
const w = new Worker(s.db, {
|
||||||
|
analyze: (ctx) => new Promise((resolve) => { ctx.signal.addEventListener('abort', () => { aborted = true; resolve({}); }); }),
|
||||||
|
}, { thermalMax: 999, log: { error() {} }, isAiJob: (t) => AI_JOBS.has(t) });
|
||||||
|
s.app.worker = w;
|
||||||
|
try {
|
||||||
|
await enqueue(s.db, { userId: u.id, projectId: p, type: 'analyze' });
|
||||||
|
const tick = w.tick();
|
||||||
|
for (let i = 0; i < 50 && !w.currentJob; i++) await new Promise((r) => setTimeout(r, 20));
|
||||||
|
assert.equal((await u.post('/link/unlink', {})).status, 200);
|
||||||
|
await tick;
|
||||||
|
assert.equal(aborted, true);
|
||||||
|
assert.equal((await s.db.prepare('SELECT status FROM jobs WHERE user_id = ?').get(u.id)).status, 'cancelled');
|
||||||
|
} finally { delete s.app.worker; await w.stop(); }
|
||||||
|
});
|
||||||
|
|
||||||
|
test('suppression du compte : liaison et trace de consentement effacées', async () => {
|
||||||
|
const u = await s.newUser({ admin: false });
|
||||||
|
s.app.validateToken = async () => {};
|
||||||
|
try { await u.post('/link/subscription', { token: TOKEN, accept: true }); } finally { delete s.app.validateToken; }
|
||||||
|
assert.ok(await getSetting(s.db, u.id, 'claude_cli_consent_json'));
|
||||||
|
const r = await u.post('/account/delete', { confirm: u.email });
|
||||||
|
assert.equal(r.status, 303);
|
||||||
|
assert.equal(await row(u.id), undefined);
|
||||||
|
assert.equal(await getSetting(s.db, u.id, 'claude_cli_consent_json'), null);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('rien d\'un secret dans les journaux du serveur sur toute la durée de ces tests', () => {
|
||||||
|
for (const secret of [KEY_A, KEY_B, TOKEN]) assert.ok(!logs.some((l) => l.includes(secret)), secret.slice(0, 12));
|
||||||
|
});
|
||||||
|
|
||||||
|
test('la température du serveur n\'est pas exposée aux comptes non admin', async () => {
|
||||||
|
const u = await s.newUser({ admin: false });
|
||||||
|
await u.post('/link/api-key', { apiKey: KEY_A });
|
||||||
|
assert.equal((await (await u.get('/api/system')).json()).temp, null);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('serveur complet (worker démarré par createApp) : job d\'un compte relié traité, job d\'un compte non relié refusé', async () => {
|
||||||
|
const full = await startApp({ worker: true, cfg: { claudeBin: makeClaudeBin(binDir, { name: 'claude-full' }) } });
|
||||||
|
try {
|
||||||
|
const mk = async (owner, url) => Number((await full.db.prepare('INSERT INTO projects(user_id, name, git_url, profile_json, target_json, created_at) VALUES(?, ?, ?, ?, ?, ?)')
|
||||||
|
.run(owner.id, 'P', url, JSON.stringify({ resume: 'x', proposition_valeur: 'y' }), JSON.stringify({ description: 'd', secteurs: ['s'] }), now())).lastInsertRowid);
|
||||||
|
const linked = await full.newUser({ admin: true });
|
||||||
|
const bare = await full.newUser({ admin: false });
|
||||||
|
const pl = await mk(linked, 'https://git.test/a.git');
|
||||||
|
const pb = await mk(bare, 'https://git.test/u.git');
|
||||||
|
const jl = (await enqueue(full.db, { userId: linked.id, projectId: pl, type: 'template' })).id;
|
||||||
|
const jb = Number((await full.db.prepare("INSERT INTO jobs(user_id, project_id, type, status, created_at) VALUES(?, ?, 'template', 'queued', ?)").run(bare.id, pb, now())).lastInsertRowid);
|
||||||
|
const status = async (id) => full.db.prepare('SELECT status, error FROM jobs WHERE id = ?').get(id);
|
||||||
|
for (let i = 0; i < 100 && ((await status(jl)).status === 'queued' || (await status(jb)).status === 'queued'); i++) await new Promise((r) => setTimeout(r, 100));
|
||||||
|
assert.equal((await status(jl)).status, 'done', (await status(jl)).error);
|
||||||
|
assert.deepEqual({ ...(await status(jb)) }, { status: 'error', error: LINK_REQUIRED_MESSAGE });
|
||||||
|
assert.equal((await full.db.prepare('SELECT COUNT(*) n FROM templates WHERE project_id = ?').get(pb)).n, 0);
|
||||||
|
} finally { await full.close(); }
|
||||||
|
});
|
||||||
380
test/claude-run.test.js
Normal file
380
test/claude-run.test.js
Normal file
|
|
@ -0,0 +1,380 @@
|
||||||
|
import { test, before, after } from 'node:test';
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import { execFileSync } from 'node:child_process';
|
||||||
|
import { mkdtempSync, mkdirSync, rmSync, readFileSync, writeFileSync } from 'node:fs';
|
||||||
|
import { tmpdir } from 'node:os';
|
||||||
|
import { join, resolve } from 'node:path';
|
||||||
|
import { now, getSetting, setSetting } from '../src/db.js';
|
||||||
|
import { encrypt } from '../src/crypto.js';
|
||||||
|
import { enqueue, Worker, latestJobs } from '../src/services/jobs.js';
|
||||||
|
import { quotaState, budgetState, AI_JOBS, isQuotaSensitive } from '../src/services/budget.js';
|
||||||
|
import { makeClaude, makeHandlers } from '../src/handlers.js';
|
||||||
|
import { extractJson } from '../src/services/claude.js';
|
||||||
|
import { buildBwrapArgs, buildChildEnv, prepareLaunch, isInside, SANDBOX_HOME } from '../src/services/sandbox.js';
|
||||||
|
import { validateGitUrl, syncRepo, gitEnv, cloneArgs, fetchArgs, GIT_HARDENING, dirSize } from '../src/services/git.js';
|
||||||
|
import { loadConfig } from '../src/config.js';
|
||||||
|
import { userRepoRoot } from '../src/users.js';
|
||||||
|
import { startApp } from './helpers/server.js';
|
||||||
|
import { makeClaudeBin } from './helpers/claude-bin.js';
|
||||||
|
|
||||||
|
// Exécution isolée : le secret vient toujours du user_id du job, environnement du processus enfant assaini,
|
||||||
|
// argv bubblewrap, clones git durcis, quota et budget par utilisateur.
|
||||||
|
// Limite connue : bwrap n'est pas exécutable sur ce poste (Windows) ; sa ligne de commande est testée, pas son effet.
|
||||||
|
let s, tmp;
|
||||||
|
const KEY_A = `sk-ant-api03-${'A'.repeat(40)}ZZ12`;
|
||||||
|
const KEY_B = `sk-ant-api03-${'B'.repeat(40)}QQ34`;
|
||||||
|
const TOK_A = `sk-ant-oat01-HOT${'a'.repeat(40)}`;
|
||||||
|
const TOK_B = `sk-ant-oat01-${'b'.repeat(40)}`;
|
||||||
|
|
||||||
|
const apiKeyLink = (key) => ({ v: 1, mode: 'api_key', valid: true, last4: key.slice(-4), secret_enc: encrypt(s.app.cfg.secretKey, key) });
|
||||||
|
const tokenLink = (tok) => ({ v: 1, mode: 'subscription_token', valid: true, secret_enc: encrypt(s.app.cfg.secretKey, tok) });
|
||||||
|
const project = async (u, extra = {}) => Number((await s.db.prepare(`INSERT INTO projects(user_id, name, git_url, profile_json, target_json, target_validated, created_at)
|
||||||
|
VALUES(?, 'P', ?, ?, ?, 1, ?)`).run(u.id, `https://git.test/u${u.id}/p${Math.random()}.git`, JSON.stringify({ resume: 'x', proposition_valeur: 'y' }),
|
||||||
|
JSON.stringify({ description: 'd', secteurs: ['s'] }), now())).lastInsertRowid);
|
||||||
|
const ctxOf = (job) => ({ job, params: {}, signal: new AbortController().signal, progress: async () => {}, cancelled: async () => false, usage: { costUsd: 0, tokensIn: 0, tokensOut: 0 } });
|
||||||
|
|
||||||
|
before(async () => {
|
||||||
|
tmp = mkdtempSync(join(tmpdir(), 'aitools-run-'));
|
||||||
|
s = await startApp({ cfg: { claudeBin: resolve('test/fixtures/fake-claude.js') } });
|
||||||
|
// Pas de vrai clone : le dossier est simplement créé (et vérifié par le bac à sable via allowedRoot)
|
||||||
|
s.app.syncRepo = async (url, dir) => { mkdirSync(dir, { recursive: true }); return 'deadbeef'; };
|
||||||
|
});
|
||||||
|
after(async () => { await s.close(); rmSync(tmp, { recursive: true, force: true }); });
|
||||||
|
|
||||||
|
// ---------- Le secret vient du user_id du job ----------
|
||||||
|
|
||||||
|
test('un utilisateur ne lance jamais un job avec le secret d\'un autre (secret relu depuis le user_id du job)', async () => {
|
||||||
|
const log = join(tmp, 'keys.log');
|
||||||
|
s.app.cfg.claudeBin = makeClaudeBin(tmp, { logVars: ['ANTHROPIC_API_KEY'], logFile: log });
|
||||||
|
const a = await s.newUser({ admin: false, link: apiKeyLink(KEY_A) });
|
||||||
|
const b = await s.newUser({ admin: false, link: apiKeyLink(KEY_B) });
|
||||||
|
const pa = await project(a), pb = await project(b);
|
||||||
|
const w = new Worker(s.db, makeHandlers(s.app), { thermalMax: 999, log: { error() {} } });
|
||||||
|
await enqueue(s.db, { userId: a.id, projectId: pa, type: 'template' });
|
||||||
|
await enqueue(s.db, { userId: b.id, projectId: pb, type: 'template' });
|
||||||
|
while (await w.tick()) { /* vide la file */ }
|
||||||
|
assert.deepEqual(readFileSync(log, 'utf8').trim().split('\n'), [KEY_A, KEY_B], 'chaque job a tourné avec la clé de SON utilisateur');
|
||||||
|
assert.equal((await latestJobs(s.db, pa)).template.status, 'done');
|
||||||
|
assert.equal((await latestJobs(s.db, pb)).template.status, 'done');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('id de projet ou de job manipulé : le job d\'A ne touche jamais au projet ni au secret de B', async () => {
|
||||||
|
s.app.cfg.claudeBin = '/inexistant/claude'; // si quoi que ce soit se lançait, l'erreur serait un ENOENT
|
||||||
|
const a = await s.newUser({ admin: false, link: apiKeyLink(KEY_A) });
|
||||||
|
const b = await s.newUser({ admin: false, link: apiKeyLink(KEY_B) });
|
||||||
|
const pb = await project(b);
|
||||||
|
const handlers = makeHandlers(s.app);
|
||||||
|
for (const type of ['analyze', 'template', 'followup_template', 'prospect', 'evolution']) {
|
||||||
|
await assert.rejects(handlers[type](ctxOf({ id: 1, user_id: a.id, project_id: pb, type })), { status: 404 }, type);
|
||||||
|
}
|
||||||
|
// Même chose via la file : un job inséré à la main avec le projet de B échoue sans exécution
|
||||||
|
await s.db.prepare("INSERT INTO jobs(user_id, project_id, type, status, created_at) VALUES(?, ?, 'template', 'queued', ?)").run(a.id, pb, now());
|
||||||
|
const w = new Worker(s.db, makeHandlers(s.app), { thermalMax: 999, log: { error() {} } });
|
||||||
|
while (await w.tick()) { /* vide la file */ }
|
||||||
|
const row = await s.db.prepare("SELECT status, error FROM jobs WHERE user_id = ? AND project_id = ?").get(a.id, pb);
|
||||||
|
assert.equal(row.status, 'error');
|
||||||
|
assert.match(row.error, /Projet introuvable/);
|
||||||
|
assert.equal((await s.db.prepare('SELECT COUNT(*) n FROM templates WHERE project_id = ?').get(pb)).n, 0);
|
||||||
|
await assert.rejects(enqueue(s.db, { userId: a.id, projectId: pb, type: 'template' }), { status: 404 });
|
||||||
|
// Le wrapper n'accepte pas non plus un répertoire hors du dossier de l'utilisateur
|
||||||
|
s.app.cfg.claudeBin = resolve('test/fixtures/fake-claude.js');
|
||||||
|
const claude = makeClaude(s.app);
|
||||||
|
await assert.rejects(claude(a.id, { prompt: 'x', cwd: join(userRepoRoot(s.app.cfg, b.id), String(pb)) }), /hors du dossier/);
|
||||||
|
await assert.rejects(claude(a.id, { prompt: 'x', cwd: s.app.cfg.dataDir }), /hors du dossier/);
|
||||||
|
});
|
||||||
|
|
||||||
|
// ---------- Environnement du processus enfant ----------
|
||||||
|
|
||||||
|
test('environnement enfant : liste blanche stricte, secret de l\'utilisateur concerné uniquement', () => {
|
||||||
|
const parent = {
|
||||||
|
PATH: '/usr/bin', LANG: 'fr_FR.UTF-8', SECRET_KEY: 'k'.repeat(64), DB_PASSWORD: 'dbpass', DB_HOST: 'h', GOOGLE_CLIENT_SECRET: 'g', APPLE_PRIVATE_KEY: 'p',
|
||||||
|
ANTHROPIC_API_KEY: 'sk-ant-du-serveur', CLAUDE_CODE_OAUTH_TOKEN: 'jeton-du-serveur', HOME: '/home/svc', NODE_ENV: 'production', ADMIN_EMAILS: 'a@b.fr',
|
||||||
|
};
|
||||||
|
const sb = { enabled: true, production: true, bwrapBin: 'bwrap', roBinds: [], serverHome: '/home/svc' };
|
||||||
|
const l = prepareLaunch({ bin: 'claude', args: ['-p', 'x'], sandbox: sb, secretEnv: { ANTHROPIC_API_KEY: KEY_A } },
|
||||||
|
{ parentEnv: parent, hasBwrap: () => true, resolveBin: () => '/usr/local/bin/claude' });
|
||||||
|
const allowed = new Set(['PATH', 'LANG', 'HOME', 'ANTHROPIC_API_KEY', ...(process.platform === 'win32' ? ['SystemRoot', 'PATHEXT', 'TEMP', 'TMP', 'COMSPEC'] : [])]);
|
||||||
|
for (const k of Object.keys(l.env)) assert.ok(allowed.has(k), `variable inattendue : ${k}`);
|
||||||
|
assert.equal(l.env.ANTHROPIC_API_KEY, KEY_A, 'la clé de l\'utilisateur, pas celle du serveur');
|
||||||
|
assert.equal(l.env.HOME, SANDBOX_HOME, 'répertoire personnel jetable du bac à sable');
|
||||||
|
assert.equal(l.env.PATH, '/usr/bin');
|
||||||
|
assert.ok(!JSON.stringify(l.env).match(/dbpass|SECRET_KEY|serveur|a@b\.fr/));
|
||||||
|
// Sans secret (mode serveur) : aucune des variables d'identification, même héritées du serveur
|
||||||
|
const none = buildChildEnv(parent, { home: '/h' });
|
||||||
|
assert.equal(none.ANTHROPIC_API_KEY, undefined);
|
||||||
|
assert.equal(none.CLAUDE_CODE_OAUTH_TOKEN, undefined);
|
||||||
|
// Un nom de variable arbitraire n'est pas accepté comme « secret »
|
||||||
|
assert.throws(() => buildChildEnv(parent, { home: '/h', secretEnv: { SECRET_KEY: 'x' } }), /non autorisée/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('environnement enfant (processus réel) : aucun secret du serveur, la clé de l\'utilisateur seulement', async () => {
|
||||||
|
const polluted = { SECRET_KEY: 'SERVEUR-SECRET-KEY', DB_PASSWORD: 'SERVEUR-DB', GOOGLE_CLIENT_SECRET: 'SERVEUR-GOOGLE', APPLE_PRIVATE_KEY: 'SERVEUR-APPLE',
|
||||||
|
ANTHROPIC_API_KEY: 'SERVEUR-ANTHROPIC', CLAUDE_CODE_OAUTH_TOKEN: 'SERVEUR-OAUTH' };
|
||||||
|
const keep = {};
|
||||||
|
for (const k of Object.keys(polluted)) { keep[k] = process.env[k]; process.env[k] = polluted[k]; }
|
||||||
|
s.app.cfg.claudeBin = resolve('test/fixtures/fake-claude.js');
|
||||||
|
try {
|
||||||
|
const a = await s.newUser({ admin: false, link: apiKeyLink(KEY_A) });
|
||||||
|
const r = await makeClaude(s.app)(a.id, { prompt: 'ENVDUMP', maxTurns: 1, tools: [] });
|
||||||
|
const { env } = extractJson(r.text);
|
||||||
|
// Présente dans l'environnement du CLI, mais masquée dans ce qu'il renvoie (le masquage est lui aussi vérifié)
|
||||||
|
assert.equal(env.ANTHROPIC_API_KEY, '***');
|
||||||
|
for (const k of Object.keys(polluted)) if (k !== 'ANTHROPIC_API_KEY') assert.equal(env[k], undefined, k);
|
||||||
|
assert.ok(!JSON.stringify(env).includes('SERVEUR-'));
|
||||||
|
// HOME jetable : pas celui du serveur
|
||||||
|
assert.notEqual(env.HOME, process.env.HOME);
|
||||||
|
// L'abonnement : seul CLAUDE_CODE_OAUTH_TOKEN, jamais ANTHROPIC_API_KEY
|
||||||
|
const t = await s.newUser({ admin: false, link: tokenLink(TOK_B) });
|
||||||
|
const r2 = await makeClaude(s.app)(t.id, { prompt: 'ENVDUMP', maxTurns: 1, tools: [] });
|
||||||
|
const env2 = extractJson(r2.text).env;
|
||||||
|
assert.equal(env2.CLAUDE_CODE_OAUTH_TOKEN, '***');
|
||||||
|
assert.equal(env2.ANTHROPIC_API_KEY, undefined);
|
||||||
|
} finally { for (const k of Object.keys(polluted)) { if (keep[k] === undefined) delete process.env[k]; else process.env[k] = keep[k]; } }
|
||||||
|
});
|
||||||
|
|
||||||
|
test('le secret n\'apparaît ni dans les erreurs du CLI, ni dans le job en erreur', async () => {
|
||||||
|
s.app.cfg.claudeBin = resolve('test/fixtures/fake-claude.js');
|
||||||
|
const a = await s.newUser({ admin: false, link: apiKeyLink(KEY_A) });
|
||||||
|
let err;
|
||||||
|
try { await makeClaude(s.app)(a.id, { prompt: 'LEAK' }); } catch (e) { err = e; }
|
||||||
|
assert.ok(err, 'le CLI a échoué');
|
||||||
|
assert.match(err.message, /\*\*\*/);
|
||||||
|
assert.ok(!err.message.includes(KEY_A));
|
||||||
|
const p = await project(a);
|
||||||
|
const w = new Worker(s.db, { template: async () => { await makeClaude(s.app)(a.id, { prompt: 'LEAK' }); } }, { thermalMax: 999, log: { error() {} } });
|
||||||
|
await enqueue(s.db, { userId: a.id, projectId: p, type: 'template' });
|
||||||
|
while (await w.tick()) { /* vide la file */ }
|
||||||
|
const row = await s.db.prepare('SELECT status, error FROM jobs WHERE project_id = ?').get(p);
|
||||||
|
assert.equal(row.status, 'error');
|
||||||
|
assert.ok(!row.error.includes(KEY_A));
|
||||||
|
});
|
||||||
|
|
||||||
|
// ---------- bubblewrap ----------
|
||||||
|
|
||||||
|
const pairIdx = (args, flag, ...vals) => args.findIndex((x, i) => x === flag && vals.every((v, j) => args[i + 1 + j] === v));
|
||||||
|
|
||||||
|
test('bwrap : ligne de commande — racine en lecture seule, tmpfs, un seul dossier utilisateur, espaces de noms', () => {
|
||||||
|
const work = resolve('/srv/aitools/repos/7/12');
|
||||||
|
const a = buildBwrapArgs({ workDir: work, command: ['/opt/claude/claude', '-p', 'x'], roBinds: ['/opt/claude'] });
|
||||||
|
for (const f of ['--die-with-parent', '--unshare-pid', '--unshare-ipc', '--unshare-uts', '--new-session']) assert.ok(a.includes(f), f);
|
||||||
|
assert.ok(!a.includes('--unshare-net') && !a.includes('--unshare-all'), 'le réseau est conservé');
|
||||||
|
assert.ok(pairIdx(a, '--tmpfs', '/tmp') >= 0, '/tmp vide');
|
||||||
|
assert.ok(pairIdx(a, '--tmpfs', SANDBOX_HOME) >= 0, 'HOME vide');
|
||||||
|
assert.ok(pairIdx(a, '--ro-bind', '/usr', '/usr') >= 0);
|
||||||
|
assert.ok(pairIdx(a, '--ro-bind', work, work) >= 0, 'clone de l\'utilisateur, en lecture seule');
|
||||||
|
assert.ok(pairIdx(a, '--ro-bind', '/opt/claude', '/opt/claude') >= 0);
|
||||||
|
assert.ok(pairIdx(a, '--chdir', work) >= 0);
|
||||||
|
assert.deepEqual(a.slice(a.indexOf('--') + 1), ['/opt/claude/claude', '-p', 'x']);
|
||||||
|
// Rien d'autre n'est monté : ni la racine entière, ni /home, /root, /var, ni la config Claude du serveur
|
||||||
|
const mounts = a.flatMap((x, i) => (['--bind', '--ro-bind', '--bind-try', '--ro-bind-try'].includes(x) ? [a[i + 1]] : []));
|
||||||
|
assert.deepEqual(mounts.sort(), ['/bin', '/etc', '/lib', '/lib64', '/opt/claude', '/run/systemd/resolve', '/sbin', '/usr', work].sort());
|
||||||
|
assert.ok(!a.includes('--bind') && !a.includes('--bind-try'), 'aucun montage en écriture hors mode serveur');
|
||||||
|
assert.ok(!a.join(' ').includes('.claude'));
|
||||||
|
assert.ok(!mounts.includes('/'));
|
||||||
|
// Sans projet : seul le HOME vide
|
||||||
|
const bare = buildBwrapArgs({ command: ['claude'] });
|
||||||
|
assert.ok(pairIdx(bare, '--chdir', SANDBOX_HOME) >= 0);
|
||||||
|
assert.throws(() => buildBwrapArgs({ workDir: 'relatif', command: ['x'] }), /absolu/);
|
||||||
|
assert.throws(() => buildBwrapArgs({ command: [] }), /vide/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('bwrap : la configuration du CLI du serveur n\'est montée que pour le mode serveur', () => {
|
||||||
|
const sb = { enabled: true, production: true, bwrapBin: 'bwrap', roBinds: [], serverHome: '/home/svc' };
|
||||||
|
const deps = { parentEnv: { PATH: '/usr/bin' }, hasBwrap: () => true, resolveBin: () => '/usr/bin/claude' };
|
||||||
|
const work = resolve('/srv/aitools/repos/1/1');
|
||||||
|
const user = prepareLaunch({ bin: 'claude', args: ['-p', 'x'], cwd: work, allowedRoot: resolve('/srv/aitools/repos/1'), sandbox: sb, secretEnv: { ANTHROPIC_API_KEY: KEY_A } }, deps);
|
||||||
|
assert.ok(!user.args.join(' ').includes('.claude'));
|
||||||
|
assert.ok(!user.args.some((x) => x === '/home/svc' || x.startsWith('/home/svc')));
|
||||||
|
const server = prepareLaunch({ bin: 'claude', args: ['-p', 'x'], cwd: work, allowedRoot: resolve('/srv/aitools/repos/1'), sandbox: sb, serverConfig: true }, deps);
|
||||||
|
assert.ok(pairIdx(server.args, '--bind-try', join('/home/svc', '.claude'), `${SANDBOX_HOME}/.claude`) >= 0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('bwrap : prepareLaunch — le secret n\'est jamais dans argv (visible dans ps), seulement dans l\'environnement', () => {
|
||||||
|
const sb = { enabled: true, production: true, bwrapBin: 'bwrap', roBinds: [], serverHome: '/home/svc' };
|
||||||
|
const l = prepareLaunch({ bin: 'claude', args: ['-p', 'bonjour'], cwd: resolve('/srv/d/repos/3/9'), allowedRoot: resolve('/srv/d/repos/3'), sandbox: sb,
|
||||||
|
secretEnv: { CLAUDE_CODE_OAUTH_TOKEN: TOK_A } }, { parentEnv: { PATH: '/usr/bin' }, hasBwrap: () => true, resolveBin: () => '/usr/local/bin/claude-x' });
|
||||||
|
assert.equal(l.command, 'nice');
|
||||||
|
assert.deepEqual(l.args.slice(0, 4), ['-n', '10', 'bwrap', '--die-with-parent']);
|
||||||
|
assert.ok(!l.args.join(' ').includes(TOK_A));
|
||||||
|
assert.equal(l.env.CLAUDE_CODE_OAUTH_TOKEN, TOK_A);
|
||||||
|
assert.ok(l.args.includes('/usr/local/bin/claude-x'), 'chemin réel de l\'exécutable (lien symbolique résolu)');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('bwrap : répertoire hors du dossier de l\'utilisateur, bwrap absent, production sans bac à sable — exécution refusée', () => {
|
||||||
|
const base = { bin: 'claude', args: ['-p', 'x'] };
|
||||||
|
const ok = { enabled: true, production: true, bwrapBin: 'bwrap', roBinds: [], serverHome: '/h' };
|
||||||
|
const deps = { parentEnv: { PATH: '/usr/bin' }, hasBwrap: () => true, resolveBin: () => '/usr/bin/claude' };
|
||||||
|
const root = resolve('/srv/d/repos/3');
|
||||||
|
assert.throws(() => prepareLaunch({ ...base, sandbox: ok, cwd: resolve('/srv/d/repos/4/1'), allowedRoot: root }, deps), /hors du dossier/);
|
||||||
|
assert.throws(() => prepareLaunch({ ...base, sandbox: ok, cwd: resolve('/srv/d/repos/3/../4/1'), allowedRoot: root }, deps), /hors du dossier/);
|
||||||
|
assert.throws(() => prepareLaunch({ ...base, sandbox: ok, cwd: resolve('/srv/d/repos/33'), allowedRoot: root }, deps), /hors du dossier/, 'préfixe de nom ≠ sous-dossier');
|
||||||
|
assert.throws(() => prepareLaunch({ ...base, sandbox: ok }, { ...deps, hasBwrap: () => false }), /bwrap/);
|
||||||
|
assert.throws(() => prepareLaunch({ ...base, sandbox: { ...ok, enabled: false } }, deps), /obligatoire en production/);
|
||||||
|
assert.throws(() => prepareLaunch({ ...base, sandbox: ok }, { ...deps, resolveBin: () => null }), /introuvable/);
|
||||||
|
assert.throws(() => prepareLaunch({ ...base }, deps), /bac à sable/);
|
||||||
|
// Développement + bwrap activé mais absent : on refuse plutôt que d'exécuter sans isolation
|
||||||
|
assert.throws(() => prepareLaunch({ ...base, sandbox: { ...ok, production: false } }, { ...deps, hasBwrap: () => false }), /bwrap/);
|
||||||
|
// Développement avec SANDBOX=off : exécution directe, HOME jetable nettoyé
|
||||||
|
const dev = prepareLaunch({ ...base, sandbox: { enabled: false, production: false, serverHome: '/h' } }, deps);
|
||||||
|
assert.equal(dev.sandboxed, false);
|
||||||
|
assert.notEqual(dev.env.HOME, '/h');
|
||||||
|
dev.cleanup();
|
||||||
|
assert.ok(isInside(root, join(root, '5')) && !isInside(root, resolve('/srv/d/repos')));
|
||||||
|
});
|
||||||
|
|
||||||
|
test('production : le wrapper refuse de lancer un job sans bwrap (même avec SANDBOX=off)', async () => {
|
||||||
|
const a = await s.newUser({ admin: false, link: apiKeyLink(KEY_A) });
|
||||||
|
const real = s.app.cfg.sandbox;
|
||||||
|
try {
|
||||||
|
s.app.cfg.sandbox = { enabled: true, production: true, bwrapBin: join(tmp, 'bwrap-inexistant'), roBinds: [], serverHome: tmp };
|
||||||
|
await assert.rejects(makeClaude(s.app)(a.id, { prompt: 'x' }), /bwrap/);
|
||||||
|
s.app.cfg.sandbox = { enabled: false, production: true, bwrapBin: 'bwrap', roBinds: [], serverHome: tmp };
|
||||||
|
await assert.rejects(makeClaude(s.app)(a.id, { prompt: 'x' }), /obligatoire en production/);
|
||||||
|
} finally { s.app.cfg.sandbox = real; }
|
||||||
|
});
|
||||||
|
|
||||||
|
test('configuration : NODE_ENV=production impose le bac à sable, SANDBOX=off seulement en développement, drapeau du mode abonnement', () => {
|
||||||
|
const keep = { ...process.env };
|
||||||
|
Object.assign(process.env, { SECRET_KEY: 'a'.repeat(64), APP_URL: 'https://x.test', GOOGLE_CLIENT_ID: 'i', GOOGLE_CLIENT_SECRET: 's', DB_HOST: 'h', DB_USER: 'u', DB_PASSWORD: 'p', DB_NAME: 'n' });
|
||||||
|
try {
|
||||||
|
const cfg = (env) => { for (const k of ['NODE_ENV', 'SANDBOX', 'CLAUDE_CLI_MODE_ENABLED']) delete process.env[k]; Object.assign(process.env, env); return loadConfig(); };
|
||||||
|
assert.equal(cfg({}).cliModeEnabled, true, 'activé par défaut');
|
||||||
|
for (const v of ['false', 'FALSE', '0', 'off', 'no']) assert.equal(cfg({ CLAUDE_CLI_MODE_ENABLED: v }).cliModeEnabled, false, v);
|
||||||
|
assert.equal(cfg({ CLAUDE_CLI_MODE_ENABLED: 'true' }).cliModeEnabled, true);
|
||||||
|
assert.deepEqual([cfg({}).sandbox.enabled, cfg({}).sandbox.production], [true, false]);
|
||||||
|
assert.equal(cfg({ SANDBOX: 'off' }).sandbox.enabled, false, 'développement : désactivable');
|
||||||
|
const prod = cfg({ NODE_ENV: 'production', SANDBOX: 'off' }).sandbox;
|
||||||
|
assert.deepEqual([prod.enabled, prod.production, prod.offIgnored], [true, true, true]);
|
||||||
|
assert.deepEqual(cfg({ SANDBOX_RO_BINDS: '/opt/node, /opt/claude' }).sandbox.roBinds, ['/opt/node', '/opt/claude']);
|
||||||
|
} finally { for (const k of Object.keys(process.env)) if (!(k in keep)) delete process.env[k]; Object.assign(process.env, keep); }
|
||||||
|
});
|
||||||
|
|
||||||
|
// ---------- Clones git ----------
|
||||||
|
|
||||||
|
test('git : https uniquement — file://, ext::, ssh, git://, http:// refusés avant tout lancement', async () => {
|
||||||
|
const dir = join(tmp, 'clone-refuse');
|
||||||
|
for (const url of ['file:///etc/passwd', 'ext::sh -c touch% /tmp/pwn', 'ssh://git@h.test/a/b.git', 'git://h.test/a/b.git', 'http://h.test/a/b.git', 'git@h.test:a/b.git', '/srv/local/repo', 'https://u:p@h.test/a/b.git']) {
|
||||||
|
assert.throws(() => validateGitUrl(url), /URL Git invalide|https|identifiants/, url);
|
||||||
|
await assert.rejects(syncRepo(url, dir, null), /Git :/, url);
|
||||||
|
}
|
||||||
|
assert.equal(validateGitUrl('https://git.tony-averty.dev/Tony/A.git', 'git.tony-averty.dev'), 'https://git.tony-averty.dev/Tony/A.git');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('git : environnement assaini, GIT_ALLOW_PROTOCOL=https, pas de hooks ni de sous-modules, token hors argv', () => {
|
||||||
|
const keep = process.env.SECRET_KEY;
|
||||||
|
process.env.SECRET_KEY = 'SERVEUR-SECRET';
|
||||||
|
try {
|
||||||
|
const env = gitEnv('tok-forgejo');
|
||||||
|
assert.equal(env.GIT_ALLOW_PROTOCOL, 'https');
|
||||||
|
assert.equal(env.GIT_TERMINAL_PROMPT, '0');
|
||||||
|
assert.equal(env.GIT_CONFIG_NOSYSTEM, '1');
|
||||||
|
assert.equal(env.GIT_CONFIG_VALUE_0, 'Authorization: token tok-forgejo');
|
||||||
|
assert.equal(env.SECRET_KEY, undefined);
|
||||||
|
assert.ok(!Object.keys(env).some((k) => /^(DB_|GOOGLE_|APPLE_)/.test(k)));
|
||||||
|
assert.equal(gitEnv(null).GIT_CONFIG_COUNT, undefined);
|
||||||
|
} finally { if (keep === undefined) delete process.env.SECRET_KEY; else process.env.SECRET_KEY = keep; }
|
||||||
|
const joined = GIT_HARDENING.join(' ');
|
||||||
|
assert.match(joined, /protocol\.allow=never/);
|
||||||
|
assert.match(joined, /protocol\.https\.allow=always/);
|
||||||
|
assert.match(joined, /core\.hooksPath=/);
|
||||||
|
assert.match(joined, /submodule\.recurse=false/);
|
||||||
|
for (const args of [cloneArgs('https://h.test/a/b.git', '/d'), fetchArgs()]) {
|
||||||
|
assert.ok(args.includes('--no-recurse-submodules'));
|
||||||
|
assert.ok(args.includes('--depth'));
|
||||||
|
assert.ok(!args.join(' ').includes('tok-forgejo'));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test('git réel : avec ce durcissement, un dépôt local (file) ne peut pas être cloné', () => {
|
||||||
|
const src = join(tmp, 'src-repo');
|
||||||
|
execFileSync('git', ['init', '-q', '-b', 'main', src]);
|
||||||
|
writeFileSync(join(src, 'a.txt'), 'x');
|
||||||
|
execFileSync('git', ['-C', src, 'add', '.']);
|
||||||
|
execFileSync('git', ['-C', src, '-c', 'user.name=t', '-c', 'user.email=t@t', 'commit', '-qm', 'c']);
|
||||||
|
assert.throws(() => execFileSync('git', cloneArgs(`file://${src}`, join(tmp, 'dest')), { env: gitEnv(null), stdio: 'pipe' }), (e) => /not allowed|protocol/i.test(String(e.stderr)));
|
||||||
|
assert.throws(() => execFileSync('git', cloneArgs(src, join(tmp, 'dest2')), { env: gitEnv(null), stdio: 'pipe' }), (e) => /not allowed|protocol/i.test(String(e.stderr)));
|
||||||
|
});
|
||||||
|
|
||||||
|
test('git : taille d\'un dossier mesurée avec coupe-circuit', () => {
|
||||||
|
const d = join(tmp, 'sz');
|
||||||
|
mkdirSync(join(d, 'sub'), { recursive: true });
|
||||||
|
writeFileSync(join(d, 'a'), Buffer.alloc(1000));
|
||||||
|
writeFileSync(join(d, 'sub', 'b'), Buffer.alloc(2000));
|
||||||
|
assert.equal(dirSize(d), 3000);
|
||||||
|
assert.ok(dirSize(d, 500) > 500, 'dépasse la limite : mesure interrompue');
|
||||||
|
});
|
||||||
|
|
||||||
|
// ---------- Quota, budget, notifications par utilisateur ----------
|
||||||
|
|
||||||
|
test('quota : chaque utilisateur voit le sien, celui du CLI de A n\'apparaît jamais chez B', async () => {
|
||||||
|
s.app.cfg.claudeBin = resolve('test/fixtures/fake-claude.js');
|
||||||
|
const a = await s.newUser({ admin: false, link: tokenLink(TOK_A) }); // jeton « HOT » : le faux CLI remonte 90 % sur la session
|
||||||
|
const b = await s.newUser({ admin: false, link: tokenLink(TOK_B) }); // 33 %
|
||||||
|
const pa = await project(a), pb = await project(b);
|
||||||
|
const w = new Worker(s.db, makeHandlers(s.app), {
|
||||||
|
thermalMax: 999, log: { error() {} }, quota: (uid) => quotaState(s.db, uid), isQuotaSensitive, isAiJob: (t) => AI_JOBS.has(t), budget: (uid) => budgetState(s.db, uid),
|
||||||
|
});
|
||||||
|
await enqueue(s.db, { userId: a.id, projectId: pa, type: 'template' });
|
||||||
|
await enqueue(s.db, { userId: b.id, projectId: pb, type: 'template' });
|
||||||
|
while (await w.tick()) { /* vide la file */ }
|
||||||
|
|
||||||
|
const rl = async (u) => (await (await u.get('/api/system')).json()).claudeRateLimit;
|
||||||
|
assert.equal((await rl(a)).fiveHour.utilization, 0.9);
|
||||||
|
assert.equal((await rl(b)).fiveHour.utilization, 0.33);
|
||||||
|
assert.equal((await quotaState(s.db, a.id)).blocked, true);
|
||||||
|
assert.equal((await quotaState(s.db, b.id)).blocked, false);
|
||||||
|
|
||||||
|
// A est serré : son analyse attend ; celle de B part, et le template de A (non sensible) aussi
|
||||||
|
await s.db.prepare("UPDATE jobs SET status = 'cancelled' WHERE status = 'queued'").run();
|
||||||
|
const done = [];
|
||||||
|
const w2 = new Worker(s.db, { analyze: async (ctx) => { done.push(ctx.job.user_id); return {}; } }, {
|
||||||
|
thermalMax: 999, log: { error() {} }, quota: (uid) => quotaState(s.db, uid), isQuotaSensitive, isAiJob: (t) => AI_JOBS.has(t),
|
||||||
|
});
|
||||||
|
await enqueue(s.db, { userId: a.id, projectId: pa, type: 'analyze' });
|
||||||
|
await enqueue(s.db, { userId: b.id, projectId: pb, type: 'analyze' });
|
||||||
|
while (await w2.tick()) { /* vide la file */ }
|
||||||
|
assert.deepEqual(done, [b.id], 'seul le job de B a tourné');
|
||||||
|
assert.equal((await s.db.prepare("SELECT status FROM jobs WHERE user_id = ? AND type = 'analyze'").get(a.id)).status, 'queued');
|
||||||
|
assert.match(JSON.parse((await s.db.prepare("SELECT progress_json FROM jobs WHERE user_id = ? AND type = 'analyze'").get(a.id)).progress_json).message, /En attente/);
|
||||||
|
await w2.idle();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('budget et usage IA : par utilisateur', async () => {
|
||||||
|
const a = await s.newUser({ admin: false, link: apiKeyLink(KEY_A) });
|
||||||
|
const b = await s.newUser({ admin: false, link: apiKeyLink(KEY_B) });
|
||||||
|
await setSetting(s.db, a.id, 'budget_day_usd', '1');
|
||||||
|
await s.db.prepare("INSERT INTO jobs(user_id, type, status, created_at, finished_at, cost_usd) VALUES(?, 'analyze', 'done', ?, ?, 2.5)").run(a.id, now(), now());
|
||||||
|
assert.equal((await budgetState(s.db, a.id)).blocked, true);
|
||||||
|
assert.equal((await budgetState(s.db, b.id)).blocked, false);
|
||||||
|
assert.equal((await (await b.get('/api/system')).json()).usage.day.cost, 0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('mode clé API : pas de barre de quota d\'abonnement, rien n\'est enregistré', async () => {
|
||||||
|
s.app.cfg.claudeBin = resolve('test/fixtures/fake-claude.js');
|
||||||
|
const a = await s.newUser({ admin: false, link: apiKeyLink(KEY_A) });
|
||||||
|
const r = await makeClaude(s.app)(a.id, { prompt: 'bonjour', maxTurns: 1, tools: [] });
|
||||||
|
assert.ok(r.rateLimit, 'le faux CLI remonte bien un quota');
|
||||||
|
assert.equal(await getSetting(s.db, a.id, 'claude_rate_limit_json'), null, 'non enregistré en mode clé API');
|
||||||
|
// Même une valeur résiduelle n'est pas exposée
|
||||||
|
await setSetting(s.db, a.id, 'claude_rate_limit_json', JSON.stringify({ fiveHour: { utilization: 0.99 } }));
|
||||||
|
const sys = await (await a.get('/api/system')).json();
|
||||||
|
assert.equal(sys.claudeRateLimit, null);
|
||||||
|
assert.equal(sys.linkMode, 'api_key');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('alertes de quota : envoyées au webhook de l\'utilisateur concerné seulement', async () => {
|
||||||
|
s.app.cfg.claudeBin = resolve('test/fixtures/fake-claude.js');
|
||||||
|
const sent = [];
|
||||||
|
s.app.fetch = async (url, opts) => { sent.push({ url, body: JSON.parse(opts.body) }); return { ok: true, status: 204 }; };
|
||||||
|
const a = await s.newUser({ admin: false, link: tokenLink(TOK_A) });
|
||||||
|
const b = await s.newUser({ admin: false, link: tokenLink(TOK_A) });
|
||||||
|
const hookA = 'https://discord.com/api/webhooks/123456789012345678/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa';
|
||||||
|
const hookB = 'https://discord.com/api/webhooks/123456789012345678/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb';
|
||||||
|
await setSetting(s.db, a.id, 'discord_webhook_enc', encrypt(s.app.cfg.secretKey, hookA));
|
||||||
|
await setSetting(s.db, b.id, 'discord_webhook_enc', encrypt(s.app.cfg.secretKey, hookB));
|
||||||
|
await makeClaude(s.app)(a.id, { prompt: 'bonjour', maxTurns: 1, tools: [] });
|
||||||
|
assert.equal(sent.length, 1);
|
||||||
|
assert.equal(sent[0].url, hookA);
|
||||||
|
assert.equal(await getSetting(s.db, b.id, 'claude_quota_notified_json'), null, 'B n\'a rien reçu ni mémorisé');
|
||||||
|
delete s.app.fetch;
|
||||||
|
});
|
||||||
|
|
@ -2,9 +2,11 @@ import { test } from 'node:test';
|
||||||
import assert from 'node:assert/strict';
|
import assert from 'node:assert/strict';
|
||||||
import { randomBytes } from 'node:crypto';
|
import { randomBytes } from 'node:crypto';
|
||||||
import { encrypt, decrypt, encryptJson, decryptJson, unsubToken, verifyUnsubToken } from '../src/crypto.js';
|
import { encrypt, decrypt, encryptJson, decryptJson, unsubToken, verifyUnsubToken } from '../src/crypto.js';
|
||||||
import { openDb, getSetting, setSetting, MIGRATIONS } from '../src/db.js';
|
import { getSetting, setSetting, MIGRATIONS } from '../src/db.js';
|
||||||
|
import { testDb } from './helpers/db.js';
|
||||||
import { Router, esc } from '../src/http.js';
|
import { Router, esc } from '../src/http.js';
|
||||||
import { checkIdTokenClaims, checkOrigin } from '../src/auth.js';
|
import { checkIdTokenClaims, checkOrigin } from '../src/auth.js';
|
||||||
|
import { addUser } from './helpers/users.js';
|
||||||
|
|
||||||
const key = randomBytes(32);
|
const key = randomBytes(32);
|
||||||
|
|
||||||
|
|
@ -25,38 +27,14 @@ test('token de désinscription', () => {
|
||||||
assert.ok(!verifyUnsubToken(key, 'foo@bar.fr', 'x'));
|
assert.ok(!verifyUnsubToken(key, 'foo@bar.fr', 'x'));
|
||||||
});
|
});
|
||||||
|
|
||||||
test('migrations et settings', () => {
|
test('migrations et settings', async () => {
|
||||||
const db = openDb(':memory:');
|
const db = await testDb();
|
||||||
assert.equal(db.prepare('PRAGMA user_version').get().user_version, MIGRATIONS.length);
|
const v = await db.prepare('SELECT COUNT(*) n, MAX(version) v FROM schema_migrations').get();
|
||||||
setSetting(db, 'a', '1'); setSetting(db, 'a', '2');
|
assert.deepEqual({ n: v.n, v: v.v }, { n: MIGRATIONS.length, v: MIGRATIONS.length });
|
||||||
assert.equal(getSetting(db, 'a'), '2');
|
const u = await addUser(db);
|
||||||
assert.equal(getSetting(db, 'nope', 'x'), 'x');
|
await setSetting(db, u, 'a', '1'); await setSetting(db, u, 'a', '2');
|
||||||
});
|
assert.equal(await getSetting(db, u, 'a'), '2');
|
||||||
|
assert.equal(await getSetting(db, u, 'nope', 'x'), 'x');
|
||||||
test('migration 2 : les modèles existants deviennent des modèles "initial"', async () => {
|
|
||||||
const { DatabaseSync } = await import('node:sqlite');
|
|
||||||
const { mkdtempSync, rmSync } = await import('node:fs');
|
|
||||||
const { join } = await import('node:path');
|
|
||||||
const { tmpdir } = await import('node:os');
|
|
||||||
const dir = mkdtempSync(join(tmpdir(), 'mig-'));
|
|
||||||
// Base en version 1 avec un modèle déjà validé
|
|
||||||
let raw = new DatabaseSync(join(dir, 'aitools.sqlite'));
|
|
||||||
raw.exec(`CREATE TABLE projects (id INTEGER PRIMARY KEY);
|
|
||||||
CREATE TABLE mail_templates (project_id INTEGER PRIMARY KEY, subject TEXT NOT NULL, body TEXT NOT NULL, status TEXT NOT NULL DEFAULT 'draft', updated_at INTEGER NOT NULL);
|
|
||||||
INSERT INTO projects VALUES (1); INSERT INTO mail_templates VALUES (1, 'Objet', 'Corps', 'validated', 123);
|
|
||||||
PRAGMA user_version = 1;`);
|
|
||||||
raw.close();
|
|
||||||
// On rejoue seulement la migration 2 (les autres tables v1 sont absentes de ce mini-schéma)
|
|
||||||
raw = new DatabaseSync(join(dir, 'aitools.sqlite'));
|
|
||||||
const { MIGRATIONS } = await import('../src/db.js');
|
|
||||||
raw.exec(MIGRATIONS[1]);
|
|
||||||
const t = raw.prepare('SELECT * FROM templates').get();
|
|
||||||
assert.equal(t.kind, 'initial');
|
|
||||||
assert.equal(t.subject, 'Objet');
|
|
||||||
assert.equal(t.status, 'validated');
|
|
||||||
assert.equal(raw.prepare("SELECT COUNT(*) n FROM sqlite_master WHERE name = 'mail_templates'").get().n, 0);
|
|
||||||
raw.close();
|
|
||||||
rmSync(dir, { recursive: true, force: true });
|
|
||||||
});
|
});
|
||||||
|
|
||||||
test('router avec paramètres', () => {
|
test('router avec paramètres', () => {
|
||||||
|
|
@ -71,15 +49,20 @@ test('échappement HTML', () => {
|
||||||
assert.equal(esc('<a href="x">\'&'), '<a href="x">'&');
|
assert.equal(esc('<a href="x">\'&'), '<a href="x">'&');
|
||||||
});
|
});
|
||||||
|
|
||||||
test('claims id_token Google', () => {
|
test('claims id_token : émetteur, audience, expiration, nonce, email vérifié', () => {
|
||||||
const base = { iss: 'https://accounts.google.com', aud: 'cid', exp: 2e9, nonce: 'n', email_verified: true, email: 'Me@Gmail.com' };
|
const base = { iss: 'https://accounts.google.com', aud: 'cid', exp: 2e9, nonce: 'n', sub: '123', email_verified: true, email: 'Me@Gmail.com' };
|
||||||
const opts = { clientId: 'cid', nonce: 'n', allowedEmails: ['me@gmail.com'], at: 1e9 };
|
const opts = { issuers: ['https://accounts.google.com', 'accounts.google.com'], clientId: 'cid', nonce: 'n', at: 1e9 };
|
||||||
assert.equal(checkIdTokenClaims(base, opts), 'me@gmail.com');
|
assert.deepEqual(checkIdTokenClaims(base, opts), { sub: '123', email: 'me@gmail.com', name: null });
|
||||||
assert.throws(() => checkIdTokenClaims({ ...base, email: 'pirate@gmail.com' }, opts), /non autorisé/);
|
assert.equal(checkIdTokenClaims({ ...base, aud: ['x', 'cid'] }, opts).sub, '123', 'audience en liste');
|
||||||
|
assert.equal(checkIdTokenClaims({ ...base, email_verified: 'true' }, opts).sub, '123', 'Apple envoie "true" en chaîne');
|
||||||
|
assert.throws(() => checkIdTokenClaims({ ...base, iss: 'https://evil.com' }, opts), /Émetteur/);
|
||||||
assert.throws(() => checkIdTokenClaims({ ...base, aud: 'x' }, opts), /Audience/);
|
assert.throws(() => checkIdTokenClaims({ ...base, aud: 'x' }, opts), /Audience/);
|
||||||
assert.throws(() => checkIdTokenClaims({ ...base, nonce: 'z' }, opts), /Nonce/);
|
assert.throws(() => checkIdTokenClaims({ ...base, nonce: 'z' }, opts), /Nonce/);
|
||||||
|
assert.throws(() => checkIdTokenClaims({ ...base, nonce: undefined }, { ...opts, nonce: undefined }), /Nonce/);
|
||||||
assert.throws(() => checkIdTokenClaims({ ...base, email_verified: false }, opts), /vérifié/);
|
assert.throws(() => checkIdTokenClaims({ ...base, email_verified: false }, opts), /vérifié/);
|
||||||
assert.throws(() => checkIdTokenClaims({ ...base, exp: 1 }, opts), /expiré/);
|
assert.throws(() => checkIdTokenClaims({ ...base, exp: 1 }, opts), /expiré/);
|
||||||
|
assert.throws(() => checkIdTokenClaims({ ...base, sub: '' }, opts), /Identifiant/);
|
||||||
|
assert.throws(() => checkIdTokenClaims({ ...base, email: '' }, opts), /Email manquant/);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('contrôle d\'origine', () => {
|
test('contrôle d\'origine', () => {
|
||||||
|
|
|
||||||
113
test/crm.test.js
113
test/crm.test.js
|
|
@ -1,18 +1,21 @@
|
||||||
import { test } from 'node:test';
|
import { test } from 'node:test';
|
||||||
import assert from 'node:assert/strict';
|
import assert from 'node:assert/strict';
|
||||||
import { openDb, now } from '../src/db.js';
|
import { now } from '../src/db.js';
|
||||||
|
import { testDb } from './helpers/db.js';
|
||||||
|
import { addUser } from './helpers/users.js';
|
||||||
import { parseFilters, listProspects } from '../src/services/crm.js';
|
import { parseFilters, listProspects } from '../src/services/crm.js';
|
||||||
|
|
||||||
function setup() {
|
async function setup() {
|
||||||
const db = openDb(':memory:');
|
const db = await testDb();
|
||||||
db.prepare("INSERT INTO projects(name, git_url, created_at) VALUES('A', 'a', ?), ('B', 'b', ?)").run(now(), now());
|
const u = await addUser(db);
|
||||||
|
await db.prepare("INSERT INTO projects(user_id, name, git_url, created_at) VALUES(?, 'A', 'a', ?), (?, 'B', 'b', ?)").run(u, now(), u, now());
|
||||||
const add = (project, company, email, o = {}) => db.prepare(`INSERT INTO prospects(project_id, company, email, city, sector, score, status, sent_at, created_at)
|
const add = (project, company, email, o = {}) => db.prepare(`INSERT INTO prospects(project_id, company, email, city, sector, score, status, sent_at, created_at)
|
||||||
VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(project, company, email, o.city ?? 'Rennes', o.sector ?? 'boulangerie', o.score ?? 5, o.status ?? 'new', o.sent ?? null, o.created ?? now());
|
VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(project, company, email, o.city ?? 'Rennes', o.sector ?? 'boulangerie', o.score ?? 5, o.status ?? 'new', o.sent ?? null, o.created ?? now());
|
||||||
add(1, 'Le Fournil', 'contact@fournil.fr', { score: 9, status: 'replied', sent: now() - 100 });
|
await add(1, 'Le Fournil', 'contact@fournil.fr', { score: 9, status: 'replied', sent: now() - 100 });
|
||||||
add(1, 'Coiffure Zen', 'hello@zen.fr', { city: 'Vern-sur-Seiche', sector: 'coiffeur', score: 6, status: 'sent', sent: now() - 50 });
|
await add(1, 'Coiffure Zen', 'hello@zen.fr', { city: 'Vern-sur-Seiche', sector: 'coiffeur', score: 6, status: 'sent', sent: now() - 50 });
|
||||||
add(1, 'Fleurs & Co', 'bonjour@fleurs.fr', { sector: 'fleuriste', score: 3, created: now() - 1000 });
|
await add(1, 'Fleurs & Co', 'bonjour@fleurs.fr', { sector: 'fleuriste', score: 3, created: now() - 1000 });
|
||||||
add(1, '100% Bio', 'bio@100pourcent.fr', { score: 7 });
|
await add(1, '100% Bio', 'bio@100pourcent.fr', { score: 7 });
|
||||||
add(2, 'Le Fournil', 'contact@fournil.fr', { score: 10 });
|
await add(2, 'Le Fournil', 'contact@fournil.fr', { score: 10 });
|
||||||
return db;
|
return db;
|
||||||
}
|
}
|
||||||
const f = (o = {}) => parseFilters(new URLSearchParams(o));
|
const f = (o = {}) => parseFilters(new URLSearchParams(o));
|
||||||
|
|
@ -23,70 +26,70 @@ test('parseFilters ignore tout ce qui n\'est pas prévu', () => {
|
||||||
{ q: 'zen', status: '', minScore: 10, sort: 'score', todo: false, page: 1 });
|
{ q: 'zen', status: '', minScore: 10, sort: 'score', todo: false, page: 1 });
|
||||||
});
|
});
|
||||||
|
|
||||||
test('recherche, filtres, tri, et isolation entre projets', () => {
|
test('recherche, filtres, tri, et isolation entre projets', async () => {
|
||||||
const db = setup();
|
const db = await setup();
|
||||||
assert.deepEqual(names(listProspects(db, 1, f())), ['Le Fournil', '100% Bio', 'Coiffure Zen', 'Fleurs & Co'], 'tri par score');
|
assert.deepEqual(names(await listProspects(db, 1, f())), ['Le Fournil', '100% Bio', 'Coiffure Zen', 'Fleurs & Co'], 'tri par score');
|
||||||
assert.deepEqual(names(listProspects(db, 1, f({ q: 'ZEN' }))), ['Coiffure Zen'], 'insensible à la casse');
|
assert.deepEqual(names(await listProspects(db, 1, f({ q: 'ZEN' }))), ['Coiffure Zen'], 'insensible à la casse');
|
||||||
assert.deepEqual(names(listProspects(db, 1, f({ q: 'vern' }))), ['Coiffure Zen'], 'par ville');
|
assert.deepEqual(names(await listProspects(db, 1, f({ q: 'vern' }))), ['Coiffure Zen'], 'par ville');
|
||||||
assert.deepEqual(names(listProspects(db, 1, f({ q: 'fleuriste' }))), ['Fleurs & Co'], 'par secteur');
|
assert.deepEqual(names(await listProspects(db, 1, f({ q: 'fleuriste' }))), ['Fleurs & Co'], 'par secteur');
|
||||||
assert.deepEqual(names(listProspects(db, 1, f({ q: '100%' }))), ['100% Bio'], '% littéral, pas un joker');
|
assert.deepEqual(names(await listProspects(db, 1, f({ q: '100%' }))), ['100% Bio'], '% littéral, pas un joker');
|
||||||
assert.deepEqual(names(listProspects(db, 1, f({ q: '_' }))), [], '_ littéral, pas un joker');
|
assert.deepEqual(names(await listProspects(db, 1, f({ q: '_' }))), [], '_ littéral, pas un joker');
|
||||||
assert.deepEqual(names(listProspects(db, 1, f({ status: 'sent' }))), ['Coiffure Zen']);
|
assert.deepEqual(names(await listProspects(db, 1, f({ status: 'sent' }))), ['Coiffure Zen']);
|
||||||
assert.deepEqual(names(listProspects(db, 1, f({ minScore: '7' }))), ['Le Fournil', '100% Bio']);
|
assert.deepEqual(names(await listProspects(db, 1, f({ minScore: '7' }))), ['Le Fournil', '100% Bio']);
|
||||||
assert.deepEqual(names(listProspects(db, 1, f({ sort: 'company' }))), ['100% Bio', 'Coiffure Zen', 'Fleurs & Co', 'Le Fournil']);
|
assert.deepEqual(names(await listProspects(db, 1, f({ sort: 'company' }))), ['100% Bio', 'Coiffure Zen', 'Fleurs & Co', 'Le Fournil']);
|
||||||
assert.deepEqual(names(listProspects(db, 1, f({ sort: 'contacted' }))).slice(0, 2), ['Coiffure Zen', 'Le Fournil']);
|
assert.deepEqual(names(await listProspects(db, 1, f({ sort: 'contacted' }))).slice(0, 2), ['Coiffure Zen', 'Le Fournil']);
|
||||||
assert.equal(listProspects(db, 2, f()).total, 1, 'jamais les prospects d\'un autre projet');
|
assert.equal((await listProspects(db, 2, f())).total, 1, 'jamais les prospects d\'un autre projet');
|
||||||
});
|
});
|
||||||
|
|
||||||
test('pagination', () => {
|
test('pagination', async () => {
|
||||||
const db = setup();
|
const db = await setup();
|
||||||
for (let i = 0; i < 250; i++) db.prepare("INSERT INTO prospects(project_id, company, email, score, created_at) VALUES(1, ?, ?, 1, ?)").run(`E${i}`, `e${i}@x.fr`, now());
|
for (let i = 0; i < 250; i++) await db.prepare("INSERT INTO prospects(project_id, company, email, score, created_at) VALUES(1, ?, ?, 1, ?)").run(`E${i}`, `e${i}@x.fr`, now());
|
||||||
const p1 = listProspects(db, 1, f());
|
const p1 = await listProspects(db, 1, f());
|
||||||
assert.deepEqual({ total: p1.total, pages: p1.pages, n: p1.rows.length }, { total: 254, pages: 3, n: 100 });
|
assert.deepEqual({ total: p1.total, pages: p1.pages, n: p1.rows.length }, { total: 254, pages: 3, n: 100 });
|
||||||
const p3 = listProspects(db, 1, f({ page: '3' }));
|
const p3 = await listProspects(db, 1, f({ page: '3' }));
|
||||||
assert.equal(p3.rows.length, 54);
|
assert.equal(p3.rows.length, 54);
|
||||||
assert.equal(listProspects(db, 1, f({ page: '99' })).page, 3, 'page trop grande ramenée à la dernière');
|
assert.equal((await listProspects(db, 1, f({ page: '99' }))).page, 3, 'page trop grande ramenée à la dernière');
|
||||||
const ids = new Set([...p1.rows, ...listProspects(db, 1, f({ page: '2' })).rows, ...p3.rows].map((x) => x.id));
|
const ids = new Set([...p1.rows, ...(await listProspects(db, 1, f({ page: '2' }))).rows, ...p3.rows].map((x) => x.id));
|
||||||
assert.equal(ids.size, 254, 'aucun doublon ni trou entre les pages');
|
assert.equal(ids.size, 254, 'aucun doublon ni trou entre les pages');
|
||||||
});
|
});
|
||||||
|
|
||||||
test('fiche : historique des mails, réponse, opposition', async () => {
|
test('fiche : historique des mails, réponse, opposition', async () => {
|
||||||
const { prospectDetail } = await import('../src/services/crm.js');
|
const { prospectDetail } = await import('../src/services/crm.js');
|
||||||
const db = setup();
|
const db = await setup();
|
||||||
db.prepare("INSERT INTO mail_log(project_id, prospect_id, email, sent_at, kind, variant, subject) VALUES(1, 1, 'contact@fournil.fr', 100, 'initial', 'B', 'Objet B')").run();
|
await db.prepare("INSERT INTO mail_log(project_id, prospect_id, email, sent_at, kind, variant, subject) VALUES(1, 1, 'contact@fournil.fr', 100, 'initial', 'B', 'Objet B')").run();
|
||||||
db.prepare("INSERT INTO mail_log(project_id, prospect_id, email, sent_at, kind, subject, error) VALUES(1, 1, 'contact@fournil.fr', 200, 'followup', 'Re: Objet B', '421 retry')").run();
|
await db.prepare("INSERT INTO mail_log(project_id, prospect_id, email, sent_at, kind, subject, error) VALUES(1, 1, 'contact@fournil.fr', 200, 'followup', 'Re: Objet B', '421 retry')").run();
|
||||||
db.prepare("INSERT INTO blacklist(email, reason, created_at) VALUES('contact@fournil.fr', 'unsubscribe', 300)").run();
|
await db.prepare("INSERT INTO blacklist(email, reason, created_at) VALUES('contact@fournil.fr', 'unsubscribe', 300)").run();
|
||||||
const d = prospectDetail(db, 1);
|
const d = await prospectDetail(db, 1);
|
||||||
assert.equal(d.prospect.company, 'Le Fournil');
|
assert.equal(d.prospect.company, 'Le Fournil');
|
||||||
assert.deepEqual(d.mails.map((m) => [m.kind, m.variant, m.error]), [['initial', 'B', null], ['followup', null, '421 retry']]);
|
assert.deepEqual(d.mails.map((m) => [m.kind, m.variant, m.error]), [['initial', 'B', null], ['followup', null, '421 retry']]);
|
||||||
assert.equal(d.optOut.reason, 'unsubscribe');
|
assert.equal(d.optOut.reason, 'unsubscribe');
|
||||||
assert.equal(prospectDetail(db, 999), null);
|
assert.equal(await prospectDetail(db, 999), null);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('notes : ajout, ordre, suppression limitée au bon prospect', async () => {
|
test('notes : ajout, ordre, suppression limitée au bon prospect', async () => {
|
||||||
const { addNote, deleteNote, prospectDetail } = await import('../src/services/crm.js');
|
const { addNote, deleteNote, prospectDetail } = await import('../src/services/crm.js');
|
||||||
const db = setup();
|
const db = await setup();
|
||||||
assert.equal(addNote(db, 1, ' '), null, 'note vide refusée');
|
assert.equal(await addNote(db, 1, ' '), null, 'note vide refusée');
|
||||||
const n1 = addNote(db, 1, 'A rappelé, intéressé');
|
const n1 = await addNote(db, 1, 'A rappelé, intéressé');
|
||||||
const n2 = addNote(db, 1, 'x'.repeat(5000));
|
const n2 = await addNote(db, 1, 'x'.repeat(5000));
|
||||||
assert.equal(prospectDetail(db, 1).notes[0].id, n2, 'plus récente en premier');
|
assert.equal((await prospectDetail(db, 1)).notes[0].id, n2, 'plus récente en premier');
|
||||||
assert.equal(prospectDetail(db, 1).notes[0].body.length, 2000, 'tronquée à 2000');
|
assert.equal((await prospectDetail(db, 1)).notes[0].body.length, 2000, 'tronquée à 2000');
|
||||||
assert.equal(deleteNote(db, 2, n1), false, 'pas la note d\'un autre prospect');
|
assert.equal(await deleteNote(db, 2, n1), false, 'pas la note d\'un autre prospect');
|
||||||
assert.equal(deleteNote(db, 1, n1), true);
|
assert.equal(await deleteNote(db, 1, n1), true);
|
||||||
db.prepare('DELETE FROM prospects WHERE id = 1').run();
|
await db.prepare('DELETE FROM prospects WHERE id = 1').run();
|
||||||
assert.equal(db.prepare('SELECT COUNT(*) n FROM prospect_notes').get().n, 0, 'supprimées avec le prospect');
|
assert.equal((await db.prepare('SELECT COUNT(*) n FROM prospect_notes').get()).n, 0, 'supprimées avec le prospect');
|
||||||
});
|
});
|
||||||
|
|
||||||
test('prochaine action : 9h heure de Paris, dates impossibles refusées, filtre "à faire"', async () => {
|
test('prochaine action : 9h heure de Paris, dates impossibles refusées, filtre "à faire"', async () => {
|
||||||
const { setNextAction } = await import('../src/services/crm.js');
|
const { setNextAction } = await import('../src/services/crm.js');
|
||||||
const db = setup();
|
const db = await setup();
|
||||||
assert.equal(setNextAction(db, 1, 'Rappeler', '2026-07-14'), Date.parse('2026-07-14T07:00:00Z') / 1000, 'été');
|
assert.equal(await setNextAction(db, 1, 'Rappeler', '2026-07-14'), Date.parse('2026-07-14T07:00:00Z') / 1000, 'été');
|
||||||
assert.equal(setNextAction(db, 2, 'Devis', '2026-12-01'), Date.parse('2026-12-01T08:00:00Z') / 1000, 'hiver');
|
assert.equal(await setNextAction(db, 2, 'Devis', '2026-12-01'), Date.parse('2026-12-01T08:00:00Z') / 1000, 'hiver');
|
||||||
assert.throws(() => setNextAction(db, 1, 'x', '2026-02-31'), /Date invalide/);
|
await assert.rejects(setNextAction(db, 1, 'x', '2026-02-31'), /Date invalide/);
|
||||||
assert.throws(() => setNextAction(db, 1, 'x', '14/07/2026'), /AAAA-MM-JJ/);
|
await assert.rejects(setNextAction(db, 1, 'x', '14/07/2026'), /AAAA-MM-JJ/);
|
||||||
const todo = (at) => names(listProspects(db, 1, { ...f({ todo: '1' }), at }));
|
const todo = async (at) => names(await listProspects(db, 1, { ...f({ todo: '1' }), at }));
|
||||||
assert.deepEqual(todo(Date.parse('2026-08-01T00:00:00Z') / 1000), ['Le Fournil'], 'seule l\'action échue');
|
assert.deepEqual(await todo(Date.parse('2026-08-01T00:00:00Z') / 1000), ['Le Fournil'], 'seule l\'action échue');
|
||||||
assert.deepEqual(todo(Date.parse('2027-01-01T00:00:00Z') / 1000), ['Le Fournil', 'Coiffure Zen']);
|
assert.deepEqual(await todo(Date.parse('2027-01-01T00:00:00Z') / 1000), ['Le Fournil', 'Coiffure Zen']);
|
||||||
assert.equal(setNextAction(db, 1, '', ''), null);
|
assert.equal(await setNextAction(db, 1, '', ''), null);
|
||||||
assert.deepEqual(todo(Date.parse('2027-01-01T00:00:00Z') / 1000), ['Coiffure Zen'], 'action effacée');
|
assert.deepEqual(await todo(Date.parse('2027-01-01T00:00:00Z') / 1000), ['Coiffure Zen'], 'action effacée');
|
||||||
});
|
});
|
||||||
|
|
|
||||||
|
|
@ -1,13 +1,16 @@
|
||||||
import { test } from 'node:test';
|
import { test } from 'node:test';
|
||||||
import assert from 'node:assert/strict';
|
import assert from 'node:assert/strict';
|
||||||
import { openDb, now } from '../src/db.js';
|
import { now } from '../src/db.js';
|
||||||
|
import { testDb } from './helpers/db.js';
|
||||||
|
import { addUser } from './helpers/users.js';
|
||||||
import { csvCell, toCsv, parseCsv, exportProspects, importProspects } from '../src/services/csv.js';
|
import { csvCell, toCsv, parseCsv, exportProspects, importProspects } from '../src/services/csv.js';
|
||||||
import { parseFilters } from '../src/services/crm.js';
|
import { parseFilters } from '../src/services/crm.js';
|
||||||
|
|
||||||
const f = (o = {}) => parseFilters(new URLSearchParams(o));
|
const f = (o = {}) => parseFilters(new URLSearchParams(o));
|
||||||
function setup() {
|
async function setup() {
|
||||||
const db = openDb(':memory:');
|
const db = await testDb();
|
||||||
db.prepare("INSERT INTO projects(name, git_url, created_at) VALUES('A', 'a', ?), ('B', 'b', ?)").run(now(), now());
|
const u = await addUser(db);
|
||||||
|
await db.prepare("INSERT INTO projects(user_id, name, git_url, created_at) VALUES(?, 'A', 'a', ?), (?, 'B', 'b', ?)").run(u, now(), u, now());
|
||||||
return db;
|
return db;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -27,10 +30,10 @@ test('parseCsv : séparateur détecté, guillemets, retours à la ligne, BOM, li
|
||||||
assert.deepEqual(parseCsv('email\tville\nx@y.fr\tBrest'), [['email', 'ville'], ['x@y.fr', 'Brest']]);
|
assert.deepEqual(parseCsv('email\tville\nx@y.fr\tBrest'), [['email', 'ville'], ['x@y.fr', 'Brest']]);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('import : en-têtes souples, doublons, opposition, invalides, origine RGPD', () => {
|
test('import : en-têtes souples, doublons, opposition, invalides, origine RGPD', async () => {
|
||||||
const db = setup();
|
const db = await setup();
|
||||||
db.prepare("INSERT INTO prospects(project_id, company, email, created_at) VALUES(1, 'Déjà', 'deja@la.fr', ?)").run(now());
|
await db.prepare("INSERT INTO prospects(project_id, company, email, created_at) VALUES(1, 'Déjà', 'deja@la.fr', ?)").run(now());
|
||||||
db.prepare("INSERT INTO blacklist(email, reason, created_at) VALUES('stop@moi.fr', 'unsubscribe', ?)").run(now());
|
await db.prepare("INSERT INTO blacklist(email, reason, created_at) VALUES('stop@moi.fr', 'unsubscribe', ?)").run(now());
|
||||||
const csv = [
|
const csv = [
|
||||||
'Raison sociale;E-mail;Site web;Commune;Activité;Note;Origine',
|
'Raison sociale;E-mail;Site web;Commune;Activité;Note;Origine',
|
||||||
'Crêperie Ty Breizh;Contact@TyBreizh.bzh;https://tybreizh.bzh;Quimper;crêperie;8;annuaire CCI',
|
'Crêperie Ty Breizh;Contact@TyBreizh.bzh;https://tybreizh.bzh;Quimper;crêperie;8;annuaire CCI',
|
||||||
|
|
@ -41,40 +44,40 @@ test('import : en-têtes souples, doublons, opposition, invalides, origine RGPD'
|
||||||
'Cassé;pas-un-email;;;;;',
|
'Cassé;pas-un-email;;;;;',
|
||||||
"Formule;f@x.fr;;'=1+1;;99;",
|
"Formule;f@x.fr;;'=1+1;;99;",
|
||||||
].join('\r\n');
|
].join('\r\n');
|
||||||
const r = importProspects(db, 1, csv, { at: Date.parse('2026-10-21T10:00:00Z') / 1000 });
|
const r = await importProspects(db, 1, csv, { at: Date.parse('2026-10-21T10:00:00Z') / 1000 });
|
||||||
assert.deepEqual({ ...r, invalid: r.invalid.map((x) => x.line) }, { total: 7, imported: 3, duplicates: 2, blacklisted: 1, invalid: [7] });
|
assert.deepEqual({ ...r, invalid: r.invalid.map((x) => x.line) }, { total: 7, imported: 3, duplicates: 2, blacklisted: 1, invalid: [7] });
|
||||||
const get = (email) => db.prepare('SELECT * FROM prospects WHERE project_id = 1 AND email = ?').get(email);
|
const get = async (email) => db.prepare('SELECT * FROM prospects WHERE project_id = 1 AND email = ?').get(email);
|
||||||
const ty = get('contact@tybreizh.bzh');
|
const ty = await get('contact@tybreizh.bzh');
|
||||||
assert.deepEqual([ty.company, ty.website, ty.city, ty.sector, ty.score, ty.source, ty.status], ['Crêperie Ty Breizh', 'https://tybreizh.bzh', 'Quimper', 'crêperie', 8, 'annuaire CCI', 'new']);
|
assert.deepEqual([ty.company, ty.website, ty.city, ty.sector, ty.score, ty.source, ty.status], ['Crêperie Ty Breizh', 'https://tybreizh.bzh', 'Quimper', 'crêperie', 8, 'annuaire CCI', 'new']);
|
||||||
const sn = get('sans-nom@atelier.fr');
|
const sn = await get('sans-nom@atelier.fr');
|
||||||
assert.equal(sn.company, 'atelier.fr', 'nom déduit du domaine');
|
assert.equal(sn.company, 'atelier.fr', 'nom déduit du domaine');
|
||||||
assert.equal(sn.website, null, 'javascript: rejeté');
|
assert.equal(sn.website, null, 'javascript: rejeté');
|
||||||
assert.equal(sn.source, 'Import CSV du 21/10/2026', 'origine toujours renseignée');
|
assert.equal(sn.source, 'Import CSV du 21/10/2026', 'origine toujours renseignée');
|
||||||
assert.equal(get('f@x.fr').city, '=1+1', 'apostrophe de notre export retirée');
|
assert.equal((await get('f@x.fr')).city, '=1+1', 'apostrophe de notre export retirée');
|
||||||
assert.equal(get('f@x.fr').score, 10, 'score borné');
|
assert.equal((await get('f@x.fr')).score, 10, 'score borné');
|
||||||
assert.equal(db.prepare('SELECT COUNT(*) n FROM prospects WHERE project_id = 2').get().n, 0, 'rien dans l\'autre projet');
|
assert.equal((await db.prepare('SELECT COUNT(*) n FROM prospects WHERE project_id = 2').get()).n, 0, 'rien dans l\'autre projet');
|
||||||
});
|
});
|
||||||
|
|
||||||
test('import : erreurs claires', () => {
|
test('import : erreurs claires', async () => {
|
||||||
const db = setup();
|
const db = await setup();
|
||||||
assert.throws(() => importProspects(db, 1, 'email\n'), /vide ou sans en-tête/);
|
await assert.rejects(importProspects(db, 1, 'email\n'), /vide ou sans en-tête/);
|
||||||
assert.throws(() => importProspects(db, 1, 'nom;ville\nA;B'), /Colonne email introuvable/);
|
await assert.rejects(importProspects(db, 1, 'nom;ville\nA;B'), /Colonne email introuvable/);
|
||||||
assert.throws(() => importProspects(db, 1, 'email\n' + 'a@b.fr\n'.repeat(2001)), /Maximum 2000 lignes/);
|
await assert.rejects(importProspects(db, 1, 'email\n' + 'a@b.fr\n'.repeat(2001)), /Maximum 2000 lignes/);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('export puis réimport dans un autre projet : aller-retour sans perte', () => {
|
test('export puis réimport dans un autre projet : aller-retour sans perte', async () => {
|
||||||
const db = setup();
|
const db = await setup();
|
||||||
db.prepare(`INSERT INTO prospects(project_id, company, email, website, city, sector, score, status, source, hook, created_at)
|
await db.prepare(`INSERT INTO prospects(project_id, company, email, website, city, sector, score, status, source, hook, created_at)
|
||||||
VALUES(1, 'Le "Fournil"; SARL', 'c@fournil.fr', 'https://fournil.fr', 'Rennes', 'boulangerie', 9, 'replied', 'https://fournil.fr/contact', '=Votre pain mérite mieux', ?)`).run(now());
|
VALUES(1, 'Le "Fournil"; SARL', 'c@fournil.fr', 'https://fournil.fr', 'Rennes', 'boulangerie', 9, 'replied', 'https://fournil.fr/contact', '=Votre pain mérite mieux', ?)`).run(now());
|
||||||
db.prepare("INSERT INTO prospects(project_id, company, email, score, status, created_at) VALUES(1, 'Zen', 'z@zen.fr', 4, 'new', ?)").run(now());
|
await db.prepare("INSERT INTO prospects(project_id, company, email, score, status, created_at) VALUES(1, 'Zen', 'z@zen.fr', 4, 'new', ?)").run(now());
|
||||||
const all = exportProspects(db, 1, f());
|
const all = await exportProspects(db, 1, f());
|
||||||
assert.match(all, /^Entreprise;Email;Site/);
|
assert.match(all, /^Entreprise;Email;Site/);
|
||||||
assert.match(all, /"Le ""Fournil""; SARL";c@fournil\.fr/);
|
assert.match(all, /"Le ""Fournil""; SARL";c@fournil\.fr/);
|
||||||
assert.match(all, /'=Votre pain/, 'formule neutralisée');
|
assert.match(all, /'=Votre pain/, 'formule neutralisée');
|
||||||
assert.match(all, /;A répondu;/, 'statut lisible');
|
assert.match(all, /;A répondu;/, 'statut lisible');
|
||||||
assert.equal(exportProspects(db, 1, f({ minScore: '5' })).trim().split('\r\n').length, 2, 'l\'export suit les filtres');
|
assert.equal((await exportProspects(db, 1, f({ minScore: '5' }))).trim().split('\r\n').length, 2, 'l\'export suit les filtres');
|
||||||
const r = importProspects(db, 2, all);
|
const r = await importProspects(db, 2, all);
|
||||||
assert.equal(r.imported, 2);
|
assert.equal(r.imported, 2);
|
||||||
const back = db.prepare("SELECT company, website, source, hook, score FROM prospects WHERE project_id = 2 AND email = 'c@fournil.fr'").get();
|
const back = await db.prepare("SELECT company, website, source, hook, score FROM prospects WHERE project_id = 2 AND email = 'c@fournil.fr'").get();
|
||||||
assert.deepEqual({ ...back }, { company: 'Le "Fournil"; SARL', website: 'https://fournil.fr', source: 'https://fournil.fr/contact', hook: '=Votre pain mérite mieux', score: 9 });
|
assert.deepEqual({ ...back }, { company: 'Le "Fournil"; SARL', website: 'https://fournil.fr', source: 'https://fournil.fr/contact', hook: '=Votre pain mérite mieux', score: 9 });
|
||||||
});
|
});
|
||||||
|
|
|
||||||
128
test/db.test.js
Normal file
128
test/db.test.js
Normal file
|
|
@ -0,0 +1,128 @@
|
||||||
|
import { test } from 'node:test';
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import { openDb, translate, dbConfigFromEnv, getSetting, setSetting, now } from '../src/db.js';
|
||||||
|
import { testDb } from './helpers/db.js';
|
||||||
|
import { addUser } from './helpers/users.js';
|
||||||
|
import { MIGRATIONS } from '../src/migrations.js';
|
||||||
|
|
||||||
|
test('translate : MySQL reçoit INSERT IGNORE, ON DUPLICATE KEY, VALUES() et pas de NOCASE', () => {
|
||||||
|
const up = 'INSERT INTO t(a, b) VALUES(?, ?) ON CONFLICT(a, b) DO UPDATE SET x = excluded.x, y = excluded.y';
|
||||||
|
assert.equal(translate('INSERT OR IGNORE INTO t VALUES(?)', 'mysql'), 'INSERT IGNORE INTO t VALUES(?)');
|
||||||
|
assert.equal(translate(up, 'mysql'), 'INSERT INTO t(a, b) VALUES(?, ?) ON DUPLICATE KEY UPDATE x = VALUES(x), y = VALUES(y)');
|
||||||
|
assert.equal(translate('SELECT * FROM t ORDER BY name COLLATE NOCASE', 'mysql'), 'SELECT * FROM t ORDER BY name');
|
||||||
|
// SQLite : la forme canonique passe telle quelle
|
||||||
|
assert.equal(translate(up, 'sqlite'), up);
|
||||||
|
assert.equal(translate('INSERT OR IGNORE INTO t VALUES(?)', 'sqlite'), 'INSERT OR IGNORE INTO t VALUES(?)');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('dbConfigFromEnv : variables DB_*, port par défaut, erreur claire', () => {
|
||||||
|
assert.deepEqual(
|
||||||
|
dbConfigFromEnv({ DB_HOST: 'h', DB_USER: 'u', DB_PASSWORD: 'p', DB_NAME: 'n' }),
|
||||||
|
{ driver: 'mysql', host: 'h', port: 3306, user: 'u', password: 'p', database: 'n' },
|
||||||
|
);
|
||||||
|
assert.equal(dbConfigFromEnv({ DB_HOST: 'h', DB_USER: 'u', DB_NAME: 'n', DB_PORT: '3307' }).port, 3307);
|
||||||
|
assert.throws(() => dbConfigFromEnv({ DB_HOST: 'h' }), /DB_USER/);
|
||||||
|
assert.deepEqual(dbConfigFromEnv({ DB_DRIVER: 'sqlite' }), { driver: 'sqlite', file: ':memory:' });
|
||||||
|
});
|
||||||
|
|
||||||
|
test('shim : get / all / run asynchrones, run → changes + lastInsertRowid', async () => {
|
||||||
|
const db = await testDb();
|
||||||
|
const u = await addUser(db);
|
||||||
|
const pending = db.prepare('INSERT INTO projects(user_id, name, git_url, created_at) VALUES(?, ?, ?, ?)').run(u, 'A', 'u1', now());
|
||||||
|
assert.ok(pending instanceof Promise);
|
||||||
|
await pending;
|
||||||
|
const r1 = await db.prepare('INSERT INTO projects(user_id, name, git_url, created_at) VALUES(?, ?, ?, ?)').run(u, 'B', 'u2', now());
|
||||||
|
assert.equal(r1.changes, 1);
|
||||||
|
assert.ok(r1.lastInsertRowid > 0);
|
||||||
|
assert.equal((await db.prepare('SELECT name FROM projects WHERE id = ?').get(r1.lastInsertRowid)).name, 'B');
|
||||||
|
assert.equal((await db.prepare('SELECT * FROM projects').all()).length, 2);
|
||||||
|
assert.equal(await db.prepare('SELECT * FROM projects WHERE id = ?').get(99999), undefined);
|
||||||
|
assert.equal((await db.prepare('UPDATE projects SET name = ? WHERE git_url = ?').run('Z', 'u2')).changes, 1);
|
||||||
|
assert.equal((await db.prepare('UPDATE projects SET name = ? WHERE git_url = ?').run('Z', 'nope')).changes, 0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('shim : undefined et NaN deviennent NULL', async () => {
|
||||||
|
const db = await testDb();
|
||||||
|
const u = await addUser(db);
|
||||||
|
await db.prepare('INSERT INTO projects(user_id, name, git_url, created_at, profile_at) VALUES(?, ?, ?, ?, ?)').run(u, 'A', 'u', now(), Number('abc'));
|
||||||
|
await db.prepare('UPDATE projects SET profile_commit = ? WHERE git_url = ?').run(undefined, 'u');
|
||||||
|
const p = await db.prepare('SELECT profile_at, profile_commit FROM projects').get();
|
||||||
|
assert.equal(p.profile_at, null);
|
||||||
|
assert.equal(p.profile_commit, null);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('upsert (ON CONFLICT) et INSERT OR IGNORE dans le sous-ensemble commun', async () => {
|
||||||
|
const db = await testDb();
|
||||||
|
const u = await addUser(db), v = await addUser(db);
|
||||||
|
await setSetting(db, u, 'a', '1'); await setSetting(db, u, 'a', '2');
|
||||||
|
assert.equal(await getSetting(db, u, 'a'), '2');
|
||||||
|
assert.equal(await getSetting(db, u, 'nope', 'x'), 'x');
|
||||||
|
assert.equal(await getSetting(db, v, 'a', 'autre'), 'autre', 'les réglages sont propres à chaque utilisateur');
|
||||||
|
await setSetting(db, u, 'a', null);
|
||||||
|
assert.equal(await getSetting(db, u, 'a', 'fallback'), null);
|
||||||
|
await assert.rejects(setSetting(db, undefined, 'a', '1'), /utilisateur requis/);
|
||||||
|
|
||||||
|
const ins = db.prepare("INSERT OR IGNORE INTO blacklist(email, reason, created_at) VALUES(?, 'x', ?)");
|
||||||
|
assert.equal((await ins.run('a@b.fr', now())).changes, 1);
|
||||||
|
assert.equal((await ins.run('a@b.fr', now())).changes, 0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('clés étrangères : supprimer un projet supprime ses dépendances (CASCADE)', async () => {
|
||||||
|
const db = await testDb();
|
||||||
|
const u = await addUser(db);
|
||||||
|
const { lastInsertRowid: pid } = await db.prepare('INSERT INTO projects(user_id, name, git_url, created_at) VALUES(?, ?, ?, ?)').run(u, 'A', 'u', now());
|
||||||
|
const { lastInsertRowid: prid } = await db.prepare('INSERT INTO prospects(project_id, company, email, created_at) VALUES(?, ?, ?, ?)').run(pid, 'C', 'c@d.fr', now());
|
||||||
|
await db.prepare('INSERT INTO prospect_notes(prospect_id, body, created_at) VALUES(?, ?, ?)').run(prid, 'n', now());
|
||||||
|
await db.prepare('INSERT INTO jobs(user_id, project_id, type, created_at) VALUES(?, ?, ?, ?)').run(u, pid, 'analyze', now());
|
||||||
|
await db.prepare('DELETE FROM projects WHERE id = ?').run(pid);
|
||||||
|
for (const t of ['prospects', 'prospect_notes', 'jobs']) assert.equal((await db.prepare(`SELECT COUNT(*) n FROM ${t}`).get()).n, 0, t);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('transaction : commit, rollback sur erreur, résultat renvoyé', async () => {
|
||||||
|
const db = await testDb();
|
||||||
|
const out = await db.transaction(async (tx) => {
|
||||||
|
await tx.prepare("INSERT INTO blacklist(email, created_at) VALUES('a@b.fr', ?)").run(now());
|
||||||
|
return 42;
|
||||||
|
});
|
||||||
|
assert.equal(out, 42);
|
||||||
|
await assert.rejects(db.transaction(async (tx) => {
|
||||||
|
await tx.prepare("INSERT INTO blacklist(email, created_at) VALUES('c@d.fr', ?)").run(now());
|
||||||
|
throw new Error('boum');
|
||||||
|
}), /boum/);
|
||||||
|
const rows = await db.prepare('SELECT email FROM blacklist').all();
|
||||||
|
assert.deepEqual(rows.map((r) => r.email), ['a@b.fr']);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('transaction : une requête hors transaction ne voit jamais une écriture annulée', async () => {
|
||||||
|
const db = await testDb();
|
||||||
|
let seen;
|
||||||
|
const tx = db.transaction(async (t) => {
|
||||||
|
await t.prepare("INSERT INTO blacklist(email, created_at) VALUES('x@y.fr', ?)").run(now());
|
||||||
|
await new Promise((r) => setTimeout(r, 30));
|
||||||
|
throw new Error('annulée');
|
||||||
|
});
|
||||||
|
const outside = new Promise((r) => setTimeout(r, 10)).then(async () => {
|
||||||
|
seen = await db.prepare('SELECT COUNT(*) n FROM blacklist').get();
|
||||||
|
});
|
||||||
|
await assert.rejects(tx, /annulée/);
|
||||||
|
await outside;
|
||||||
|
assert.equal(seen.n, 0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('migrations idempotentes : rouvrir une base déjà migrée ne casse rien (SQLite fichier)', async () => {
|
||||||
|
const { mkdtempSync, rmSync } = await import('node:fs');
|
||||||
|
const { join } = await import('node:path');
|
||||||
|
const { tmpdir } = await import('node:os');
|
||||||
|
const dir = mkdtempSync(join(tmpdir(), 'mig-'));
|
||||||
|
try {
|
||||||
|
const file = join(dir, 't.sqlite');
|
||||||
|
const a = await openDb({ driver: 'sqlite', file });
|
||||||
|
const u = await addUser(a);
|
||||||
|
await setSetting(a, u, 'k', 'v');
|
||||||
|
await a.close();
|
||||||
|
const b = await openDb({ driver: 'sqlite', file });
|
||||||
|
assert.equal(await getSetting(b, u, 'k'), 'v');
|
||||||
|
assert.equal((await b.prepare('SELECT COUNT(*) n FROM schema_migrations').get()).n, MIGRATIONS.length);
|
||||||
|
await b.close();
|
||||||
|
} finally { rmSync(dir, { recursive: true, force: true }); }
|
||||||
|
});
|
||||||
12
test/fixtures/fake-claude.js
vendored
12
test/fixtures/fake-claude.js
vendored
|
|
@ -4,8 +4,16 @@ const prompt = process.argv[process.argv.indexOf('-p') + 1] || '';
|
||||||
const out = (o) => process.stdout.write(JSON.stringify(o) + '\n');
|
const out = (o) => process.stdout.write(JSON.stringify(o) + '\n');
|
||||||
out({ type: 'system', subtype: 'init', args: process.argv.slice(2) });
|
out({ type: 'system', subtype: 'init', args: process.argv.slice(2) });
|
||||||
if (prompt.includes('CRASH')) process.exit(3);
|
if (prompt.includes('CRASH')) process.exit(3);
|
||||||
|
// Le secret de l'utilisateur fuit dans stderr : l'application ne doit jamais le répercuter
|
||||||
|
if (prompt.includes('LEAK')) { process.stderr.write('echec avec ' + (process.env.ANTHROPIC_API_KEY || process.env.CLAUDE_CODE_OAUTH_TOKEN || '') + ' fin'); process.exit(3); }
|
||||||
|
// Jeton d'abonnement refusé par Claude
|
||||||
|
if ((process.env.CLAUDE_CODE_OAUTH_TOKEN || '').includes('REVOKED')) {
|
||||||
|
out({ type: 'result', subtype: 'success', is_error: true, result: 'Invalid bearer token · Please run /login', total_cost_usd: 0, num_turns: 0, usage: {} });
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
const profile = { resume: 'Cartes de fidélité digitales.', proposition_valeur: 'Fidélisez sans carton.', fonctionnalites: ['tampons'], stack: 'node', modele_eco: 'abonnement', cible: { description: 'commerces de proximité', secteurs: ['boulangerie'], zone: 'Bretagne', taille: 'TPE', decideur: 'gérant', requetes: ['boulangerie rennes'] }, arguments: ['simple'], ton: 'direct' };
|
const profile = { resume: 'Cartes de fidélité digitales.', proposition_valeur: 'Fidélisez sans carton.', fonctionnalites: ['tampons'], stack: 'node', modele_eco: 'abonnement', cible: { description: 'commerces de proximité', secteurs: ['boulangerie'], zone: 'Bretagne', taille: 'TPE', decideur: 'gérant', requetes: ['boulangerie rennes'] }, arguments: ['simple'], ton: 'direct' };
|
||||||
const lines = prompt.includes('fiche commerciale') ? ['```json\n' + JSON.stringify(profile) + '\n```']
|
const lines = prompt.includes('ENVDUMP') ? ['```json\n' + JSON.stringify({ env: process.env, cwd: process.cwd() }) + '\n```']
|
||||||
|
: prompt.includes('fiche commerciale') ? ['```json\n' + JSON.stringify(profile) + '\n```']
|
||||||
: prompt.includes('mail de RELANCE') ? ['{"body":"Petite relance : toujours partant, {{entreprise}} ?"}']
|
: prompt.includes('mail de RELANCE') ? ['{"body":"Petite relance : toujours partant, {{entreprise}} ?"}']
|
||||||
: prompt.includes('email de prospection') ? ['{"subject":"Idée pour {{entreprise}}","body":"{{accroche}}\\n\\nBonjour {{entreprise}} à {{ville}}.\\n\\n{{expediteur}}"}']
|
: prompt.includes('email de prospection') ? ['{"subject":"Idée pour {{entreprise}}","body":"{{accroche}}\\n\\nBonjour {{entreprise}} à {{ville}}.\\n\\n{{expediteur}}"}']
|
||||||
: prompt.includes('évolutions') ? ['### 1. Export CSV\n- **Pourquoi** : pratique']
|
: prompt.includes('évolutions') ? ['### 1. Export CSV\n- **Pourquoi** : pratique']
|
||||||
|
|
@ -18,7 +26,7 @@ for (const t of lines) out({ type: 'assistant', message: { content: [{ type: 'te
|
||||||
// Quota du compte (session 5h + semaine), remonté par la vraie CLI à chaque appel.
|
// Quota du compte (session 5h + semaine), remonté par la vraie CLI à chaque appel.
|
||||||
// Surchargeable par les tests qui veulent simuler un quota serré (FAKE_FIVE_HOUR / FAKE_SEVEN_DAY).
|
// Surchargeable par les tests qui veulent simuler un quota serré (FAKE_FIVE_HOUR / FAKE_SEVEN_DAY).
|
||||||
out({ type: 'rate_limit_event', rate_limit_info: { status: 'allowed', unifiedWindows: {
|
out({ type: 'rate_limit_event', rate_limit_info: { status: 'allowed', unifiedWindows: {
|
||||||
five_hour: { utilization: Number(process.env.FAKE_FIVE_HOUR ?? 0.33), resetsAt: 1_700_000_000 },
|
five_hour: { utilization: Number(process.env.FAKE_FIVE_HOUR ?? ((process.env.CLAUDE_CODE_OAUTH_TOKEN || '').includes('HOT') ? 0.9 : 0.33)), resetsAt: 1_700_000_000 },
|
||||||
seven_day: { utilization: Number(process.env.FAKE_SEVEN_DAY ?? 0.5), resetsAt: 1_700_300_000 },
|
seven_day: { utilization: Number(process.env.FAKE_SEVEN_DAY ?? 0.5), resetsAt: 1_700_300_000 },
|
||||||
} } });
|
} } });
|
||||||
out({ type: 'result', subtype: 'success', is_error: false, result: lines[lines.length - 1], total_cost_usd: 0.0123, num_turns: 2, usage: { input_tokens: 100, cache_read_input_tokens: 50, output_tokens: 20 } });
|
out({ type: 'result', subtype: 'success', is_error: false, result: lines[lines.length - 1], total_cost_usd: 0.0123, num_turns: 2, usage: { input_tokens: 100, cache_read_input_tokens: 50, output_tokens: 20 } });
|
||||||
|
|
|
||||||
|
|
@ -4,12 +4,15 @@ import { mkdtempSync, rmSync } from 'node:fs';
|
||||||
import { tmpdir } from 'node:os';
|
import { tmpdir } from 'node:os';
|
||||||
import { join, resolve } from 'node:path';
|
import { join, resolve } from 'node:path';
|
||||||
import { randomBytes } from 'node:crypto';
|
import { randomBytes } from 'node:crypto';
|
||||||
import { openDb, now, setSetting } from '../src/db.js';
|
import { now, setSetting } from '../src/db.js';
|
||||||
|
import { testDb } from './helpers/db.js';
|
||||||
|
|
||||||
import { isBusinessHours, followupPlan, followupSubject } from '../src/services/followup.js';
|
import { isBusinessHours, followupPlan, followupSubject } from '../src/services/followup.js';
|
||||||
import { Worker, latestJobs } from '../src/services/jobs.js';
|
import { Worker, latestJobs } from '../src/services/jobs.js';
|
||||||
import { Scheduler } from '../src/services/scheduler.js';
|
import { Scheduler } from '../src/services/scheduler.js';
|
||||||
import { makeHandlers } from '../src/handlers.js';
|
import { makeHandlers } from '../src/handlers.js';
|
||||||
import { createProject, saveSecretConfig, getProject } from '../src/projects.js';
|
import { createProject, saveSecretConfig, getProject } from '../src/projects.js';
|
||||||
|
import { addUser } from './helpers/users.js';
|
||||||
|
|
||||||
const paris = (iso) => new Date(iso); // ISO avec décalage explicite
|
const paris = (iso) => new Date(iso); // ISO avec décalage explicite
|
||||||
|
|
||||||
|
|
@ -33,54 +36,55 @@ test('objet de la relance : même fil par défaut', () => {
|
||||||
|
|
||||||
const WED_10H = Math.floor(new Date('2026-10-21T10:00:00+02:00').getTime() / 1000);
|
const WED_10H = Math.floor(new Date('2026-10-21T10:00:00+02:00').getTime() / 1000);
|
||||||
|
|
||||||
function setup() {
|
async function setup() {
|
||||||
const tmp = mkdtempSync(join(tmpdir(), 'aitools-fu-'));
|
const tmp = mkdtempSync(join(tmpdir(), 'aitools-fu-'));
|
||||||
const db = openDb(':memory:');
|
const db = await testDb();
|
||||||
const sentMails = [];
|
const sentMails = [];
|
||||||
const app = {
|
const app = {
|
||||||
db, cfg: { dataDir: tmp, claudeBin: resolve('test/fixtures/fake-claude.js'), secretKey: randomBytes(32), appUrl: 'https://ai.test' },
|
db, cfg: { dataDir: tmp, claudeBin: resolve('test/fixtures/fake-claude.js'), sandbox: { enabled: false, production: false }, secretKey: randomBytes(32), appUrl: 'https://ai.test' },
|
||||||
createTransport: () => ({ verify: async () => true, sendMail: async (m) => { sentMails.push(m); }, close() {} }),
|
createTransport: () => ({ verify: async () => true, sendMail: async (m) => { sentMails.push(m); }, close() {} }),
|
||||||
isBusinessHours: () => true, // horloge figée : le test ne dépend pas de l'heure à laquelle on le lance
|
isBusinessHours: () => true, // horloge figée : le test ne dépend pas de l'heure à laquelle on le lance
|
||||||
};
|
};
|
||||||
setSetting(db, 'send_delay_min', '0');
|
const userId = await addUser(db);
|
||||||
setSetting(db, 'send_delay_max', '0');
|
await setSetting(db, userId, 'send_delay_min', '0');
|
||||||
const id = createProject(app, { name: 'P', gitUrl: 'https://git.x/T/P.git' });
|
await setSetting(db, userId, 'send_delay_max', '0');
|
||||||
saveSecretConfig(app, id, 'smtp_enc', { host: 'smtp.x', user: 'u', pass: 'p', fromEmail: 'tony@codebzh.fr' }, 'pass');
|
const id = await createProject(app, { userId, name: 'P', gitUrl: 'https://git.x/T/P.git' });
|
||||||
saveSecretConfig(app, id, 'imap_enc', { host: 'imap.x', port: 993 }, 'pass');
|
await saveSecretConfig(app, id, 'smtp_enc', { host: 'smtp.x', user: 'u', pass: 'p', fromEmail: 'tony@codebzh.fr' }, 'pass');
|
||||||
|
await saveSecretConfig(app, id, 'imap_enc', { host: 'imap.x', port: 993 }, 'pass');
|
||||||
const inboxOk = (at = now(), extra = {}) => db.prepare('UPDATE projects SET inbox_json = ? WHERE id = ?')
|
const inboxOk = (at = now(), extra = {}) => db.prepare('UPDATE projects SET inbox_json = ? WHERE id = ?')
|
||||||
.run(JSON.stringify({ lastOk: at, lastCheck: at, lastError: null, ...extra }), id);
|
.run(JSON.stringify({ lastOk: at, lastCheck: at, lastError: null, ...extra }), id);
|
||||||
inboxOk();
|
await inboxOk();
|
||||||
db.prepare("INSERT INTO templates(project_id, kind, subject, body, status, updated_at) VALUES(?, 'followup', '', 'Toujours partant, {{entreprise}} ?', 'validated', ?)").run(id, now());
|
await db.prepare("INSERT INTO templates(project_id, kind, subject, body, status, updated_at) VALUES(?, 'followup', '', 'Toujours partant, {{entreprise}} ?', 'validated', ?)").run(id, now());
|
||||||
db.prepare('UPDATE projects SET followup_enabled = 1, followup_days = 7 WHERE id = ?').run(id);
|
await db.prepare('UPDATE projects SET followup_enabled = 1, followup_days = 7 WHERE id = ?').run(id);
|
||||||
const add = (email, daysAgo, status = 'sent') => {
|
const add = async (email, daysAgo, status = 'sent') => {
|
||||||
const t = now() - daysAgo * 86400;
|
const t = now() - daysAgo * 86400;
|
||||||
const pid = Number(db.prepare('INSERT INTO prospects(project_id, company, email, status, sent_at, created_at) VALUES(?, ?, ?, ?, ?, ?)')
|
const pid = Number((await db.prepare('INSERT INTO prospects(project_id, company, email, status, sent_at, created_at) VALUES(?, ?, ?, ?, ?, ?)')
|
||||||
.run(id, email.split('@')[1], email, status, t, t).lastInsertRowid);
|
.run(id, email.split('@')[1], email, status, t, t)).lastInsertRowid);
|
||||||
db.prepare("INSERT INTO mail_log(project_id, prospect_id, email, sent_at, kind, subject, message_id) VALUES(?, ?, ?, ?, 'initial', ?, ?)")
|
await db.prepare("INSERT INTO mail_log(project_id, prospect_id, email, sent_at, kind, subject, message_id) VALUES(?, ?, ?, ?, 'initial', ?, ?)")
|
||||||
.run(id, pid, email, t, `Une idée pour ${email}`, `<orig-${pid}@codebzh.fr>`);
|
.run(id, pid, email, t, `Une idée pour ${email}`, `<orig-${pid}@codebzh.fr>`);
|
||||||
return pid;
|
return pid;
|
||||||
};
|
};
|
||||||
const worker = new Worker(db, makeHandlers(app), { thermalMax: 999, log: { error() {} } });
|
const worker = new Worker(db, makeHandlers(app), { thermalMax: 999, log: { error() {} } });
|
||||||
const scheduler = new Scheduler(app, { log: { error() {} } });
|
const scheduler = new Scheduler(app, { log: { error() {} } });
|
||||||
return { tmp, db, app, id, add, inboxOk, worker, scheduler, sentMails };
|
return { tmp, db, app, id, userId, add, inboxOk, worker, scheduler, sentMails };
|
||||||
}
|
}
|
||||||
|
|
||||||
test('relance : seulement les prospects dus, sans réponse, dans le même fil, une seule fois', async () => {
|
test('relance : seulement les prospects dus, sans réponse, dans le même fil, une seule fois', async () => {
|
||||||
const s = setup();
|
const s = await setup();
|
||||||
try {
|
try {
|
||||||
const due = s.add('contact@fournil.fr', 8);
|
const due = await s.add('contact@fournil.fr', 8);
|
||||||
const tooEarly = s.add('hello@zen.fr', 3);
|
const tooEarly = await s.add('hello@zen.fr', 3);
|
||||||
const replied = s.add('jean@atelier.fr', 10, 'replied');
|
const replied = await s.add('jean@atelier.fr', 10, 'replied');
|
||||||
const blacklisted = s.add('stop@ferme.fr', 9);
|
const blacklisted = await s.add('stop@ferme.fr', 9);
|
||||||
s.db.prepare("INSERT INTO blacklist(email, reason, created_at) VALUES('stop@ferme.fr', 'unsubscribe', ?)").run(now());
|
await s.db.prepare("INSERT INTO blacklist(email, reason, created_at) VALUES('stop@ferme.fr', 'unsubscribe', ?)").run(now());
|
||||||
|
|
||||||
const plan = followupPlan(s.db, getProject(s.app, s.id), { date: new Date(WED_10H * 1000) });
|
const plan = await followupPlan(s.db, await getProject(s.app, s.id, { userId: s.userId }), { date: new Date(WED_10H * 1000) });
|
||||||
assert.deepEqual({ due: plan.due, blockers: plan.blockers }, { due: 1, blockers: [] });
|
assert.deepEqual({ due: plan.due, blockers: plan.blockers }, { due: 1, blockers: [] });
|
||||||
|
|
||||||
const queued = s.scheduler.queueFollowups({ date: new Date(WED_10H * 1000) });
|
const queued = await s.scheduler.queueFollowups({ date: new Date(WED_10H * 1000) });
|
||||||
assert.equal(queued.length, 1);
|
assert.equal(queued.length, 1);
|
||||||
await s.worker.tick();
|
await s.worker.tick();
|
||||||
const job = latestJobs(s.db, s.id).followup;
|
const job = (await latestJobs(s.db, s.id)).followup;
|
||||||
assert.equal(job.status, 'done', job.error);
|
assert.equal(job.status, 'done', job.error);
|
||||||
assert.deepEqual(job.result, { sent: 1, failed: 0, total: 1 });
|
assert.deepEqual(job.result, { sent: 1, failed: 0, total: 1 });
|
||||||
|
|
||||||
|
|
@ -90,78 +94,78 @@ test('relance : seulement les prospects dus, sans réponse, dans le même fil, u
|
||||||
assert.equal(m.inReplyTo, `<orig-${due}@codebzh.fr>`);
|
assert.equal(m.inReplyTo, `<orig-${due}@codebzh.fr>`);
|
||||||
assert.match(m.text, /Toujours partant, fournil\.fr \?/);
|
assert.match(m.text, /Toujours partant, fournil\.fr \?/);
|
||||||
assert.match(m.text, /Pour ne plus être contacté/);
|
assert.match(m.text, /Pour ne plus être contacté/);
|
||||||
const log = s.db.prepare("SELECT * FROM mail_log WHERE kind = 'followup'").all();
|
const log = await s.db.prepare("SELECT * FROM mail_log WHERE kind = 'followup'").all();
|
||||||
assert.equal(log.length, 1);
|
assert.equal(log.length, 1);
|
||||||
assert.equal(log[0].message_id, m.messageId);
|
assert.equal(log[0].message_id, m.messageId);
|
||||||
|
|
||||||
const st = (pid) => s.db.prepare('SELECT status, followup_at FROM prospects WHERE id = ?').get(pid);
|
const st = (pid) => s.db.prepare('SELECT status, followup_at FROM prospects WHERE id = ?').get(pid);
|
||||||
assert.ok(st(due).followup_at > 0);
|
assert.ok((await st(due)).followup_at > 0);
|
||||||
assert.equal(st(due).status, 'sent', 'reste "contacté" : une réponse à la relance sera détectée normalement');
|
assert.equal((await st(due)).status, 'sent', 'reste "contacté" : une réponse à la relance sera détectée normalement');
|
||||||
for (const pid of [tooEarly, replied, blacklisted]) assert.equal(st(pid).followup_at, null);
|
for (const pid of [tooEarly, replied, blacklisted]) assert.equal((await st(pid)).followup_at, null);
|
||||||
|
|
||||||
assert.equal(s.scheduler.queueFollowups({ date: new Date(WED_10H * 1000) }).length, 0, 'jamais 2 relances');
|
assert.equal((await s.scheduler.queueFollowups({ date: new Date(WED_10H * 1000) })).length, 0, 'jamais 2 relances');
|
||||||
} finally { rmSync(s.tmp, { recursive: true, force: true }); }
|
} finally { rmSync(s.tmp, { recursive: true, force: true }); }
|
||||||
});
|
});
|
||||||
|
|
||||||
test('relance bloquée : boîte en erreur, boîte pas lue récemment, week-end, désactivée, modèle non validé', () => {
|
test('relance bloquée : boîte en erreur, boîte pas lue récemment, week-end, désactivée, modèle non validé', async () => {
|
||||||
const s = setup();
|
const s = await setup();
|
||||||
try {
|
try {
|
||||||
s.add('contact@fournil.fr', 8);
|
await s.add('contact@fournil.fr', 8);
|
||||||
const plan = (o = {}) => followupPlan(s.db, getProject(s.app, s.id), o);
|
const plan = async (o = {}) => followupPlan(s.db, await getProject(s.app, s.id, { userId: s.userId }), o);
|
||||||
const sat = new Date('2026-10-24T11:00:00+02:00');
|
const sat = new Date('2026-10-24T11:00:00+02:00');
|
||||||
assert.equal(plan({ date: sat }).ready, false);
|
assert.equal((await plan({ date: sat })).ready, false);
|
||||||
assert.equal(plan({ date: sat }).inHours, false);
|
assert.equal((await plan({ date: sat })).inHours, false);
|
||||||
assert.equal(s.scheduler.queueFollowups({ date: sat }).length, 0, 'pas le week-end');
|
assert.equal((await s.scheduler.queueFollowups({ date: sat })).length, 0, 'pas le week-end');
|
||||||
|
|
||||||
s.inboxOk(now(), { lastError: 'AUTHENTICATIONFAILED' });
|
await s.inboxOk(now(), { lastError: 'AUTHENTICATIONFAILED' });
|
||||||
assert.deepEqual(plan().blockers, ['boîte non vérifiée récemment']);
|
assert.deepEqual((await plan()).blockers, ['boîte non vérifiée récemment']);
|
||||||
s.inboxOk(now() - 3 * 3600);
|
await s.inboxOk(now() - 3 * 3600);
|
||||||
assert.deepEqual(plan().blockers, ['boîte non vérifiée récemment']);
|
assert.deepEqual((await plan()).blockers, ['boîte non vérifiée récemment']);
|
||||||
s.db.prepare('UPDATE projects SET imap_enc = NULL WHERE id = ?').run(s.id);
|
await s.db.prepare('UPDATE projects SET imap_enc = NULL WHERE id = ?').run(s.id);
|
||||||
assert.deepEqual(plan().blockers, ['boîte IMAP à connecter']);
|
assert.deepEqual((await plan()).blockers, ['boîte IMAP à connecter']);
|
||||||
s.db.prepare("UPDATE templates SET status = 'draft' WHERE kind = 'followup'").run();
|
await s.db.prepare("UPDATE templates SET status = 'draft' WHERE kind = 'followup'").run();
|
||||||
s.db.prepare('UPDATE projects SET followup_enabled = 0 WHERE id = ?').run(s.id);
|
await s.db.prepare('UPDATE projects SET followup_enabled = 0 WHERE id = ?').run(s.id);
|
||||||
assert.deepEqual(plan().blockers, ['relance désactivée', 'modèle de relance à valider', 'boîte IMAP à connecter']);
|
assert.deepEqual((await plan()).blockers, ['relance désactivée', 'modèle de relance à valider', 'boîte IMAP à connecter']);
|
||||||
} finally { rmSync(s.tmp, { recursive: true, force: true }); }
|
} finally { rmSync(s.tmp, { recursive: true, force: true }); }
|
||||||
});
|
});
|
||||||
|
|
||||||
test('réponse arrivée entre la mise en file et l\'envoi : pas de relance', async () => {
|
test('réponse arrivée entre la mise en file et l\'envoi : pas de relance', async () => {
|
||||||
const s = setup();
|
const s = await setup();
|
||||||
try {
|
try {
|
||||||
const pid = s.add('contact@fournil.fr', 8);
|
const pid = await s.add('contact@fournil.fr', 8);
|
||||||
assert.equal(s.scheduler.queueFollowups({ date: new Date(WED_10H * 1000) }).length, 1);
|
assert.equal((await s.scheduler.queueFollowups({ date: new Date(WED_10H * 1000) })).length, 1);
|
||||||
s.db.prepare("UPDATE prospects SET status = 'replied' WHERE id = ?").run(pid);
|
await s.db.prepare("UPDATE prospects SET status = 'replied' WHERE id = ?").run(pid);
|
||||||
await s.worker.tick();
|
await s.worker.tick();
|
||||||
assert.equal(s.sentMails.length, 0);
|
assert.equal(s.sentMails.length, 0);
|
||||||
} finally { rmSync(s.tmp, { recursive: true, force: true }); }
|
} finally { rmSync(s.tmp, { recursive: true, force: true }); }
|
||||||
});
|
});
|
||||||
|
|
||||||
test('relance en file mais heures ouvrées dépassées : reportée, rien n\'est envoyé', async () => {
|
test('relance en file mais heures ouvrées dépassées : reportée, rien n\'est envoyé', async () => {
|
||||||
const s = setup();
|
const s = await setup();
|
||||||
try {
|
try {
|
||||||
const pid = s.add('contact@fournil.fr', 8);
|
const pid = await s.add('contact@fournil.fr', 8);
|
||||||
s.scheduler.queueFollowups({ date: new Date(WED_10H * 1000) });
|
await s.scheduler.queueFollowups({ date: new Date(WED_10H * 1000) });
|
||||||
s.app.isBusinessHours = () => false;
|
s.app.isBusinessHours = () => false;
|
||||||
await s.worker.tick();
|
await s.worker.tick();
|
||||||
assert.equal(s.sentMails.length, 0);
|
assert.equal(s.sentMails.length, 0);
|
||||||
assert.equal(latestJobs(s.db, s.id).followup.result.postponed, true);
|
assert.equal((await latestJobs(s.db, s.id)).followup.result.postponed, true);
|
||||||
assert.equal(s.db.prepare('SELECT followup_at FROM prospects WHERE id = ?').get(pid).followup_at, null, 'toujours due');
|
assert.equal((await s.db.prepare('SELECT followup_at FROM prospects WHERE id = ?').get(pid)).followup_at, null, 'toujours due');
|
||||||
s.app.isBusinessHours = () => true;
|
s.app.isBusinessHours = () => true;
|
||||||
assert.equal(s.scheduler.queueFollowups({ date: new Date(WED_10H * 1000) }).length, 1, 'reprogrammée au créneau suivant');
|
assert.equal((await s.scheduler.queueFollowups({ date: new Date(WED_10H * 1000) })).length, 1, 'reprogrammée au créneau suivant');
|
||||||
} finally { rmSync(s.tmp, { recursive: true, force: true }); }
|
} finally { rmSync(s.tmp, { recursive: true, force: true }); }
|
||||||
});
|
});
|
||||||
|
|
||||||
test('génération du modèle de relance par l\'IA', async () => {
|
test('génération du modèle de relance par l\'IA', async () => {
|
||||||
const s = setup();
|
const s = await setup();
|
||||||
try {
|
try {
|
||||||
s.db.prepare('UPDATE projects SET profile_json = ? WHERE id = ?').run(JSON.stringify({ resume: 'x', proposition_valeur: 'y' }), s.id);
|
await s.db.prepare('UPDATE projects SET profile_json = ? WHERE id = ?').run(JSON.stringify({ resume: 'x', proposition_valeur: 'y' }), s.id);
|
||||||
s.db.prepare("DELETE FROM templates WHERE kind = 'followup'").run();
|
await s.db.prepare("DELETE FROM templates WHERE kind = 'followup'").run();
|
||||||
const { enqueue } = await import('../src/services/jobs.js');
|
const { enqueue } = await import('../src/services/jobs.js');
|
||||||
enqueue(s.db, { projectId: s.id, type: 'followup_template' });
|
await enqueue(s.db, { userId: s.userId, projectId: s.id, type: 'followup_template' });
|
||||||
await s.worker.tick();
|
await s.worker.tick();
|
||||||
const job = latestJobs(s.db, s.id).followup_template;
|
const job = (await latestJobs(s.db, s.id)).followup_template;
|
||||||
assert.equal(job.status, 'done', job.error);
|
assert.equal(job.status, 'done', job.error);
|
||||||
const t = s.db.prepare("SELECT * FROM templates WHERE kind = 'followup'").get();
|
const t = await s.db.prepare("SELECT * FROM templates WHERE kind = 'followup'").get();
|
||||||
assert.equal(t.status, 'draft');
|
assert.equal(t.status, 'draft');
|
||||||
assert.equal(t.subject, '');
|
assert.equal(t.subject, '');
|
||||||
assert.match(t.body, /relance/i);
|
assert.match(t.body, /relance/i);
|
||||||
|
|
|
||||||
|
|
@ -1,11 +1,12 @@
|
||||||
import { test } from 'node:test';
|
import { test } from 'node:test';
|
||||||
import assert from 'node:assert/strict';
|
import assert from 'node:assert/strict';
|
||||||
import { execFileSync } from 'node:child_process';
|
import { execFileSync } from 'node:child_process';
|
||||||
import { mkdtempSync, writeFileSync, readFileSync, rmSync } from 'node:fs';
|
import { mkdtempSync, writeFileSync, readFileSync, rmSync, existsSync } from 'node:fs';
|
||||||
import { tmpdir } from 'node:os';
|
import { tmpdir } from 'node:os';
|
||||||
import { join, resolve } from 'node:path';
|
import { join, resolve } from 'node:path';
|
||||||
import { randomBytes } from 'node:crypto';
|
import { randomBytes } from 'node:crypto';
|
||||||
import { openDb, setSetting, getSetting, now } from '../src/db.js';
|
import { setSetting, getSetting, now } from '../src/db.js';
|
||||||
|
import { testDb } from './helpers/db.js';
|
||||||
import { Worker, enqueue, latestJobs } from '../src/services/jobs.js';
|
import { Worker, enqueue, latestJobs } from '../src/services/jobs.js';
|
||||||
import { makeHandlers, parseProspectLine } from '../src/handlers.js';
|
import { makeHandlers, parseProspectLine } from '../src/handlers.js';
|
||||||
import { createProject, saveSecretConfig, getProject, prospectStats, pickVariant } from '../src/projects.js';
|
import { createProject, saveSecretConfig, getProject, prospectStats, pickVariant } from '../src/projects.js';
|
||||||
|
|
@ -13,8 +14,10 @@ import { allowedToSend, buildProspectMail, fillTemplate } from '../src/services/
|
||||||
import { validateSelect, firstValue } from '../src/services/recap.js';
|
import { validateSelect, firstValue } from '../src/services/recap.js';
|
||||||
import { validateGitUrl } from '../src/services/git.js';
|
import { validateGitUrl } from '../src/services/git.js';
|
||||||
import { verifyUnsubToken, encrypt } from '../src/crypto.js';
|
import { verifyUnsubToken, encrypt } from '../src/crypto.js';
|
||||||
|
import { addUser } from './helpers/users.js';
|
||||||
|
import { makeClaudeBin } from './helpers/claude-bin.js';
|
||||||
|
|
||||||
function setup() {
|
async function setup() {
|
||||||
const tmp = mkdtempSync(join(tmpdir(), 'aitools-'));
|
const tmp = mkdtempSync(join(tmpdir(), 'aitools-'));
|
||||||
const src = join(tmp, 'src-repo');
|
const src = join(tmp, 'src-repo');
|
||||||
execFileSync('git', ['init', '-q', '-b', 'main', src]);
|
execFileSync('git', ['init', '-q', '-b', 'main', src]);
|
||||||
|
|
@ -22,56 +25,63 @@ function setup() {
|
||||||
execFileSync('git', ['-C', src, '-c', 'user.name=t', '-c', 'user.email=t@t', 'commit', '-qam', 'init', '--allow-empty']);
|
execFileSync('git', ['-C', src, '-c', 'user.name=t', '-c', 'user.email=t@t', 'commit', '-qam', 'init', '--allow-empty']);
|
||||||
execFileSync('git', ['-C', src, 'add', '.']);
|
execFileSync('git', ['-C', src, 'add', '.']);
|
||||||
execFileSync('git', ['-C', src, '-c', 'user.name=t', '-c', 'user.email=t@t', 'commit', '-qm', 'readme']);
|
execFileSync('git', ['-C', src, '-c', 'user.name=t', '-c', 'user.email=t@t', 'commit', '-qm', 'readme']);
|
||||||
const db = openDb(':memory:');
|
const db = await testDb();
|
||||||
const sentMails = [];
|
const sentMails = [];
|
||||||
const app = {
|
const app = {
|
||||||
db,
|
db,
|
||||||
cfg: { dataDir: tmp, claudeBin: resolve('test/fixtures/fake-claude.js'), secretKey: randomBytes(32), appUrl: 'https://ai.test' },
|
cfg: { dataDir: tmp, claudeBin: resolve('test/fixtures/fake-claude.js'), sandbox: { enabled: false, production: false }, secretKey: randomBytes(32), appUrl: 'https://ai.test' },
|
||||||
|
// syncRepo refuse file:// (clones d'URL fournies par l'utilisateur : https seulement) : le test clone le dépôt local à la place
|
||||||
|
syncRepo: async (url, dir) => {
|
||||||
|
if (existsSync(join(dir, '.git'))) execFileSync('git', ['-C', dir, 'pull', '-q']);
|
||||||
|
else execFileSync('git', ['clone', '-q', '--depth', '1', url, dir]);
|
||||||
|
return execFileSync('git', ['-C', dir, 'rev-parse', 'HEAD']).toString().trim();
|
||||||
|
},
|
||||||
createTransport: () => ({ verify: async () => true, sendMail: async (m) => { sentMails.push(m); }, close() {} }),
|
createTransport: () => ({ verify: async () => true, sendMail: async (m) => { sentMails.push(m); }, close() {} }),
|
||||||
};
|
};
|
||||||
setSetting(db, 'send_delay_min', '0');
|
const userId = await addUser(db);
|
||||||
setSetting(db, 'send_delay_max', '0');
|
await setSetting(db, userId, 'send_delay_min', '0');
|
||||||
const id = createProject(app, { name: 'MonEspacePro', gitUrl: `file://${src}` });
|
await setSetting(db, userId, 'send_delay_max', '0');
|
||||||
|
const id = await createProject(app, { userId, name: 'MonEspacePro', gitUrl: `file://${src}` });
|
||||||
const worker = new Worker(db, makeHandlers(app), { thermalMax: 999, log: { error: (...a) => console.error(...a) } });
|
const worker = new Worker(db, makeHandlers(app), { thermalMax: 999, log: { error: (...a) => console.error(...a) } });
|
||||||
return { tmp, db, app, id, worker, sentMails };
|
return { tmp, db, app, id, userId, worker, sentMails };
|
||||||
}
|
}
|
||||||
|
|
||||||
const run = async (s, type, params) => { enqueue(s.db, { projectId: s.id, type, params }); await s.worker.tick(); return latestJobs(s.db, s.id)[type]; };
|
const run = async (s, type, params) => { await enqueue(s.db, { userId: s.userId, projectId: s.id, type, params }); await s.worker.tick(); return (await latestJobs(s.db, s.id))[type]; };
|
||||||
|
|
||||||
test('flux complet : analyse → cible → prospection → modèle → envoi → évolution', async () => {
|
test('flux complet : analyse → cible → prospection → modèle → envoi → évolution', async () => {
|
||||||
const s = setup();
|
const s = await setup();
|
||||||
try {
|
try {
|
||||||
const a = await run(s, 'analyze');
|
const a = await run(s, 'analyze');
|
||||||
assert.equal(a.status, 'done', a.error);
|
assert.equal(a.status, 'done', a.error);
|
||||||
let p = getProject(s.app, s.id);
|
let p = await getProject(s.app, s.id, { userId: s.userId });
|
||||||
assert.equal(p.profile.resume, 'Cartes de fidélité digitales.');
|
assert.equal(p.profile.resume, 'Cartes de fidélité digitales.');
|
||||||
assert.equal(p.target.zone, 'Bretagne');
|
assert.equal(p.target.zone, 'Bretagne');
|
||||||
assert.equal(p.targetValidated, false);
|
assert.equal(p.targetValidated, false);
|
||||||
assert.match(p.profileCommit, /^[0-9a-f]{40}$/);
|
assert.match(p.profileCommit, /^[0-9a-f]{40}$/);
|
||||||
const rl = JSON.parse(getSetting(s.db, 'claude_rate_limit_json'));
|
const rl = JSON.parse(await getSetting(s.db, s.userId, 'claude_rate_limit_json'));
|
||||||
assert.equal(rl.fiveHour.utilization, 0.33, 'quota Claude (session) enregistré après l\'appel');
|
assert.equal(rl.fiveHour.utilization, 0.33, 'quota Claude (session) enregistré après l\'appel');
|
||||||
assert.equal(rl.sevenDay.utilization, 0.5, 'quota Claude (semaine) enregistré après l\'appel');
|
assert.equal(rl.sevenDay.utilization, 0.5, 'quota Claude (semaine) enregistré après l\'appel');
|
||||||
|
|
||||||
const refused = await run(s, 'prospect', { count: 3 });
|
const refused = await run(s, 'prospect', { count: 3 });
|
||||||
assert.match(refused.error, /Valide la cible/);
|
assert.match(refused.error, /Valide la cible/);
|
||||||
|
|
||||||
s.db.prepare('UPDATE projects SET target_validated = 1 WHERE id = ?').run(s.id);
|
await s.db.prepare('UPDATE projects SET target_validated = 1 WHERE id = ?').run(s.id);
|
||||||
s.db.prepare("INSERT INTO blacklist(email, created_at) VALUES('hello@zen.fr', ?)").run(now());
|
await s.db.prepare("INSERT INTO blacklist(email, created_at) VALUES('hello@zen.fr', ?)").run(now());
|
||||||
const pr = await run(s, 'prospect', { count: 3 });
|
const pr = await run(s, 'prospect', { count: 3 });
|
||||||
assert.equal(pr.status, 'done', pr.error);
|
assert.equal(pr.status, 'done', pr.error);
|
||||||
assert.equal(pr.result.found, 1, 'email invalide rejeté + blacklisté ignoré');
|
assert.equal(pr.result.found, 1, 'email invalide rejeté + blacklisté ignoré');
|
||||||
assert.equal(prospectStats(s.db, s.id).new, 1);
|
assert.equal((await prospectStats(s.db, s.id)).new, 1);
|
||||||
|
|
||||||
const t = await run(s, 'template');
|
const t = await run(s, 'template');
|
||||||
assert.equal(t.status, 'done', t.error);
|
assert.equal(t.status, 'done', t.error);
|
||||||
const noValid = await run(s, 'send', { count: 5 });
|
const noValid = await run(s, 'send', { count: 5 });
|
||||||
assert.match(noValid.error, /non validé/);
|
assert.match(noValid.error, /non validé/);
|
||||||
|
|
||||||
s.db.prepare("UPDATE templates SET status = 'validated' WHERE project_id = ? AND kind = 'initial'").run(s.id);
|
await s.db.prepare("UPDATE templates SET status = 'validated' WHERE project_id = ? AND kind = 'initial'").run(s.id);
|
||||||
const noSmtp = await run(s, 'send', { count: 5 });
|
const noSmtp = await run(s, 'send', { count: 5 });
|
||||||
assert.match(noSmtp.error, /SMTP/);
|
assert.match(noSmtp.error, /SMTP/);
|
||||||
|
|
||||||
saveSecretConfig(s.app, s.id, 'smtp_enc', { host: 'smtp.x', port: 587, user: 'u', pass: 'secret', fromEmail: 'tony@x.fr', fromName: 'Tony' }, 'pass');
|
await saveSecretConfig(s.app, s.id, 'smtp_enc', { host: 'smtp.x', port: 587, user: 'u', pass: 'secret', fromEmail: 'tony@x.fr', fromName: 'Tony' }, 'pass');
|
||||||
const sent = await run(s, 'send', { count: 5 });
|
const sent = await run(s, 'send', { count: 5 });
|
||||||
assert.equal(sent.status, 'done', sent.error);
|
assert.equal(sent.status, 'done', sent.error);
|
||||||
assert.deepEqual(sent.result, { sent: 1, failed: 0, total: 1 });
|
assert.deepEqual(sent.result, { sent: 1, failed: 0, total: 1 });
|
||||||
|
|
@ -84,14 +94,14 @@ test('flux complet : analyse → cible → prospection → modèle → envoi →
|
||||||
assert.match(mail.html, /Ne plus recevoir de messages/);
|
assert.match(mail.html, /Ne plus recevoir de messages/);
|
||||||
const unsub = /\/u\/([^/]+)\/(\S+)/.exec(mail.headers['List-Unsubscribe']);
|
const unsub = /\/u\/([^/]+)\/(\S+)/.exec(mail.headers['List-Unsubscribe']);
|
||||||
assert.ok(verifyUnsubToken(s.app.cfg.secretKey, decodeURIComponent(unsub[1]), unsub[2].replace('>', '')));
|
assert.ok(verifyUnsubToken(s.app.cfg.secretKey, decodeURIComponent(unsub[1]), unsub[2].replace('>', '')));
|
||||||
assert.equal(prospectStats(s.db, s.id).sent, 1);
|
assert.equal((await prospectStats(s.db, s.id)).sent, 1);
|
||||||
|
|
||||||
const again = await run(s, 'send', { count: 5 });
|
const again = await run(s, 'send', { count: 5 });
|
||||||
assert.match(again.error, /aucun prospect/, 'jamais 2 fois le même prospect');
|
assert.match(again.error, /aucun prospect/, 'jamais 2 fois le même prospect');
|
||||||
|
|
||||||
const ev1 = await run(s, 'evolution', { count: 3, level: 'rapide' });
|
const ev1 = await run(s, 'evolution', { count: 3, level: 'rapide' });
|
||||||
assert.match(ev1.error, /Adresse de réception/);
|
assert.match(ev1.error, /Adresse de réception/);
|
||||||
setSetting(s.db, 'notify_email', 'moi@x.fr');
|
await setSetting(s.db, s.userId, 'notify_email', 'moi@x.fr');
|
||||||
const ev = await run(s, 'evolution', { count: 3, level: 'rapide' });
|
const ev = await run(s, 'evolution', { count: 3, level: 'rapide' });
|
||||||
assert.equal(ev.status, 'done', ev.error);
|
assert.equal(ev.status, 'done', ev.error);
|
||||||
assert.equal(s.sentMails.at(-1).to, 'moi@x.fr');
|
assert.equal(s.sentMails.at(-1).to, 'moi@x.fr');
|
||||||
|
|
@ -100,7 +110,7 @@ test('flux complet : analyse → cible → prospection → modèle → envoi →
|
||||||
assert.match(s.sentMails.at(-1).html, /Export CSV/);
|
assert.match(s.sentMails.at(-1).html, /Export CSV/);
|
||||||
assert.equal(ev.progress.pct, 95, 'avancement remonté jusqu\'au mail');
|
assert.equal(ev.progress.pct, 95, 'avancement remonté jusqu\'au mail');
|
||||||
|
|
||||||
const usage = s.db.prepare('SELECT SUM(cost_usd) c FROM jobs').get().c;
|
const usage = (await s.db.prepare('SELECT SUM(cost_usd) c FROM jobs').get()).c;
|
||||||
assert.ok(usage > 0);
|
assert.ok(usage > 0);
|
||||||
} finally { rmSync(s.tmp, { recursive: true, force: true }); }
|
} finally { rmSync(s.tmp, { recursive: true, force: true }); }
|
||||||
});
|
});
|
||||||
|
|
@ -164,18 +174,18 @@ test('URL Git Forgejo', () => {
|
||||||
});
|
});
|
||||||
|
|
||||||
test('envoi : Message-ID journalisé et objets A/B alternés équitablement', async () => {
|
test('envoi : Message-ID journalisé et objets A/B alternés équitablement', async () => {
|
||||||
const s = setup();
|
const s = await setup();
|
||||||
try {
|
try {
|
||||||
saveSecretConfig(s.app, s.id, 'smtp_enc', { host: 'smtp.x', port: 587, user: 'u', pass: 'p', fromEmail: 'tony@codebzh.fr' }, 'pass');
|
await saveSecretConfig(s.app, s.id, 'smtp_enc', { host: 'smtp.x', port: 587, user: 'u', pass: 'p', fromEmail: 'tony@codebzh.fr' }, 'pass');
|
||||||
s.db.prepare(`INSERT INTO templates(project_id, kind, subject, subject_b, body, status, updated_at)
|
await s.db.prepare(`INSERT INTO templates(project_id, kind, subject, subject_b, body, status, updated_at)
|
||||||
VALUES(?, 'initial', 'Objet A {{entreprise}}', 'Objet B {{entreprise}}', 'Bonjour', 'validated', ?)`).run(s.id, now());
|
VALUES(?, 'initial', 'Objet A {{entreprise}}', 'Objet B {{entreprise}}', 'Bonjour', 'validated', ?)`).run(s.id, now());
|
||||||
for (const n of [1, 2, 3, 4]) {
|
for (const n of [1, 2, 3, 4]) {
|
||||||
s.db.prepare("INSERT INTO prospects(project_id, company, email, score, created_at) VALUES(?, ?, ?, ?, ?)").run(s.id, `Ent${n}`, `c${n}@ent${n}.fr`, 10 - n, now());
|
await s.db.prepare("INSERT INTO prospects(project_id, company, email, score, created_at) VALUES(?, ?, ?, ?, ?)").run(s.id, `Ent${n}`, `c${n}@ent${n}.fr`, 10 - n, now());
|
||||||
}
|
}
|
||||||
const job = await run(s, 'send', { count: 4 });
|
const job = await run(s, 'send', { count: 4 });
|
||||||
assert.equal(job.status, 'done', job.error);
|
assert.equal(job.status, 'done', job.error);
|
||||||
assert.deepEqual(s.sentMails.map((m) => m.subject), ['Objet A Ent1', 'Objet B Ent2', 'Objet A Ent3', 'Objet B Ent4']);
|
assert.deepEqual(s.sentMails.map((m) => m.subject), ['Objet A Ent1', 'Objet B Ent2', 'Objet A Ent3', 'Objet B Ent4']);
|
||||||
const logs = s.db.prepare("SELECT * FROM mail_log WHERE kind = 'initial' ORDER BY id").all();
|
const logs = await s.db.prepare("SELECT * FROM mail_log WHERE kind = 'initial' ORDER BY id").all();
|
||||||
assert.equal(logs.length, 4);
|
assert.equal(logs.length, 4);
|
||||||
for (const [i, l] of logs.entries()) {
|
for (const [i, l] of logs.entries()) {
|
||||||
assert.equal(l.message_id, s.sentMails[i].messageId);
|
assert.equal(l.message_id, s.sentMails[i].messageId);
|
||||||
|
|
@ -183,43 +193,42 @@ test('envoi : Message-ID journalisé et objets A/B alternés équitablement', as
|
||||||
assert.equal(l.subject, s.sentMails[i].subject);
|
assert.equal(l.subject, s.sentMails[i].subject);
|
||||||
}
|
}
|
||||||
assert.equal(new Set(logs.map((l) => l.message_id)).size, 4, 'Message-ID uniques');
|
assert.equal(new Set(logs.map((l) => l.message_id)).size, 4, 'Message-ID uniques');
|
||||||
assert.deepEqual(s.db.prepare('SELECT variant FROM prospects ORDER BY id').all().map((r) => r.variant), ['A', 'B', 'A', 'B']);
|
assert.deepEqual((await s.db.prepare('SELECT variant FROM prospects ORDER BY id').all()).map((r) => r.variant), ['A', 'B', 'A', 'B']);
|
||||||
} finally { rmSync(s.tmp, { recursive: true, force: true }); }
|
} finally { rmSync(s.tmp, { recursive: true, force: true }); }
|
||||||
});
|
});
|
||||||
|
|
||||||
test('sans objet B : tout part en A', () => {
|
test('sans objet B : tout part en A', async () => {
|
||||||
const db = openDb(':memory:');
|
const db = await testDb();
|
||||||
assert.equal(pickVariant(db, 1, { subject_b: null }), 'A');
|
assert.equal(await pickVariant(db, 1, { subject_b: null }), 'A');
|
||||||
assert.equal(pickVariant(db, 1, { subject_b: '' }), 'A');
|
assert.equal(await pickVariant(db, 1, { subject_b: '' }), 'A');
|
||||||
});
|
});
|
||||||
|
|
||||||
test('analyse : modèle économique (Haiku) par défaut, Sonnet uniquement sur demande', async () => {
|
test('analyse : modèle économique (Haiku) par défaut, Sonnet uniquement sur demande', async () => {
|
||||||
const s = setup();
|
const s = await setup();
|
||||||
const spyFile = join(s.tmp, 'models.log');
|
const spyFile = join(s.tmp, 'models.log');
|
||||||
s.app.cfg.claudeBin = resolve('test/fixtures/spy-claude.js');
|
s.app.cfg.claudeBin = makeClaudeBin(s.tmp, { fixture: 'spy-claude.js', env: { MODEL_SPY_FILE: spyFile } });
|
||||||
process.env.MODEL_SPY_FILE = spyFile;
|
|
||||||
try {
|
try {
|
||||||
const a = await run(s, 'analyze');
|
const a = await run(s, 'analyze');
|
||||||
assert.equal(a.status, 'done', a.error);
|
assert.equal(a.status, 'done', a.error);
|
||||||
setSetting(s.db, 'analyze_model', 'sonnet');
|
await setSetting(s.db, s.userId, 'analyze_model', 'sonnet');
|
||||||
const a2 = await run(s, 'analyze');
|
const a2 = await run(s, 'analyze');
|
||||||
assert.equal(a2.status, 'done', a2.error);
|
assert.equal(a2.status, 'done', a2.error);
|
||||||
assert.deepEqual(readFileSync(spyFile, 'utf8').trim().split('\n'), ['haiku', 'sonnet']);
|
assert.deepEqual(readFileSync(spyFile, 'utf8').trim().split('\n'), ['haiku', 'sonnet']);
|
||||||
} finally { delete process.env.MODEL_SPY_FILE; rmSync(s.tmp, { recursive: true, force: true }); }
|
} finally { rmSync(s.tmp, { recursive: true, force: true }); }
|
||||||
});
|
});
|
||||||
|
|
||||||
test('quota Claude serré : alerte Discord à 80 %, pas en dessous', async () => {
|
test('quota Claude serré : alerte Discord à 80 %, pas en dessous', async () => {
|
||||||
const s = setup();
|
const s = await setup();
|
||||||
const sent = [];
|
const sent = [];
|
||||||
s.app.fetch = async (url, opts) => { sent.push({ url, body: JSON.parse(opts.body) }); return { ok: true, status: 204 }; };
|
s.app.fetch = async (url, opts) => { sent.push({ url, body: JSON.parse(opts.body) }); return { ok: true, status: 204 }; };
|
||||||
const hook = 'https://discord.com/api/webhooks/123456789012345678/abcdefghijklmnopqrstuvwxyz-ABC_123';
|
const hook = 'https://discord.com/api/webhooks/123456789012345678/abcdefghijklmnopqrstuvwxyz-ABC_123';
|
||||||
setSetting(s.db, 'discord_webhook_enc', encrypt(s.app.cfg.secretKey, hook));
|
await setSetting(s.db, s.userId, 'discord_webhook_enc', encrypt(s.app.cfg.secretKey, hook));
|
||||||
try {
|
try {
|
||||||
const a = await run(s, 'analyze'); // fake-claude : 33 % / 50 % par défaut
|
const a = await run(s, 'analyze'); // fake-claude : 33 % / 50 % par défaut
|
||||||
assert.equal(a.status, 'done', a.error);
|
assert.equal(a.status, 'done', a.error);
|
||||||
assert.equal(sent.length, 0, 'sous le seuil : pas d\'alerte');
|
assert.equal(sent.length, 0, 'sous le seuil : pas d\'alerte');
|
||||||
|
|
||||||
process.env.FAKE_FIVE_HOUR = '0.84';
|
s.app.cfg.claudeBin = makeClaudeBin(s.tmp, { env: { FAKE_FIVE_HOUR: '0.84' } });
|
||||||
const a2 = await run(s, 'analyze');
|
const a2 = await run(s, 'analyze');
|
||||||
assert.equal(a2.status, 'done', a2.error);
|
assert.equal(a2.status, 'done', a2.error);
|
||||||
assert.equal(sent.length, 1);
|
assert.equal(sent.length, 1);
|
||||||
|
|
@ -230,5 +239,5 @@ test('quota Claude serré : alerte Discord à 80 %, pas en dessous', async () =>
|
||||||
const a3 = await run(s, 'analyze');
|
const a3 = await run(s, 'analyze');
|
||||||
assert.equal(a3.status, 'done', a3.error);
|
assert.equal(a3.status, 'done', a3.error);
|
||||||
assert.equal(sent.length, 1);
|
assert.equal(sent.length, 1);
|
||||||
} finally { delete process.env.FAKE_FIVE_HOUR; rmSync(s.tmp, { recursive: true, force: true }); }
|
} finally { rmSync(s.tmp, { recursive: true, force: true }); }
|
||||||
});
|
});
|
||||||
|
|
|
||||||
19
test/helpers/claude-bin.js
Normal file
19
test/helpers/claude-bin.js
Normal file
|
|
@ -0,0 +1,19 @@
|
||||||
|
// Faux exécutable `claude` pour un test : script sh qui fixe des variables d'environnement puis lance une fixture.
|
||||||
|
// Nécessaire parce que l'environnement du processus enfant est assaini (liste blanche) : un test ne peut plus
|
||||||
|
// piloter la fixture en modifiant process.env.
|
||||||
|
import { chmodSync, writeFileSync } from 'node:fs';
|
||||||
|
import { join, resolve } from 'node:path';
|
||||||
|
|
||||||
|
const posix = (p) => p.split('\\').join('/');
|
||||||
|
const q = (s) => `'${String(s).split("'").join("'\\''")}'`;
|
||||||
|
|
||||||
|
/** @returns {string} chemin du script ; `fixture` : nom dans test/fixtures, `env` : variables à fixer */
|
||||||
|
export function makeClaudeBin(dir, { fixture = 'fake-claude.js', env = {}, name = 'claude-test', logVars = [], logFile } = {}) {
|
||||||
|
const file = join(dir, name);
|
||||||
|
const vars = Object.entries(env).map(([k, v]) => `${k}=${q(v)}`).join(' ');
|
||||||
|
// logVars : variables reçues par le processus, ajoutées (une ligne par appel) à logFile avant de lancer la fixture
|
||||||
|
const log = logVars.length ? `echo "${logVars.map((v) => '${' + v + '}').join(' ')}" >> ${q(posix(logFile))}\n` : '';
|
||||||
|
writeFileSync(file, `#!/bin/sh\n${log}${vars} exec ${q(posix(process.execPath))} ${q(posix(resolve('test/fixtures', fixture)))} "$@"\n`);
|
||||||
|
chmodSync(file, 0o755);
|
||||||
|
return file;
|
||||||
|
}
|
||||||
37
test/helpers/db.js
Normal file
37
test/helpers/db.js
Normal file
|
|
@ -0,0 +1,37 @@
|
||||||
|
// Base de test : SQLite en mémoire par défaut ; si TEST_DB_HOST est défini, le même test tourne
|
||||||
|
// contre un vrai MySQL/MariaDB (TEST_DB_PORT, TEST_DB_USER, TEST_DB_PASSWORD, TEST_DB_NAME).
|
||||||
|
// ATTENTION : toutes les tables de cette base sont supprimées à chaque ouverture. Utiliser une base
|
||||||
|
// dédiée aux tests, et lancer avec --test-concurrency=1 (npm run test:mysql) : les fichiers de test
|
||||||
|
// partagent la même base.
|
||||||
|
import { after } from 'node:test';
|
||||||
|
import { openDb, dbConfigFromEnv } from '../../src/db.js';
|
||||||
|
|
||||||
|
export const USING_MYSQL = !!process.env.TEST_DB_HOST;
|
||||||
|
|
||||||
|
const opened = [];
|
||||||
|
if (USING_MYSQL) after(() => Promise.all(opened.map((d) => d.close().catch(() => {}))));
|
||||||
|
|
||||||
|
async function wipe(db) {
|
||||||
|
const tables = (await db.query('SHOW TABLES')).map((r) => Object.values(r)[0]);
|
||||||
|
await db.transaction(async (tx) => {
|
||||||
|
await tx.query('SET FOREIGN_KEY_CHECKS = 0');
|
||||||
|
for (const t of tables) await tx.query(`DROP TABLE IF EXISTS \`${t}\``);
|
||||||
|
await tx.query('SET FOREIGN_KEY_CHECKS = 1');
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function testDbConfig() {
|
||||||
|
return dbConfigFromEnv(process.env, 'TEST_DB_');
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Base vide, schéma migré. `opts` : { upTo, adminEmails } (voir openDb), pour tester les migrations. */
|
||||||
|
export async function testDb(opts = {}) {
|
||||||
|
if (!USING_MYSQL) return openDb(':memory:', opts);
|
||||||
|
const cfg = { ...testDbConfig(), connectionLimit: 4 };
|
||||||
|
const raw = await openDb(cfg, { upTo: 0 });
|
||||||
|
await wipe(raw);
|
||||||
|
await raw.close();
|
||||||
|
const db = await openDb(cfg, opts);
|
||||||
|
opened.push(db);
|
||||||
|
return db;
|
||||||
|
}
|
||||||
29
test/helpers/oidc.js
Normal file
29
test/helpers/oidc.js
Normal file
|
|
@ -0,0 +1,29 @@
|
||||||
|
// Faux fournisseur OIDC (Google / Apple) : clés RSA pour les id_token, clé EC pour le secret client Apple.
|
||||||
|
import { generateKeyPairSync, sign } from 'node:crypto';
|
||||||
|
|
||||||
|
const b64 = (o) => Buffer.from(JSON.stringify(o)).toString('base64url');
|
||||||
|
|
||||||
|
export function makeProvider() {
|
||||||
|
const rsa = generateKeyPairSync('rsa', { modulusLength: 2048 });
|
||||||
|
const other = generateKeyPairSync('rsa', { modulusLength: 2048 }); // clé d'un faussaire
|
||||||
|
const jwk = { ...rsa.publicKey.export({ format: 'jwk' }), kid: 'k1', alg: 'RS256', use: 'sig' };
|
||||||
|
const ec = generateKeyPairSync('ec', { namedCurve: 'P-256' });
|
||||||
|
|
||||||
|
/** id_token signé. `claims` complète/écrase les valeurs par défaut ; `opts` choisit clé, kid et algorithme. */
|
||||||
|
function idToken(claims, { key = rsa.privateKey, kid = 'k1', alg = 'RS256' } = {}) {
|
||||||
|
const head = b64({ alg, kid, typ: 'JWT' });
|
||||||
|
const body = b64(claims);
|
||||||
|
if (alg === 'none') return `${head}.${body}.`;
|
||||||
|
const sig = sign('RSA-SHA256', Buffer.from(`${head}.${body}`), key);
|
||||||
|
return `${head}.${body}.${sig.toString('base64url')}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
jwk, idToken, forgerKey: other.privateKey,
|
||||||
|
apple: {
|
||||||
|
teamId: 'TEAM123456', keyId: 'KEY1234567', clientId: 'dev.tony.aitools.web',
|
||||||
|
privateKey: ec.privateKey.export({ type: 'pkcs8', format: 'pem' }),
|
||||||
|
publicKey: ec.publicKey,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
51
test/helpers/server.js
Normal file
51
test/helpers/server.js
Normal file
|
|
@ -0,0 +1,51 @@
|
||||||
|
// Serveur HTTP de test : vraie application sur un port libre, base de test, comptes créés à la demande.
|
||||||
|
import { randomBytes } from 'node:crypto';
|
||||||
|
import { mkdtempSync, rmSync } from 'node:fs';
|
||||||
|
import { tmpdir } from 'node:os';
|
||||||
|
import { join } from 'node:path';
|
||||||
|
import { now } from '../../src/db.js';
|
||||||
|
import { createApp } from '../../src/server.js';
|
||||||
|
import { testDb } from './db.js';
|
||||||
|
import { addUser } from './users.js';
|
||||||
|
|
||||||
|
export const APP_URL = 'https://ai.tony-averty.dev';
|
||||||
|
|
||||||
|
export async function startApp({ cfg = {}, worker = false } = {}) {
|
||||||
|
const tmp = mkdtempSync(join(tmpdir(), 'aitools-srv-'));
|
||||||
|
const config = {
|
||||||
|
appUrl: APP_URL, google: { clientId: 'gid', clientSecret: 'gsecret' }, apple: null, adminEmails: [],
|
||||||
|
secretKey: randomBytes(32), dataDir: tmp, claudeBin: 'claude', thermalMax: 75, cliModeEnabled: true,
|
||||||
|
sandbox: { enabled: false, production: false, roBinds: [], serverHome: tmp }, ...cfg,
|
||||||
|
};
|
||||||
|
const app = await createApp(config, { db: await testDb(), worker });
|
||||||
|
await new Promise((r) => app.server.listen(0, '127.0.0.1', r));
|
||||||
|
const base = `http://127.0.0.1:${app.server.address().port}`;
|
||||||
|
|
||||||
|
/** Requêtes avec la session d'un cookie (ou sans). */
|
||||||
|
const client = (cookie) => ({
|
||||||
|
get: (p, opts = {}) => fetch(base + p, { redirect: 'manual', headers: { ...(cookie ? { cookie } : {}), accept: 'application/json', ...opts.headers } }),
|
||||||
|
post: (p, body = {}, { origin = APP_URL, form = false } = {}) => fetch(base + p, {
|
||||||
|
method: 'POST', redirect: 'manual',
|
||||||
|
headers: {
|
||||||
|
...(cookie ? { cookie } : {}), ...(origin ? { origin } : {}), accept: 'application/json',
|
||||||
|
'content-type': form ? 'application/x-www-form-urlencoded' : 'application/json',
|
||||||
|
},
|
||||||
|
body: form ? new URLSearchParams(body).toString() : JSON.stringify(body),
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
/** Crée un compte avec une session ouverte. */
|
||||||
|
let n = 0;
|
||||||
|
const newUser = async (opts = {}) => {
|
||||||
|
n++;
|
||||||
|
const email = opts.email || `user${n}@test.fr`;
|
||||||
|
const id = await addUser(app.db, { ...opts, email });
|
||||||
|
const sid = `sess-${id}-${n}`;
|
||||||
|
await app.db.prepare('INSERT INTO sessions(id, user_id, created_at, expires_at) VALUES(?, ?, ?, ?)').run(sid, id, now(), now() + 3600);
|
||||||
|
const cookie = `sid=${sid}`;
|
||||||
|
return { id, email, cookie, ...client(cookie) };
|
||||||
|
};
|
||||||
|
|
||||||
|
const close = async () => { await app.close(); rmSync(tmp, { recursive: true, force: true }); };
|
||||||
|
return { app, db: app.db, base, tmp, client, newUser, close, anon: client(null) };
|
||||||
|
}
|
||||||
22
test/helpers/users.js
Normal file
22
test/helpers/users.js
Normal file
|
|
@ -0,0 +1,22 @@
|
||||||
|
// Comptes de test
|
||||||
|
let seq = 0;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Crée un compte et renvoie son id. Admin et actif par défaut, avec la liaison « Claude du serveur » (les tests historiques
|
||||||
|
* lancent des jobs IA). `link` : null = aucune liaison, ou un objet claude_link_json complet.
|
||||||
|
*/
|
||||||
|
export async function addUser(db, { email, admin = true, status = 'active', provider = 'google', sub, name = null, link } = {}) {
|
||||||
|
seq++;
|
||||||
|
const linkJson = link === undefined ? (admin ? { v: 1, mode: 'server', valid: true, linked_at: 1_700_000_000, validated_at: 1_700_000_000 } : null) : link;
|
||||||
|
const r = await db.prepare(`INSERT INTO users(email, name, provider, provider_sub, status, is_admin, plan, created_at, claude_link_json)
|
||||||
|
VALUES(?, ?, ?, ?, ?, ?, 'free', ?, ?)`).run(email || `user${seq}@test.fr`, name, provider, sub || `sub-${seq}`, status, admin ? 1 : 0, 1_700_000_000, linkJson ? JSON.stringify(linkJson) : null);
|
||||||
|
return Number(r.lastInsertRowid);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Projet minimal d'un utilisateur. */
|
||||||
|
export async function addProject(db, userId, { name = 'p', gitUrl } = {}) {
|
||||||
|
seq++;
|
||||||
|
const r = await db.prepare('INSERT INTO projects(user_id, name, git_url, created_at) VALUES(?, ?, ?, ?)')
|
||||||
|
.run(userId, name, gitUrl || `https://git.test/u/${seq}.git`, 1_700_000_000);
|
||||||
|
return Number(r.lastInsertRowid);
|
||||||
|
}
|
||||||
|
|
@ -4,23 +4,26 @@ import { randomBytes } from 'node:crypto';
|
||||||
import { mkdtempSync, rmSync } from 'node:fs';
|
import { mkdtempSync, rmSync } from 'node:fs';
|
||||||
import { tmpdir } from 'node:os';
|
import { tmpdir } from 'node:os';
|
||||||
import { join } from 'node:path';
|
import { join } from 'node:path';
|
||||||
import { openDb, now, setSetting } from '../src/db.js';
|
import { now, setSetting } from '../src/db.js';
|
||||||
|
import { testDb } from './helpers/db.js';
|
||||||
import { createApp } from '../src/server.js';
|
import { createApp } from '../src/server.js';
|
||||||
import { unsubToken } from '../src/crypto.js';
|
import { unsubToken } from '../src/crypto.js';
|
||||||
|
import { addUser } from './helpers/users.js';
|
||||||
|
|
||||||
const APP_URL = 'https://ai.tony-averty.dev';
|
const APP_URL = 'https://ai.tony-averty.dev';
|
||||||
let app, base, cookie, tmp;
|
let app, base, cookie, tmp, uid;
|
||||||
|
|
||||||
before(async () => {
|
before(async () => {
|
||||||
tmp = mkdtempSync(join(tmpdir(), 'aitools-http-'));
|
tmp = mkdtempSync(join(tmpdir(), 'aitools-http-'));
|
||||||
const cfg = {
|
const cfg = {
|
||||||
appUrl: APP_URL, google: { clientId: 'cid', clientSecret: 'cs' }, allowedEmails: ['me@gmail.com'],
|
appUrl: APP_URL, google: { clientId: 'cid', clientSecret: 'cs' }, apple: null, adminEmails: ['me@gmail.com'],
|
||||||
secretKey: randomBytes(32), dataDir: tmp, claudeBin: 'claude', thermalMax: 75,
|
secretKey: randomBytes(32), dataDir: tmp, claudeBin: 'claude', thermalMax: 75, sandbox: { enabled: false, production: false },
|
||||||
};
|
};
|
||||||
app = createApp(cfg, { db: openDb(':memory:'), worker: false });
|
app = await createApp(cfg, { db: await testDb(), worker: false });
|
||||||
await new Promise((r) => app.server.listen(0, '127.0.0.1', r));
|
await new Promise((r) => app.server.listen(0, '127.0.0.1', r));
|
||||||
base = `http://127.0.0.1:${app.server.address().port}`;
|
base = `http://127.0.0.1:${app.server.address().port}`;
|
||||||
app.db.prepare('INSERT INTO sessions(id, email, created_at, expires_at) VALUES(?, ?, ?, ?)').run('sess1', 'me@gmail.com', now(), now() + 3600);
|
uid = await addUser(app.db, { email: 'me@gmail.com' });
|
||||||
|
await app.db.prepare('INSERT INTO sessions(id, user_id, created_at, expires_at) VALUES(?, ?, ?, ?)').run('sess1', uid, now(), now() + 3600);
|
||||||
cookie = 'sid=sess1';
|
cookie = 'sid=sess1';
|
||||||
});
|
});
|
||||||
after(async () => { await app.close(); rmSync(tmp, { recursive: true, force: true }); });
|
after(async () => { await app.close(); rmSync(tmp, { recursive: true, force: true }); });
|
||||||
|
|
@ -36,7 +39,11 @@ const post = (p, body, { auth = true, origin = APP_URL, form = false } = {}) =>
|
||||||
});
|
});
|
||||||
|
|
||||||
test('non connecté : redirection / 401 et pages publiques', async () => {
|
test('non connecté : redirection / 401 et pages publiques', async () => {
|
||||||
|
// La racine est le site public pour un visiteur ; une page d'application renvoie vers la connexion
|
||||||
let r = await get('/', false);
|
let r = await get('/', false);
|
||||||
|
assert.equal(r.status, 200);
|
||||||
|
assert.match(await r.text(), /<h1[^>]*>Un panel pour prospecter/);
|
||||||
|
r = await get('/account', false);
|
||||||
assert.equal(r.status, 303);
|
assert.equal(r.status, 303);
|
||||||
assert.equal(r.headers.get('location'), '/login');
|
assert.equal(r.headers.get('location'), '/login');
|
||||||
r = await get('/api/system', false);
|
r = await get('/api/system', false);
|
||||||
|
|
@ -79,13 +86,13 @@ test('dashboard, réglages, création de projet et statut', async () => {
|
||||||
|
|
||||||
r = await post('/settings', { notify_email: 'moi@x.fr', forgejo_host: 'https://git.tony-averty.dev/', forgejo_token: 'tok123', global_daily_cap: '9999', send_delay_min: '1', send_delay_max: '2', prospect_model: 'opus', analyze_model: 'opus' }, { form: true });
|
r = await post('/settings', { notify_email: 'moi@x.fr', forgejo_host: 'https://git.tony-averty.dev/', forgejo_token: 'tok123', global_daily_cap: '9999', send_delay_min: '1', send_delay_max: '2', prospect_model: 'opus', analyze_model: 'opus' }, { form: true });
|
||||||
assert.equal(r.status, 303);
|
assert.equal(r.status, 303);
|
||||||
const s = (k) => app.db.prepare('SELECT value FROM settings WHERE key = ?').get(k)?.value;
|
const s = async (k) => (await app.db.prepare('SELECT value FROM user_settings WHERE user_id = ? AND `key` = ?').get(uid, k))?.value;
|
||||||
assert.equal(s('forgejo_host'), 'git.tony-averty.dev');
|
assert.equal(await s('forgejo_host'), 'git.tony-averty.dev');
|
||||||
assert.equal(s('global_daily_cap'), '300', 'plafond borné');
|
assert.equal(await s('global_daily_cap'), '300', 'plafond borné');
|
||||||
assert.equal(s('send_delay_min'), '5');
|
assert.equal(await s('send_delay_min'), '5');
|
||||||
assert.equal(s('prospect_model'), 'haiku', 'opus refusé pour la prospection');
|
assert.equal(await s('prospect_model'), 'haiku', 'opus refusé pour la prospection');
|
||||||
assert.equal(s('analyze_model'), 'haiku', 'opus refusé pour l\'analyse');
|
assert.equal(await s('analyze_model'), 'haiku', 'opus refusé pour l\'analyse');
|
||||||
assert.ok(!s('forgejo_token_enc').includes('tok123'), 'token chiffré');
|
assert.ok(!(await s('forgejo_token_enc')).includes('tok123'), 'token chiffré');
|
||||||
|
|
||||||
r = await post('/api/projects', { name: 'MEP', gitUrl: 'https://github.com/Tony/MEP.git' });
|
r = await post('/api/projects', { name: 'MEP', gitUrl: 'https://github.com/Tony/MEP.git' });
|
||||||
assert.equal(r.status, 400);
|
assert.equal(r.status, 400);
|
||||||
|
|
@ -107,7 +114,7 @@ test('dashboard, réglages, création de projet et statut', async () => {
|
||||||
assert.equal(r.status, 200);
|
assert.equal(r.status, 200);
|
||||||
r = await post(`/api/projects/${id}/prospect`, { count: 999 });
|
r = await post(`/api/projects/${id}/prospect`, { count: 999 });
|
||||||
assert.equal(r.status, 200);
|
assert.equal(r.status, 200);
|
||||||
const job = app.db.prepare("SELECT params_json FROM jobs WHERE type = 'prospect'").get();
|
const job = await app.db.prepare("SELECT params_json FROM jobs WHERE type = 'prospect'").get();
|
||||||
assert.equal(JSON.parse(job.params_json).count, 50, 'borné à 50');
|
assert.equal(JSON.parse(job.params_json).count, 50, 'borné à 50');
|
||||||
|
|
||||||
r = await post(`/api/projects/${id}/send`, { count: 5 });
|
r = await post(`/api/projects/${id}/send`, { count: 5 });
|
||||||
|
|
@ -119,7 +126,7 @@ test('dashboard, réglages, création de projet et statut', async () => {
|
||||||
assert.equal(r.status, 400);
|
assert.equal(r.status, 400);
|
||||||
r = await post(`/api/projects/${id}/smtp`, { host: 'smtp.x', user: 'u', pass: 'secretpass', fromEmail: 'a@x.fr', dailyCap: 5000 });
|
r = await post(`/api/projects/${id}/smtp`, { host: 'smtp.x', user: 'u', pass: 'secretpass', fromEmail: 'a@x.fr', dailyCap: 5000 });
|
||||||
assert.equal(r.status, 200);
|
assert.equal(r.status, 200);
|
||||||
const row = app.db.prepare('SELECT smtp_enc, daily_mail_cap FROM projects WHERE id = ?').get(id);
|
const row = await app.db.prepare('SELECT smtp_enc, daily_mail_cap FROM projects WHERE id = ?').get(id);
|
||||||
assert.ok(!row.smtp_enc.includes('secretpass'));
|
assert.ok(!row.smtp_enc.includes('secretpass'));
|
||||||
assert.equal(row.daily_mail_cap, 200);
|
assert.equal(row.daily_mail_cap, 200);
|
||||||
|
|
||||||
|
|
@ -138,17 +145,17 @@ test('désinscription : GET confirme, POST blackliste, token forgé refusé', as
|
||||||
let r = await get(`/u/${encodeURIComponent(email)}/${tok}`, false);
|
let r = await get(`/u/${encodeURIComponent(email)}/${tok}`, false);
|
||||||
assert.equal(r.status, 200);
|
assert.equal(r.status, 200);
|
||||||
assert.match(await r.text(), /Confirmer/);
|
assert.match(await r.text(), /Confirmer/);
|
||||||
assert.equal(app.db.prepare('SELECT COUNT(*) n FROM blacklist').get().n, 0);
|
assert.equal((await app.db.prepare('SELECT COUNT(*) n FROM blacklist').get()).n, 0);
|
||||||
r = await post(`/u/${encodeURIComponent(email)}/${tok}`, 'List-Unsubscribe=One-Click', { auth: false, origin: null, form: true });
|
r = await post(`/u/${encodeURIComponent(email)}/${tok}`, 'List-Unsubscribe=One-Click', { auth: false, origin: null, form: true });
|
||||||
assert.equal(r.status, 200);
|
assert.equal(r.status, 200);
|
||||||
assert.equal(app.db.prepare('SELECT COUNT(*) n FROM blacklist WHERE email = ?').get(email).n, 1);
|
assert.equal((await app.db.prepare('SELECT COUNT(*) n FROM blacklist WHERE email = ?').get(email)).n, 1);
|
||||||
r = await post(`/u/${encodeURIComponent(email)}/faux`, {}, { auth: false, origin: null });
|
r = await post(`/u/${encodeURIComponent(email)}/faux`, {}, { auth: false, origin: null });
|
||||||
assert.equal(r.status, 400);
|
assert.equal(r.status, 400);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('SECRET_KEY changée : le panel reste utilisable, les secrets sont à ressaisir', async () => {
|
test('SECRET_KEY changée : le panel reste utilisable, les secrets sont à ressaisir', async () => {
|
||||||
const id = app.db.prepare('SELECT id FROM projects LIMIT 1').get().id;
|
const id = (await app.db.prepare('SELECT id FROM projects LIMIT 1').get()).id;
|
||||||
app.db.prepare('UPDATE projects SET smtp_enc = ? WHERE id = ?').run('v1:AAAA:BBBB:CCCC', id);
|
await app.db.prepare('UPDATE projects SET smtp_enc = ? WHERE id = ?').run('v1:AAAA:BBBB:CCCC', id);
|
||||||
const warn = console.warn; console.warn = () => {};
|
const warn = console.warn; console.warn = () => {};
|
||||||
try {
|
try {
|
||||||
let r = await get('/');
|
let r = await get('/');
|
||||||
|
|
@ -164,11 +171,11 @@ test('SECRET_KEY changée : le panel reste utilisable, les secrets sont à ressa
|
||||||
});
|
});
|
||||||
|
|
||||||
test('« Cette nuit » programme le job au prochain créneau 1h-6h', async () => {
|
test('« Cette nuit » programme le job au prochain créneau 1h-6h', async () => {
|
||||||
const id = app.db.prepare('SELECT id FROM projects LIMIT 1').get().id;
|
const id = (await app.db.prepare('SELECT id FROM projects LIMIT 1').get()).id;
|
||||||
app.db.prepare("UPDATE jobs SET status = 'cancelled' WHERE status IN ('queued', 'running')").run();
|
await app.db.prepare("UPDATE jobs SET status = 'cancelled' WHERE status IN ('queued', 'running')").run();
|
||||||
const r = await post(`/api/projects/${id}/evolution`, { count: 3, level: 'rapide', when: 'night' });
|
const r = await post(`/api/projects/${id}/evolution`, { count: 3, level: 'rapide', when: 'night' });
|
||||||
assert.equal(r.status, 200);
|
assert.equal(r.status, 200);
|
||||||
const job = app.db.prepare("SELECT run_after FROM jobs WHERE type = 'evolution' ORDER BY id DESC LIMIT 1").get();
|
const job = await app.db.prepare("SELECT run_after FROM jobs WHERE type = 'evolution' ORDER BY id DESC LIMIT 1").get();
|
||||||
const { parisParts } = await import('../src/services/paris-time.js');
|
const { parisParts } = await import('../src/services/paris-time.js');
|
||||||
const p = parisParts(new Date(job.run_after * 1000));
|
const p = parisParts(new Date(job.run_after * 1000));
|
||||||
assert.ok(p.hour >= 1 && p.hour < 6, `démarrage à ${p.hour}h`);
|
assert.ok(p.hour >= 1 && p.hour < 6, `démarrage à ${p.hour}h`);
|
||||||
|
|
@ -188,42 +195,42 @@ test('réglages Discord : URL validée, chiffrée, événements enregistrés', a
|
||||||
const hook = 'https://discord.com/api/webhooks/123456789012345678/abcdefghijklmnopqrstuvwxyz-ABC_123';
|
const hook = 'https://discord.com/api/webhooks/123456789012345678/abcdefghijklmnopqrstuvwxyz-ABC_123';
|
||||||
r = await post('/settings', { ...base, discord_webhook: hook, ev_reply: 'on', ev_job_error: 'on' }, { form: true });
|
r = await post('/settings', { ...base, discord_webhook: hook, ev_reply: 'on', ev_job_error: 'on' }, { form: true });
|
||||||
assert.equal(r.status, 303);
|
assert.equal(r.status, 303);
|
||||||
const enc = app.db.prepare("SELECT value FROM settings WHERE key = 'discord_webhook_enc'").get().value;
|
const enc = (await app.db.prepare("SELECT value FROM user_settings WHERE user_id = ? AND `key` = 'discord_webhook_enc'").get(uid)).value;
|
||||||
assert.ok(!enc.includes('abcdefghijklmnop'), 'URL chiffrée');
|
assert.ok(!enc.includes('abcdefghijklmnop'), 'URL chiffrée');
|
||||||
assert.deepEqual(JSON.parse(app.db.prepare("SELECT value FROM settings WHERE key = 'discord_events'").get().value), ['job_error', 'reply']);
|
assert.deepEqual(JSON.parse((await app.db.prepare("SELECT value FROM user_settings WHERE user_id = ? AND `key` = 'discord_events'").get(uid)).value), ['job_error', 'reply']);
|
||||||
r = await get('/settings');
|
r = await get('/settings');
|
||||||
const page = await r.text();
|
const page = await r.text();
|
||||||
assert.ok(!page.includes('abcdefghijklmnop'), 'URL jamais réaffichée');
|
assert.ok(!page.includes('abcdefghijklmnop'), 'URL jamais réaffichée');
|
||||||
assert.match(page, /data-notify-test/);
|
assert.match(page, /data-notify-test/);
|
||||||
r = await post('/settings', { ...base, discord_remove: 'on' }, { form: true });
|
r = await post('/settings', { ...base, discord_remove: 'on' }, { form: true });
|
||||||
assert.equal(app.db.prepare("SELECT value FROM settings WHERE key = 'discord_webhook_enc'").get().value, null);
|
assert.equal((await app.db.prepare("SELECT value FROM user_settings WHERE user_id = ? AND `key` = 'discord_webhook_enc'").get(uid)).value, null);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('budget : réglages, jauge et avertissement au lancement', async () => {
|
test('budget : réglages, jauge et avertissement au lancement', async () => {
|
||||||
const base = { notify_email: 'moi@x.fr', forgejo_host: 'git.tony-averty.dev', global_daily_cap: '100', send_delay_min: '20', send_delay_max: '60' };
|
const base = { notify_email: 'moi@x.fr', forgejo_host: 'git.tony-averty.dev', global_daily_cap: '100', send_delay_min: '20', send_delay_max: '60' };
|
||||||
let r = await post('/settings', { ...base, budget_day_usd: '0,5', budget_month_usd: 'abc' }, { form: true });
|
let r = await post('/settings', { ...base, budget_day_usd: '0,5', budget_month_usd: 'abc' }, { form: true });
|
||||||
assert.equal(r.status, 303);
|
assert.equal(r.status, 303);
|
||||||
const s = (k) => app.db.prepare('SELECT value FROM settings WHERE key = ?').get(k)?.value;
|
const s = async (k) => (await app.db.prepare('SELECT value FROM user_settings WHERE user_id = ? AND `key` = ?').get(uid, k))?.value;
|
||||||
assert.equal(s('budget_day_usd'), '0.5', 'virgule française acceptée');
|
assert.equal(await s('budget_day_usd'), '0.5', 'virgule française acceptée');
|
||||||
assert.equal(s('budget_month_usd'), '', 'valeur invalide = pas de limite');
|
assert.equal(await s('budget_month_usd'), '', 'valeur invalide = pas de limite');
|
||||||
app.db.prepare("INSERT INTO jobs(type, status, cost_usd, created_at, finished_at) VALUES('evolution', 'done', 0.8, ?, ?)").run(now(), now());
|
await app.db.prepare("INSERT INTO jobs(user_id, type, status, cost_usd, created_at, finished_at) VALUES(?, 'evolution', 'done', 0.8, ?, ?)").run(uid, now(), now());
|
||||||
let sys = await (await get('/api/system')).json();
|
let sys = await (await get('/api/system')).json();
|
||||||
assert.equal(sys.budget.blocked, true);
|
assert.equal(sys.budget.blocked, true);
|
||||||
assert.equal(sys.claudeRateLimit, null, 'pas encore mesuré sans appel Claude');
|
assert.equal(sys.claudeRateLimit, null, 'pas encore mesuré sans appel Claude');
|
||||||
setSetting(app.db, 'claude_rate_limit_json', JSON.stringify({ at: now(), fiveHour: { utilization: 0.42, resetsAt: 123 }, sevenDay: { utilization: 0.1, resetsAt: 456 } }));
|
await setSetting(app.db, uid, 'claude_rate_limit_json', JSON.stringify({ at: now(), fiveHour: { utilization: 0.42, resetsAt: 123 }, sevenDay: { utilization: 0.1, resetsAt: 456 } }));
|
||||||
sys = await (await get('/api/system')).json();
|
sys = await (await get('/api/system')).json();
|
||||||
assert.equal(sys.claudeRateLimit.fiveHour.utilization, 0.42);
|
assert.equal(sys.claudeRateLimit.fiveHour.utilization, 0.42);
|
||||||
assert.equal(sys.claudeRateLimit.sevenDay.utilization, 0.1);
|
assert.equal(sys.claudeRateLimit.sevenDay.utilization, 0.1);
|
||||||
const id = app.db.prepare('SELECT id FROM projects LIMIT 1').get().id;
|
const id = (await app.db.prepare('SELECT id FROM projects LIMIT 1').get()).id;
|
||||||
app.db.prepare("UPDATE jobs SET status = 'cancelled' WHERE status IN ('queued', 'running')").run();
|
await app.db.prepare("UPDATE jobs SET status = 'cancelled' WHERE status IN ('queued', 'running')").run();
|
||||||
r = await post(`/api/projects/${id}/evolution`, { count: 2, level: 'rapide' });
|
r = await post(`/api/projects/${id}/evolution`, { count: 2, level: 'rapide' });
|
||||||
assert.match((await r.json()).budgetBlocked, /budget IA des dernières 24 h atteint/);
|
assert.match((await r.json()).budgetBlocked, /budget IA des dernières 24 h atteint/);
|
||||||
await post('/settings', { ...base, budget_day_usd: '' }, { form: true });
|
await post('/settings', { ...base, budget_day_usd: '' }, { form: true });
|
||||||
});
|
});
|
||||||
|
|
||||||
test('fiche prospect : routes notes et prochaine action', async () => {
|
test('fiche prospect : routes notes et prochaine action', async () => {
|
||||||
const pid = app.db.prepare('SELECT id FROM projects LIMIT 1').get().id;
|
const pid = (await app.db.prepare('SELECT id FROM projects LIMIT 1').get()).id;
|
||||||
const id = Number(app.db.prepare("INSERT INTO prospects(project_id, company, email, website, created_at) VALUES(?, 'Atelier', 'a@atelier.fr', 'javascript:alert(1)', ?)").run(pid, now()).lastInsertRowid);
|
const id = Number((await app.db.prepare("INSERT INTO prospects(project_id, company, email, website, created_at) VALUES(?, 'Atelier', 'a@atelier.fr', 'javascript:alert(1)', ?)").run(pid, now())).lastInsertRowid);
|
||||||
let r = await post(`/api/prospects/${id}/notes`, { body: '<script>x</script>' });
|
let r = await post(`/api/prospects/${id}/notes`, { body: '<script>x</script>' });
|
||||||
assert.equal(r.status, 200);
|
assert.equal(r.status, 200);
|
||||||
r = await post(`/api/prospects/${id}/notes`, { body: '' });
|
r = await post(`/api/prospects/${id}/notes`, { body: '' });
|
||||||
|
|
@ -244,7 +251,7 @@ test('fiche prospect : routes notes et prochaine action', async () => {
|
||||||
});
|
});
|
||||||
|
|
||||||
test('CSV : export en pièce jointe, import via l\'API', async () => {
|
test('CSV : export en pièce jointe, import via l\'API', async () => {
|
||||||
const pid = app.db.prepare('SELECT id FROM projects LIMIT 1').get().id;
|
const pid = (await app.db.prepare('SELECT id FROM projects LIMIT 1').get()).id;
|
||||||
let r = await get(`/api/projects/${pid}/prospects.csv?q=atelier`);
|
let r = await get(`/api/projects/${pid}/prospects.csv?q=atelier`);
|
||||||
assert.equal(r.status, 200);
|
assert.equal(r.status, 200);
|
||||||
assert.match(r.headers.get('content-type'), /text\/csv/);
|
assert.match(r.headers.get('content-type'), /text\/csv/);
|
||||||
|
|
|
||||||
|
|
@ -3,7 +3,10 @@
|
||||||
import { test } from 'node:test';
|
import { test } from 'node:test';
|
||||||
import assert from 'node:assert/strict';
|
import assert from 'node:assert/strict';
|
||||||
import { randomBytes } from 'node:crypto';
|
import { randomBytes } from 'node:crypto';
|
||||||
import { openDb, now } from '../src/db.js';
|
import { now } from '../src/db.js';
|
||||||
|
import { testDb } from './helpers/db.js';
|
||||||
|
import { addUser } from './helpers/users.js';
|
||||||
|
|
||||||
import { checkInbox } from '../src/services/inbox.js';
|
import { checkInbox } from '../src/services/inbox.js';
|
||||||
import { createProject, saveSecretConfig, getProject } from '../src/projects.js';
|
import { createProject, saveSecretConfig, getProject } from '../src/projects.js';
|
||||||
|
|
||||||
|
|
@ -11,27 +14,28 @@ const live = process.env.IMAP_TEST;
|
||||||
|
|
||||||
test('checkInbox sur un vrai serveur IMAP', { skip: !live && 'IMAP_TEST non défini' }, async () => {
|
test('checkInbox sur un vrai serveur IMAP', { skip: !live && 'IMAP_TEST non défini' }, async () => {
|
||||||
const [host, port, user, pass] = live.split(':');
|
const [host, port, user, pass] = live.split(':');
|
||||||
const db = openDb(':memory:');
|
const db = await testDb();
|
||||||
const app = { db, cfg: { secretKey: randomBytes(32) } };
|
const app = { db, cfg: { secretKey: randomBytes(32) } };
|
||||||
const id = createProject(app, { name: 'P', gitUrl: 'https://git.x/T/P.git' });
|
const userId = await addUser(db);
|
||||||
saveSecretConfig(app, id, 'smtp_enc', { host: 'smtp.x', user, pass, fromEmail: user }, 'pass');
|
const id = await createProject(app, { userId, name: 'P', gitUrl: 'https://git.x/T/P.git' });
|
||||||
saveSecretConfig(app, id, 'imap_enc', { host, port: Number(port), user: '', pass: '' }, 'pass');
|
await saveSecretConfig(app, id, 'smtp_enc', { host: 'smtp.x', user, pass, fromEmail: user }, 'pass');
|
||||||
const add = (email, msgId) => {
|
await saveSecretConfig(app, id, 'imap_enc', { host, port: Number(port), user: '', pass: '' }, 'pass');
|
||||||
const pid = Number(db.prepare("INSERT INTO prospects(project_id, company, email, status, sent_at, created_at) VALUES(?, 'X', ?, 'sent', ?, ?)")
|
const add = async (email, msgId) => {
|
||||||
.run(id, email, now() - 86400 * 30, now()).lastInsertRowid);
|
const pid = Number((await db.prepare("INSERT INTO prospects(project_id, company, email, status, sent_at, created_at) VALUES(?, 'X', ?, 'sent', ?, ?)")
|
||||||
db.prepare("INSERT INTO mail_log(project_id, prospect_id, email, sent_at, kind, message_id) VALUES(?, ?, ?, ?, 'initial', ?)")
|
.run(id, email, now() - 86400 * 30, now())).lastInsertRowid);
|
||||||
|
await db.prepare("INSERT INTO mail_log(project_id, prospect_id, email, sent_at, kind, message_id) VALUES(?, ?, ?, ?, 'initial', ?)")
|
||||||
.run(id, pid, email, now() - 86400 * 30, msgId);
|
.run(id, pid, email, now() - 86400 * 30, msgId);
|
||||||
return pid;
|
return pid;
|
||||||
};
|
};
|
||||||
const fournil = add('contact@fournil.fr', '<m1@codebzh.fr>');
|
const fournil = await add('contact@fournil.fr', '<m1@codebzh.fr>');
|
||||||
const zen = add('hello@zen.fr', '<m2@codebzh.fr>');
|
const zen = await add('hello@zen.fr', '<m2@codebzh.fr>');
|
||||||
const ferme = add('contact@ferme.fr', '<m3@codebzh.fr>');
|
const ferme = await add('contact@ferme.fr', '<m3@codebzh.fr>');
|
||||||
|
|
||||||
assert.deepEqual(await checkInbox(app, id), { replies: 1, bounces: 1, ignored: 2 });
|
assert.deepEqual(await checkInbox(app, userId, id), { replies: 1, bounces: 1, ignored: 2 });
|
||||||
const st = (pid) => db.prepare('SELECT status FROM prospects WHERE id = ?').get(pid).status;
|
const st = async (pid) => (await db.prepare('SELECT status FROM prospects WHERE id = ?').get(pid)).status;
|
||||||
assert.equal(st(fournil), 'replied');
|
assert.equal(await st(fournil), 'replied');
|
||||||
assert.equal(st(zen), 'sent', 'une absence n\'est pas une réponse');
|
assert.equal(await st(zen), 'sent', 'une absence n\'est pas une réponse');
|
||||||
assert.equal(st(ferme), 'bounced');
|
assert.equal(await st(ferme), 'bounced');
|
||||||
assert.deepEqual(await checkInbox(app, id), { replies: 0, bounces: 0, ignored: 0 }, 'rien de relu');
|
assert.deepEqual(await checkInbox(app, userId, id), { replies: 0, bounces: 0, ignored: 0 }, 'rien de relu');
|
||||||
assert.equal(getProject(app, id).inbox.lastUid, 4);
|
assert.equal((await getProject(app, id, { userId })).inbox.lastUid, 4);
|
||||||
});
|
});
|
||||||
|
|
|
||||||
|
|
@ -1,26 +1,30 @@
|
||||||
import { test } from 'node:test';
|
import { test } from 'node:test';
|
||||||
import assert from 'node:assert/strict';
|
import assert from 'node:assert/strict';
|
||||||
import { randomBytes } from 'node:crypto';
|
import { randomBytes } from 'node:crypto';
|
||||||
import { openDb, now } from '../src/db.js';
|
import { now } from '../src/db.js';
|
||||||
|
import { testDb } from './helpers/db.js';
|
||||||
|
import { addUser } from './helpers/users.js';
|
||||||
|
|
||||||
import { parseHeaders, classify, applyMessages, checkInbox } from '../src/services/inbox.js';
|
import { parseHeaders, classify, applyMessages, checkInbox } from '../src/services/inbox.js';
|
||||||
import { createProject, saveSecretConfig, getProject, imapCredentials } from '../src/projects.js';
|
import { createProject, saveSecretConfig, getProject, imapCredentials } from '../src/projects.js';
|
||||||
|
|
||||||
function setup() {
|
async function setup() {
|
||||||
const db = openDb(':memory:');
|
const db = await testDb();
|
||||||
const app = { db, cfg: { secretKey: randomBytes(32) } };
|
const app = { db, cfg: { secretKey: randomBytes(32) } };
|
||||||
const id = createProject(app, { name: 'P', gitUrl: 'https://git.x/T/P.git' });
|
const userId = await addUser(db);
|
||||||
const add = (company, email, msgId, status = 'sent') => {
|
const id = await createProject(app, { userId, name: 'P', gitUrl: 'https://git.x/T/P.git' });
|
||||||
const r = db.prepare('INSERT INTO prospects(project_id, company, email, status, sent_at, created_at) VALUES(?, ?, ?, ?, ?, ?)')
|
const add = async (company, email, msgId, status = 'sent') => {
|
||||||
|
const r = await db.prepare('INSERT INTO prospects(project_id, company, email, status, sent_at, created_at) VALUES(?, ?, ?, ?, ?, ?)')
|
||||||
.run(id, company, email, status, now(), now());
|
.run(id, company, email, status, now(), now());
|
||||||
const pid = Number(r.lastInsertRowid);
|
const pid = Number(r.lastInsertRowid);
|
||||||
if (msgId) {
|
if (msgId) {
|
||||||
db.prepare("INSERT INTO mail_log(project_id, prospect_id, email, sent_at, kind, message_id) VALUES(?, ?, ?, ?, 'initial', ?)")
|
await db.prepare("INSERT INTO mail_log(project_id, prospect_id, email, sent_at, kind, message_id) VALUES(?, ?, ?, ?, 'initial', ?)")
|
||||||
.run(id, pid, email, now(), msgId);
|
.run(id, pid, email, now(), msgId);
|
||||||
}
|
}
|
||||||
return pid;
|
return pid;
|
||||||
};
|
};
|
||||||
const status = (pid) => db.prepare('SELECT status, replied_at, reply_subject FROM prospects WHERE id = ?').get(pid);
|
const status = (pid) => db.prepare('SELECT status, replied_at, reply_subject FROM prospects WHERE id = ?').get(pid);
|
||||||
return { db, app, id, add, status };
|
return { db, app, id, userId, add, status };
|
||||||
}
|
}
|
||||||
|
|
||||||
test('parseHeaders déplie les en-têtes multi-lignes', () => {
|
test('parseHeaders déplie les en-têtes multi-lignes', () => {
|
||||||
|
|
@ -42,36 +46,36 @@ test('classify : réponse, réponse automatique, bounce', () => {
|
||||||
assert.equal(classify({ from: 'x@y.fr', subject: 'Rapport', headers: { 'content-type': 'multipart/report; report-type=delivery-status' } }).type, 'bounce');
|
assert.equal(classify({ from: 'x@y.fr', subject: 'Rapport', headers: { 'content-type': 'multipart/report; report-type=delivery-status' } }).type, 'bounce');
|
||||||
});
|
});
|
||||||
|
|
||||||
test('réponse rattachée par le fil (In-Reply-To), même depuis une autre adresse', () => {
|
test('réponse rattachée par le fil (In-Reply-To), même depuis une autre adresse', async () => {
|
||||||
const s = setup();
|
const s = await setup();
|
||||||
const p = s.add('Fournil', 'contact@fournil.fr', '<m1@codebzh.fr>');
|
const p = await s.add('Fournil', 'contact@fournil.fr', '<m1@codebzh.fr>');
|
||||||
const r = applyMessages(s.db, s.id, [{ from: 'jean.dupont@gmail.com', subject: 'Re: Une idée', inReplyTo: '<m1@codebzh.fr>' }]);
|
const r = await applyMessages(s.db, s.id, [{ from: 'jean.dupont@gmail.com', subject: 'Re: Une idée', inReplyTo: '<m1@codebzh.fr>' }]);
|
||||||
assert.deepEqual(r, { replies: 1, bounces: 0, ignored: 0 });
|
assert.deepEqual(r, { replies: 1, bounces: 0, ignored: 0 });
|
||||||
assert.equal(s.status(p).status, 'replied');
|
assert.equal((await s.status(p)).status, 'replied');
|
||||||
assert.equal(s.status(p).reply_subject, 'Re: Une idée');
|
assert.equal((await s.status(p)).reply_subject, 'Re: Une idée');
|
||||||
assert.ok(s.status(p).replied_at > 0);
|
assert.ok((await s.status(p)).replied_at > 0);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('réponse rattachée par adresse puis par domaine pro', () => {
|
test('réponse rattachée par adresse puis par domaine pro', async () => {
|
||||||
const s = setup();
|
const s = await setup();
|
||||||
const byMail = s.add('Zen', 'hello@zen.fr', null);
|
const byMail = await s.add('Zen', 'hello@zen.fr', null);
|
||||||
const byDomain = s.add('Atelier', 'contact@atelier-bois.fr', null);
|
const byDomain = await s.add('Atelier', 'contact@atelier-bois.fr', null);
|
||||||
const r = applyMessages(s.db, s.id, [
|
const r = await applyMessages(s.db, s.id, [
|
||||||
{ from: 'Hello@Zen.fr', subject: 'Intéressé' },
|
{ from: 'Hello@Zen.fr', subject: 'Intéressé' },
|
||||||
{ from: 'marc@atelier-bois.fr', subject: 'Re: votre message' },
|
{ from: 'marc@atelier-bois.fr', subject: 'Re: votre message' },
|
||||||
]);
|
]);
|
||||||
assert.equal(r.replies, 2);
|
assert.equal(r.replies, 2);
|
||||||
assert.equal(s.status(byMail).status, 'replied');
|
assert.equal((await s.status(byMail)).status, 'replied');
|
||||||
assert.equal(s.status(byDomain).status, 'replied');
|
assert.equal((await s.status(byDomain)).status, 'replied');
|
||||||
});
|
});
|
||||||
|
|
||||||
test('pas de faux positif : webmail générique, domaine ambigu, réponse auto, statut déjà traité', () => {
|
test('pas de faux positif : webmail générique, domaine ambigu, réponse auto, statut déjà traité', async () => {
|
||||||
const s = setup();
|
const s = await setup();
|
||||||
const g = s.add('Perso', 'boulanger.rennes@gmail.com', null);
|
const g = await s.add('Perso', 'boulanger.rennes@gmail.com', null);
|
||||||
const a1 = s.add('Groupe A', 'rennes@groupe.fr', null);
|
const a1 = await s.add('Groupe A', 'rennes@groupe.fr', null);
|
||||||
const a2 = s.add('Groupe B', 'nantes@groupe.fr', null);
|
const a2 = await s.add('Groupe B', 'nantes@groupe.fr', null);
|
||||||
const client = s.add('Déjà client', 'boss@client.fr', null, 'client');
|
const client = await s.add('Déjà client', 'boss@client.fr', null, 'client');
|
||||||
const r = applyMessages(s.db, s.id, [
|
const r = await applyMessages(s.db, s.id, [
|
||||||
{ from: 'autre@gmail.com', subject: 'Re: ?' }, // gmail : on ne devine pas
|
{ from: 'autre@gmail.com', subject: 'Re: ?' }, // gmail : on ne devine pas
|
||||||
{ from: 'direction@groupe.fr', subject: 'Re: ?' }, // 2 prospects sur ce domaine
|
{ from: 'direction@groupe.fr', subject: 'Re: ?' }, // 2 prospects sur ce domaine
|
||||||
{ from: 'boulanger.rennes@gmail.com', subject: 'Absence', headers: {} },
|
{ from: 'boulanger.rennes@gmail.com', subject: 'Absence', headers: {} },
|
||||||
|
|
@ -79,18 +83,18 @@ test('pas de faux positif : webmail générique, domaine ambigu, réponse auto,
|
||||||
{ from: 'inconnu@ailleurs.fr', subject: 'Spam' },
|
{ from: 'inconnu@ailleurs.fr', subject: 'Spam' },
|
||||||
]);
|
]);
|
||||||
assert.deepEqual(r, { replies: 0, bounces: 0, ignored: 5 });
|
assert.deepEqual(r, { replies: 0, bounces: 0, ignored: 5 });
|
||||||
for (const pid of [g, a1, a2]) assert.equal(s.status(pid).status, 'sent');
|
for (const pid of [g, a1, a2]) assert.equal((await s.status(pid)).status, 'sent');
|
||||||
assert.equal(s.status(client).status, 'client');
|
assert.equal((await s.status(client)).status, 'client');
|
||||||
});
|
});
|
||||||
|
|
||||||
test('bounce : prospect rejeté + liste d\'opposition, et traitement idempotent', () => {
|
test('bounce : prospect rejeté + liste d\'opposition, et traitement idempotent', async () => {
|
||||||
const s = setup();
|
const s = await setup();
|
||||||
const p = s.add('Fermé', 'contact@ferme-definitivement.fr', '<m9@codebzh.fr>');
|
const p = await s.add('Fermé', 'contact@ferme-definitivement.fr', '<m9@codebzh.fr>');
|
||||||
const bounce = { from: 'mailer-daemon@mx.ovh.net', subject: 'Mail delivery failed', body: 'Message-ID: <m9@codebzh.fr>\n550 user unknown' };
|
const bounce = { from: 'mailer-daemon@mx.ovh.net', subject: 'Mail delivery failed', body: 'Message-ID: <m9@codebzh.fr>\n550 user unknown' };
|
||||||
assert.equal(applyMessages(s.db, s.id, [bounce]).bounces, 1);
|
assert.equal((await applyMessages(s.db, s.id, [bounce])).bounces, 1);
|
||||||
assert.equal(s.status(p).status, 'bounced');
|
assert.equal((await s.status(p)).status, 'bounced');
|
||||||
assert.equal(s.db.prepare("SELECT reason FROM blacklist WHERE email = 'contact@ferme-definitivement.fr'").get().reason, 'bounce');
|
assert.equal((await s.db.prepare("SELECT reason FROM blacklist WHERE email = 'contact@ferme-definitivement.fr'").get()).reason, 'bounce');
|
||||||
assert.deepEqual(applyMessages(s.db, s.id, [bounce]), { replies: 0, bounces: 0, ignored: 1 });
|
assert.deepEqual(await applyMessages(s.db, s.id, [bounce]), { replies: 0, bounces: 0, ignored: 1 });
|
||||||
});
|
});
|
||||||
|
|
||||||
test('imapCredentials : utilisateur vide = identifiants SMTP', () => {
|
test('imapCredentials : utilisateur vide = identifiants SMTP', () => {
|
||||||
|
|
@ -102,10 +106,10 @@ test('imapCredentials : utilisateur vide = identifiants SMTP', () => {
|
||||||
});
|
});
|
||||||
|
|
||||||
test('checkInbox : reprend au dernier UID, mémorise l\'état et les erreurs', async () => {
|
test('checkInbox : reprend au dernier UID, mémorise l\'état et les erreurs', async () => {
|
||||||
const s = setup();
|
const s = await setup();
|
||||||
saveSecretConfig(s.app, s.id, 'smtp_enc', { host: 'smtp.x', user: 'u', pass: 'p', fromEmail: 'a@x.fr' }, 'pass');
|
await saveSecretConfig(s.app, s.id, 'smtp_enc', { host: 'smtp.x', user: 'u', pass: 'p', fromEmail: 'a@x.fr' }, 'pass');
|
||||||
saveSecretConfig(s.app, s.id, 'imap_enc', { host: 'imap.x', port: 993, user: '', pass: '' }, 'pass');
|
await saveSecretConfig(s.app, s.id, 'imap_enc', { host: 'imap.x', port: 993, user: '', pass: '' }, 'pass');
|
||||||
const p = s.add('Fournil', 'contact@fournil.fr', '<m1@x.fr>');
|
const p = await s.add('Fournil', 'contact@fournil.fr', '<m1@x.fr>');
|
||||||
const calls = [];
|
const calls = [];
|
||||||
s.app.fetchInbox = async (creds, state) => {
|
s.app.fetchInbox = async (creds, state) => {
|
||||||
calls.push({ creds, state });
|
calls.push({ creds, state });
|
||||||
|
|
@ -114,14 +118,14 @@ test('checkInbox : reprend au dernier UID, mémorise l\'état et les erreurs', a
|
||||||
? { uidValidity: '7', lastUid: 12, messages: [{ uid: 12, from: 'contact@fournil.fr', subject: 'Re: idée' }] }
|
? { uidValidity: '7', lastUid: 12, messages: [{ uid: 12, from: 'contact@fournil.fr', subject: 'Re: idée' }] }
|
||||||
: { uidValidity: '7', lastUid: 12, messages: [] };
|
: { uidValidity: '7', lastUid: 12, messages: [] };
|
||||||
};
|
};
|
||||||
assert.deepEqual(await checkInbox(s.app, s.id), { replies: 1, bounces: 0, ignored: 0 });
|
assert.deepEqual(await checkInbox(s.app, s.userId, s.id), { replies: 1, bounces: 0, ignored: 0 });
|
||||||
assert.equal(calls[0].creds.user, 'u', 'identifiants SMTP réutilisés');
|
assert.equal(calls[0].creds.user, 'u', 'identifiants SMTP réutilisés');
|
||||||
await checkInbox(s.app, s.id);
|
await checkInbox(s.app, s.userId, s.id);
|
||||||
assert.deepEqual(calls[1].state && { v: calls[1].state.uidValidity, u: calls[1].state.lastUid }, { v: '7', u: 12 });
|
assert.deepEqual(calls[1].state && { v: calls[1].state.uidValidity, u: calls[1].state.lastUid }, { v: '7', u: 12 });
|
||||||
await assert.rejects(checkInbox(s.app, s.id), /AUTHENTICATIONFAILED/);
|
await assert.rejects(checkInbox(s.app, s.userId, s.id), /AUTHENTICATIONFAILED/);
|
||||||
const inbox = getProject(s.app, s.id).inbox;
|
const inbox = (await getProject(s.app, s.id, { userId: s.userId })).inbox;
|
||||||
assert.equal(inbox.lastError, 'AUTHENTICATIONFAILED');
|
assert.equal(inbox.lastError, 'AUTHENTICATIONFAILED');
|
||||||
assert.equal(inbox.replies, 1);
|
assert.equal(inbox.replies, 1);
|
||||||
assert.equal(inbox.lastUid, 12, 'le dernier UID est conservé après une erreur');
|
assert.equal(inbox.lastUid, 12, 'le dernier UID est conservé après une erreur');
|
||||||
assert.equal(s.status(p).status, 'replied');
|
assert.equal((await s.status(p)).status, 'replied');
|
||||||
});
|
});
|
||||||
|
|
|
||||||
246
test/isolation.test.js
Normal file
246
test/isolation.test.js
Normal file
|
|
@ -0,0 +1,246 @@
|
||||||
|
import { test, before, after } from 'node:test';
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import { now, setSetting } from '../src/db.js';
|
||||||
|
import { encrypt } from '../src/crypto.js';
|
||||||
|
import { saveSecretConfig, getProject, listProjects, sentSince } from '../src/projects.js';
|
||||||
|
import { enqueue, cancelJob, latestJobs, usageSummary } from '../src/services/jobs.js';
|
||||||
|
import { budgetState } from '../src/services/budget.js';
|
||||||
|
import { weeklyStats } from '../src/services/report.js';
|
||||||
|
import { exportProspects, importProspects } from '../src/services/csv.js';
|
||||||
|
import { parseFilters } from '../src/services/crm.js';
|
||||||
|
import { Scheduler } from '../src/services/scheduler.js';
|
||||||
|
import { startApp } from './helpers/server.js';
|
||||||
|
import { unsubToken } from '../src/crypto.js';
|
||||||
|
|
||||||
|
// Deux comptes (tous deux admins : l'isolation ne doit rien au rôle). A possède des données de chaque type,
|
||||||
|
// B essaie de tout lire et tout modifier : 404 partout, et les données de A restent intactes.
|
||||||
|
let s, A, B, ids;
|
||||||
|
|
||||||
|
before(async () => {
|
||||||
|
s = await startApp();
|
||||||
|
A = await s.newUser({ email: 'a@x.fr' });
|
||||||
|
B = await s.newUser({ email: 'b@x.fr' });
|
||||||
|
const { db, app } = s;
|
||||||
|
const t = now();
|
||||||
|
const pa = Number((await db.prepare('INSERT INTO projects(user_id, name, git_url, profile_json, target_json, target_validated, created_at) VALUES(?, ?, ?, ?, ?, 1, ?)')
|
||||||
|
.run(A.id, 'Projet Secret A', 'https://git.test/a/secret.git', JSON.stringify({ resume: 'x' }), JSON.stringify({ description: 'd', secteurs: ['s'] }), t)).lastInsertRowid);
|
||||||
|
await saveSecretConfig(app, pa, 'smtp_enc', { host: 'smtp.secret-a.fr', user: 'u', pass: 'pw-secret-a', fromEmail: 'a@secret-a.fr' }, 'pass');
|
||||||
|
await saveSecretConfig(app, pa, 'imap_enc', { host: 'imap.secret-a.fr' }, 'pass');
|
||||||
|
await saveSecretConfig(app, pa, 'db_enc', { type: 'mysql', host: 'db.secret-a.fr', sql_users: 'SELECT 1' }, 'password');
|
||||||
|
const prospect = Number((await db.prepare("INSERT INTO prospects(project_id, company, email, status, sent_at, created_at) VALUES(?, 'Alpha SARL', 'alpha@secret-a.fr', 'sent', ?, ?)").run(pa, t, t)).lastInsertRowid);
|
||||||
|
const note = Number((await db.prepare("INSERT INTO prospect_notes(prospect_id, body, created_at) VALUES(?, 'note confidentielle A', ?)").run(prospect, t)).lastInsertRowid);
|
||||||
|
await db.prepare("INSERT INTO mail_log(project_id, prospect_id, email, sent_at, kind, subject) VALUES(?, ?, 'alpha@secret-a.fr', ?, 'initial', 'Objet confidentiel A')").run(pa, prospect, t);
|
||||||
|
await db.prepare("INSERT INTO templates(project_id, kind, subject, body, status, updated_at) VALUES(?, 'initial', 'Objet A', 'Corps A', 'validated', ?)").run(pa, t);
|
||||||
|
await db.prepare('INSERT INTO metrics_daily(project_id, day, users, clients, revenue) VALUES(?, ?, 42, 7, 999)').run(pa, '2026-10-21');
|
||||||
|
const job = Number((await db.prepare("INSERT INTO jobs(user_id, project_id, type, status, cost_usd, created_at) VALUES(?, ?, 'send', 'queued', 3.5, ?)").run(A.id, pa, t)).lastInsertRowid);
|
||||||
|
await setSetting(db, A.id, 'notify_email', 'a-notify@secret-a.fr');
|
||||||
|
await setSetting(db, A.id, 'forgejo_host', 'git.secret-a.fr');
|
||||||
|
await setSetting(db, A.id, 'discord_webhook_enc', encrypt(app.cfg.secretKey, 'https://discord.com/api/webhooks/123456789012345678/secretsecretsecretsecret'));
|
||||||
|
await db.prepare("INSERT INTO blacklist(email, reason, created_at) VALUES('refus@secret-a.fr', 'refused', ?)").run(t);
|
||||||
|
ids = { pa, prospect, note, job };
|
||||||
|
});
|
||||||
|
after(() => s.close());
|
||||||
|
|
||||||
|
const REFUS = (r) => assert.ok([403, 404].includes(r.status), `statut ${r.status} au lieu de 403/404`);
|
||||||
|
|
||||||
|
test('IDOR : B ne peut lire ni modifier aucune ressource de A (404 partout)', async () => {
|
||||||
|
const { pa, prospect, note, job } = ids;
|
||||||
|
const routes = [
|
||||||
|
['GET', `/api/projects/${pa}/status`],
|
||||||
|
['GET', `/api/projects/${pa}/recap`],
|
||||||
|
['GET', `/api/projects/${pa}/history`],
|
||||||
|
['GET', `/api/projects/${pa}/prospects`],
|
||||||
|
['GET', `/api/projects/${pa}/prospects.csv`],
|
||||||
|
['POST', `/api/projects/${pa}/prospects/import`, { csv: 'email;entreprise\nx@y.fr;X' }],
|
||||||
|
['POST', `/api/projects/${pa}/target`, { description: 'pirate', secteurs: 'x' }],
|
||||||
|
['POST', `/api/projects/${pa}/followup`, { enabled: true, days: 3 }],
|
||||||
|
['POST', `/api/projects/${pa}/smtp`, { host: 'evil.example', user: 'u', pass: 'p', fromEmail: 'e@e.fr' }],
|
||||||
|
['POST', `/api/projects/${pa}/imap`, { host: 'evil.example' }],
|
||||||
|
['POST', `/api/projects/${pa}/inbox/check`, {}],
|
||||||
|
['POST', `/api/projects/${pa}/db`, { type: 'mysql', host: 'evil.example', sql_users: 'SELECT 1' }],
|
||||||
|
['POST', `/api/projects/${pa}/template/save`, { kind: 'initial', subject: 'pirate', body: 'pirate' }],
|
||||||
|
['POST', `/api/projects/${pa}/analyze`, {}],
|
||||||
|
['POST', `/api/projects/${pa}/template`, {}],
|
||||||
|
['POST', `/api/projects/${pa}/followup_template`, {}],
|
||||||
|
['POST', `/api/projects/${pa}/prospect`, { count: 5 }],
|
||||||
|
['POST', `/api/projects/${pa}/evolution`, { count: 5 }],
|
||||||
|
['POST', `/api/projects/${pa}/send`, { count: 5, confirm: true }],
|
||||||
|
['POST', `/api/projects/${pa}/delete`, {}],
|
||||||
|
['GET', `/api/prospects/${prospect}`],
|
||||||
|
['POST', `/api/prospects/${prospect}/status`, { status: 'client' }],
|
||||||
|
['POST', `/api/prospects/${prospect}/notes`, { body: 'pirate' }],
|
||||||
|
['POST', `/api/prospects/${prospect}/notes/${note}/delete`, {}],
|
||||||
|
['POST', `/api/prospects/${prospect}/next`, { action: 'pirate', day: '2026-11-03' }],
|
||||||
|
['POST', `/api/jobs/${job}/cancel`, {}],
|
||||||
|
];
|
||||||
|
for (const [method, path, body] of routes) {
|
||||||
|
const r = method === 'GET' ? await B.get(path) : await B.post(path, body);
|
||||||
|
REFUS(r);
|
||||||
|
const text = await r.text();
|
||||||
|
assert.ok(!/secret-a|Projet Secret|confidentiel|pw-secret/i.test(text), `${method} ${path} ne divulgue rien`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Rien n'a bougé chez A
|
||||||
|
const { db } = s;
|
||||||
|
assert.equal((await db.prepare('SELECT COUNT(*) n FROM projects WHERE id = ?').get(pa)).n, 1);
|
||||||
|
assert.equal((await db.prepare('SELECT status FROM prospects WHERE id = ?').get(prospect)).status, 'sent');
|
||||||
|
assert.equal((await db.prepare('SELECT COUNT(*) n FROM prospect_notes WHERE id = ?').get(note)).n, 1);
|
||||||
|
assert.equal((await db.prepare('SELECT COUNT(*) n FROM prospect_notes').get()).n, 1);
|
||||||
|
assert.equal((await db.prepare('SELECT status FROM jobs WHERE id = ?').get(job)).status, 'queued');
|
||||||
|
assert.equal((await db.prepare('SELECT COUNT(*) n FROM jobs').get()).n, 1, 'aucun job créé');
|
||||||
|
const p = await db.prepare('SELECT * FROM projects WHERE id = ?').get(pa);
|
||||||
|
assert.equal(p.followup_enabled, 0);
|
||||||
|
assert.equal(JSON.parse(p.target_json).description, 'd');
|
||||||
|
assert.ok(p.smtp_enc && !p.smtp_enc.includes('evil'));
|
||||||
|
assert.equal((await db.prepare('SELECT subject FROM templates WHERE project_id = ?').get(pa)).subject, 'Objet A');
|
||||||
|
assert.equal((await db.prepare("SELECT COUNT(*) n FROM prospects WHERE company = 'X'").get()).n, 0, 'rien importé');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('A accède bien à ses propres ressources (contre-épreuve)', async () => {
|
||||||
|
const { pa, prospect } = ids;
|
||||||
|
assert.equal((await A.get(`/api/projects/${pa}/status`)).status, 200);
|
||||||
|
assert.equal((await A.get(`/api/projects/${pa}/prospects`)).status, 200);
|
||||||
|
assert.equal((await A.get(`/api/prospects/${prospect}`)).status, 200);
|
||||||
|
const csv = await A.get(`/api/projects/${pa}/prospects.csv`);
|
||||||
|
assert.equal(csv.status, 200);
|
||||||
|
assert.match(await csv.text(), /alpha@secret-a\.fr/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('listes et pages de B : aucune donnée de A (tableau de bord, réglages, système)', async () => {
|
||||||
|
const dash = await (await B.get('/')).text();
|
||||||
|
assert.doesNotMatch(dash, /Projet Secret|secret-a/i);
|
||||||
|
assert.match(dash, /Aucun projet/);
|
||||||
|
|
||||||
|
const settings = await (await B.get('/settings')).text();
|
||||||
|
assert.doesNotMatch(settings, /secret-a|a-notify|smtp\.secret/i);
|
||||||
|
assert.match(settings, /0 de tes prospects/, 'la liste d\'opposition commune ne montre rien des autres comptes');
|
||||||
|
|
||||||
|
const sys = await (await B.get('/api/system')).json();
|
||||||
|
assert.equal(sys.queue, 0);
|
||||||
|
assert.deepEqual(sys.jobs, []);
|
||||||
|
assert.equal(sys.usage.month.cost, 0);
|
||||||
|
assert.equal(sys.budget.month.used, 0);
|
||||||
|
|
||||||
|
const sysA = await (await A.get('/api/system')).json();
|
||||||
|
assert.equal(sysA.queue, 1);
|
||||||
|
assert.equal(sysA.usage.month.cost, 3.5);
|
||||||
|
assert.equal(sysA.jobs[0].project, 'Projet Secret A');
|
||||||
|
|
||||||
|
const dashA = await (await A.get('/')).text();
|
||||||
|
assert.match(dashA, /Projet Secret A/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('exports et imports CSV : jamais les prospects d\'un autre compte', async () => {
|
||||||
|
const pb = Number((await s.db.prepare('INSERT INTO projects(user_id, name, git_url, created_at) VALUES(?, ?, ?, ?)').run(B.id, 'Projet B', 'https://git.test/b/b.git', now())).lastInsertRowid);
|
||||||
|
await s.db.prepare("INSERT INTO prospects(project_id, company, email, created_at) VALUES(?, 'Beta SAS', 'beta@b.fr', ?)").run(pb, now());
|
||||||
|
const csv = await (await B.get(`/api/projects/${pb}/prospects.csv`)).text();
|
||||||
|
assert.match(csv, /beta@b\.fr/);
|
||||||
|
assert.doesNotMatch(csv, /alpha|secret-a/i);
|
||||||
|
const list = await (await B.get(`/api/projects/${pb}/prospects`)).json();
|
||||||
|
assert.deepEqual(list.rows.map((x) => x.email), ['beta@b.fr']);
|
||||||
|
|
||||||
|
// Importer chez B la même adresse que A : c'est un nouveau prospect de B, sans aucun signe de l'existence de celui de A
|
||||||
|
const r = await B.post(`/api/projects/${pb}/prospects/import`, { csv: 'email;entreprise\nalpha@secret-a.fr;Alpha chez B' });
|
||||||
|
assert.deepEqual(await r.json(), { total: 1, imported: 1, duplicates: 0, blacklisted: 0, invalid: [] });
|
||||||
|
assert.equal((await s.db.prepare('SELECT COUNT(*) n FROM prospects WHERE email = ?').get('alpha@secret-a.fr')).n, 2);
|
||||||
|
const detail = await (await B.get(`/api/prospects/${(await s.db.prepare("SELECT id FROM prospects WHERE project_id = ? AND email = 'alpha@secret-a.fr'").get(pb)).id}`)).json();
|
||||||
|
assert.deepEqual(detail.mails, [], 'pas les mails envoyés par A');
|
||||||
|
assert.deepEqual(detail.notes, [], 'pas les notes de A');
|
||||||
|
|
||||||
|
// Au niveau service : l'export est borné au projet passé
|
||||||
|
const direct = await exportProspects(s.db, pb, parseFilters(new URLSearchParams()));
|
||||||
|
assert.doesNotMatch(direct, /Alpha SARL/);
|
||||||
|
const res = await importProspects(s.db, pb, 'email\nbeta@b.fr');
|
||||||
|
assert.equal(res.duplicates, 1);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('liste d\'opposition commune : elle bloque, mais ne révèle ni motif ni origine d\'un autre compte', async () => {
|
||||||
|
// L'adresse refusée par A bloque aussi B (RGPD), et c'est tout ce que B apprend
|
||||||
|
const pb = (await s.db.prepare("SELECT id FROM projects WHERE user_id = ?").get(B.id)).id;
|
||||||
|
const r = await B.post(`/api/projects/${pb}/prospects/import`, { csv: 'email;entreprise\nrefus@secret-a.fr;Refus' });
|
||||||
|
assert.deepEqual(await r.json(), { total: 1, imported: 0, duplicates: 0, blacklisted: 1, invalid: [] });
|
||||||
|
|
||||||
|
// Un prospect de B dont l'adresse est sur la liste à cause de A : motif générique
|
||||||
|
const id = Number((await s.db.prepare("INSERT INTO prospects(project_id, company, email, status, created_at) VALUES(?, 'Doublon', 'gamma@secret-a.fr', 'new', ?)").run(pb, now())).lastInsertRowid);
|
||||||
|
await s.db.prepare("INSERT INTO blacklist(email, reason, created_at) VALUES('gamma@secret-a.fr', 'bounce', ?)").run(now());
|
||||||
|
const d = await (await B.get(`/api/prospects/${id}`)).json();
|
||||||
|
assert.deepEqual(d.optOut, { reason: 'refused' }, 'le motif « bounce » vient d\'un autre compte : non divulgué');
|
||||||
|
const settings = await (await B.get('/settings')).text();
|
||||||
|
assert.doesNotMatch(settings, /refus@secret-a/);
|
||||||
|
assert.match(settings, /1 de tes prospects/);
|
||||||
|
|
||||||
|
// Désinscription publique : n'expose ni projet ni compte
|
||||||
|
const email = 'alpha@secret-a.fr';
|
||||||
|
const tok = unsubToken(s.app.cfg.secretKey, email);
|
||||||
|
const page = await (await s.anon.get(`/u/${encodeURIComponent(email)}/${tok}`)).text();
|
||||||
|
assert.doesNotMatch(page, /Projet Secret|Alpha SARL|a@x\.fr/);
|
||||||
|
const done = await (await s.anon.post(`/u/${encodeURIComponent(email)}/${tok}`, {}, { origin: null })).text();
|
||||||
|
assert.doesNotMatch(done, /Projet Secret|Alpha SARL|a@x\.fr/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('un même dépôt peut être un projet pour deux comptes (unicité par utilisateur)', async () => {
|
||||||
|
await setSetting(s.db, A.id, 'forgejo_host', 'git.test');
|
||||||
|
await setSetting(s.db, B.id, 'forgejo_host', 'git.test');
|
||||||
|
const url = 'https://git.test/shared/repo.git';
|
||||||
|
assert.equal((await A.post('/api/projects', { name: 'Partagé', gitUrl: url })).status, 200);
|
||||||
|
assert.equal((await B.post('/api/projects', { name: 'Partagé', gitUrl: url })).status, 200);
|
||||||
|
assert.equal((await A.post('/api/projects', { name: 'Doublon', gitUrl: url })).status, 409, 'doublon refusé chez le même compte');
|
||||||
|
assert.equal((await s.db.prepare('SELECT COUNT(*) n FROM projects WHERE git_url = ?').get(url)).n, 2);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('couche service : getProject, enqueue, cancelJob, budget, usage, rapport, envois sont bornés à l\'utilisateur', async () => {
|
||||||
|
const { pa, job } = ids;
|
||||||
|
const { app, db } = s;
|
||||||
|
await assert.rejects(getProject(app, pa, { userId: B.id }), { status: 404 });
|
||||||
|
await assert.rejects(getProject(app, pa), /userId requis/, 'impossible d\'oublier l\'utilisateur');
|
||||||
|
assert.equal((await getProject(app, pa, { userId: A.id })).name, 'Projet Secret A');
|
||||||
|
assert.ok(!(await listProjects(app, B.id)).some((p) => p.id === pa));
|
||||||
|
|
||||||
|
await assert.rejects(enqueue(db, { userId: B.id, projectId: pa, type: 'send' }), { status: 404 });
|
||||||
|
await assert.rejects(cancelJob(db, B.id, job), { status: 404 });
|
||||||
|
assert.equal((await db.prepare('SELECT status FROM jobs WHERE id = ?').get(job)).status, 'queued');
|
||||||
|
|
||||||
|
assert.equal((await budgetState(db, B.id)).month.used, 0);
|
||||||
|
assert.equal((await budgetState(db, A.id)).month.used, 3.5);
|
||||||
|
assert.equal((await usageSummary(db, B.id)).month.cost, 0);
|
||||||
|
|
||||||
|
const wb = await weeklyStats(db, B.id);
|
||||||
|
assert.ok(!wb.projects.some((p) => p.name === 'Projet Secret A'));
|
||||||
|
assert.equal(wb.totals.cost, 0);
|
||||||
|
|
||||||
|
assert.equal(await sentSince(db, 0, A.id), 1);
|
||||||
|
assert.equal(await sentSince(db, 0, B.id), 0, 'plafond d\'envoi calculé par utilisateur');
|
||||||
|
assert.equal(await sentSince(db, 0, B.id, pa), 0, 'même avec un projet qui n\'est pas le sien');
|
||||||
|
|
||||||
|
const jobs = await latestJobs(db, pa);
|
||||||
|
assert.equal(jobs.send.status, 'queued');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('réglages : chaque compte a les siens', async () => {
|
||||||
|
const r = await B.post('/settings', { notify_email: 'b-notify@x.fr', forgejo_host: 'git.b.fr', global_daily_cap: '5', send_delay_min: '5', send_delay_max: '6' }, { form: true });
|
||||||
|
assert.equal(r.status, 303);
|
||||||
|
const val = (u, k) => s.db.prepare('SELECT value FROM user_settings WHERE user_id = ? AND `key` = ?').get(u, k).then((x) => x?.value);
|
||||||
|
assert.equal(await val(B.id, 'notify_email'), 'b-notify@x.fr');
|
||||||
|
assert.equal(await val(A.id, 'notify_email'), 'a-notify@secret-a.fr', 'les réglages de A sont intacts');
|
||||||
|
assert.equal(await val(A.id, 'forgejo_host'), 'git.test');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('tâches de fond : le planificateur ne traite que les comptes actifs, projet par projet avec son propriétaire', async () => {
|
||||||
|
const { app, db } = s;
|
||||||
|
const pb = (await db.prepare('SELECT id FROM projects WHERE user_id = ? LIMIT 1').get(B.id)).id;
|
||||||
|
await db.prepare('UPDATE projects SET followup_enabled = 1 WHERE id = ?').run(pb);
|
||||||
|
await db.prepare("INSERT INTO templates(project_id, kind, subject, body, status, updated_at) VALUES(?, 'followup', '', 'x', 'validated', ?)").run(pb, now());
|
||||||
|
await saveSecretConfig(app, pb, 'smtp_enc', { host: 'h', user: 'u', pass: 'p', fromEmail: 'b@b.fr' }, 'pass');
|
||||||
|
await saveSecretConfig(app, pb, 'imap_enc', { host: 'i' }, 'pass');
|
||||||
|
await db.prepare('UPDATE projects SET inbox_json = ? WHERE id = ?').run(JSON.stringify({ lastOk: now(), lastError: null }), pb);
|
||||||
|
await db.prepare("INSERT INTO prospects(project_id, company, email, status, sent_at, created_at) VALUES(?, 'Due', 'due@b.fr', 'sent', ?, ?)").run(pb, now() - 20 * 86400, now() - 20 * 86400);
|
||||||
|
const sched = new Scheduler({ ...app, isBusinessHours: () => true }, { log: { error() {} } });
|
||||||
|
const wed = new Date('2026-10-21T10:00:00+02:00');
|
||||||
|
await db.prepare("UPDATE users SET status = 'suspended' WHERE id = ?").run(B.id);
|
||||||
|
assert.equal((await sched.queueFollowups({ date: wed })).length, 0, 'compte suspendu : rien en file');
|
||||||
|
await db.prepare("UPDATE users SET status = 'active' WHERE id = ?").run(B.id);
|
||||||
|
const queued = await sched.queueFollowups({ date: wed });
|
||||||
|
assert.equal(queued.length, 1);
|
||||||
|
const j = await db.prepare('SELECT user_id, project_id FROM jobs WHERE id = ?').get(queued[0].id);
|
||||||
|
assert.deepEqual({ u: Number(j.user_id), p: Number(j.project_id) }, { u: B.id, p: pb }, 'le job appartient au propriétaire du projet');
|
||||||
|
});
|
||||||
|
|
@ -1,17 +1,19 @@
|
||||||
import { test } from 'node:test';
|
import { test } from 'node:test';
|
||||||
import assert from 'node:assert/strict';
|
import assert from 'node:assert/strict';
|
||||||
import { randomBytes } from 'node:crypto';
|
import { randomBytes } from 'node:crypto';
|
||||||
import { openDb } from '../src/db.js';
|
import { testDb } from './helpers/db.js';
|
||||||
|
import { addUser } from './helpers/users.js';
|
||||||
import { saveSnapshot, snapshotAll, history, parisDay } from '../src/services/metrics.js';
|
import { saveSnapshot, snapshotAll, history, parisDay } from '../src/services/metrics.js';
|
||||||
import { createProject, saveSecretConfig } from '../src/projects.js';
|
import { createProject, saveSecretConfig } from '../src/projects.js';
|
||||||
|
|
||||||
const ts = (iso) => Math.floor(Date.parse(iso) / 1000);
|
const ts = (iso) => Math.floor(Date.parse(iso) / 1000);
|
||||||
|
|
||||||
function setup() {
|
async function setup() {
|
||||||
const db = openDb(':memory:');
|
const db = await testDb();
|
||||||
const app = { db, cfg: { secretKey: randomBytes(32) } };
|
const app = { db, cfg: { secretKey: randomBytes(32) } };
|
||||||
const id = createProject(app, { name: 'MEP', gitUrl: 'https://g/T/M.git' });
|
const userId = await addUser(db);
|
||||||
return { db, app, id };
|
const id = await createProject(app, { userId, name: 'MEP', gitUrl: 'https://g/T/M.git' });
|
||||||
|
return { db, app, id, userId };
|
||||||
}
|
}
|
||||||
|
|
||||||
test('jour de Paris, même à 23h30 UTC', () => {
|
test('jour de Paris, même à 23h30 UTC', () => {
|
||||||
|
|
@ -19,21 +21,21 @@ test('jour de Paris, même à 23h30 UTC', () => {
|
||||||
assert.equal(parisDay(new Date('2026-12-31T22:59:00Z')), '2026-12-31');
|
assert.equal(parisDay(new Date('2026-12-31T22:59:00Z')), '2026-12-31');
|
||||||
});
|
});
|
||||||
|
|
||||||
test('photo du jour : une ligne par jour, valeurs non numériques ignorées', () => {
|
test('photo du jour : une ligne par jour, valeurs non numériques ignorées', async () => {
|
||||||
const s = setup();
|
const s = await setup();
|
||||||
const d = new Date('2026-10-21T10:00:00Z');
|
const d = new Date('2026-10-21T10:00:00Z');
|
||||||
saveSnapshot(s.db, s.id, { users: 10, clients: 2, revenue: 'n/a' }, { date: d });
|
await saveSnapshot(s.db, s.id, { users: 10, clients: 2, revenue: 'n/a' }, { date: d });
|
||||||
saveSnapshot(s.db, s.id, { users: 12, clients: 3, revenue: 150.5 }, { date: d });
|
await saveSnapshot(s.db, s.id, { users: 12, clients: 3, revenue: 150.5 }, { date: d });
|
||||||
const rows = s.db.prepare('SELECT * FROM metrics_daily').all();
|
const rows = await s.db.prepare('SELECT * FROM metrics_daily').all();
|
||||||
assert.equal(rows.length, 1, 'mise à jour, pas de doublon');
|
assert.equal(rows.length, 1, 'mise à jour, pas de doublon');
|
||||||
assert.deepEqual({ ...rows[0] }, { project_id: s.id, day: '2026-10-21', users: 12, clients: 3, revenue: 150.5 });
|
assert.deepEqual({ ...rows[0] }, { project_id: s.id, day: '2026-10-21', users: 12, clients: 3, revenue: 150.5 });
|
||||||
});
|
});
|
||||||
|
|
||||||
test('photo automatique : une seule par jour et par projet, les erreurs n\'arrêtent pas les autres', async () => {
|
test('photo automatique : une seule par jour et par projet, les erreurs n\'arrêtent pas les autres', async () => {
|
||||||
const s = setup();
|
const s = await setup();
|
||||||
const other = createProject(s.app, { name: 'GoSortir', gitUrl: 'https://g/T/G.git' });
|
const other = await createProject(s.app, { userId: s.userId, name: 'GoSortir', gitUrl: 'https://g/T/G.git' });
|
||||||
createProject(s.app, { name: 'Sans BDD', gitUrl: 'https://g/T/X.git' });
|
await createProject(s.app, { userId: s.userId, name: 'Sans BDD', gitUrl: 'https://g/T/X.git' });
|
||||||
for (const id of [s.id, other]) saveSecretConfig(s.app, id, 'db_enc', { type: 'mysql', host: 'h', sql_users: 'SELECT 1' }, 'password');
|
for (const id of [s.id, other]) await saveSecretConfig(s.app, id, 'db_enc', { type: 'mysql', host: 'h', sql_users: 'SELECT 1' }, 'password');
|
||||||
let calls = 0;
|
let calls = 0;
|
||||||
s.app.fetchRecap = async (id) => { calls++; if (id === other) throw new Error('BDD injoignable'); return { users: 5, clients: 1, revenue: 30 }; };
|
s.app.fetchRecap = async (id) => { calls++; if (id === other) throw new Error('BDD injoignable'); return { users: 5, clients: 1, revenue: 30 }; };
|
||||||
const log = { errors: [], error(...a) { this.errors.push(a.join(' ')); } };
|
const log = { errors: [], error(...a) { this.errors.push(a.join(' ')); } };
|
||||||
|
|
@ -44,15 +46,15 @@ test('photo automatique : une seule par jour et par projet, les erreurs n\'arrê
|
||||||
await snapshotAll(s.app, { date: new Date('2026-10-21T15:00:00Z'), log });
|
await snapshotAll(s.app, { date: new Date('2026-10-21T15:00:00Z'), log });
|
||||||
assert.equal(calls, 3, 'déjà pris : seul le projet en erreur est retenté');
|
assert.equal(calls, 3, 'déjà pris : seul le projet en erreur est retenté');
|
||||||
await snapshotAll(s.app, { date: new Date('2026-10-22T08:00:00Z'), log });
|
await snapshotAll(s.app, { date: new Date('2026-10-22T08:00:00Z'), log });
|
||||||
assert.equal(s.db.prepare('SELECT COUNT(*) n FROM metrics_daily WHERE project_id = ?').get(s.id).n, 2);
|
assert.equal((await s.db.prepare('SELECT COUNT(*) n FROM metrics_daily WHERE project_id = ?').get(s.id)).n, 2);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('historique : fenêtre 30/90 jours et semaines du lundi au dimanche (heure de Paris)', () => {
|
test('historique : fenêtre 30/90 jours et semaines du lundi au dimanche (heure de Paris)', async () => {
|
||||||
const s = setup();
|
const s = await setup();
|
||||||
const at = ts('2026-10-21T12:00:00Z'); // mercredi
|
const at = ts('2026-10-21T12:00:00Z'); // mercredi
|
||||||
for (const day of ['2026-08-01', '2026-09-25', '2026-10-20']) s.db.prepare('INSERT INTO metrics_daily VALUES(?, ?, 1, 1, 1)').run(s.id, day);
|
for (const day of ['2026-08-01', '2026-09-25', '2026-10-20']) await s.db.prepare('INSERT INTO metrics_daily VALUES(?, ?, 1, 1, 1)').run(s.id, day);
|
||||||
assert.deepEqual(history(s.db, s.id, { days: 30, at }).daily.map((d) => d.day), ['2026-09-25', '2026-10-20']);
|
assert.deepEqual((await history(s.db, s.id, { days: 30, at })).daily.map((d) => d.day), ['2026-09-25', '2026-10-20']);
|
||||||
assert.equal(history(s.db, s.id, { days: 90, at }).daily.length, 3);
|
assert.equal((await history(s.db, s.id, { days: 90, at })).daily.length, 3);
|
||||||
|
|
||||||
const log = (iso, kind = 'initial', error = null) => s.db.prepare('INSERT INTO mail_log(project_id, email, sent_at, kind, error) VALUES(?, ?, ?, ?, ?)').run(s.id, 'x@y.fr', ts(iso), kind, error);
|
const log = (iso, kind = 'initial', error = null) => s.db.prepare('INSERT INTO mail_log(project_id, email, sent_at, kind, error) VALUES(?, ?, ?, ?, ?)').run(s.id, 'x@y.fr', ts(iso), kind, error);
|
||||||
log('2026-10-19T00:30:00+02:00'); // lundi 0h30 Paris = dimanche UTC : semaine du 19
|
log('2026-10-19T00:30:00+02:00'); // lundi 0h30 Paris = dimanche UTC : semaine du 19
|
||||||
|
|
@ -60,8 +62,8 @@ test('historique : fenêtre 30/90 jours et semaines du lundi au dimanche (heure
|
||||||
log('2026-10-20T10:00:00+02:00');
|
log('2026-10-20T10:00:00+02:00');
|
||||||
log('2026-10-20T10:00:00+02:00', 'followup'); // les relances ne comptent pas comme premiers mails
|
log('2026-10-20T10:00:00+02:00', 'followup'); // les relances ne comptent pas comme premiers mails
|
||||||
log('2026-10-20T10:00:00+02:00', 'initial', '550'); // ni les échecs
|
log('2026-10-20T10:00:00+02:00', 'initial', '550'); // ni les échecs
|
||||||
s.db.prepare('INSERT INTO prospects(project_id, company, email, replied_at, created_at) VALUES(?, ?, ?, ?, ?)').run(s.id, 'A', 'a@a.fr', ts('2026-10-21T09:00:00+02:00'), at);
|
await s.db.prepare('INSERT INTO prospects(project_id, company, email, replied_at, created_at) VALUES(?, ?, ?, ?, ?)').run(s.id, 'A', 'a@a.fr', ts('2026-10-21T09:00:00+02:00'), at);
|
||||||
const w = history(s.db, s.id, { days: 30, at }).weeks;
|
const w = (await history(s.db, s.id, { days: 30, at })).weeks;
|
||||||
assert.equal(w.length, 5);
|
assert.equal(w.length, 5);
|
||||||
assert.equal(w.at(-1).start, '2026-10-19');
|
assert.equal(w.at(-1).start, '2026-10-19');
|
||||||
assert.deepEqual(w.slice(-2).map((x) => [x.start, x.sent, x.replies]), [['2026-10-12', 1, 0], ['2026-10-19', 2, 1]]);
|
assert.deepEqual(w.slice(-2).map((x) => [x.start, x.sent, x.replies]), [['2026-10-12', 1, 0], ['2026-10-19', 2, 1]]);
|
||||||
|
|
|
||||||
136
test/migrate-sqlite.test.js
Normal file
136
test/migrate-sqlite.test.js
Normal file
|
|
@ -0,0 +1,136 @@
|
||||||
|
import { test } from 'node:test';
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import { mkdtempSync, rmSync } from 'node:fs';
|
||||||
|
import { join } from 'node:path';
|
||||||
|
import { tmpdir } from 'node:os';
|
||||||
|
import { DatabaseSync } from 'node:sqlite';
|
||||||
|
import { openDb, now } from '../src/db.js';
|
||||||
|
import { migrateSqliteToMysql, TABLES } from '../scripts/migrate-sqlite-to-mysql.js';
|
||||||
|
import { testDb } from './helpers/db.js';
|
||||||
|
import { addUser } from './helpers/users.js';
|
||||||
|
|
||||||
|
const OWNER = 'tony@x.fr';
|
||||||
|
|
||||||
|
// Fabrique une "ancienne" base mono-utilisateur : schéma d'avant les comptes (migration 1), ids non contigus,
|
||||||
|
// accents, puis marquée user_version 8 (ancien format sans schema_migrations)
|
||||||
|
async function legacyFile(dir) {
|
||||||
|
const file = join(dir, 'aitools.sqlite');
|
||||||
|
const db = await openDb({ driver: 'sqlite', file }, { upTo: 1 });
|
||||||
|
const t = now();
|
||||||
|
await db.prepare('INSERT INTO projects(id, name, git_url, daily_mail_cap, created_at) VALUES(?, ?, ?, ?, ?)').run(7, 'Café Été', 'https://git.x/a.git', 12, t);
|
||||||
|
await db.prepare('INSERT INTO projects(id, name, git_url, created_at) VALUES(?, ?, ?, ?)').run(42, 'Autre', 'https://git.x/b.git', t);
|
||||||
|
await db.prepare('INSERT INTO prospects(id, project_id, company, email, score, created_at) VALUES(?, ?, ?, ?, ?, ?)').run(1001, 7, 'Boulangerie Léa', 'lea@x.fr', 8, t);
|
||||||
|
await db.prepare('INSERT INTO prospects(id, project_id, company, email, created_at) VALUES(?, ?, ?, ?, ?)').run(1002, 7, 'Garage', 'g@x.fr', t);
|
||||||
|
await db.prepare('INSERT INTO prospect_notes(id, prospect_id, body, created_at) VALUES(?, ?, ?, ?)').run(5, 1001, 'à rappeler 🙂', t);
|
||||||
|
await db.prepare('INSERT INTO templates(project_id, kind, subject, body, updated_at) VALUES(?, ?, ?, ?, ?)').run(7, 'initial', 'Objet', 'Corps', t);
|
||||||
|
await db.prepare('INSERT INTO jobs(id, project_id, type, status, cost_usd, created_at) VALUES(?, ?, ?, ?, ?, ?)').run(300, 7, 'analyze', 'done', 0.0123, t);
|
||||||
|
await db.prepare('INSERT INTO mail_log(id, project_id, prospect_id, email, sent_at, message_id) VALUES(?, ?, ?, ?, ?, ?)').run(9, 7, 1001, 'lea@x.fr', t, '<a@b>');
|
||||||
|
await db.prepare('INSERT INTO blacklist(email, reason, created_at) VALUES(?, ?, ?)').run('no@x.fr', 'unsubscribe', t);
|
||||||
|
await db.prepare('INSERT INTO metrics_daily(project_id, day, users, clients, revenue) VALUES(?, ?, ?, ?, ?)').run(7, '2026-10-21', 10, 2, 99.5);
|
||||||
|
await db.prepare('INSERT INTO settings(`key`, value) VALUES(?, ?)').run('notify_email', 'tony@x.fr');
|
||||||
|
await db.prepare('INSERT INTO sessions(id, email, created_at, expires_at) VALUES(?, ?, ?, ?)').run('AbC_d-1', 'tony@x.fr', t, t + 100);
|
||||||
|
await db.close();
|
||||||
|
// Ancien format : pas de schema_migrations, version dans user_version
|
||||||
|
const raw = new DatabaseSync(file);
|
||||||
|
raw.exec('DROP TABLE schema_migrations; PRAGMA user_version = 8;');
|
||||||
|
raw.close();
|
||||||
|
return file;
|
||||||
|
}
|
||||||
|
|
||||||
|
test('migration SQLite → cible : ids conservés, tout rattaché au propriétaire, comptes identiques', async () => {
|
||||||
|
const dir = mkdtempSync(join(tmpdir(), 'mig-'));
|
||||||
|
try {
|
||||||
|
const sourcePath = await legacyFile(dir);
|
||||||
|
const db = await testDb();
|
||||||
|
const lines = [];
|
||||||
|
const r = await migrateSqliteToMysql({ sourcePath, db, ownerEmail: OWNER, log: (l) => lines.push(l) });
|
||||||
|
assert.deepEqual(r.tables.map((x) => x.table), TABLES);
|
||||||
|
for (const x of r.tables) assert.equal(x.source, x.target, x.table);
|
||||||
|
assert.equal(r.tables.find((x) => x.table === 'prospects').copied, 2);
|
||||||
|
assert.equal(r.total, 11, 'les sessions de l\'ancienne base ne sont pas copiées');
|
||||||
|
assert.equal(lines.length, TABLES.length + 1, 'une ligne par table + le propriétaire');
|
||||||
|
|
||||||
|
const owner = await db.prepare('SELECT id, is_admin, status FROM users WHERE email = ?').get(OWNER);
|
||||||
|
assert.equal(owner.is_admin, 1);
|
||||||
|
assert.equal(owner.id, r.ownerId);
|
||||||
|
assert.equal((await db.prepare('SELECT COUNT(*) n FROM users').get()).n, 1);
|
||||||
|
assert.deepEqual((await db.prepare('SELECT id, name, user_id FROM projects ORDER BY id').all()).map((p) => [p.id, p.name, Number(p.user_id)]),
|
||||||
|
[[7, 'Café Été', owner.id], [42, 'Autre', owner.id]]);
|
||||||
|
assert.equal((await db.prepare('SELECT user_id FROM jobs WHERE id = 300').get()).user_id, owner.id);
|
||||||
|
assert.deepEqual({ ...(await db.prepare('SELECT user_id, `key`, value FROM user_settings').get()) }, { user_id: owner.id, key: 'notify_email', value: 'tony@x.fr' });
|
||||||
|
assert.equal((await db.prepare('SELECT COUNT(*) n FROM sessions').get()).n, 0);
|
||||||
|
assert.equal((await db.prepare('SELECT company FROM prospects WHERE id = ?').get(1001)).company, 'Boulangerie Léa');
|
||||||
|
assert.equal((await db.prepare('SELECT body FROM prospect_notes WHERE id = 5').get()).body, 'à rappeler 🙂');
|
||||||
|
assert.equal((await db.prepare('SELECT cost_usd FROM jobs WHERE id = 300').get()).cost_usd, 0.0123);
|
||||||
|
assert.equal((await db.prepare('SELECT daily_mail_cap FROM projects WHERE id = 7').get()).daily_mail_cap, 12);
|
||||||
|
assert.equal((await db.prepare('SELECT revenue FROM metrics_daily').get()).revenue, 99.5);
|
||||||
|
// Les relations survivent à la copie : suppression en cascade
|
||||||
|
await db.prepare('DELETE FROM projects WHERE id = 7').run();
|
||||||
|
assert.equal((await db.prepare('SELECT COUNT(*) n FROM prospects').get()).n, 0);
|
||||||
|
// Les nouvelles lignes continuent après le plus grand id copié
|
||||||
|
const next = await db.prepare('INSERT INTO projects(user_id, name, git_url, created_at) VALUES(?, ?, ?, ?)').run(owner.id, 'Neuf', 'https://git.x/c.git', now());
|
||||||
|
assert.ok(next.lastInsertRowid > 42);
|
||||||
|
} finally { rmSync(dir, { recursive: true, force: true }); }
|
||||||
|
});
|
||||||
|
|
||||||
|
test('migration : le propriétaire existant (même email) est réutilisé, l\'email est obligatoire', async () => {
|
||||||
|
const dir = mkdtempSync(join(tmpdir(), 'mig-'));
|
||||||
|
try {
|
||||||
|
const sourcePath = await legacyFile(dir);
|
||||||
|
const db = await testDb();
|
||||||
|
const id = await addUser(db, { email: OWNER, admin: false });
|
||||||
|
await assert.rejects(migrateSqliteToMysql({ sourcePath, db, ownerEmail: '' }), /ADMIN_EMAILS/);
|
||||||
|
const r = await migrateSqliteToMysql({ sourcePath, db, ownerEmail: 'Tony@X.fr' });
|
||||||
|
assert.equal(r.ownerId, id);
|
||||||
|
assert.equal((await db.prepare('SELECT COUNT(*) n FROM users').get()).n, 1);
|
||||||
|
assert.equal((await db.prepare('SELECT COUNT(*) n FROM projects WHERE user_id = ?').get(id)).n, 2);
|
||||||
|
} finally { rmSync(dir, { recursive: true, force: true }); }
|
||||||
|
});
|
||||||
|
|
||||||
|
test('migration : refuse une cible non vide, --force la vide puis copie', async () => {
|
||||||
|
const dir = mkdtempSync(join(tmpdir(), 'mig-'));
|
||||||
|
try {
|
||||||
|
const sourcePath = await legacyFile(dir);
|
||||||
|
const db = await testDb();
|
||||||
|
const u = await addUser(db, { email: OWNER });
|
||||||
|
await db.prepare('INSERT INTO projects(id, user_id, name, git_url, created_at) VALUES(?, ?, ?, ?, ?)').run(1, u, 'Déjà là', 'https://git.x/z.git', now());
|
||||||
|
await assert.rejects(migrateSqliteToMysql({ sourcePath, db, ownerEmail: OWNER }), /pas vide.*projects \(1\).*--force/s);
|
||||||
|
assert.equal((await db.prepare('SELECT COUNT(*) n FROM projects').get()).n, 1, 'rien n\'a été touché');
|
||||||
|
|
||||||
|
const r = await migrateSqliteToMysql({ sourcePath, db, ownerEmail: OWNER, force: true });
|
||||||
|
assert.equal(r.total, 11);
|
||||||
|
assert.deepEqual((await db.prepare('SELECT id FROM projects ORDER BY id').all()).map((p) => p.id), [7, 42]);
|
||||||
|
} finally { rmSync(dir, { recursive: true, force: true }); }
|
||||||
|
});
|
||||||
|
|
||||||
|
test('migration : une erreur en cours de copie annule tout (transaction), propriétaire compris', async () => {
|
||||||
|
const dir = mkdtempSync(join(tmpdir(), 'mig-'));
|
||||||
|
try {
|
||||||
|
const sourcePath = await legacyFile(dir);
|
||||||
|
// Source corrompue après coup : un prospect pointe vers un projet qui n'existe pas
|
||||||
|
const raw = new DatabaseSync(sourcePath);
|
||||||
|
raw.exec('PRAGMA foreign_keys = OFF; UPDATE prospects SET project_id = 999 WHERE id = 1002;');
|
||||||
|
raw.close();
|
||||||
|
const db = await testDb();
|
||||||
|
await assert.rejects(migrateSqliteToMysql({ sourcePath, db, ownerEmail: OWNER }), /FOREIGN KEY|child row/i);
|
||||||
|
for (const t of TABLES) assert.equal((await db.prepare(`SELECT COUNT(*) n FROM \`${t === 'settings' ? 'user_settings' : t}\``).get()).n, 0, `${t} doit rester vide`);
|
||||||
|
assert.equal((await db.prepare('SELECT COUNT(*) n FROM users').get()).n, 0, 'le propriétaire n\'est pas créé non plus');
|
||||||
|
} finally { rmSync(dir, { recursive: true, force: true }); }
|
||||||
|
});
|
||||||
|
|
||||||
|
test('migration : refuse une source dans une mauvaise version, déjà multi-utilisateur, ou absente', async () => {
|
||||||
|
const dir = mkdtempSync(join(tmpdir(), 'mig-'));
|
||||||
|
try {
|
||||||
|
const sourcePath = await legacyFile(dir);
|
||||||
|
const raw = new DatabaseSync(sourcePath);
|
||||||
|
raw.exec('PRAGMA user_version = 5;');
|
||||||
|
raw.close();
|
||||||
|
const db = await testDb();
|
||||||
|
await assert.rejects(migrateSqliteToMysql({ sourcePath, db, ownerEmail: OWNER }), /version 5/);
|
||||||
|
await assert.rejects(migrateSqliteToMysql({ sourcePath: join(dir, 'nope.sqlite'), db, ownerEmail: OWNER }), /introuvable/);
|
||||||
|
|
||||||
|
const current = join(dir, 'current.sqlite');
|
||||||
|
await (await openDb({ driver: 'sqlite', file: current })).close();
|
||||||
|
await assert.rejects(migrateSqliteToMysql({ sourcePath: current, db, ownerEmail: OWNER }), /multi-utilisateur/);
|
||||||
|
} finally { rmSync(dir, { recursive: true, force: true }); }
|
||||||
|
});
|
||||||
|
|
@ -1,7 +1,9 @@
|
||||||
import { test } from 'node:test';
|
import { test } from 'node:test';
|
||||||
import assert from 'node:assert/strict';
|
import assert from 'node:assert/strict';
|
||||||
import { parisParts, parisTime, nextNightSlot, addParisDays } from '../src/services/paris-time.js';
|
import { parisParts, parisTime, nextNightSlot, addParisDays } from '../src/services/paris-time.js';
|
||||||
import { openDb, now } from '../src/db.js';
|
import { now } from '../src/db.js';
|
||||||
|
import { testDb } from './helpers/db.js';
|
||||||
|
import { addUser } from './helpers/users.js';
|
||||||
import { enqueue, Worker, latestJobs } from '../src/services/jobs.js';
|
import { enqueue, Worker, latestJobs } from '../src/services/jobs.js';
|
||||||
|
|
||||||
const iso = (d) => d.toISOString();
|
const iso = (d) => d.toISOString();
|
||||||
|
|
@ -25,18 +27,19 @@ test('prochain créneau de nuit (1h-6h Paris)', () => {
|
||||||
});
|
});
|
||||||
|
|
||||||
test('le worker ne démarre pas un job programmé avant son heure', async () => {
|
test('le worker ne démarre pas un job programmé avant son heure', async () => {
|
||||||
const db = openDb(':memory:');
|
const db = await testDb();
|
||||||
let clock = now();
|
let clock = now();
|
||||||
const ran = [];
|
const ran = [];
|
||||||
const w = new Worker(db, { prospect: async () => { ran.push('prospect'); }, evolution: async () => { ran.push('evolution'); } },
|
const w = new Worker(db, { prospect: async () => { ran.push('prospect'); }, evolution: async () => { ran.push('evolution'); } },
|
||||||
{ thermalMax: 999, log: { error() {} }, clock: () => clock });
|
{ thermalMax: 999, log: { error() {} }, clock: () => clock });
|
||||||
db.prepare("INSERT INTO projects(name, git_url, created_at) VALUES('p', 'u', ?)").run(now());
|
const u = await addUser(db);
|
||||||
enqueue(db, { projectId: 1, type: 'prospect', runAfter: clock + 3600 });
|
await db.prepare("INSERT INTO projects(user_id, name, git_url, created_at) VALUES(?, 'p', 'u', ?)").run(u, now());
|
||||||
enqueue(db, { projectId: 1, type: 'evolution' });
|
await enqueue(db, { userId: u, projectId: 1, type: 'prospect', runAfter: clock + 3600 });
|
||||||
|
await enqueue(db, { userId: u, projectId: 1, type: 'evolution' });
|
||||||
assert.equal(await w.tick(), true);
|
assert.equal(await w.tick(), true);
|
||||||
assert.deepEqual(ran, ['evolution'], 'le job immédiat passe devant le job programmé');
|
assert.deepEqual(ran, ['evolution'], 'le job immédiat passe devant le job programmé');
|
||||||
assert.equal(await w.tick(), false, 'rien à faire avant l\'heure');
|
assert.equal(await w.tick(), false, 'rien à faire avant l\'heure');
|
||||||
assert.equal(latestJobs(db, 1).prospect.runAfter, clock + 3600);
|
assert.equal((await latestJobs(db, 1)).prospect.runAfter, clock + 3600);
|
||||||
clock += 3601;
|
clock += 3601;
|
||||||
assert.equal(await w.tick(), true);
|
assert.equal(await w.tick(), true);
|
||||||
assert.deepEqual(ran, ['evolution', 'prospect']);
|
assert.deepEqual(ran, ['evolution', 'prospect']);
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,9 @@
|
||||||
import { test } from 'node:test';
|
import { test } from 'node:test';
|
||||||
import assert from 'node:assert/strict';
|
import assert from 'node:assert/strict';
|
||||||
import { randomBytes } from 'node:crypto';
|
import { randomBytes } from 'node:crypto';
|
||||||
import { openDb, now, setSetting } from '../src/db.js';
|
import { now, setSetting } from '../src/db.js';
|
||||||
|
import { testDb } from './helpers/db.js';
|
||||||
|
import { addUser } from './helpers/users.js';
|
||||||
import { encrypt } from '../src/crypto.js';
|
import { encrypt } from '../src/crypto.js';
|
||||||
import { notify, notifyJob, WEBHOOK_RE } from '../src/services/notify.js';
|
import { notify, notifyJob, WEBHOOK_RE } from '../src/services/notify.js';
|
||||||
import { Worker, enqueue } from '../src/services/jobs.js';
|
import { Worker, enqueue } from '../src/services/jobs.js';
|
||||||
|
|
@ -10,17 +12,18 @@ import { createProject, saveSecretConfig } from '../src/projects.js';
|
||||||
|
|
||||||
const HOOK = 'https://discord.com/api/webhooks/123456789012345678/abcdefghijklmnopqrstuvwxyz-ABC_123';
|
const HOOK = 'https://discord.com/api/webhooks/123456789012345678/abcdefghijklmnopqrstuvwxyz-ABC_123';
|
||||||
|
|
||||||
function setup({ events } = {}) {
|
async function setup({ events } = {}) {
|
||||||
const db = openDb(':memory:');
|
const db = await testDb();
|
||||||
const sent = [];
|
const sent = [];
|
||||||
const app = {
|
const app = {
|
||||||
db, cfg: { secretKey: randomBytes(32), appUrl: 'https://ai.test' },
|
db, cfg: { secretKey: randomBytes(32), appUrl: 'https://ai.test' },
|
||||||
fetch: async (url, opts) => { sent.push({ url, body: JSON.parse(opts.body) }); return { ok: true, status: 204 }; },
|
fetch: async (url, opts) => { sent.push({ url, body: JSON.parse(opts.body) }); return { ok: true, status: 204 }; },
|
||||||
};
|
};
|
||||||
setSetting(db, 'discord_webhook_enc', encrypt(app.cfg.secretKey, HOOK));
|
const userId = await addUser(db);
|
||||||
if (events) setSetting(db, 'discord_events', JSON.stringify(events));
|
await setSetting(db, userId, 'discord_webhook_enc', encrypt(app.cfg.secretKey, HOOK));
|
||||||
const id = createProject(app, { name: 'MonEspacePro', gitUrl: 'https://g/T/M.git' });
|
if (events) await setSetting(db, userId, 'discord_events', JSON.stringify(events));
|
||||||
return { db, app, sent, id };
|
const id = await createProject(app, { userId, name: 'MonEspacePro', gitUrl: 'https://g/T/M.git' });
|
||||||
|
return { db, app, sent, id, userId };
|
||||||
}
|
}
|
||||||
|
|
||||||
test('validation stricte de l\'URL de webhook', () => {
|
test('validation stricte de l\'URL de webhook', () => {
|
||||||
|
|
@ -33,8 +36,8 @@ test('validation stricte de l\'URL de webhook', () => {
|
||||||
});
|
});
|
||||||
|
|
||||||
test('notif : forme du message, aucune mention possible', async () => {
|
test('notif : forme du message, aucune mention possible', async () => {
|
||||||
const s = setup();
|
const s = await setup();
|
||||||
assert.equal(await notify(s.app, 'reply', { title: '@everyone Boulangerie', description: 'x', level: 'ok', fields: [{ name: 'a', value: '' }] }), true);
|
assert.equal(await notify(s.app, s.userId, 'reply', { title: '@everyone Boulangerie', description: 'x', level: 'ok', fields: [{ name: 'a', value: '' }] }), true);
|
||||||
const b = s.sent[0].body;
|
const b = s.sent[0].body;
|
||||||
assert.equal(s.sent[0].url, HOOK);
|
assert.equal(s.sent[0].url, HOOK);
|
||||||
assert.deepEqual(b.allowed_mentions, { parse: [] });
|
assert.deepEqual(b.allowed_mentions, { parse: [] });
|
||||||
|
|
@ -44,24 +47,24 @@ test('notif : forme du message, aucune mention possible', async () => {
|
||||||
});
|
});
|
||||||
|
|
||||||
test('événement désactivé, webhook absent ou Discord en panne : rien ne casse', async () => {
|
test('événement désactivé, webhook absent ou Discord en panne : rien ne casse', async () => {
|
||||||
const s = setup({ events: ['job_error'] });
|
const s = await setup({ events: ['job_error'] });
|
||||||
assert.equal(await notify(s.app, 'reply', { title: 'x' }), false);
|
assert.equal(await notify(s.app, s.userId, 'reply', { title: 'x' }), false);
|
||||||
assert.equal(s.sent.length, 0);
|
assert.equal(s.sent.length, 0);
|
||||||
assert.equal(await notify(s.app, 'reply', { title: 'x' }, { force: true }), true, 'le bouton de test force l\'envoi');
|
assert.equal(await notify(s.app, s.userId, 'reply', { title: 'x' }, { force: true }), true, 'le bouton de test force l\'envoi');
|
||||||
const warn = console.warn; console.warn = () => {};
|
const warn = console.warn; console.warn = () => {};
|
||||||
try {
|
try {
|
||||||
s.app.fetch = async () => ({ ok: false, status: 404 });
|
s.app.fetch = async () => ({ ok: false, status: 404 });
|
||||||
assert.equal(await notify(s.app, 'job_error', { title: 'x' }), false);
|
assert.equal(await notify(s.app, s.userId, 'job_error', { title: 'x' }), false);
|
||||||
s.app.fetch = async () => { throw new Error('réseau'); };
|
s.app.fetch = async () => { throw new Error('réseau'); };
|
||||||
assert.equal(await notify(s.app, 'job_error', { title: 'x' }), false);
|
assert.equal(await notify(s.app, s.userId, 'job_error', { title: 'x' }), false);
|
||||||
} finally { console.warn = warn; }
|
} finally { console.warn = warn; }
|
||||||
setSetting(s.db, 'discord_webhook_enc', null);
|
await setSetting(s.db, s.userId, 'discord_webhook_enc', null);
|
||||||
assert.equal(await notify(s.app, 'job_error', { title: 'x' }), false);
|
assert.equal(await notify(s.app, s.userId, 'job_error', { title: 'x' }), false);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('fin de job : succès, erreur, relances, et silence pour les jobs courts', async () => {
|
test('fin de job : succès, erreur, relances, et silence pour les jobs courts', async () => {
|
||||||
const s = setup();
|
const s = await setup();
|
||||||
const job = (type) => ({ type, project_id: s.id });
|
const job = (type) => ({ type, project_id: s.id, user_id: s.userId });
|
||||||
await notifyJob(s.app, job('prospect'), { status: 'done', result: { found: 7, requested: 10 } });
|
await notifyJob(s.app, job('prospect'), { status: 'done', result: { found: 7, requested: 10 } });
|
||||||
await notifyJob(s.app, job('send'), { status: 'error', error: 'SMTP refusé' });
|
await notifyJob(s.app, job('send'), { status: 'error', error: 'SMTP refusé' });
|
||||||
await notifyJob(s.app, job('followup'), { status: 'done', result: { sent: 3, failed: 0 } });
|
await notifyJob(s.app, job('followup'), { status: 'done', result: { sent: 3, failed: 0 } });
|
||||||
|
|
@ -76,29 +79,29 @@ test('fin de job : succès, erreur, relances, et silence pour les jobs courts',
|
||||||
});
|
});
|
||||||
|
|
||||||
test('le worker notifie en fin de job, et un callback qui plante ne le bloque pas', async () => {
|
test('le worker notifie en fin de job, et un callback qui plante ne le bloque pas', async () => {
|
||||||
const s = setup();
|
const s = await setup();
|
||||||
const seen = [];
|
const seen = [];
|
||||||
const w = new Worker(s.db, { prospect: async () => ({ found: 2, requested: 5 }), evolution: async () => { throw new Error('boom'); } }, {
|
const w = new Worker(s.db, { prospect: async () => ({ found: 2, requested: 5 }), evolution: async () => { throw new Error('boom'); } }, {
|
||||||
thermalMax: 999, log: { error() {} },
|
thermalMax: 999, log: { error() {} },
|
||||||
onFinish: (job, r) => { seen.push(`${job.type}:${r.status}`); if (job.type === 'evolution') throw new Error('callback cassé'); },
|
onFinish: (job, r) => { seen.push(`${job.type}:${r.status}`); if (job.type === 'evolution') throw new Error('callback cassé'); },
|
||||||
});
|
});
|
||||||
enqueue(s.db, { projectId: s.id, type: 'prospect' });
|
await enqueue(s.db, { userId: s.userId, projectId: s.id, type: 'prospect' });
|
||||||
enqueue(s.db, { projectId: s.id, type: 'evolution' });
|
await enqueue(s.db, { userId: s.userId, projectId: s.id, type: 'evolution' });
|
||||||
await w.tick(); await w.tick();
|
await w.tick(); await w.tick();
|
||||||
assert.deepEqual(seen, ['prospect:done', 'evolution:error']);
|
assert.deepEqual(seen, ['prospect:done', 'evolution:error']);
|
||||||
assert.equal(s.db.prepare("SELECT COUNT(*) n FROM jobs WHERE status IN ('done','error')").get().n, 2);
|
assert.equal((await s.db.prepare("SELECT COUNT(*) n FROM jobs WHERE status IN ('done','error')").get()).n, 2);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('nouvelles réponses détectées → une notif avec les entreprises', async () => {
|
test('nouvelles réponses détectées → une notif avec les entreprises', async () => {
|
||||||
const s = setup();
|
const s = await setup();
|
||||||
saveSecretConfig(s.app, s.id, 'smtp_enc', { host: 'h', user: 'u', pass: 'p', fromEmail: 'a@x.fr' }, 'pass');
|
await saveSecretConfig(s.app, s.id, 'smtp_enc', { host: 'h', user: 'u', pass: 'p', fromEmail: 'a@x.fr' }, 'pass');
|
||||||
saveSecretConfig(s.app, s.id, 'imap_enc', { host: 'imap.x' }, 'pass');
|
await saveSecretConfig(s.app, s.id, 'imap_enc', { host: 'imap.x' }, 'pass');
|
||||||
s.db.prepare("INSERT INTO prospects(project_id, company, email, status, sent_at, created_at) VALUES(?, 'Le Fournil', 'contact@fournil.fr', 'sent', ?, ?)").run(s.id, now(), now());
|
await s.db.prepare("INSERT INTO prospects(project_id, company, email, status, sent_at, created_at) VALUES(?, 'Le Fournil', 'contact@fournil.fr', 'sent', ?, ?)").run(s.id, now(), now());
|
||||||
s.app.fetchInbox = async () => ({ uidValidity: '1', lastUid: 1, messages: [{ uid: 1, from: 'contact@fournil.fr', subject: 'Re: idée' }] });
|
s.app.fetchInbox = async () => ({ uidValidity: '1', lastUid: 1, messages: [{ uid: 1, from: 'contact@fournil.fr', subject: 'Re: idée' }] });
|
||||||
await checkInbox(s.app, s.id);
|
await checkInbox(s.app, s.userId, s.id);
|
||||||
assert.equal(s.sent.length, 1);
|
assert.equal(s.sent.length, 1);
|
||||||
assert.equal(s.sent[0].body.embeds[0].title, 'MonEspacePro · 1 réponse(s) de prospect');
|
assert.equal(s.sent[0].body.embeds[0].title, 'MonEspacePro · 1 réponse(s) de prospect');
|
||||||
assert.match(s.sent[0].body.embeds[0].description, /\*\*Le Fournil\*\* \(contact@fournil\.fr\) : Re: idée/);
|
assert.match(s.sent[0].body.embeds[0].description, /\*\*Le Fournil\*\* \(contact@fournil\.fr\) : Re: idée/);
|
||||||
await checkInbox(s.app, s.id);
|
await checkInbox(s.app, s.userId, s.id);
|
||||||
assert.equal(s.sent.length, 1, 'pas de notif quand rien de neuf');
|
assert.equal(s.sent.length, 1, 'pas de notif quand rien de neuf');
|
||||||
});
|
});
|
||||||
|
|
|
||||||
|
|
@ -1,40 +1,43 @@
|
||||||
import { test } from 'node:test';
|
import { test } from 'node:test';
|
||||||
import assert from 'node:assert/strict';
|
import assert from 'node:assert/strict';
|
||||||
import { randomBytes } from 'node:crypto';
|
import { randomBytes } from 'node:crypto';
|
||||||
import { openDb, now, setSetting, getSetting } from '../src/db.js';
|
import { now, setSetting, getSetting } from '../src/db.js';
|
||||||
|
import { testDb } from './helpers/db.js';
|
||||||
|
import { addUser } from './helpers/users.js';
|
||||||
import { encrypt, encryptJson } from '../src/crypto.js';
|
import { encrypt, encryptJson } from '../src/crypto.js';
|
||||||
import { weeklyStats, weeklyText, maybeSendWeekly } from '../src/services/report.js';
|
import { weeklyStats, weeklyText, maybeSendWeekly } from '../src/services/report.js';
|
||||||
import { createProject } from '../src/projects.js';
|
import { createProject } from '../src/projects.js';
|
||||||
|
|
||||||
function setup() {
|
async function setup() {
|
||||||
const db = openDb(':memory:');
|
const db = await testDb();
|
||||||
const mails = [], hooks = [];
|
const mails = [], hooks = [];
|
||||||
const app = {
|
const app = {
|
||||||
db, cfg: { secretKey: randomBytes(32), appUrl: 'https://ai.test' },
|
db, cfg: { secretKey: randomBytes(32), appUrl: 'https://ai.test' },
|
||||||
createTransport: () => ({ sendMail: async (m) => { mails.push(m); }, close() {} }),
|
createTransport: () => ({ sendMail: async (m) => { mails.push(m); }, close() {} }),
|
||||||
fetch: async (url, o) => { hooks.push(JSON.parse(o.body)); return { ok: true }; },
|
fetch: async (url, o) => { hooks.push(JSON.parse(o.body)); return { ok: true }; },
|
||||||
};
|
};
|
||||||
const mep = createProject(app, { name: 'MonEspacePro', gitUrl: 'https://g/T/M.git' });
|
const userId = await addUser(db);
|
||||||
createProject(app, { name: 'GoSortir', gitUrl: 'https://g/T/G.git' });
|
const mep = await createProject(app, { userId, name: 'MonEspacePro', gitUrl: 'https://g/T/M.git' });
|
||||||
|
await createProject(app, { userId, name: 'GoSortir', gitUrl: 'https://g/T/G.git' });
|
||||||
const t = now() - 2 * 86400;
|
const t = now() - 2 * 86400;
|
||||||
for (let i = 0; i < 20; i++) {
|
for (let i = 0; i < 20; i++) {
|
||||||
const v = i % 2 ? 'B' : 'A';
|
const v = i % 2 ? 'B' : 'A';
|
||||||
const replied = (v === 'B' && i < 10) || i === 0;
|
const replied = (v === 'B' && i < 10) || i === 0;
|
||||||
const pid = Number(db.prepare('INSERT INTO prospects(project_id, company, email, status, sent_at, variant, replied_at, created_at) VALUES(?, ?, ?, ?, ?, ?, ?, ?)')
|
const pid = Number((await db.prepare('INSERT INTO prospects(project_id, company, email, status, sent_at, variant, replied_at, created_at) VALUES(?, ?, ?, ?, ?, ?, ?, ?)')
|
||||||
.run(mep, `E${i}`, `e${i}@x${i}.fr`, i === 3 ? 'client' : replied ? 'replied' : 'sent', t, v, replied ? t + 60 : null, t).lastInsertRowid);
|
.run(mep, `E${i}`, `e${i}@x${i}.fr`, i === 3 ? 'client' : replied ? 'replied' : 'sent', t, v, replied ? t + 60 : null, t)).lastInsertRowid);
|
||||||
db.prepare("INSERT INTO mail_log(project_id, prospect_id, email, sent_at, kind, variant) VALUES(?, ?, ?, ?, 'initial', ?)").run(mep, pid, `e${i}@x${i}.fr`, t, v);
|
await db.prepare("INSERT INTO mail_log(project_id, prospect_id, email, sent_at, kind, variant) VALUES(?, ?, ?, ?, 'initial', ?)").run(mep, pid, `e${i}@x${i}.fr`, t, v);
|
||||||
}
|
}
|
||||||
db.prepare("INSERT INTO mail_log(project_id, email, sent_at, kind) VALUES(?, 'e5@x5.fr', ?, 'followup')").run(mep, t);
|
await db.prepare("INSERT INTO mail_log(project_id, email, sent_at, kind) VALUES(?, 'e5@x5.fr', ?, 'followup')").run(mep, t);
|
||||||
db.prepare("INSERT INTO mail_log(project_id, email, sent_at, kind, error) VALUES(?, 'e6@x6.fr', ?, 'followup', 'refusé')").run(mep, t);
|
await db.prepare("INSERT INTO mail_log(project_id, email, sent_at, kind, error) VALUES(?, 'e6@x6.fr', ?, 'followup', 'refusé')").run(mep, t);
|
||||||
db.prepare("INSERT INTO blacklist(email, reason, created_at) VALUES('e7@x7.fr', 'bounce', ?)").run(t);
|
await db.prepare("INSERT INTO blacklist(email, reason, created_at) VALUES('e7@x7.fr', 'bounce', ?)").run(t);
|
||||||
db.prepare("INSERT INTO jobs(project_id, type, status, cost_usd, created_at, finished_at) VALUES(?, 'prospect', 'done', 0.42, ?, ?)").run(mep, t, t);
|
await db.prepare("INSERT INTO jobs(user_id, project_id, type, status, cost_usd, created_at, finished_at) VALUES(?, ?, 'prospect', 'done', 0.42, ?, ?)").run(userId, mep, t, t);
|
||||||
db.prepare("INSERT INTO jobs(project_id, type, status, cost_usd, created_at, finished_at) VALUES(?, 'prospect', 'done', 9, ?, ?)").run(mep, t - 30 * 86400, t - 30 * 86400);
|
await db.prepare("INSERT INTO jobs(user_id, project_id, type, status, cost_usd, created_at, finished_at) VALUES(?, ?, 'prospect', 'done', 9, ?, ?)").run(userId, mep, t - 30 * 86400, t - 30 * 86400);
|
||||||
return { db, app, mails, hooks };
|
return { db, app, mails, hooks, userId };
|
||||||
}
|
}
|
||||||
|
|
||||||
test('statistiques de la semaine', () => {
|
test('statistiques de la semaine', async () => {
|
||||||
const s = setup();
|
const s = await setup();
|
||||||
const st = weeklyStats(s.db);
|
const st = await weeklyStats(s.db, s.userId);
|
||||||
const mep = st.projects.find((p) => p.name === 'MonEspacePro');
|
const mep = st.projects.find((p) => p.name === 'MonEspacePro');
|
||||||
assert.deepEqual({ ...mep, bestSubject: mep.bestSubject?.variant }, {
|
assert.deepEqual({ ...mep, bestSubject: mep.bestSubject?.variant }, {
|
||||||
name: 'MonEspacePro', found: 20, sent: 20, followups: 1, replies: 6, clients: 1, bounces: 1, cost: 0.42, bestSubject: 'B',
|
name: 'MonEspacePro', found: 20, sent: 20, followups: 1, replies: 6, clients: 1, bounces: 1, cost: 0.42, bestSubject: 'B',
|
||||||
|
|
@ -50,17 +53,17 @@ test('statistiques de la semaine', () => {
|
||||||
const MON_0830 = new Date('2026-10-26T08:30:00+01:00');
|
const MON_0830 = new Date('2026-10-26T08:30:00+01:00');
|
||||||
|
|
||||||
test('envoi automatique : lundi 8h, une seule fois par semaine, désactivé par défaut', async () => {
|
test('envoi automatique : lundi 8h, une seule fois par semaine, désactivé par défaut', async () => {
|
||||||
const s = setup();
|
const s = await setup();
|
||||||
setSetting(s.db, 'notify_email', 'moi@x.fr');
|
await setSetting(s.db, s.userId, 'notify_email', 'moi@x.fr');
|
||||||
setSetting(s.db, 'smtp_enc', encryptJson(s.app.cfg.secretKey, { host: 'h', user: 'u', pass: 'p', fromEmail: 'aitools@x.fr' }));
|
await setSetting(s.db, s.userId, 'smtp_enc', encryptJson(s.app.cfg.secretKey, { host: 'h', user: 'u', pass: 'p', fromEmail: 'aitools@x.fr' }));
|
||||||
setSetting(s.db, 'discord_webhook_enc', encrypt(s.app.cfg.secretKey, 'https://discord.com/api/webhooks/123456789012345678/abcdefghijklmnopqrstuvwxyz'));
|
await setSetting(s.db, s.userId, 'discord_webhook_enc', encrypt(s.app.cfg.secretKey, 'https://discord.com/api/webhooks/123456789012345678/abcdefghijklmnopqrstuvwxyz'));
|
||||||
|
|
||||||
assert.equal(await maybeSendWeekly(s.app, { date: MON_0830 }), null, 'désactivé par défaut');
|
assert.equal(await maybeSendWeekly(s.app, s.userId, { date: MON_0830 }), null, 'désactivé par défaut');
|
||||||
setSetting(s.db, 'weekly_report', '1');
|
await setSetting(s.db, s.userId, 'weekly_report', '1');
|
||||||
assert.equal(await maybeSendWeekly(s.app, { date: new Date('2026-10-26T07:45:00+01:00') }), null, 'lundi 7h45 : trop tôt');
|
assert.equal(await maybeSendWeekly(s.app, s.userId, { date: new Date('2026-10-26T07:45:00+01:00') }), null, 'lundi 7h45 : trop tôt');
|
||||||
assert.equal(await maybeSendWeekly(s.app, { date: new Date('2026-10-27T09:00:00+01:00') }), null, 'mardi : non');
|
assert.equal(await maybeSendWeekly(s.app, s.userId, { date: new Date('2026-10-27T09:00:00+01:00') }), null, 'mardi : non');
|
||||||
|
|
||||||
const r = await maybeSendWeekly(s.app, { date: MON_0830 });
|
const r = await maybeSendWeekly(s.app, s.userId, { date: MON_0830 });
|
||||||
assert.deepEqual(r.channels, ['mail', 'discord']);
|
assert.deepEqual(r.channels, ['mail', 'discord']);
|
||||||
assert.equal(s.mails[0].to, 'moi@x.fr');
|
assert.equal(s.mails[0].to, 'moi@x.fr');
|
||||||
assert.match(s.mails[0].subject, /^\[AiTools\] Rapport du/);
|
assert.match(s.mails[0].subject, /^\[AiTools\] Rapport du/);
|
||||||
|
|
@ -69,15 +72,15 @@ test('envoi automatique : lundi 8h, une seule fois par semaine, désactivé par
|
||||||
assert.match(s.mails[0].html, /Rapport hebdo/);
|
assert.match(s.mails[0].html, /Rapport hebdo/);
|
||||||
assert.match(s.mails[0].html, /MonEspacePro/);
|
assert.match(s.mails[0].html, /MonEspacePro/);
|
||||||
|
|
||||||
assert.equal(await maybeSendWeekly(s.app, { date: new Date('2026-10-26T08:45:00+01:00') }), null, 'pas deux fois le même lundi');
|
assert.equal(await maybeSendWeekly(s.app, s.userId, { date: new Date('2026-10-26T08:45:00+01:00') }), null, 'pas deux fois le même lundi');
|
||||||
assert.notEqual(await maybeSendWeekly(s.app, { date: new Date('2026-11-02T08:15:00+01:00') }), null, 'lundi suivant');
|
assert.notEqual(await maybeSendWeekly(s.app, s.userId, { date: new Date('2026-11-02T08:15:00+01:00') }), null, 'lundi suivant');
|
||||||
assert.equal(s.mails.length, 2);
|
assert.equal(s.mails.length, 2);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('aucun canal configuré : rien n\'est marqué comme envoyé', async () => {
|
test('aucun canal configuré : rien n\'est marqué comme envoyé', async () => {
|
||||||
const s = setup();
|
const s = await setup();
|
||||||
setSetting(s.db, 'weekly_report', '1');
|
await setSetting(s.db, s.userId, 'weekly_report', '1');
|
||||||
const r = await maybeSendWeekly(s.app, { date: MON_0830 });
|
const r = await maybeSendWeekly(s.app, s.userId, { date: MON_0830 });
|
||||||
assert.deepEqual(r.channels, []);
|
assert.deepEqual(r.channels, []);
|
||||||
assert.equal(getSetting(s.db, 'weekly_report_last'), null);
|
assert.equal(await getSetting(s.db, s.userId, 'weekly_report_last'), null);
|
||||||
});
|
});
|
||||||
|
|
|
||||||
127
test/schema.test.js
Normal file
127
test/schema.test.js
Normal file
|
|
@ -0,0 +1,127 @@
|
||||||
|
import { test } from 'node:test';
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import { MIGRATIONS } from '../src/db.js';
|
||||||
|
import { testDb, USING_MYSQL } from './helpers/db.js';
|
||||||
|
|
||||||
|
// Découpe "a, b(c, d), e" sur les virgules de premier niveau
|
||||||
|
function splitTop(s) {
|
||||||
|
const out = [];
|
||||||
|
let depth = 0, cur = '';
|
||||||
|
for (const c of s) {
|
||||||
|
if (c === '(') depth++;
|
||||||
|
if (c === ')') depth--;
|
||||||
|
if (c === ',' && depth === 0) { out.push(cur); cur = ''; } else cur += c;
|
||||||
|
}
|
||||||
|
if (cur.trim()) out.push(cur);
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Tables, colonnes et clés étrangères déclarées par la suite d'instructions des migrations : CREATE TABLE,
|
||||||
|
// puis DROP TABLE, RENAME TO, ADD COLUMN et ADD CONSTRAINT ... FOREIGN KEY rejoués dans l'ordre (état final).
|
||||||
|
function parseDdl(statements) {
|
||||||
|
const tables = new Map();
|
||||||
|
const cascade = (item) => [...item.matchAll(/REFERENCES\s+`?(\w+)`?\s*\([^)]*\)\s*ON DELETE CASCADE/gi)].map((r) => r[1]);
|
||||||
|
for (const st of statements) {
|
||||||
|
const sql = (typeof st === 'string' ? st : st.sql).replace(/--[^\n]*/g, '').trim();
|
||||||
|
let a;
|
||||||
|
if ((a = /^DROP TABLE (?:IF EXISTS )?`?(\w+)`?/i.exec(sql))) { tables.delete(a[1]); continue; }
|
||||||
|
if ((a = /^ALTER TABLE `?(\w+)`? RENAME TO `?(\w+)`?/i.exec(sql))) { tables.set(a[2], tables.get(a[1])); tables.delete(a[1]); continue; }
|
||||||
|
if ((a = /^ALTER TABLE `?(\w+)`? ADD COLUMN `?(\w+)`?/i.exec(sql))) {
|
||||||
|
const t = tables.get(a[1]);
|
||||||
|
t.columns.add(a[2]); t.refs = [...t.refs, ...cascade(sql)].sort();
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if ((a = /^ALTER TABLE `?(\w+)`? ADD CONSTRAINT/i.exec(sql))) {
|
||||||
|
const t = tables.get(a[1]);
|
||||||
|
t.refs = [...t.refs, ...cascade(sql)].sort();
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const m = /CREATE TABLE (?:IF NOT EXISTS )?`?(\w+)`?\s*\(/i.exec(sql);
|
||||||
|
if (!m) continue;
|
||||||
|
let depth = 1, i = m.index + m[0].length;
|
||||||
|
const start = i;
|
||||||
|
for (; i < sql.length && depth > 0; i++) { if (sql[i] === '(') depth++; else if (sql[i] === ')') depth--; }
|
||||||
|
const columns = new Set(), refs = [];
|
||||||
|
for (const item of splitTop(sql.slice(start, i - 1)).map((x) => x.trim())) {
|
||||||
|
refs.push(...cascade(item));
|
||||||
|
if (/^(?:PRIMARY\s+KEY|UNIQUE|KEY\s+\w+\s*\(|INDEX|CONSTRAINT|FOREIGN\s+KEY|CHECK)/i.test(item)) continue;
|
||||||
|
columns.add(item.match(/^`?(\w+)`?/)[1]);
|
||||||
|
}
|
||||||
|
tables.set(m[1], { columns, refs: refs.sort() });
|
||||||
|
}
|
||||||
|
return tables;
|
||||||
|
}
|
||||||
|
|
||||||
|
const ddl = (dialect) => parseDdl(MIGRATIONS.flatMap((m) => m[dialect]));
|
||||||
|
|
||||||
|
// Tables volontairement hors du périmètre d'un utilisateur : liste d'opposition (RGPD) et états OAuth éphémères
|
||||||
|
const NOT_OWNED = new Set(['blacklist', 'oauth_states', 'users']);
|
||||||
|
const shape = (tables) => Object.fromEntries([...tables].map(([t, v]) => [t, { columns: [...v.columns].sort(), refs: v.refs }]));
|
||||||
|
|
||||||
|
test('schémas SQLite et MySQL : mêmes tables et mêmes colonnes', () => {
|
||||||
|
const sqlite = ddl('sqlite');
|
||||||
|
const mysql = ddl('mysql');
|
||||||
|
assert.ok(sqlite.size >= 10, 'le parseur doit voir les tables');
|
||||||
|
assert.deepEqual([...mysql.keys()].sort(), [...sqlite.keys()].sort());
|
||||||
|
for (const [t, v] of sqlite) assert.deepEqual([...mysql.get(t).columns].sort(), [...v.columns].sort(), `colonnes de ${t}`);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('schémas : mêmes clés étrangères ON DELETE CASCADE des deux côtés', () => {
|
||||||
|
const s = shape(ddl('sqlite')), m = shape(ddl('mysql'));
|
||||||
|
for (const t of Object.keys(s)) assert.deepEqual(m[t].refs, s[t].refs, `FK de ${t}`);
|
||||||
|
assert.deepEqual(m.prospects.refs, ['projects']);
|
||||||
|
assert.deepEqual(m.prospect_notes.refs, ['prospects']);
|
||||||
|
assert.deepEqual(m.projects.refs, ['users']);
|
||||||
|
assert.deepEqual(m.jobs.refs, ['projects', 'users']);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('multi-tenant : toute table métier descend d\'un utilisateur par cascade (donc la suppression de compte efface tout)', () => {
|
||||||
|
for (const dialect of ['sqlite', 'mysql']) {
|
||||||
|
const tables = ddl(dialect);
|
||||||
|
const owned = (t, seen = new Set()) => {
|
||||||
|
if (seen.has(t)) return false;
|
||||||
|
seen.add(t);
|
||||||
|
return tables.get(t).refs.some((p) => p === 'users' || owned(p, seen));
|
||||||
|
};
|
||||||
|
for (const t of tables.keys()) {
|
||||||
|
if (NOT_OWNED.has(t)) continue;
|
||||||
|
assert.ok(owned(t), `${dialect} : ${t} n'est rattachée à aucun utilisateur`);
|
||||||
|
}
|
||||||
|
assert.ok(!tables.has('settings'), 'plus de réglages globaux');
|
||||||
|
assert.ok(tables.get('user_settings').columns.has('user_id'));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test('MySQL : InnoDB, utf8mb4, migrations rejouables', () => {
|
||||||
|
for (const m of MIGRATIONS) {
|
||||||
|
for (const sql of m.mysql.filter((x) => /CREATE TABLE/i.test(x))) {
|
||||||
|
assert.match(sql, /ENGINE=InnoDB/);
|
||||||
|
assert.match(sql, /CHARSET=utf8mb4/);
|
||||||
|
assert.match(sql, /IF NOT EXISTS/, 'migration rejouable');
|
||||||
|
}
|
||||||
|
assert.ok(m.name);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test('la base réellement migrée correspond au DDL déclaré', async () => {
|
||||||
|
const db = await testDb();
|
||||||
|
const declared = shape(ddl(db.dialect));
|
||||||
|
const live = {};
|
||||||
|
if (db.dialect === 'sqlite') {
|
||||||
|
const tables = await db.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' AND name <> 'schema_migrations'").all();
|
||||||
|
for (const { name } of tables) live[name] = (await db.query(`PRAGMA table_info(${name})`)).map((c) => c.name).sort();
|
||||||
|
} else {
|
||||||
|
const rows = await db.query(`SELECT table_name t, column_name c FROM information_schema.columns
|
||||||
|
WHERE table_schema = DATABASE() AND table_name <> 'schema_migrations'`);
|
||||||
|
for (const r of rows) (live[r.t ?? r.T] ||= []).push(r.c ?? r.C);
|
||||||
|
for (const k of Object.keys(live)) live[k].sort();
|
||||||
|
}
|
||||||
|
assert.deepEqual(live, Object.fromEntries(Object.entries(declared).map(([t, v]) => [t, v.columns])));
|
||||||
|
const v = await db.prepare('SELECT COUNT(*) n, MAX(version) v FROM schema_migrations').get();
|
||||||
|
assert.equal(v.n, MIGRATIONS.length);
|
||||||
|
assert.equal(v.v, MIGRATIONS.length);
|
||||||
|
if (USING_MYSQL) {
|
||||||
|
const t = await db.query("SELECT engine e FROM information_schema.tables WHERE table_schema = DATABASE() AND table_name = 'prospects'");
|
||||||
|
assert.equal(t[0].e ?? t[0].ENGINE, 'InnoDB');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
@ -3,14 +3,17 @@ import assert from 'node:assert/strict';
|
||||||
import { resolve } from 'node:path';
|
import { resolve } from 'node:path';
|
||||||
import { runClaude, extractJson, rateLimitWindows } from '../src/services/claude.js';
|
import { runClaude, extractJson, rateLimitWindows } from '../src/services/claude.js';
|
||||||
import { waitCool } from '../src/services/thermal.js';
|
import { waitCool } from '../src/services/thermal.js';
|
||||||
import { openDb, now } from '../src/db.js';
|
import { now } from '../src/db.js';
|
||||||
|
import { testDb } from './helpers/db.js';
|
||||||
|
import { addUser } from './helpers/users.js';
|
||||||
import { enqueue, Worker, latestJobs, cancelJob, addUsage, usageSummary } from '../src/services/jobs.js';
|
import { enqueue, Worker, latestJobs, cancelJob, addUsage, usageSummary } from '../src/services/jobs.js';
|
||||||
|
|
||||||
const bin = resolve('test/fixtures/fake-claude.js');
|
const bin = resolve('test/fixtures/fake-claude.js');
|
||||||
|
const sandbox = { enabled: false, production: false };
|
||||||
|
|
||||||
test('runClaude parse le flux et la conso', async () => {
|
test('runClaude parse le flux et la conso', async () => {
|
||||||
const seen = [];
|
const seen = [];
|
||||||
const r = await runClaude({ bin, prompt: 'hello', model: 'haiku', maxTurns: 3, tools: ['Read', 'Grep'], onText: (t) => seen.push(t) });
|
const r = await runClaude({ bin, sandbox, prompt: 'hello', model: 'haiku', maxTurns: 3, tools: ['Read', 'Grep'], onText: (t) => seen.push(t) });
|
||||||
assert.equal(r.ok, true);
|
assert.equal(r.ok, true);
|
||||||
assert.equal(r.costUsd, 0.0123);
|
assert.equal(r.costUsd, 0.0123);
|
||||||
assert.equal(r.tokensIn, 150);
|
assert.equal(r.tokensIn, 150);
|
||||||
|
|
@ -24,7 +27,7 @@ test('runClaude parse le flux et la conso', async () => {
|
||||||
});
|
});
|
||||||
|
|
||||||
test('runClaude remonte une erreur si le process meurt', async () => {
|
test('runClaude remonte une erreur si le process meurt', async () => {
|
||||||
await assert.rejects(runClaude({ bin, prompt: 'CRASH' }), /sans résultat/);
|
await assert.rejects(runClaude({ bin, sandbox, prompt: 'CRASH' }), /sans résultat/);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('rateLimitWindows normalise la session (5h) et la semaine, quel que soit le format reçu', () => {
|
test('rateLimitWindows normalise la session (5h) et la semaine, quel que soit le format reçu', () => {
|
||||||
|
|
@ -55,28 +58,29 @@ test('waitCool attend la redescente avec hystérésis', async () => {
|
||||||
});
|
});
|
||||||
|
|
||||||
test('worker : exécution, dédoublonnage, erreurs, annulation, conso', async () => {
|
test('worker : exécution, dédoublonnage, erreurs, annulation, conso', async () => {
|
||||||
const db = openDb(':memory:');
|
const db = await testDb();
|
||||||
db.prepare("INSERT INTO projects(name, git_url, created_at) VALUES('p','u',?)").run(now());
|
const u = await addUser(db);
|
||||||
const a = enqueue(db, { projectId: 1, type: 'ok', params: { x: 2 } });
|
await db.prepare("INSERT INTO projects(user_id, name, git_url, created_at) VALUES(?, 'p','u',?)").run(u, now());
|
||||||
assert.equal(enqueue(db, { projectId: 1, type: 'ok' }).existing, true);
|
const a = await enqueue(db, { userId: u, projectId: 1, type: 'ok', params: { x: 2 } });
|
||||||
|
assert.equal((await enqueue(db, { userId: u, projectId: 1, type: 'ok' })).existing, true);
|
||||||
const handlers = {
|
const handlers = {
|
||||||
ok: async (ctx) => { ctx.progress({ found: 1 }); addUsage(ctx, { costUsd: 0.5, tokensIn: 10, tokensOut: 5 }); return { double: ctx.params.x * 2 }; },
|
ok: async (ctx) => { ctx.progress({ found: 1 }); addUsage(ctx, { costUsd: 0.5, tokensIn: 10, tokensOut: 5 }); return { double: ctx.params.x * 2 }; },
|
||||||
boom: async () => { throw new Error('raté'); },
|
boom: async () => { throw new Error('raté'); },
|
||||||
};
|
};
|
||||||
const w = new Worker(db, handlers, { thermalMax: 999, log: { error() {} } });
|
const w = new Worker(db, handlers, { thermalMax: 999, log: { error() {} } });
|
||||||
assert.equal(await w.tick(), true);
|
assert.equal(await w.tick(), true);
|
||||||
enqueue(db, { projectId: 1, type: 'boom' });
|
await enqueue(db, { userId: u, projectId: 1, type: 'boom' });
|
||||||
await w.tick();
|
await w.tick();
|
||||||
const c = enqueue(db, { projectId: 1, type: 'ok' });
|
const c = await enqueue(db, { userId: u, projectId: 1, type: 'ok' });
|
||||||
cancelJob(db, c.id);
|
await cancelJob(db, u, c.id);
|
||||||
assert.equal(await w.tick(), false);
|
assert.equal(await w.tick(), false);
|
||||||
const jobs = latestJobs(db, 1);
|
const jobs = await latestJobs(db, 1);
|
||||||
assert.equal(a.id, 1);
|
assert.equal(a.id, 1);
|
||||||
assert.equal(jobs.boom.status, 'error');
|
assert.equal(jobs.boom.status, 'error');
|
||||||
assert.equal(jobs.boom.error, 'raté');
|
assert.equal(jobs.boom.error, 'raté');
|
||||||
assert.equal(jobs.ok.status, 'cancelled');
|
assert.equal(jobs.ok.status, 'cancelled');
|
||||||
const first = db.prepare('SELECT * FROM jobs WHERE id = 1').get();
|
const first = await db.prepare('SELECT * FROM jobs WHERE id = 1').get();
|
||||||
assert.equal(first.status, 'done');
|
assert.equal(first.status, 'done');
|
||||||
assert.deepEqual(JSON.parse(first.result_json), { double: 4 });
|
assert.deepEqual(JSON.parse(first.result_json), { double: 4 });
|
||||||
assert.equal(usageSummary(db).month.cost, 0.5);
|
assert.equal((await usageSummary(db, u)).month.cost, 0.5);
|
||||||
});
|
});
|
||||||
|
|
|
||||||
289
test/site.test.js
Normal file
289
test/site.test.js
Normal file
|
|
@ -0,0 +1,289 @@
|
||||||
|
// Site public : pages accessibles sans compte, SEO, en-têtes, aucune ressource externe, marqueurs légaux, contrastes.
|
||||||
|
import { test, before, after } from 'node:test';
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import { readFileSync } from 'node:fs';
|
||||||
|
import { startApp, APP_URL } from './helpers/server.js';
|
||||||
|
import { LEGAL_MARKERS } from '../src/site/legal.js';
|
||||||
|
import { CONSENT_CHECKBOX } from '../src/claudelink.js';
|
||||||
|
|
||||||
|
let s;
|
||||||
|
before(async () => { s = await startApp(); });
|
||||||
|
after(async () => { await s.close(); });
|
||||||
|
|
||||||
|
const PUBLIC_PAGES = ['/', '/fonctionnement', '/tarifs', '/mentions-legales', '/confidentialite', '/cgu'];
|
||||||
|
const read = (p) => readFileSync(new URL(`../${p}`, import.meta.url), 'utf8');
|
||||||
|
// Les clients de test envoient accept: application/json ; un navigateur demande du HTML
|
||||||
|
const page = (p, headers = {}) => s.anon.get(p, { headers: { accept: 'text/html', ...headers } });
|
||||||
|
const text = async (p) => (await page(p)).text();
|
||||||
|
|
||||||
|
test('pages publiques : 200 sans session, complètes (une h1, title, description, canonical, lang)', async () => {
|
||||||
|
for (const p of PUBLIC_PAGES) {
|
||||||
|
const r = await page(p);
|
||||||
|
assert.equal(r.status, 200, p);
|
||||||
|
assert.match(r.headers.get('content-type'), /text\/html/);
|
||||||
|
const h = await r.text();
|
||||||
|
assert.match(h, /<html lang="fr">/, p);
|
||||||
|
assert.equal((h.match(/<h1[\s>]/g) || []).length, 1, `${p} : une seule h1`);
|
||||||
|
const title = h.match(/<title>([^<]+)<\/title>/)?.[1];
|
||||||
|
assert.ok(title && title.length >= 10 && title.length <= 70, `${p} : title (${title})`);
|
||||||
|
const desc = h.match(/<meta name="description" content="([^"]+)"/)?.[1];
|
||||||
|
assert.ok(desc && desc.length >= 50 && desc.length <= 200, `${p} : description`);
|
||||||
|
const expected = APP_URL + (p === '/' ? '/' : p);
|
||||||
|
assert.ok(h.includes(`<link rel="canonical" href="${expected}">`), `${p} : canonical`);
|
||||||
|
assert.ok(h.includes(`<meta property="og:url" content="${expected}">`), `${p} : og:url`);
|
||||||
|
assert.match(h, /<meta property="og:title"/);
|
||||||
|
assert.match(h, /<meta name="robots" content="index, follow">/);
|
||||||
|
assert.match(h, /<a class="skip" href="#contenu">/, `${p} : lien d'évitement`);
|
||||||
|
assert.match(h, /<main id="contenu"/);
|
||||||
|
assert.match(h, /<header class="site-head">/);
|
||||||
|
assert.match(h, /<footer class="site-foot">/);
|
||||||
|
assert.match(h, /<link rel="icon" type="image\/svg\+xml" href="\/static\/favicon\.svg">/);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test('connexion et 404 : une h1, noindex, bouton Google', async () => {
|
||||||
|
let h = await text('/login');
|
||||||
|
assert.equal((h.match(/<h1[\s>]/g) || []).length, 1);
|
||||||
|
assert.match(h, /noindex/);
|
||||||
|
assert.match(h, /Se connecter avec Google/);
|
||||||
|
assert.match(h, /<html lang="fr">/);
|
||||||
|
|
||||||
|
const r = await page('/cette-page-n-existe-pas');
|
||||||
|
assert.equal(r.status, 404);
|
||||||
|
h = await r.text();
|
||||||
|
assert.equal((h.match(/<h1[\s>]/g) || []).length, 1);
|
||||||
|
assert.match(h, /Cette page n'existe pas/);
|
||||||
|
assert.match(h, /noindex/);
|
||||||
|
assert.doesNotMatch(h, /rel="canonical"/);
|
||||||
|
// L'API garde ses erreurs JSON
|
||||||
|
const j = await s.anon.get('/api/inconnu');
|
||||||
|
assert.equal(j.status, 404);
|
||||||
|
assert.ok((await j.json()).error);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('pages d\'application : toujours protégées, la racine dépend de la session', async () => {
|
||||||
|
for (const p of ['/account', '/settings', '/link']) {
|
||||||
|
const r = await page(p);
|
||||||
|
assert.equal(r.status, 303, p);
|
||||||
|
assert.equal(r.headers.get('location'), '/login');
|
||||||
|
}
|
||||||
|
assert.equal((await s.anon.get('/api/system')).status, 401);
|
||||||
|
assert.equal((await s.anon.post('/account/delete', { confirm: 'x' }, { form: true })).status, 303);
|
||||||
|
|
||||||
|
// Connecté sans liaison Claude : la racine ne montre plus le site, l'onboarding reprend la main
|
||||||
|
const linked = await s.newUser({ email: 'lie@x.fr' });
|
||||||
|
const dash = await (await linked.get('/', { headers: { accept: 'text/html' } })).text();
|
||||||
|
assert.match(dash, /<h1>Projets<\/h1>/, 'compte relié : le tableau de bord');
|
||||||
|
assert.doesNotMatch(dash, /Un panel pour prospecter/);
|
||||||
|
const u = await s.newUser({ email: 'site@x.fr', admin: false });
|
||||||
|
let r = await u.get('/', { headers: { accept: 'text/html' } });
|
||||||
|
assert.equal(r.status, 303);
|
||||||
|
assert.equal(r.headers.get('location'), '/link');
|
||||||
|
r = await u.get('/login', { headers: { accept: 'text/html' } });
|
||||||
|
assert.equal(r.status, 303);
|
||||||
|
assert.equal(r.headers.get('location'), '/');
|
||||||
|
// Les pages du site restent lisibles connecté
|
||||||
|
assert.equal((await u.get('/tarifs', { headers: { accept: 'text/html' } })).status, 200);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('flux de connexion : Google redirige, le retour Apple (POST cross-site) reste accepté', async () => {
|
||||||
|
const r = await s.anon.get('/auth/google');
|
||||||
|
assert.equal(r.status, 303);
|
||||||
|
assert.equal(new URL(r.headers.get('location')).host, 'accounts.google.com');
|
||||||
|
// Sans configuration Apple, le POST échoue proprement vers /login (pas de 403 d'origine ni de 404)
|
||||||
|
const bare = await s.anon.post('/auth/apple/callback', {}, { origin: null });
|
||||||
|
assert.equal(bare.status, 303);
|
||||||
|
assert.match(bare.headers.get('location'), /^\/login\?e=/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('robots.txt et sitemap.xml', async () => {
|
||||||
|
let r = await s.anon.get('/robots.txt');
|
||||||
|
assert.equal(r.status, 200);
|
||||||
|
assert.match(r.headers.get('content-type'), /text\/plain/);
|
||||||
|
const robots = await r.text();
|
||||||
|
assert.match(robots, /User-agent: \*/);
|
||||||
|
for (const p of ['/account', '/settings', '/link', '/api/', '/auth/', '/u/']) assert.match(robots, new RegExp(`Disallow: ${p}\\n`), p);
|
||||||
|
assert.match(robots, new RegExp(`Sitemap: ${APP_URL}/sitemap\\.xml`));
|
||||||
|
assert.doesNotMatch(robots, /Disallow: \/static/, 'les feuilles de style restent explorables');
|
||||||
|
assert.doesNotMatch(robots, /noindex-test/);
|
||||||
|
|
||||||
|
r = await s.anon.get('/sitemap.xml');
|
||||||
|
assert.equal(r.status, 200);
|
||||||
|
assert.match(r.headers.get('content-type'), /xml/);
|
||||||
|
const xml = await r.text();
|
||||||
|
for (const p of PUBLIC_PAGES) assert.ok(xml.includes(`<loc>${APP_URL}${p === '/' ? '/' : p}</loc>`), p);
|
||||||
|
assert.doesNotMatch(xml, /login|account|settings|\/api\//);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('en-têtes de sécurité, HSTS seulement en https, noindex sur l\'application', async () => {
|
||||||
|
const r = await page('/');
|
||||||
|
const h = (n) => r.headers.get(n);
|
||||||
|
assert.equal(h('x-content-type-options'), 'nosniff');
|
||||||
|
assert.equal(h('x-frame-options'), 'DENY');
|
||||||
|
assert.equal(h('referrer-policy'), 'same-origin');
|
||||||
|
assert.match(h('permissions-policy'), /camera=\(\)/);
|
||||||
|
assert.match(h('permissions-policy'), /geolocation=\(\)/);
|
||||||
|
assert.match(h('strict-transport-security'), /max-age=\d+/);
|
||||||
|
const csp = h('content-security-policy');
|
||||||
|
for (const d of ["default-src 'self'", "script-src 'self'", "style-src 'self'", "frame-ancestors 'none'", "object-src 'none'", "base-uri 'self'"]) {
|
||||||
|
assert.ok(csp.includes(d), d);
|
||||||
|
}
|
||||||
|
assert.doesNotMatch(csp, /unsafe-inline|unsafe-eval|\*/);
|
||||||
|
assert.equal(h('x-robots-tag'), null, 'la page d\'accueil est indexable');
|
||||||
|
assert.equal((await page('/tarifs')).headers.get('x-robots-tag'), null);
|
||||||
|
|
||||||
|
for (const p of ['/login', '/account', '/api/system', '/link']) {
|
||||||
|
assert.match((await page(p)).headers.get('x-robots-tag'), /noindex/, p);
|
||||||
|
}
|
||||||
|
|
||||||
|
const http = await startApp({ cfg: { appUrl: 'http://localhost:3100' } });
|
||||||
|
try {
|
||||||
|
const hr = await http.anon.get('/tarifs', { headers: { accept: 'text/html' } });
|
||||||
|
assert.equal(hr.status, 200);
|
||||||
|
assert.equal(hr.headers.get('strict-transport-security'), null, 'pas de HSTS sans https');
|
||||||
|
assert.equal(hr.headers.get('x-content-type-options'), 'nosniff');
|
||||||
|
} finally { await http.close(); }
|
||||||
|
});
|
||||||
|
|
||||||
|
test('fichiers statiques : cache, ETag, 304, HEAD', async () => {
|
||||||
|
for (const [p, type] of [['/static/site.css', /text\/css/], ['/static/app.css', /text\/css/], ['/static/favicon.svg', /image\/svg\+xml/]]) {
|
||||||
|
const r = await s.anon.get(p);
|
||||||
|
assert.equal(r.status, 200, p);
|
||||||
|
assert.match(r.headers.get('content-type'), type);
|
||||||
|
assert.match(r.headers.get('cache-control'), /max-age=\d+/);
|
||||||
|
const etag = r.headers.get('etag');
|
||||||
|
assert.ok(etag, p);
|
||||||
|
const again = await s.anon.get(p, { headers: { 'if-none-match': etag } });
|
||||||
|
assert.equal(again.status, 304, p);
|
||||||
|
}
|
||||||
|
const head = await fetch(`http://127.0.0.1:${new URL(s.base).port}/tarifs`, { method: 'HEAD' });
|
||||||
|
assert.equal(head.status, 200);
|
||||||
|
assert.equal((await head.text()), '');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('aucune ressource externe : tout est servi par l\'application, rien en ligne', async () => {
|
||||||
|
// Liens sortants explicites (balise <a>) : seuls ceux-ci sont permis
|
||||||
|
const outbound = new Set([
|
||||||
|
'https://www.anthropic.com/legal/consumer-terms', 'https://www.anthropic.com/legal/privacy',
|
||||||
|
'https://policies.google.com/privacy', 'https://www.cnil.fr/fr/plaintes', 'https://www.apple.com/legal/privacy/fr-fr/',
|
||||||
|
]);
|
||||||
|
const apple = await startApp({ cfg: { apple: { teamId: 't', keyId: 'k', clientId: 'c', privateKey: 'p' } } });
|
||||||
|
try {
|
||||||
|
for (const client of [s.anon, apple.anon]) {
|
||||||
|
for (const p of [...PUBLIC_PAGES, '/login', '/inexistant']) {
|
||||||
|
const h = await (await client.get(p, { headers: { accept: 'text/html' } })).text();
|
||||||
|
assert.doesNotMatch(h, /<script[^>]*\ssrc=/i, `${p} : aucun script`);
|
||||||
|
assert.doesNotMatch(h, /<script(?![^>]*ld\+json)/i, `${p} : aucun script exécutable`);
|
||||||
|
assert.doesNotMatch(h, /<style[\s>]/i, `${p} : pas de <style>`);
|
||||||
|
assert.doesNotMatch(h, /\sstyle="/i, `${p} : pas de style en ligne (CSP)`);
|
||||||
|
assert.doesNotMatch(h, /<(img|iframe|video|audio|source|embed|object)[^>]*\s(src|data)="https?:/i, p);
|
||||||
|
for (const m of h.matchAll(/<link[^>]+href="([^"]+)"/g)) assert.ok(m[1].startsWith('/') || m[1].startsWith(APP_URL), `${p} : <link> ${m[1]}`);
|
||||||
|
for (const m of h.matchAll(/<a [^>]*href="(https?:[^"]+)"/g)) {
|
||||||
|
assert.ok(outbound.has(m[1]) || m[1].startsWith(APP_URL), `${p} : lien sortant non listé ${m[1]}`);
|
||||||
|
}
|
||||||
|
for (const m of h.matchAll(/<a [^>]*href="https?:\/\/(?!ai\.tony-averty\.dev)[^"]+"[^>]*>/g)) assert.match(m[0], /rel="noopener noreferrer"/, p);
|
||||||
|
for (const m of h.matchAll(/<form[^>]+action="([^"]+)"/g)) assert.ok(m[1].startsWith('/'), p);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// L'accueil annonce Apple seulement quand il est configuré
|
||||||
|
assert.match(await (await apple.anon.get('/', { headers: { accept: 'text/html' } })).text(), /Google ou Apple/);
|
||||||
|
assert.doesNotMatch(await text('/'), /Apple/);
|
||||||
|
} finally { await apple.close(); }
|
||||||
|
assert.doesNotMatch(read('public/site.css'), /@import|url\(\s*["']?https?:/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('textes : faits réels du statut, tarifs sans prix inventé, aucun terme interdit', async () => {
|
||||||
|
const mentions = await text('/mentions-legales');
|
||||||
|
for (const f of ['Tony AVERTY', '100 142 819 00018', '62.01Z', 'contact@tony-averty.dev', 'TVA non applicable, art. 293 B du CGI', 'Directeur de la publication']) {
|
||||||
|
assert.ok(mentions.includes(f), f);
|
||||||
|
}
|
||||||
|
const tarifs = await text('/tarifs');
|
||||||
|
assert.match(tarifs, /Bientôt/);
|
||||||
|
for (const n of ['>1<', '>50<', '>100<', '>5<']) assert.ok(tarifs.includes(`<strong>${n.slice(1, -1)}</strong>`), n);
|
||||||
|
assert.doesNotMatch(tarifs.replace(/0 €/g, ''), /\d\s?€|€\s?\d/, 'aucun prix inventé');
|
||||||
|
assert.match(tarifs, /pas encore automatiquement/);
|
||||||
|
assert.match(tarifs, /suspendu ou fermé/);
|
||||||
|
|
||||||
|
const cgu = await text('/cgu');
|
||||||
|
assert.ok(cgu.includes(CONSENT_CHECKBOX.replace(/'/g, '\'')) || cgu.includes('J\'ai compris et j\'accepte ce risque'));
|
||||||
|
assert.match(cgu, /suspendu ou fermé/);
|
||||||
|
assert.match(cgu, /n'en est pas responsable/);
|
||||||
|
assert.match(cgu, /B2C|particuliers/);
|
||||||
|
assert.match(cgu, /droit français/);
|
||||||
|
|
||||||
|
const conf = await text('/confidentialite');
|
||||||
|
for (const f of ['responsable de traitement', 'sous-traitant', 'Anthropic', 'Google', 'CNIL', 'strictement nécessaires', '<code>sid</code>', 'Mon compte']) {
|
||||||
|
assert.ok(conf.includes(f), f);
|
||||||
|
}
|
||||||
|
assert.doesNotMatch(conf, /<!--/, 'aucun commentaire HTML (le paragraphe reCAPTCHA reste dans le code)');
|
||||||
|
assert.doesNotMatch(conf, /reCAPTCHA/);
|
||||||
|
|
||||||
|
for (const p of [...PUBLIC_PAGES, '/login']) {
|
||||||
|
const h = await text(p);
|
||||||
|
assert.doesNotMatch(h, /généré par (l')?IA|assistant|(?<!n'est |pas )\bgaranti\b|n'importe quel taux/i, p);
|
||||||
|
assert.doesNotMatch(h, /[\u{1F300}-\u{1FAFF}\u{2600}-\u{27BF}]/u, `${p} : pas d'emoji`);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test('marqueurs légaux : ceux des pages sont exactement ceux listés dans le journal', async () => {
|
||||||
|
const journal = read('docs/JOURNAL.md');
|
||||||
|
const section = journal.match(/### Marqueurs à compléter[\s\S]*?(?=\n##|$)/)?.[0];
|
||||||
|
assert.ok(section, 'section « Marqueurs à compléter » absente du journal');
|
||||||
|
const re = /\[À (?:COMPLÉTER|VALIDER) : [^\]]+\]/g;
|
||||||
|
const listed = new Set(section.match(re));
|
||||||
|
const inPages = new Set();
|
||||||
|
for (const p of ['/mentions-legales', '/confidentialite', '/cgu']) {
|
||||||
|
for (const m of (await text(p)).match(re) || []) inPages.add(m);
|
||||||
|
}
|
||||||
|
assert.deepEqual([...inPages].sort(), [...listed].sort(), 'écart entre les pages et la liste du journal');
|
||||||
|
assert.deepEqual([...new Set(LEGAL_MARKERS)].sort(), [...listed].sort(), 'écart entre le code et la liste du journal');
|
||||||
|
for (const m of ['[À COMPLÉTER : adresse du siège]', '[À COMPLÉTER : hébergeur]']) assert.ok(listed.has(m), m);
|
||||||
|
// Pas de marqueur sur les pages commerciales
|
||||||
|
for (const p of ['/', '/fonctionnement', '/tarifs', '/login']) assert.doesNotMatch(await text(p), /\[À (COMPLÉTER|VALIDER)/, p);
|
||||||
|
});
|
||||||
|
|
||||||
|
// ---------- Couleurs : mêmes jetons que le tableau de bord, contrastes AA ----------
|
||||||
|
const hexToRgb = (h) => { let v = h.replace('#', ''); if (v.length === 3) v = [...v].map((c) => c + c).join(''); return [0, 2, 4].map((i) => parseInt(v.slice(i, i + 2), 16) / 255); };
|
||||||
|
const lum = (hex) => {
|
||||||
|
const [r, g, b] = hexToRgb(hex).map((c) => (c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4));
|
||||||
|
return 0.2126 * r + 0.7152 * g + 0.0722 * b;
|
||||||
|
};
|
||||||
|
const ratio = (a, b) => { const [x, y] = [lum(a), lum(b)].sort((p, q) => q - p); return (x + 0.05) / (y + 0.05); };
|
||||||
|
const tokens = (block) => Object.fromEntries([...block.matchAll(/--([\w-]+):\s*(#[0-9a-fA-F]{3,6})\b/g)].map((m) => [m[1], m[2]]));
|
||||||
|
|
||||||
|
test('couleurs : site.css réutilise les jetons du tableau de bord, sans seconde palette', () => {
|
||||||
|
const app = read('public/app.css');
|
||||||
|
const site = read('public/site.css');
|
||||||
|
const code = site.replace(/\/\*[\s\S]*?\*\//g, ''); // les commentaires peuvent citer ce qu'on évite
|
||||||
|
for (const t of ['bg', 'card', 'text', 'muted', 'line', 'accent']) {
|
||||||
|
assert.match(site, new RegExp(`var\\(--${t}\\)`), `--${t} utilisé par le site`);
|
||||||
|
assert.match(app, new RegExp(`--${t}:`), `--${t} défini par le tableau de bord`);
|
||||||
|
assert.doesNotMatch(site, new RegExp(`--${t}\\s*:`), `--${t} ne doit pas être redéfini`);
|
||||||
|
}
|
||||||
|
assert.doesNotMatch(site, /#[0-9a-fA-F]{3,8}\b/, 'aucune couleur en dur dans site.css');
|
||||||
|
assert.doesNotMatch(site, /\b(rgb|hsl|oklch)a?\(/, 'aucune couleur calculée hors jetons');
|
||||||
|
assert.doesNotMatch(code, /--accent-2|violet|purple/i, 'pas de dégradé violet');
|
||||||
|
assert.match(site, /prefers-reduced-motion: no-preference/, 'animations réservées à qui les accepte');
|
||||||
|
assert.match(site, /:focus-visible/);
|
||||||
|
const layout = readFileSync(new URL('../src/site/layout.js', import.meta.url), 'utf8');
|
||||||
|
assert.match(layout, /\/static\/app\.css[\s\S]*\/static\/site\.css/, 'site.css chargé après app.css');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('contrastes AA (4,5:1) des couples texte/fond du site, thèmes clair et sombre', () => {
|
||||||
|
const app = read('public/app.css');
|
||||||
|
const light = tokens(app.match(/:root\s*\{([^}]*)\}/)[1]);
|
||||||
|
const dark = tokens(app.match(/prefers-color-scheme: dark\)\s*\{\s*:root\s*\{([^}]*)\}/)[1]);
|
||||||
|
const themes = {
|
||||||
|
clair: { ...light, onAccent: light['accent-text'] }, // bouton principal : --accent-text sur --accent
|
||||||
|
sombre: { ...light, ...dark, onAccent: dark.bg }, // thème sombre : site.css passe le texte du bouton en var(--bg)
|
||||||
|
};
|
||||||
|
for (const [name, t] of Object.entries(themes)) {
|
||||||
|
const pairs = [
|
||||||
|
['text/bg', t.text, t.bg], ['text/card', t.text, t.card], ['muted/bg', t.muted, t.bg], ['muted/card', t.muted, t.card],
|
||||||
|
['accent/bg', t.accent, t.bg], ['accent/card', t.accent, t.card], ['bouton principal', t.onAccent, t.accent],
|
||||||
|
['ok/card', t.ok, t.card], ['warn/card', t.warn, t.card], ['err/card', t.err, t.card],
|
||||||
|
];
|
||||||
|
for (const [label, fg, bg] of pairs) assert.ok(ratio(fg, bg) >= 4.5, `${name} : ${label} = ${ratio(fg, bg).toFixed(2)}`);
|
||||||
|
}
|
||||||
|
assert.match(read('public/site.css'), /prefers-color-scheme: dark\)\s*\{\s*body\.site \.btn\.primary \{ color: var\(--bg\); \}/);
|
||||||
|
});
|
||||||
66
test/worker.test.js
Normal file
66
test/worker.test.js
Normal file
|
|
@ -0,0 +1,66 @@
|
||||||
|
import { test } from 'node:test';
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import { now } from '../src/db.js';
|
||||||
|
import { testDb } from './helpers/db.js';
|
||||||
|
import { addUser } from './helpers/users.js';
|
||||||
|
import { Worker, enqueue, latestJobs } from '../src/services/jobs.js';
|
||||||
|
|
||||||
|
async function setup() {
|
||||||
|
const db = await testDb();
|
||||||
|
const u = await addUser(db);
|
||||||
|
await db.prepare("INSERT INTO projects(user_id, name, git_url, created_at) VALUES(?, 'p', 'u', ?)").run(u, now());
|
||||||
|
db.userId = u;
|
||||||
|
return db;
|
||||||
|
}
|
||||||
|
|
||||||
|
test('start puis stop : la boucle s\'arrête, le job en cours est annulé et attendu', async () => {
|
||||||
|
const db = await setup();
|
||||||
|
let started;
|
||||||
|
const running = new Promise((r) => { started = r; });
|
||||||
|
const w = new Worker(db, {
|
||||||
|
prospect: (ctx) => new Promise((_, reject) => {
|
||||||
|
started();
|
||||||
|
ctx.signal.addEventListener('abort', () => reject(new Error('Annulé')), { once: true });
|
||||||
|
}),
|
||||||
|
}, { thermalMax: 999, pollMs: 10, log: { error() {} } });
|
||||||
|
await enqueue(db, { userId: db.userId, projectId: 1, type: 'prospect' });
|
||||||
|
await w.start();
|
||||||
|
await running;
|
||||||
|
await w.stop();
|
||||||
|
assert.equal(w.current, null);
|
||||||
|
const job = (await latestJobs(db, 1)).prospect;
|
||||||
|
assert.equal(job.status, 'error');
|
||||||
|
assert.match(job.error, /Annulé/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('stop attend les notifications en vol, et un callback qui échoue est journalisé', async () => {
|
||||||
|
const db = await setup();
|
||||||
|
const seen = [];
|
||||||
|
const errors = [];
|
||||||
|
const w = new Worker(db, { prospect: async () => ({ ok: true }), evolution: async () => { throw new Error('boum'); } }, {
|
||||||
|
thermalMax: 999, pollMs: 10, log: { error: (...a) => errors.push(a.join(' ')) },
|
||||||
|
onFinish: async (job, r) => {
|
||||||
|
await new Promise((res) => setTimeout(res, 30));
|
||||||
|
seen.push(`${job.type}:${r.status}`);
|
||||||
|
if (job.type === 'evolution') throw new Error('notification cassée');
|
||||||
|
},
|
||||||
|
});
|
||||||
|
await enqueue(db, { userId: db.userId, projectId: 1, type: 'prospect' });
|
||||||
|
await enqueue(db, { userId: db.userId, projectId: 1, type: 'evolution' });
|
||||||
|
await w.tick(); await w.tick();
|
||||||
|
assert.deepEqual(seen, [], 'les notifications ne bloquent pas la file');
|
||||||
|
await w.stop();
|
||||||
|
assert.deepEqual(seen.sort(), ['evolution:error', 'prospect:done']);
|
||||||
|
assert.ok(errors.some((e) => /notification cassée/.test(e)));
|
||||||
|
});
|
||||||
|
|
||||||
|
test('un job "running" laissé par un crash est marqué en erreur au démarrage', async () => {
|
||||||
|
const db = await setup();
|
||||||
|
await db.prepare("INSERT INTO jobs(user_id, project_id, type, status, created_at) VALUES(?, 1, 'analyze', 'running', ?)").run(db.userId, now());
|
||||||
|
const w = new Worker(db, {}, { thermalMax: 999, pollMs: 10, log: { error() {} } });
|
||||||
|
await w.start();
|
||||||
|
await w.stop();
|
||||||
|
const job = (await latestJobs(db, 1)).analyze;
|
||||||
|
assert.equal(job.status, 'error');
|
||||||
|
assert.equal(job.error, 'Interrompu (redémarrage)');
|
||||||
|
});
|
||||||
Loading…
Reference in a new issue