Compare commits
11 commits
feat/saas-
...
develop
| Author | SHA1 | Date | |
|---|---|---|---|
| 323b44d3d3 | |||
| d76800af6c | |||
| 433c74fc54 | |||
| c9066e9e8d | |||
| d2c424811d | |||
| 5d94058e31 | |||
| a7adb1e906 | |||
| be3fb43a2d | |||
| 59039ea411 | |||
| 75980c4613 | |||
| a3188356dd |
70 changed files with 3801 additions and 250 deletions
33
.env.example
33
.env.example
|
|
@ -51,5 +51,34 @@ CLAUDE_CLI_MODE_ENABLED=true
|
|||
# SANDBOX_RO_BINDS=
|
||||
# Binaire bubblewrap si hors du PATH
|
||||
# BWRAP_BIN=bwrap
|
||||
# Pause des jobs au-delà de cette température CPU (°C)
|
||||
THERMAL_MAX=75
|
||||
|
||||
# --- Anti-abus, plafonds et administration (jalon J5) ---
|
||||
# Derrière Nginx / CloudPanel : lire X-Forwarded-For, mais seulement depuis un proxy de confiance.
|
||||
# false (défaut) | true (proxy local 127.0.0.0/8 et ::1) | liste d'adresses ou de plages CIDR séparées par des virgules
|
||||
TRUST_PROXY=false
|
||||
|
||||
# Google reCAPTCHA v3 sur la connexion (console.google.com/recaptcha, type v3, domaine ai.tony-averty.dev).
|
||||
# Les deux clés ensemble, ou aucune (désactivé : développement). Le script de Google n'est chargé qu'après un clic de l'utilisateur.
|
||||
RECAPTCHA_SITE_KEY=
|
||||
RECAPTCHA_SECRET=
|
||||
# Score minimal accepté (0 à 1)
|
||||
RECAPTCHA_MIN_SCORE=0.5
|
||||
|
||||
# Jobs IA simultanés sur le serveur (un seul par utilisateur). 4 pour 6 cœurs en gardant 2 cœurs pour MySQL, Nginx et les autres sites.
|
||||
MAX_AI_JOBS=4
|
||||
# Les nouveaux jobs attendent quand charge moyenne (1 min) / nombre de cœurs dépasse cette valeur (remplace THERMAL_MAX)
|
||||
LOAD_MAX=0.9
|
||||
|
||||
# Hôtes privés (127.0.0.1, 10.x, 192.168.x…) autorisés pour SMTP, IMAP, base du récap et Forgejo, et tous les ports.
|
||||
# Développement seulement ; en production, réservé aux comptes administrateurs. Laisser à false sinon.
|
||||
ALLOW_PRIVATE_HOSTS=false
|
||||
|
||||
# Comptes inactifs : suppression après ce nombre de mois sans connexion ni job (0 = désactivé), avertissement 30 jours avant.
|
||||
INACTIVE_ACCOUNT_MONTHS=24
|
||||
# SMTP du serveur pour les mails système (avertissement d'inactivité). Toutes les variables ensemble, ou aucune :
|
||||
# sans lui, l'avertissement est seulement journalisé et AUCUN compte n'est supprimé automatiquement.
|
||||
SYSTEM_SMTP_HOST=
|
||||
SYSTEM_SMTP_PORT=587
|
||||
SYSTEM_SMTP_USER=
|
||||
SYSTEM_SMTP_PASSWORD=
|
||||
SYSTEM_SMTP_FROM=
|
||||
|
|
|
|||
42
README.md
42
README.md
|
|
@ -9,7 +9,7 @@ la version publique cible un serveur CloudPanel avec une base MySQL/MariaDB (voi
|
|||
- **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.
|
||||
- **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`.
|
||||
- **File de jobs équitable** (en base) : `MAX_AI_JOBS` jobs en parallèle, un seul par utilisateur, tourniquet entre utilisateurs. Le process Claude tourne en `nice 10`. Les nouveaux jobs attendent si la charge du serveur dépasse `LOAD_MAX` (voir « Anti-abus, plafonds et administration »).
|
||||
- **Économie de tokens** :
|
||||
- outils Claude restreints à chaque job (lecture seule pour le code, WebSearch/WebFetch pour la prospection) ;
|
||||
- `--max-turns` borné ;
|
||||
|
|
@ -57,7 +57,7 @@ Le site (`ai.tony-averty.dev`) est servi par la même application, dans `src/sit
|
|||
|
||||
## Pilotage
|
||||
|
||||
- **Jobs de nuit** : Prospecter et Évolution proposent « Maintenant » ou « Cette nuit ». Le job démarre au prochain créneau entre 1h et 6h (heure de Paris, changements d'heure gérés), quand le Pi est au frais et que ton quota Claude est libre. Il est annulable jusqu'au départ.
|
||||
- **Jobs de nuit** : Prospecter et Évolution proposent « Maintenant » ou « Cette nuit ». Le job démarre au prochain créneau entre 1h et 6h (heure de Paris, changements d'heure gérés), quand le serveur est peu chargé et que ton quota Claude est libre. Il est annulable jusqu'au départ.
|
||||
- **Budget IA** : plafonds glissants sur 24 h et sur 30 jours, en équivalent $ API remonté par Claude Code. L'abonnement Pro ne facture rien en plus ; c'est un garde-fou pour ton quota.
|
||||
- Plafond atteint : les jobs IA **restent en file** et repartent seuls quand la fenêtre glisse. Les envois et relances, qui ne consomment pas d'IA, continuent.
|
||||
- Un job en cours n'est jamais coupé : le plafond peut donc être dépassé d'un job.
|
||||
|
|
@ -153,6 +153,44 @@ Chaque utilisateur relie SON accès ; ses jobs IA tournent avec cet accès uniqu
|
|||
- **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`.
|
||||
|
||||
## Anti-abus, plafonds et administration
|
||||
|
||||
Les seuils, fenêtres et plafonds vivent dans **un seul module : `src/limits.js`**. Les pages Tarifs lisent les mêmes chiffres.
|
||||
|
||||
### Limitation de débit
|
||||
|
||||
En mémoire (fenêtre glissante, sans dépendance), par adresse IP et par compte. Au-delà du seuil : `429` avec `Retry-After`. Règles : démarrage et retours de connexion, routes `/link/*`, export et import CSV, envois (lot, rapport, notification de test), création de projet, suppression de compte, tests de connexion (IMAP, base du récap), back-office. Les compteurs sont perdus à un redémarrage et non partagés entre instances (une seule instance en production).
|
||||
|
||||
**`TRUST_PROXY`** (désactivé par défaut) : derrière Nginx de CloudPanel, toutes les requêtes arrivent de `127.0.0.1` ; sans réglage, tous les visiteurs partagent donc le même compteur.
|
||||
- `TRUST_PROXY=true` : `X-Forwarded-For` est lu **seulement** si la connexion vient d'un proxy local (127.0.0.0/8, `::1`).
|
||||
- `TRUST_PROXY=127.0.0.1,10.0.0.0/8` : liste d'adresses ou de plages CIDR de proxys de confiance.
|
||||
- L'en-tête est lu de droite à gauche et on garde la première adresse qui n'est pas un proxy de confiance : les valeurs inventées par le client à gauche sont ignorées. Nginx doit AJOUTER l'adresse (`proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;`). Sans `TRUST_PROXY`, un en-tête forgé n'a aucun effet. Derrière Cloudflare Tunnel seul, l'adresse réelle est dans `CF-Connecting-IP`, qui n'est pas lue : garde Nginx devant.
|
||||
|
||||
### reCAPTCHA v3 (connexion)
|
||||
|
||||
`RECAPTCHA_SITE_KEY` + `RECAPTCHA_SECRET` (les deux ou aucune), `RECAPTCHA_MIN_SCORE` (0,5 par défaut). Le démarrage de la connexion Google et Apple devient un POST qui porte un jeton, vérifié côté serveur (score, action `login`, site). **Rien n'est chargé depuis Google avant le clic sur « Charger la vérification anti-robot »** de la page de connexion ; la CSP n'ouvre les domaines reCAPTCHA que sur `/login`. Sans clés, reCAPTCHA est désactivé (développement, avertissement au démarrage) ; avec les clés, aucun réglage ne permet de le contourner. Le choix n'est pas mémorisé. La politique de confidentialité décrit reCAPTCHA seulement quand il est configuré.
|
||||
|
||||
### Plafonds des plans
|
||||
|
||||
Plan gratuit : 1 projet, 50 prospects, 100 mails et 5 jobs IA par mois (mois calendaire, heure de Paris). Un administrateur (`ADMIN_EMAILS`) n'a pas de limite ; le plan `pro` est illimité en attendant qu'il soit défini. Projets et prospects se comptent dans leurs tables ; mails et jobs IA dans `usage_events`, qui survit à la suppression d'un projet. Rien ne se stocke en compteur : l'usage est toujours une somme. Un dépassement refuse l'action (`403`, code `plan_limit`, lien `/tarifs`) sans rien supprimer : un import CSV trop gros est refusé en entier, un lot de mails est tronqué à ce qui reste, une recherche de prospects n'enregistre pas au-delà du plafond. L'usage du mois s'affiche (barres) dans Mon compte et sur le tableau de bord.
|
||||
|
||||
### File de jobs
|
||||
|
||||
`MAX_AI_JOBS` jobs en parallèle (4 par défaut, un serveur de 6 cœurs), **au plus un par utilisateur**, prochain job choisi en tourniquet entre utilisateurs. Réservation atomique en base. L'arrêt attend tous les jobs en cours. Les nouveaux jobs attendent quand la charge du serveur dépasse `LOAD_MAX` (charge moyenne sur 1 minute divisée par le nombre de cœurs, 0,9 par défaut, reprise 0,1 plus bas) ; les jobs en cours continuent. `nice 10` est conservé. Budget IA et quota Claude restent par utilisateur.
|
||||
|
||||
### Hôtes saisis par l'utilisateur (SSRF)
|
||||
|
||||
SMTP, IMAP, base du récap et hôte Forgejo : le nom est résolu, toute adresse privée, loopback, link-local (dont `169.254.169.254`), CGNAT, `fc00::/7`, `fe80::/10` ou IPv4 mappée est refusée, et la connexion se fait **à l'adresse vérifiée** (nom conservé pour SNI et certificat), revérifiée à chaque connexion (pas de rebinding DNS). Git est épinglé par `http.curloptResolve` (git 2.37 ou plus) et ne suit aucune redirection. Ports par type dans `ALLOWED_PORTS` (`src/limits.js`) : SMTP 25/465/587/2525, IMAP 143/993, MySQL 3306/3307/25060, PostgreSQL 5432/5433/25061, Git 443/8443. `ALLOW_PRIVATE_HOSTS=true` autorise les hôtes privés et tous les ports : pour le développement, et en production pour les administrateurs seulement.
|
||||
|
||||
### Back-office `/admin`
|
||||
|
||||
Réservé aux administrateurs (`404` pour tous les autres). Liste paginée des comptes (email, fournisseur, plan, statut, dates, mode de liaison sans secret, usage du mois), recherche par email, suspendre / réactiver, plan gratuit ou pro, supprimer (saisie de l'email), rétablir les envois. Un administrateur ne peut ni se suspendre ni se supprimer, ni agir sur un autre administrateur. Aucune donnée métier (prospects, mails, notes) n'est consultable. Journal d'audit en lecture seule, adresses masquées, conservé 12 mois.
|
||||
|
||||
### Comptes inactifs et abus d'envoi
|
||||
|
||||
- **Inactifs** : après `INACTIVE_ACCOUNT_MONTHS` mois (24, `0` pour désactiver) sans connexion ni job, un mail d'avertissement part via le SMTP du serveur (`SYSTEM_SMTP_HOST`, `_PORT`, `_USER`, `_PASSWORD`, `_FROM`, toutes ensemble), puis le compte est supprimé 30 jours plus tard s'il est resté inactif. **Sans SMTP du serveur, rien n'est supprimé automatiquement** : l'avertissement est journalisé. Jamais un administrateur ni un compte suspendu.
|
||||
- **Rejets** : au-delà de 10 % de rejets sur au moins 50 prospects contactés (30 jours), les envois du compte sont mis en pause, avec message clair, audit, journal du serveur et Discord de l'administrateur. L'administrateur rétablit depuis `/admin`. Désinscription et liste d'opposition inchangées.
|
||||
|
||||
## 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,6 +1,48 @@
|
|||
# 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`.
|
||||
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) et `feat/saas-guardrails` (J5, depuis J4) — version publique, voir `docs/CADRAGE.md`.
|
||||
|
||||
## 2026-10-22 — J5 « Anti-abus, quotas et administration »
|
||||
|
||||
### Fait
|
||||
- **Limitation de débit** (`src/ratelimit.js`, seuils dans `src/limits.js`) : fenêtre glissante en mémoire, par IP et par compte, sans dépendance. Connexion (démarrage, retours Google et Apple), `/link/*`, export et import CSV, envois (lot, rapport, notification de test), création de projet, suppression de compte, tests IMAP et récap, back-office. `429` + `Retry-After` ; une requête refusée n'est pas comptée. `TRUST_PROXY` (défaut : désactivé) : `X-Forwarded-For` lu de droite à gauche, seulement depuis un proxy de confiance (loopback, ou liste/CIDR), les valeurs de gauche forgées par le client sont ignorées.
|
||||
- **reCAPTCHA v3** (`src/captcha.js`, `public/captcha.js`) : le démarrage de la connexion devient un POST avec jeton, vérifié côté serveur (score ≥ `RECAPTCHA_MIN_SCORE`, action, site). Le script de Google n'est chargé qu'après le clic sur « Charger la vérification anti-robot » ; la CSP ouvre les domaines reCAPTCHA sur `/login` seulement. Sans clés : désactivé. Politique de confidentialité mise à jour (destinataires, cookies, adresse IP en mémoire) seulement quand reCAPTCHA est configuré.
|
||||
- **Plafonds du plan gratuit** (`src/services/plans.js`) : 1 projet, 50 prospects, 100 mails, 5 jobs IA par mois (mois calendaire Paris). Migration 3 `usage_events` (journal d'usage qui survit à la suppression d'un projet). Refus `403 plan_limit` avec lien `/tarifs`, sans perte (import CSV refusé en entier, lot de mails tronqué, recherche de prospects arrêtée au plafond, projet créé même si l'analyse est refusée). Barres d'usage dans Mon compte et sur le tableau de bord. Page Tarifs corrigée.
|
||||
- **File de jobs** : `MAX_AI_JOBS` (4) en parallèle, un seul par utilisateur, tourniquet, réservation atomique (`UPDATE … WHERE status = 'queued'` + contrôle des lignes affectées et d'un job `running` du même utilisateur), arrêt qui attend tous les jobs. Pause thermique remplacée par une pause selon `charge / cœurs` (`LOAD_MAX`, hystérésis de 0,1). `nice 10` conservé. Testée avec le CLI simulé (`FAKE_DELAY_MS`, `FAKE_LOG` dans la fixture).
|
||||
- **SSRF** (`src/netguard.js`, `src/ip.js`) : SMTP, IMAP, base du récap, Forgejo. Résolution puis refus des adresses privées ; connexion à l'adresse vérifiée (SMTP/IMAP/BDD : `host` = IP + `servername`), git épinglé (`http.curloptResolve`, sans redirection). Ports par type. `ALLOW_PRIVATE_HOSTS` : dev, et admins seulement en production. Contrôle aussi à l'enregistrement (réponse 400 immédiate ; hôte non résolu accepté, revérifié à l'usage).
|
||||
- **Back-office `/admin`** (`src/admin.js`, `adminroutes.js`, `adminviews.js`) : 404 pour les non-admins et les visiteurs, liste paginée avec recherche, suspendre / réactiver / plan gratuit-pro / supprimer (saisie de l'email) / rétablir les envois. Migration 4 `admin_audit` (sans clé étrangère, adresses masquées, conservé 12 mois, lecture seule).
|
||||
- **Comptes inactifs** (`src/services/inactive.js`) : planificateur, `INACTIVE_ACCOUNT_MONTHS` (24, 0 = désactivé), avertissement 30 jours avant via `SYSTEM_SMTP_*`, suppression 30 jours après l'avertissement si pas de reconnexion. Page confidentialité corrigée (en place, durée configurée).
|
||||
- **Abus d'envoi** (`src/services/abuse.js`) : > 10 % de rejets sur ≥ 50 prospects contactés (30 jours) → pause d'envoi, message clair, audit, journal serveur, Discord des admins (forcé) et du compte. Rétablissement par l'admin.
|
||||
- **Tests** : `ratelimit`, `captcha`, `plans`, `queue`, `netguard`, `admin`, `abuse`, `inactive`.
|
||||
|
||||
### Décisions
|
||||
- **Journal d'usage plutôt que `mail_log`/`jobs`** pour les plafonds mensuels : supprimer un projet efface ses jobs et ses logs de mail (cascade) et remettrait sinon le mois à zéro. Un job IA annulé ou refusé sans jamais démarrer n'est pas compté ; un job dont le projet a disparu l'est (prudence).
|
||||
- **Pas de suppression automatique sans avertissement reçu** : sans SMTP du serveur, les comptes inactifs sont journalisés et à traiter à la main (le brief disait « sinon journalisé » ; supprimer sans prévenir semblait pire).
|
||||
- **Le plan `pro` est illimité** tant qu'il n'est pas défini (`PLAN_LIMITS.pro` dans `src/limits.js`).
|
||||
- **Un admin ne touche pas aux autres admins** (suspension, plan, suppression) : leur rôle vient de `ADMIN_EMAILS`.
|
||||
- **Sans consentement reCAPTCHA, pas de connexion** (aucun contournement demandé) : la politique le dit. Le consentement n'est pas mémorisé.
|
||||
- **Git épinglé sans suivre de redirection** (`http.followRedirects=false`) : un dépôt hébergé derrière une redirection ne se clone plus.
|
||||
- Événement Discord `thermal` renommé `load` (les anciens réglages sont convertis à la lecture).
|
||||
|
||||
### Non vérifié (à faire par Tony ou au prochain passage)
|
||||
- **MySQL/MariaDB réel** : toujours aucune base de test. Nouveau à valider avec `npm run test:mysql` : migrations 3 et 4, et surtout `UPDATE jobs … AND (SELECT COUNT(*) FROM (SELECT id FROM jobs WHERE … LIMIT 1) busy) = 0` (table dérivée avec `LIMIT` pour éviter l'erreur 1093 ; à confirmer sur MySQL 8 et MariaDB), `COUNT(DISTINCT CASE …)`, `LIKE … ESCAPE '!'`.
|
||||
- **reCAPTCHA réel** : clés, score, rendu du badge masqué, et surtout la **CSP** (`style-src 'self'` sans `unsafe-inline` : si reCAPTCHA injecte des styles en ligne, la console affichera des violations ; à vérifier dans un navigateur sur le domaine, ajuster seulement la CSP de `/login`). Durée du cookie `_GRECAPTCHA` non vérifiée (la page dit « durée fixée par Google »).
|
||||
- **Connexions réelles bloquées par le filtre** : SMTP/IMAP/MySQL réels avec `servername`, `tls.servername` pour STARTTLS (nodemailer), `http.curloptResolve` (git ≥ 2.37), non exécutables ici. Vérifier un envoi réel, une lecture IMAP et un clone sur le serveur.
|
||||
- **Charge** : `os.loadavg()` vaut toujours 0 sous Windows ; la pause de charge n'est testée qu'avec une charge injectée. Valeurs `MAX_AI_JOBS`/`LOAD_MAX` à régler sur le vrai serveur (bwrap, 4 jobs réels, mémoire non mesurés).
|
||||
- **TRUST_PROXY** derrière le Nginx de CloudPanel : à tester avec l'en-tête réellement posé.
|
||||
- **Mail d'avertissement d'inactivité** : jamais envoyé pour de vrai (transport simulé).
|
||||
|
||||
### Risques
|
||||
- Compteurs de débit en mémoire : un redémarrage les remet à zéro ; plusieurs instances ne les partagent pas.
|
||||
- Quotas : `withUserLock` est un verrou de processus ; deux instances pourraient dépasser un plafond d'une unité.
|
||||
- Ports autorisés : un fournisseur de base managée sur un port inhabituel est refusé (liste dans `ALLOWED_PORTS`).
|
||||
- Une pause d'envoi se déclenche aussi sur des rejets dont l'utilisateur n'est pas responsable (liste achetée, panne chez un destinataire) : l'admin rétablit.
|
||||
- Aucune relecture juridique du paragraphe reCAPTCHA (consentement obligatoire pour se connecter : un consentement « libre » peut être contesté).
|
||||
|
||||
### À faire
|
||||
- Fixer le plan `pro` (limites, prix) avec le jalon paiement.
|
||||
- Poser les clés reCAPTCHA, `SYSTEM_SMTP_*`, `TRUST_PROXY=true` (ou la liste) dans le `.env` du serveur ; `MAX_AI_JOBS` selon la charge réelle.
|
||||
- J6 : `install.sh` (Pi) propose encore `THERMAL_MAX` ; il n'est plus lu.
|
||||
|
||||
## 2026-10-22 — J4 « Site public »
|
||||
|
||||
|
|
@ -29,7 +71,7 @@ Visibles en jaune sur les pages légales tant que l'information manque. Un test
|
|||
- `[À 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 : durées de conservation]` : confidentialité. Propositions : compte inactif supprimé après 24 mois (implémenté au J5, avec avertissement 30 jours avant), journal d'administration 12 mois, 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.
|
||||
|
|
@ -50,7 +92,7 @@ Visibles en jaune sur les pages légales tant que l'information manque. Un test
|
|||
### À 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.
|
||||
- ~~J5 : plafonds, reCAPTCHA, comptes inactifs~~ : faits (voir J5).
|
||||
- Les pages d'erreur HTML autres que 404 (403, 500) utilisent encore l'ancien gabarit.
|
||||
|
||||
## 2026-10-22 — J3 « Liaison Claude »
|
||||
|
|
|
|||
|
|
@ -340,3 +340,36 @@ form.send { margin-top: 6px; padding-top: 0; border-top: 0; }
|
|||
animation-duration: .01ms !important; animation-iteration-count: 1 !important; transition-duration: .01ms !important;
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------- Usage du mois (largeurs par classes : la CSP interdit le style en ligne) ---------- */
|
||||
.usage-list { list-style: none; margin: 0; padding: 0; display: grid; gap: 12px; }
|
||||
.bar.usage > span::after { content: none; }
|
||||
.bar.usage.full > span { background: var(--err); }
|
||||
.bar > span.w-0 { width: 0%; }
|
||||
.bar > span.w-5 { width: 5%; }
|
||||
.bar > span.w-10 { width: 10%; }
|
||||
.bar > span.w-15 { width: 15%; }
|
||||
.bar > span.w-20 { width: 20%; }
|
||||
.bar > span.w-25 { width: 25%; }
|
||||
.bar > span.w-30 { width: 30%; }
|
||||
.bar > span.w-35 { width: 35%; }
|
||||
.bar > span.w-40 { width: 40%; }
|
||||
.bar > span.w-45 { width: 45%; }
|
||||
.bar > span.w-50 { width: 50%; }
|
||||
.bar > span.w-55 { width: 55%; }
|
||||
.bar > span.w-60 { width: 60%; }
|
||||
.bar > span.w-65 { width: 65%; }
|
||||
.bar > span.w-70 { width: 70%; }
|
||||
.bar > span.w-75 { width: 75%; }
|
||||
.bar > span.w-80 { width: 80%; }
|
||||
.bar > span.w-85 { width: 85%; }
|
||||
.bar > span.w-90 { width: 90%; }
|
||||
.bar > span.w-95 { width: 95%; }
|
||||
.bar > span.w-100 { width: 100%; }
|
||||
|
||||
/* ---------- Administration ---------- */
|
||||
.admin-table td { vertical-align: top; }
|
||||
.admin-actions { display: grid; gap: 6px; min-width: 200px; }
|
||||
form.inline { display: inline-flex; gap: 6px; align-items: end; flex-wrap: wrap; margin: 0; }
|
||||
.admin-actions .del summary { list-style: none; cursor: pointer; display: inline-block; }
|
||||
.admin-pager { display: flex; gap: 8px; }
|
||||
|
|
|
|||
|
|
@ -169,7 +169,7 @@
|
|||
let busy = false;
|
||||
try {
|
||||
const s = await api('/api/system');
|
||||
const hot = s.temp !== null && s.temp >= s.thermalMax - 5;
|
||||
const hot = s.temp !== null && s.temp >= 70;
|
||||
el.innerHTML = `${s.temp !== null ? `<span class="${hot ? 'warn' : ''}">${s.temp} °C</span>` : ''}
|
||||
${claudeQuota(s.claudeRateLimit, s.linkMode)}
|
||||
${gauge('24 h', s.budget.day)} ${gauge('30 j', s.budget.month)}
|
||||
|
|
|
|||
39
public/captcha.js
Normal file
39
public/captcha.js
Normal file
|
|
@ -0,0 +1,39 @@
|
|||
// Vérification anti-robot de la page de connexion (Google reCAPTCHA v3), chargée seulement APRÈS le clic de l'utilisateur.
|
||||
// Tant qu'il n'a pas cliqué sur « Charger la vérification anti-robot », aucune requête ne part vers Google.
|
||||
(() => {
|
||||
const box = document.querySelector('[data-captcha]');
|
||||
if (!box) return;
|
||||
const key = box.dataset.sitekey;
|
||||
const status = box.querySelector('[data-captcha-status]');
|
||||
const load = box.querySelector('[data-captcha-load]');
|
||||
const forms = [...document.querySelectorAll('form[data-captcha-form]')];
|
||||
let ready = false;
|
||||
const say = (text) => { status.textContent = text; };
|
||||
|
||||
load.addEventListener('click', () => {
|
||||
load.disabled = true;
|
||||
say('Chargement de la vérification…');
|
||||
const s = document.createElement('script');
|
||||
s.src = `https://www.google.com/recaptcha/api.js?render=${encodeURIComponent(key)}`;
|
||||
s.async = true;
|
||||
s.onload = () => window.grecaptcha.ready(() => {
|
||||
ready = true;
|
||||
for (const f of forms) f.querySelector('button').disabled = false;
|
||||
load.hidden = true;
|
||||
say('Vérification chargée : tu peux te connecter.');
|
||||
});
|
||||
s.onerror = () => { load.disabled = false; say('La vérification n\'a pas pu être chargée (réseau ou bloqueur de contenu). Réessaie.'); };
|
||||
document.head.append(s);
|
||||
});
|
||||
|
||||
for (const f of forms) {
|
||||
f.addEventListener('submit', (e) => {
|
||||
e.preventDefault();
|
||||
if (!ready) return;
|
||||
window.grecaptcha.execute(key, { action: 'login' }).then((token) => {
|
||||
f.querySelector('input[name="captcha"]').value = token;
|
||||
f.submit();
|
||||
}, () => say('La vérification a échoué : réessaie.'));
|
||||
});
|
||||
}
|
||||
})();
|
||||
|
|
@ -235,3 +235,13 @@ mark.todo { background: color-mix(in srgb, var(--warn) 16%, transparent); color:
|
|||
.shot { animation-delay: .08s; }
|
||||
@keyframes site-in { from { opacity: 0; transform: translateY(8px); } }
|
||||
}
|
||||
|
||||
/* ---------- Vérification anti-robot (connexion) ---------- */
|
||||
.captcha { margin: 0 0 16px; padding: 14px 16px; border: 1px solid var(--line); border-radius: 12px; }
|
||||
.captcha h3 { margin: 0 0 6px; font-size: 1rem; }
|
||||
.captcha p { margin: 0 0 10px; }
|
||||
.auth .login-btns form { margin: 0; }
|
||||
.auth .login-btns form .btn { width: 100%; }
|
||||
.auth .login-btns .btn[disabled] { opacity: .55; cursor: not-allowed; }
|
||||
/* Le badge de Google est masqué : sa mention obligatoire figure dans le texte sous les boutons */
|
||||
.grecaptcha-badge { visibility: hidden; }
|
||||
|
|
|
|||
93
src/admin.js
Normal file
93
src/admin.js
Normal file
|
|
@ -0,0 +1,93 @@
|
|||
// Back-office : liste des comptes, suspension, plan, suppression, journal d'audit. RIEN des données métier d'un compte
|
||||
// (prospects, mails, notes, projets) n'est lu ici : uniquement l'identité du compte, sa liaison (mode, sans secret) et des compteurs.
|
||||
import { now } from './db.js';
|
||||
import { logAudit } from './audit.js';
|
||||
import { sendPause, resumeSending } from './services/abuse.js';
|
||||
import { HttpError } from './http.js';
|
||||
import { destroyUserSessions } from './auth.js';
|
||||
import { getUser, deleteUser, normalizeEmail } from './users.js';
|
||||
import { ADMIN_PAGE_SIZE, PAID_PLANS } from './limits.js';
|
||||
import { usageOf, limitsFor } from './services/plans.js';
|
||||
import { MODE_LABELS } from './claudelink.js';
|
||||
|
||||
const like = (q) => `%${String(q).replace(/[!%_]/g, '!$&')}%`;
|
||||
|
||||
export { maskEmail, ACTION_LABELS, logAudit, recentAudit, purgeAudit } from './audit.js';
|
||||
|
||||
/** Page de comptes : identité, liaison (mode seulement), usage du mois. Aucune donnée métier. */
|
||||
export async function listAccounts(db, { page = 1, q = '', at = now() } = {}) {
|
||||
const where = q ? "WHERE email LIKE ? ESCAPE '!'" : '';
|
||||
const args = q ? [like(q)] : [];
|
||||
const total = Number((await db.prepare(`SELECT COUNT(*) n FROM users ${where}`).get(...args)).n);
|
||||
const pages = Math.max(1, Math.ceil(total / ADMIN_PAGE_SIZE));
|
||||
const p = Math.min(Math.max(1, Math.floor(Number(page)) || 1), pages);
|
||||
const rows = await db.prepare(`SELECT id, email, provider, status, is_admin, plan, created_at, last_login_at, claude_link_json
|
||||
FROM users ${where} ORDER BY id DESC LIMIT ? OFFSET ?`).all(...args, ADMIN_PAGE_SIZE, (p - 1) * ADMIN_PAGE_SIZE);
|
||||
const accounts = [];
|
||||
for (const r of rows) {
|
||||
let link = null;
|
||||
try { const j = r.claude_link_json ? JSON.parse(r.claude_link_json) : null; if (j?.mode) link = { mode: MODE_LABELS[j.mode] || j.mode, valid: !!j.valid }; } catch { link = null; }
|
||||
const user = await getUser(db, r.id);
|
||||
const usage = await usageOf(db, r.id, { at });
|
||||
accounts.push({
|
||||
id: Number(r.id), email: r.email, provider: r.provider, status: r.status, isAdmin: !!r.is_admin, plan: r.plan,
|
||||
createdAt: r.created_at, lastLoginAt: r.last_login_at, link,
|
||||
usage: { ...usage, limits: limitsFor(user) }, sendPause: await sendPause(db, r.id),
|
||||
});
|
||||
}
|
||||
return { accounts, total, page: p, pages };
|
||||
}
|
||||
|
||||
// Un administrateur ne touche jamais à son propre compte ni à un autre compte administrateur (leur rôle vient de ADMIN_EMAILS)
|
||||
function assertManageable(actor, target, verb) {
|
||||
if (!target) throw new HttpError(404, 'Compte introuvable');
|
||||
if (Number(target.id) === Number(actor.id)) throw new HttpError(400, `Tu ne peux pas ${verb} ton propre compte.`, { expose: true });
|
||||
if (target.isAdmin) throw new HttpError(400, `Ce compte est administrateur (ADMIN_EMAILS) : il ne se ${verb === 'suspendre' ? 'suspend' : 'modifie'} pas ici.`, { expose: true });
|
||||
}
|
||||
|
||||
/**
|
||||
* Exécute une action d'administration, la journalise et renvoie un message pour l'écran.
|
||||
* @param {{db, worker?}} app
|
||||
* @param {{id: number, email: string}} actor administrateur connecté
|
||||
* @param {'suspend'|'reactivate'|'plan'|'delete'|'resume_send'} action
|
||||
*/
|
||||
export async function adminAction(app, actor, action, targetId, { plan, confirm } = {}) {
|
||||
const { db } = app;
|
||||
const target = await getUser(db, targetId);
|
||||
if (action === 'suspend') {
|
||||
assertManageable(actor, target, 'suspendre');
|
||||
await db.prepare("UPDATE users SET status = 'suspended' WHERE id = ?").run(target.id);
|
||||
await destroyUserSessions(db, target.id);
|
||||
app.worker?.abortUser(target.id); // le job en cours s'arrête ; les jobs en file sont refusés par le worker
|
||||
await logAudit(db, { admin: actor, action: 'suspend', target });
|
||||
return `Compte suspendu : ${target.email}`;
|
||||
}
|
||||
if (action === 'reactivate') {
|
||||
assertManageable(actor, target, 'réactiver');
|
||||
await db.prepare("UPDATE users SET status = 'active' WHERE id = ?").run(target.id);
|
||||
await logAudit(db, { admin: actor, action: 'reactivate', target });
|
||||
return `Compte réactivé : ${target.email}`;
|
||||
}
|
||||
if (action === 'plan') {
|
||||
assertManageable(actor, target, 'modifier');
|
||||
if (!PAID_PLANS.includes(plan)) throw new HttpError(400, 'Plan inconnu', { expose: true });
|
||||
await db.prepare('UPDATE users SET plan = ? WHERE id = ?').run(plan, target.id);
|
||||
await logAudit(db, { admin: actor, action: plan === 'pro' ? 'plan_pro' : 'plan_free', target });
|
||||
return `Plan ${plan === 'pro' ? 'pro' : 'gratuit'} attribué à ${target.email}`;
|
||||
}
|
||||
if (action === 'delete') {
|
||||
assertManageable(actor, target, 'supprimer');
|
||||
if (normalizeEmail(confirm) !== normalizeEmail(target.email)) throw new HttpError(400, "L'email saisi ne correspond pas à celui du compte", { expose: true });
|
||||
await logAudit(db, { admin: actor, action: 'delete', target }); // avant : la suite efface le compte
|
||||
app.worker?.abortUser(target.id);
|
||||
await deleteUser(app, target.id);
|
||||
return 'Compte supprimé avec toutes ses données.';
|
||||
}
|
||||
if (action === 'resume_send') {
|
||||
if (!target) throw new HttpError(404, 'Compte introuvable');
|
||||
await resumeSending(db, target.id);
|
||||
await logAudit(db, { admin: actor, action: 'resume_send', target });
|
||||
return `Envois rétablis pour ${target.email}`;
|
||||
}
|
||||
throw new HttpError(400, 'Action inconnue');
|
||||
}
|
||||
46
src/adminroutes.js
Normal file
46
src/adminroutes.js
Normal file
|
|
@ -0,0 +1,46 @@
|
|||
// Routes du back-office. Réservées aux administrateurs : le serveur répond 404 à tous les autres (visiteurs compris),
|
||||
// comme si la page n'existait pas (voir server.js, option `admin`).
|
||||
import { html, redirect, readBody, HttpError } from './http.js';
|
||||
import { adminAction, listAccounts, recentAudit } from './admin.js';
|
||||
import { adminPage } from './adminviews.js';
|
||||
|
||||
const DONE = {
|
||||
suspend: 'Compte suspendu : ses sessions sont fermées et ses jobs ne démarrent plus.',
|
||||
reactivate: 'Compte réactivé.',
|
||||
plan: 'Plan modifié.',
|
||||
delete: 'Compte supprimé avec toutes ses données.',
|
||||
resume_send: 'Envois rétablis.',
|
||||
};
|
||||
|
||||
export function registerAdminRoutes(router, app) {
|
||||
const opts = { admin: true, limit: 'admin' };
|
||||
|
||||
router.get('/admin', async ({ res, session, url }) => {
|
||||
const q = (url.searchParams.get('q') || '').trim().slice(0, 100);
|
||||
const done = url.searchParams.get('done');
|
||||
html(res, adminPage({
|
||||
user: session.user, q,
|
||||
list: await listAccounts(app.db, { page: url.searchParams.get('page'), q }),
|
||||
audit: await recentAudit(app.db),
|
||||
notice: DONE[done] || null, error: url.searchParams.get('e'),
|
||||
}));
|
||||
}, opts);
|
||||
|
||||
const act = (action, route) => router.post(`/admin/users/:id/${route}`, async ({ req, res, session, params }) => {
|
||||
const b = await readBody(req);
|
||||
const back = `page=${encodeURIComponent(String(b.page || '1').slice(0, 6))}${b.q ? `&q=${encodeURIComponent(String(b.q).slice(0, 100))}` : ''}`;
|
||||
try {
|
||||
await adminAction(app, { id: session.userId, email: session.email }, action, Number(params.id), { plan: b.plan, confirm: b.confirm });
|
||||
redirect(res, `/admin?${back}&done=${action}`);
|
||||
} catch (e) {
|
||||
if (!(e instanceof HttpError) || e.status >= 500) throw e;
|
||||
redirect(res, `/admin?${back}&e=${encodeURIComponent(e.message)}`);
|
||||
}
|
||||
}, opts);
|
||||
|
||||
act('suspend', 'suspend');
|
||||
act('reactivate', 'reactivate');
|
||||
act('plan', 'plan');
|
||||
act('delete', 'delete');
|
||||
act('resume_send', 'resume-send');
|
||||
}
|
||||
66
src/adminviews.js
Normal file
66
src/adminviews.js
Normal file
|
|
@ -0,0 +1,66 @@
|
|||
// Page /admin : comptes (identité, liaison, usage du mois) et journal d'audit. Aucune donnée métier.
|
||||
import { esc } from './http.js';
|
||||
import { layout } from './views.js';
|
||||
|
||||
const fmt = (ts) => (ts ? new Date(ts * 1000).toLocaleString('fr-FR', { dateStyle: 'short', timeStyle: 'short', timeZone: 'Europe/Paris' }) : '—');
|
||||
const PROVIDERS = { google: 'Google', apple: 'Apple' };
|
||||
const PLANS = { free: 'gratuit', pro: 'pro', admin: 'administrateur' };
|
||||
|
||||
const cap = (used, limit) => (limit == null ? `${used}` : `${used}/${limit}`);
|
||||
const usageCell = (u) => `<span title="Projets">P ${cap(u.projects, u.limits.projects)}</span> · <span title="Prospects">Pr ${cap(u.prospects, u.limits.prospects)}</span> · <span title="Mails ce mois-ci">M ${cap(u.mails, u.limits.mails)}</span> · <span title="Jobs IA ce mois-ci">IA ${cap(u.aiJobs, u.limits.aiJobs)}</span>`;
|
||||
|
||||
function actions(a, page, q, selfId) {
|
||||
if (a.id === selfId) return '<span class="muted small">Ton compte</span>';
|
||||
if (a.isAdmin) return '<span class="muted small">Administrateur (ADMIN_EMAILS)</span>';
|
||||
const back = `<input type="hidden" name="page" value="${page}"><input type="hidden" name="q" value="${esc(q)}">`;
|
||||
const f = (path, body) => `<form method="post" action="/admin/users/${a.id}/${path}" class="inline">${back}${body}</form>`;
|
||||
return `<div class="admin-actions">
|
||||
${a.status === 'active' ? f('suspend', '<button class="btn small">Suspendre</button>') : f('reactivate', '<button class="btn small">Réactiver</button>')}
|
||||
${f('plan', `<select name="plan" aria-label="Plan de ${esc(a.email)}"><option value="free"${a.plan === 'free' ? ' selected' : ''}>gratuit</option><option value="pro"${a.plan === 'pro' ? ' selected' : ''}>pro</option></select> <button class="btn small">Appliquer</button>`)}
|
||||
${a.sendPause ? f('resume-send', '<button class="btn small">Rétablir les envois</button>') : ''}
|
||||
<details class="del"><summary class="btn small danger">Supprimer</summary>
|
||||
${f('delete', `<label>Saisis l'email du compte pour confirmer<input name="confirm" type="email" required autocomplete="off" placeholder="${esc(a.email)}"></label><button class="btn small danger">Supprimer définitivement</button>`)}
|
||||
</details>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
export function adminPage({ user, list, audit, q = '', notice = null, error = null }) {
|
||||
const nav = (p) => `/admin?page=${p}${q ? `&q=${encodeURIComponent(q)}` : ''}`;
|
||||
const rows = list.accounts.map((a) => `<tr>
|
||||
<td>${esc(a.email)}${a.isAdmin ? ' <span class="badge">admin</span>' : ''}</td>
|
||||
<td>${esc(PROVIDERS[a.provider] || '—')}</td>
|
||||
<td>${esc(PLANS[a.plan] || a.plan)}</td>
|
||||
<td>${a.status === 'active' ? '<span class="ok">actif</span>' : '<span class="error">suspendu</span>'}${a.sendPause ? '<br><span class="error small">envois en pause</span>' : ''}</td>
|
||||
<td>${fmt(a.createdAt)}</td>
|
||||
<td>${fmt(a.lastLoginAt)}</td>
|
||||
<td>${a.link ? `${esc(a.link.mode)}${a.link.valid ? '' : ' <span class="error small">invalide</span>'}` : '—'}</td>
|
||||
<td class="small">${usageCell(a.usage)}</td>
|
||||
<td>${actions(a, list.page, q, user.id)}</td>
|
||||
</tr>`).join('');
|
||||
const auditRows = audit.map((r) => `<tr><td>${fmt(r.at)}</td><td>${esc(r.admin)}</td><td>${esc(r.label)}</td><td>${esc(r.target || '—')}</td><td class="small">${esc(r.detail || '')}</td></tr>`).join('');
|
||||
return layout({
|
||||
title: 'Administration', email: user.email,
|
||||
body: `<h1>Administration</h1>
|
||||
<p class="muted small">Comptes et compteurs d'usage uniquement : aucun accès aux prospects, mails ni notes des utilisateurs.</p>
|
||||
${notice ? `<p class="ok" role="status">${esc(notice)}</p>` : ''}
|
||||
${error ? `<p class="error" role="alert">${esc(error)}</p>` : ''}
|
||||
<section class="card">
|
||||
<form method="get" action="/admin" class="inline"><label>Rechercher un email<input name="q" value="${esc(q)}" maxlength="100"></label> <button class="btn small">Chercher</button></form>
|
||||
<p class="muted small">${list.total} compte(s) · page ${list.page} / ${list.pages}</p>
|
||||
<div class="table-wrap"><table class="admin-table">
|
||||
<thead><tr><th>Email</th><th>Connexion</th><th>Plan</th><th>Statut</th><th>Créé</th><th>Dernière connexion</th><th>Liaison</th><th>Usage du mois</th><th>Actions</th></tr></thead>
|
||||
<tbody>${rows || '<tr><td colspan="9">Aucun compte.</td></tr>'}</tbody>
|
||||
</table></div>
|
||||
<p class="admin-pager">${list.page > 1 ? `<a class="btn small" href="${nav(list.page - 1)}">Précédent</a>` : ''} ${list.page < list.pages ? `<a class="btn small" href="${nav(list.page + 1)}">Suivant</a>` : ''}</p>
|
||||
<p class="muted small">Usage : P projets, Pr prospects, M mails du mois, IA jobs IA du mois (utilisé/plafond).</p>
|
||||
</section>
|
||||
<section class="card">
|
||||
<h4>Journal d'audit</h4>
|
||||
<p class="muted small">Actions d'administration et décisions automatiques. Lecture seule ; les adresses sont masquées ; conservé 12 mois.</p>
|
||||
<div class="table-wrap"><table>
|
||||
<thead><tr><th>Date</th><th>Par</th><th>Action</th><th>Compte</th><th>Détail</th></tr></thead>
|
||||
<tbody>${auditRows || '<tr><td colspan="5">Rien pour le moment.</td></tr>'}</tbody>
|
||||
</table></div>
|
||||
</section>`,
|
||||
});
|
||||
}
|
||||
36
src/audit.js
Normal file
36
src/audit.js
Normal file
|
|
@ -0,0 +1,36 @@
|
|||
// Journal d'audit : actions d'administration et décisions automatiques (pause d'envoi, comptes inactifs).
|
||||
// Les adresses y sont masquées ; aucune route ne modifie ni n'efface une ligne (seule la purge ancienne en retire).
|
||||
import { now } from './db.js';
|
||||
|
||||
/** « jean.dupont@exemple.fr » → « j***@exemple.fr » : l'identification suffit, l'adresse complète n'est pas gardée dans le journal. */
|
||||
export function maskEmail(email) {
|
||||
const [local = '', domain = ''] = String(email || '').split('@');
|
||||
return `${local.slice(0, 1)}***${domain ? `@${domain}` : ''}`;
|
||||
}
|
||||
|
||||
const ACTIONS = {
|
||||
suspend: 'Compte suspendu', reactivate: 'Compte réactivé', plan_free: 'Plan gratuit attribué', plan_pro: 'Plan pro attribué',
|
||||
delete: 'Compte supprimé', resume_send: 'Envois rétablis', abuse_pause: 'Envois mis en pause (rejets)',
|
||||
inactive_warning: 'Avertissement d\'inactivité', inactive_delete: 'Compte inactif supprimé',
|
||||
};
|
||||
export const ACTION_LABELS = ACTIONS;
|
||||
|
||||
/** Ajoute une ligne au journal. `admin` = { id, email } de l'administrateur, ou null pour une décision du système. */
|
||||
export async function logAudit(db, { admin = null, action, target = null, detail = null, at = now() }) {
|
||||
if (!ACTIONS[action]) throw new Error(`Action d'audit inconnue : ${action}`);
|
||||
await db.prepare('INSERT INTO admin_audit(admin_id, admin_label, action, target_id, target_label, detail, created_at) VALUES(?, ?, ?, ?, ?, ?, ?)')
|
||||
.run(admin?.id ?? null, admin ? admin.email : 'système', action, target?.id ?? null, target ? maskEmail(target.email) : null, detail ? String(detail).slice(0, 500) : null, at);
|
||||
}
|
||||
|
||||
export async function recentAudit(db, limit = 50) {
|
||||
return (await db.prepare('SELECT * FROM admin_audit ORDER BY id DESC LIMIT ?').all(limit)).map((r) => ({
|
||||
id: r.id, at: r.created_at, admin: r.admin_label, action: r.action, label: ACTIONS[r.action] || r.action,
|
||||
target: r.target_label, targetId: r.target_id, detail: r.detail,
|
||||
}));
|
||||
}
|
||||
|
||||
/** Nettoyage du journal ancien (planificateur). */
|
||||
export async function purgeAudit(db, months, at = now()) {
|
||||
const d = new Date(at * 1000); d.setUTCMonth(d.getUTCMonth() - months);
|
||||
await db.prepare('DELETE FROM admin_audit WHERE created_at < ?').run(Math.floor(d.getTime() / 1000));
|
||||
}
|
||||
42
src/captcha.js
Normal file
42
src/captcha.js
Normal file
|
|
@ -0,0 +1,42 @@
|
|||
// Google reCAPTCHA v3 : vérification côté serveur du jeton produit par le navigateur après consentement.
|
||||
// Sans clés configurées (RECAPTCHA_SITE_KEY / RECAPTCHA_SECRET), reCAPTCHA est désactivé : développement seulement.
|
||||
// Il n'existe aucun indicateur pour contourner la vérification quand les clés sont présentes.
|
||||
import { HttpError } from './http.js';
|
||||
|
||||
export const CAPTCHA_ACTION = 'login';
|
||||
const VERIFY_URL = 'https://www.google.com/recaptcha/api/siteverify';
|
||||
|
||||
const refus = (status, message, code) => new HttpError(status, message, { expose: true, code });
|
||||
|
||||
/**
|
||||
* Valide le jeton reçu avec le formulaire de connexion. `app.fetch` est injectable (aucun appel réel dans les tests).
|
||||
* Refuse : jeton absent (400), refusé par Google, expiré, d'une autre action ou d'un autre site, ou score trop bas (403),
|
||||
* Google injoignable (503 : on ne laisse pas passer faute de réponse).
|
||||
* @returns {Promise<{skipped: true} | {score: number}>}
|
||||
*/
|
||||
export async function verifyCaptcha(app, token) {
|
||||
const rc = app.cfg.recaptcha;
|
||||
if (!rc) return { skipped: true };
|
||||
const t = typeof token === 'string' ? token.trim() : '';
|
||||
if (!t) throw refus(400, 'Vérification anti-robot manquante : charge-la, puis réessaie.', 'captcha_missing');
|
||||
if (t.length > 4096) throw refus(403, 'Vérification anti-robot invalide : recharge la page.', 'captcha_invalid');
|
||||
let data;
|
||||
try {
|
||||
const r = await (app.fetch || fetch)(VERIFY_URL, {
|
||||
method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
||||
body: new URLSearchParams({ secret: rc.secret, response: t }), signal: AbortSignal.timeout(8000),
|
||||
});
|
||||
if (!r.ok) throw new Error(`HTTP ${r.status}`);
|
||||
data = await r.json();
|
||||
} catch {
|
||||
throw refus(503, 'La vérification anti-robot est indisponible pour le moment : réessaie dans un instant.', 'captcha_unavailable');
|
||||
}
|
||||
if (!data?.success) throw refus(403, 'Vérification anti-robot refusée (invalide ou expirée) : recharge la page et réessaie.', 'captcha_invalid');
|
||||
if (data.action !== CAPTCHA_ACTION) throw refus(403, 'Vérification anti-robot invalide : recharge la page.', 'captcha_invalid');
|
||||
if (data.hostname !== new URL(app.cfg.appUrl).hostname) throw refus(403, 'Vérification anti-robot invalide : recharge la page.', 'captcha_invalid');
|
||||
const score = Number(data.score);
|
||||
if (!(score >= rc.minScore)) {
|
||||
throw refus(403, "Vérification anti-robot : ton activité a été jugée suspecte. Réessaie plus tard, ou écris-nous si cela se répète.", 'captcha_low_score');
|
||||
}
|
||||
return { score };
|
||||
}
|
||||
|
|
@ -251,5 +251,6 @@ export async function lastConsent(db, userId) {
|
|||
export function isLinkExempt(method, pathname) {
|
||||
if (pathname === '/link' || pathname.startsWith('/link/')) return true;
|
||||
if (pathname === '/account' || pathname === '/account/delete') return true;
|
||||
if (pathname === '/admin' || pathname.startsWith('/admin/')) return true; // les administrateurs gèrent les comptes même sans liaison
|
||||
return method === 'POST' && pathname === '/logout';
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
import { resolve } from 'node:path';
|
||||
import { homedir } from 'node:os';
|
||||
import { dbConfigFromEnv } from './db.js';
|
||||
import { parseTrustProxy } from './ratelimit.js';
|
||||
|
||||
const env = process.env;
|
||||
|
||||
|
|
@ -25,6 +26,48 @@ function appleConfig() {
|
|||
};
|
||||
}
|
||||
|
||||
// Google reCAPTCHA v3 sur le démarrage de la connexion : les deux clés ensemble, ou aucune (reCAPTCHA désactivé, développement)
|
||||
function recaptchaConfig() {
|
||||
const siteKey = (env.RECAPTCHA_SITE_KEY || '').trim();
|
||||
const secret = (env.RECAPTCHA_SECRET || '').trim();
|
||||
if (!siteKey && !secret) return null;
|
||||
if (!siteKey || !secret) throw new Error('reCAPTCHA : RECAPTCHA_SITE_KEY et RECAPTCHA_SECRET vont ensemble');
|
||||
const raw = (env.RECAPTCHA_MIN_SCORE || '').trim();
|
||||
const minScore = raw === '' ? 0.5 : Number(raw);
|
||||
if (!(minScore >= 0 && minScore <= 1)) throw new Error('RECAPTCHA_MIN_SCORE doit être un nombre entre 0 et 1');
|
||||
return { siteKey, secret, minScore };
|
||||
}
|
||||
|
||||
function positive(v, def, name) {
|
||||
if (v == null || String(v).trim() === '') return def;
|
||||
const n = Number(v);
|
||||
if (!Number.isInteger(n) || n < 1 || n > 64) throw new Error(`${name} doit être un entier entre 1 et 64`);
|
||||
return n;
|
||||
}
|
||||
function ratio(v, def, name) {
|
||||
if (v == null || String(v).trim() === '') return def;
|
||||
const n = Number(v);
|
||||
if (!(n > 0.1 && n <= 4)) throw new Error(`${name} doit être un nombre entre 0,1 et 4 (charge divisée par le nombre de cœurs)`);
|
||||
return n;
|
||||
}
|
||||
|
||||
// SMTP du serveur (mails système : avertissement avant suppression d'un compte inactif). Facultatif ; toutes les variables ensemble.
|
||||
function systemSmtpConfig() {
|
||||
const keys = ['SYSTEM_SMTP_HOST', 'SYSTEM_SMTP_USER', 'SYSTEM_SMTP_PASSWORD', 'SYSTEM_SMTP_FROM'];
|
||||
const set = keys.filter((k) => env[k]);
|
||||
if (!set.length) return null;
|
||||
if (set.length < keys.length) throw new Error(`SMTP du serveur : variables incomplètes (manque ${keys.filter((k) => !env[k]).join(', ')})`);
|
||||
return { host: env.SYSTEM_SMTP_HOST, port: Number(env.SYSTEM_SMTP_PORT || 587), user: env.SYSTEM_SMTP_USER, pass: env.SYSTEM_SMTP_PASSWORD, fromEmail: env.SYSTEM_SMTP_FROM };
|
||||
}
|
||||
|
||||
function inactiveMonths() {
|
||||
const raw = (env.INACTIVE_ACCOUNT_MONTHS || '').trim();
|
||||
if (raw === '') return 24;
|
||||
const n = Number(raw);
|
||||
if (!Number.isInteger(n) || n < 0 || n > 120) throw new Error('INACTIVE_ACCOUNT_MONTHS doit être un nombre entier de mois entre 0 (désactivé) et 120');
|
||||
return 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.
|
||||
|
|
@ -58,6 +101,12 @@ export function loadConfig() {
|
|||
clientSecret: required('GOOGLE_CLIENT_SECRET'),
|
||||
},
|
||||
apple: appleConfig(),
|
||||
recaptcha: recaptchaConfig(),
|
||||
systemSmtp: systemSmtpConfig(),
|
||||
inactiveMonths: inactiveMonths(),
|
||||
production: env.NODE_ENV === 'production',
|
||||
// Développement : autorise les hôtes privés (SMTP local, etc.). En production, seulement pour les administrateurs.
|
||||
allowPrivateHosts: flag(env.ALLOW_PRIVATE_HOSTS, false),
|
||||
// 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'),
|
||||
|
|
@ -67,6 +116,10 @@ export function loadConfig() {
|
|||
// 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),
|
||||
// Jobs IA simultanés sur le serveur (un seul par utilisateur) et charge (charge/cœurs) au-delà de laquelle les nouveaux jobs attendent
|
||||
maxAiJobs: positive(env.MAX_AI_JOBS, 4, 'MAX_AI_JOBS'),
|
||||
loadMax: ratio(env.LOAD_MAX, 0.9, 'LOAD_MAX'),
|
||||
// Derrière Nginx/CloudPanel : lire X-Forwarded-For, mais seulement depuis un proxy de confiance (voir ratelimit.js)
|
||||
trustProxy: parseTrustProxy(env.TRUST_PROXY),
|
||||
};
|
||||
}
|
||||
|
|
|
|||
|
|
@ -11,6 +11,10 @@ import { resolveCredentials } from './claudelink.js';
|
|||
import { userRepoRoot } from './users.js';
|
||||
import { quotaAlerts } from './services/budget.js';
|
||||
import { notify } from './services/notify.js';
|
||||
import { quotaFor, recordUsage, planLimitMessage } from './services/plans.js';
|
||||
import { getUser } from './users.js';
|
||||
import { pinSmtp, pinGit } from './netguard.js';
|
||||
import { sendPause, pauseMessage, evaluateSending } from './services/abuse.js';
|
||||
import { evolutionMail } from './services/mailhtml.js';
|
||||
import { getProject, repoDir, forgejoToken, globalSmtp, sentSince, getTemplate, saveTemplate, pickVariant } from './projects.js';
|
||||
|
||||
|
|
@ -87,7 +91,8 @@ export function makeClaude(app) {
|
|||
export function makeHandlers(app) {
|
||||
const { db, cfg } = app;
|
||||
const claude = makeClaude(app);
|
||||
const sync = (...a) => (app.syncRepo || syncRepo)(...a);
|
||||
// Forgejo : l'hôte est revérifié à chaque synchronisation, git se connecte à l'adresse vérifiée
|
||||
const sync = async (userId, url, dir, token) => (app.syncRepo || syncRepo)(url, dir, token, { pin: await pinGit(app, userId, url) });
|
||||
const inHours = () => (app.isBusinessHours || isBusinessHours)();
|
||||
|
||||
// Premier mail ou relance : mêmes plafonds, mêmes délais, même journal
|
||||
|
|
@ -95,6 +100,8 @@ export function makeHandlers(app) {
|
|||
// 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 };
|
||||
const userId = ctx.job.user_id;
|
||||
const pause = await sendPause(db, userId);
|
||||
if (pause) throw new Error(pauseMessage(pause)); // la désinscription et la liste d'opposition restent appliquées ci-dessous
|
||||
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é');
|
||||
|
|
@ -105,7 +112,11 @@ export function makeHandlers(app) {
|
|||
? await followupCandidates(db, project)
|
||||
: 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);
|
||||
const n = allowedToSend({
|
||||
// Plafond mensuel du plan : on n'envoie que ce qui reste (le reste attend, rien n'est perdu)
|
||||
const user = await getUser(db, userId);
|
||||
const mq = await quotaFor(db, user, 'mails');
|
||||
if (!mq.unlimited && mq.remaining <= 0) throw new Error(planLimitMessage(user, mq));
|
||||
const n0 = allowedToSend({
|
||||
requested: ctx.params.count,
|
||||
available: candidates.length,
|
||||
projectCap: project.dailyMailCap,
|
||||
|
|
@ -113,9 +124,10 @@ export function makeHandlers(app) {
|
|||
globalCap: Number(await getSetting(db, userId, 'global_daily_cap', '100')),
|
||||
sentTodayGlobal: await sentSince(db, day, userId),
|
||||
});
|
||||
const n = mq.unlimited ? n0 : Math.min(n0, mq.remaining);
|
||||
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)(await pinSmtp(app, userId, project.smtp));
|
||||
await transport.verify();
|
||||
const minDelay = Number(await getSetting(db, userId, 'send_delay_min', '20')) * 1000;
|
||||
const maxDelay = Number(await getSetting(db, userId, 'send_delay_max', '60')) * 1000;
|
||||
|
|
@ -155,6 +167,7 @@ export function makeHandlers(app) {
|
|||
try {
|
||||
await transport.sendMail(mail);
|
||||
await log.run(project.id, p.id, p.email, now(), null, kind, variant, mail.subject, mail.messageId);
|
||||
await recordUsage(db, userId, 'mail');
|
||||
if (kind === 'initial') await markInitial.run('sent', now(), variant, p.id);
|
||||
else await markFollowup.run(now(), p.id);
|
||||
sent++;
|
||||
|
|
@ -168,6 +181,7 @@ export function makeHandlers(app) {
|
|||
if (sent + failed < n) await sleep(minDelay + Math.random() * (maxDelay - minDelay), ctx.signal).catch(() => {});
|
||||
}
|
||||
transport.close();
|
||||
await evaluateSending(app, userId); // trop de rejets : le compte passe en pause d'envoi
|
||||
return { sent, failed, total: n };
|
||||
}
|
||||
|
||||
|
|
@ -177,7 +191,7 @@ export function makeHandlers(app) {
|
|||
const project = await getProject(app, ctx.job.project_id, { userId });
|
||||
await ctx.progress({ message: 'Récupération du repo…', pct: 3 });
|
||||
const dir = repoDir(cfg, userId, project.id);
|
||||
const commit = await sync(project.gitUrl, dir, await forgejoToken(app, userId));
|
||||
const commit = await sync(userId, project.gitUrl, dir, await forgejoToken(app, userId));
|
||||
|
||||
await ctx.progress({ message: 'Analyse du code par Claude…', pct: 10 });
|
||||
const { prompt, system } = analyzePrompt(project.name);
|
||||
|
|
@ -206,6 +220,10 @@ export function makeHandlers(app) {
|
|||
|
||||
// Domaines déjà connus de ce projet : Claude ne les recherche pas une 2e fois. La liste d'opposition,
|
||||
// commune à tous les comptes, n'entre pas dans le prompt (elle est appliquée à l'insertion, ci-dessous).
|
||||
const user = await getUser(db, userId);
|
||||
const pq = await quotaFor(db, user, 'prospects');
|
||||
let room = pq.unlimited ? Infinity : pq.remaining;
|
||||
let capped = false;
|
||||
const exclude = (await db.prepare(`
|
||||
SELECT DISTINCT substr(email, instr(email, '@') + 1) d FROM prospects WHERE project_id = ?
|
||||
LIMIT 300`).all(project.id)).map((r) => r.d);
|
||||
|
|
@ -234,8 +252,10 @@ export function makeHandlers(app) {
|
|||
sink.push(async () => {
|
||||
for (const p of parsed) {
|
||||
if (await optedOut.get(p.email)) continue;
|
||||
if (room <= 0) { capped = true; continue; }
|
||||
const res = await insert.run(project.id, p.company, p.email, p.website, p.city, p.sector, p.hook, p.source, p.score, now());
|
||||
if (res.changes) {
|
||||
room--;
|
||||
found++;
|
||||
message = `${found}/${count} — ${p.company}`;
|
||||
await report();
|
||||
|
|
@ -254,7 +274,7 @@ export function makeHandlers(app) {
|
|||
onText('\n');
|
||||
await sink.flush();
|
||||
addUsage(ctx, r);
|
||||
return { found, requested: count, stoppedBy: r.subtype };
|
||||
return { found, requested: count, stoppedBy: r.subtype, ...(capped ? { capped: true } : {}) };
|
||||
},
|
||||
|
||||
async template(ctx) {
|
||||
|
|
@ -300,7 +320,7 @@ export function makeHandlers(app) {
|
|||
|
||||
await ctx.progress({ message: 'Mise à jour du repo…', pct: 3 });
|
||||
const dir = repoDir(cfg, userId, project.id);
|
||||
await sync(project.gitUrl, dir, await forgejoToken(app, userId));
|
||||
await sync(userId, project.gitUrl, dir, await forgejoToken(app, userId));
|
||||
|
||||
await ctx.progress({ message: `Recherche de ${count} évolutions (${level})…`, pct: 10 });
|
||||
const { prompt, system } = evolutionPrompt({ projectName: project.name, profile: project.profile, count, level });
|
||||
|
|
@ -315,7 +335,7 @@ export function makeHandlers(app) {
|
|||
if (!r.text?.trim()) throw new Error(`Pas de résultat (${r.subtype})`);
|
||||
|
||||
await ctx.progress({ message: 'Envoi par mail…', pct: 95 });
|
||||
const transport = (app.createTransport || createTransport)(smtp);
|
||||
const transport = (app.createTransport || createTransport)(await pinSmtp(app, userId, smtp));
|
||||
await transport.sendMail({
|
||||
from: smtp.fromEmail, to,
|
||||
subject: `[AiTools] ${count} évolutions pour ${project.name}`,
|
||||
|
|
|
|||
11
src/http.js
11
src/http.js
|
|
@ -5,7 +5,7 @@ export class Router {
|
|||
add(method, path, handler, opts = {}) {
|
||||
const keys = [];
|
||||
const re = new RegExp('^' + path.replace(/:(\w+)/g, (_, k) => { keys.push(k); return '([^/]+)'; }) + '/?$');
|
||||
this.routes.push({ method, re, keys, handler, public: !!opts.public });
|
||||
this.routes.push({ method, re, keys, handler, public: !!opts.public, limit: opts.limit || null, admin: !!opts.admin });
|
||||
}
|
||||
get(p, h, o) { this.add('GET', p, h, o); }
|
||||
post(p, h, o) { this.add('POST', p, h, o); }
|
||||
|
|
@ -65,9 +65,14 @@ 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 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)
|
||||
// `expose` : message sûr destiné à l'utilisateur même pour un 5xx (ex. impossible de joindre un service tiers).
|
||||
// `headers` : en-têtes ajoutés à la réponse d'erreur (Retry-After d'un 429). `code` et `data` : champs ajoutés au JSON
|
||||
// d'erreur, pour que le front distingue un plafond de plan (plan_limit) d'une erreur ordinaire.
|
||||
export class HttpError extends Error {
|
||||
constructor(status, message, { expose = false } = {}) { super(message); this.status = status; this.expose = expose; }
|
||||
constructor(status, message, { expose = false, headers = null, code = null, data = null } = {}) {
|
||||
super(message);
|
||||
this.status = status; this.expose = expose; this.headers = headers; this.code = code; this.data = data;
|
||||
}
|
||||
}
|
||||
|
||||
// Échappement HTML pour les templates
|
||||
|
|
|
|||
87
src/ip.js
Normal file
87
src/ip.js
Normal file
|
|
@ -0,0 +1,87 @@
|
|||
// Analyse des adresses IP : lecture IPv4/IPv6, adresses privées ou réservées, forme canonique.
|
||||
// Sert au filtrage des hôtes saisis par l'utilisateur (netguard.js) et à la lecture de l'IP du client (ratelimit.js).
|
||||
import { isIP } from 'node:net';
|
||||
|
||||
/** @returns {{family: 4|6, bytes: number[]} | null} */
|
||||
export function parseIp(input) {
|
||||
let s = String(input ?? '').trim().replace(/^\[|\]$/g, '');
|
||||
const zone = s.indexOf('%');
|
||||
if (zone >= 0) s = s.slice(0, zone);
|
||||
const family = isIP(s);
|
||||
if (family === 4) return { family, bytes: s.split('.').map(Number) };
|
||||
if (family !== 6) return null;
|
||||
let head = s;
|
||||
const quad = /^(.*:)(\d+)\.(\d+)\.(\d+)\.(\d+)$/.exec(s); // ::ffff:127.0.0.1
|
||||
if (quad) head = `${quad[1]}${((+quad[2] << 8) | +quad[3]).toString(16)}:${((+quad[4] << 8) | +quad[5]).toString(16)}`;
|
||||
const [a, b] = head.split('::');
|
||||
const left = a ? a.split(':') : [];
|
||||
const right = b ? b.split(':') : [];
|
||||
const groups = b === undefined ? left : [...left, ...Array(8 - left.length - right.length).fill('0'), ...right];
|
||||
return { family, bytes: groups.flatMap((g) => { const v = parseInt(g, 16); return [v >> 8, v & 255]; }) };
|
||||
}
|
||||
|
||||
const inV4 = (b, base, bits) => {
|
||||
let rest = bits;
|
||||
for (let i = 0; i < 4 && rest > 0; i++, rest -= 8) {
|
||||
const mask = rest >= 8 ? 0xff : (0xff << (8 - rest)) & 0xff;
|
||||
if ((b[i] & mask) !== (base[i] & mask)) return false;
|
||||
}
|
||||
return true;
|
||||
};
|
||||
|
||||
const V4_BLOCKED = [
|
||||
[[0, 0, 0, 0], 8, 'adresse non routable'],
|
||||
[[10, 0, 0, 0], 8, 'réseau privé'],
|
||||
[[100, 64, 0, 0], 10, 'réseau partagé (CGNAT)'],
|
||||
[[127, 0, 0, 0], 8, 'boucle locale'],
|
||||
[[169, 254, 0, 0], 16, 'adresse locale (dont les métadonnées cloud)'],
|
||||
[[172, 16, 0, 0], 12, 'réseau privé'],
|
||||
[[192, 0, 0, 0], 24, 'adresse réservée'],
|
||||
[[192, 0, 2, 0], 24, 'adresse de documentation'],
|
||||
[[192, 168, 0, 0], 16, 'réseau privé'],
|
||||
[[198, 18, 0, 0], 15, 'adresse de test réseau'],
|
||||
[[198, 51, 100, 0], 24, 'adresse de documentation'],
|
||||
[[203, 0, 113, 0], 24, 'adresse de documentation'],
|
||||
[[224, 0, 0, 0], 4, 'multicast'],
|
||||
[[240, 0, 0, 0], 4, 'adresse réservée'],
|
||||
];
|
||||
|
||||
function blockedV4(b) {
|
||||
for (const [base, bits, why] of V4_BLOCKED) if (inV4(b, base, bits)) return why;
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Raison du refus d'une adresse IP (texte pour l'utilisateur), ou null si elle est publique. Texte non IP : refusé. */
|
||||
export function blockedReason(ip) {
|
||||
const p = parseIp(ip);
|
||||
if (!p) return 'adresse invalide';
|
||||
if (p.family === 4) return blockedV4(p.bytes);
|
||||
const b = p.bytes;
|
||||
const zeros = (from, to) => b.slice(from, to).every((x) => x === 0);
|
||||
if (zeros(0, 10) && b[10] === 0xff && b[11] === 0xff) return blockedV4(b.slice(12)); // IPv4 mappée (::ffff:a.b.c.d)
|
||||
if (zeros(0, 12)) return 'boucle locale'; // ::, ::1 et ::a.b.c.d (IPv4 « compatible »)
|
||||
if (b[0] === 0 && b[1] === 0x64 && b[2] === 0xff && b[3] === 0x9b) { // NAT64 : l'IPv4 est dans les 4 derniers octets
|
||||
return zeros(4, 12) ? blockedV4(b.slice(12)) : 'adresse réservée (NAT64)';
|
||||
}
|
||||
if (b[0] === 0x20 && b[1] === 0x02) return blockedV4(b.slice(2, 6)); // 6to4 : l'IPv4 est dans les octets 2 à 5
|
||||
if (b[0] === 0x20 && b[1] === 0x01 && b[2] === 0 && b[3] === 0) return 'adresse de tunnel (Teredo)';
|
||||
if (b[0] === 0x20 && b[1] === 0x01 && b[2] === 0x0d && b[3] === 0xb8) return 'adresse de documentation';
|
||||
if (b[0] === 0x01 && zeros(1, 8)) return 'adresse réservée'; // 100::/64
|
||||
if ((b[0] & 0xfe) === 0xfc) return 'réseau privé (fc00::/7)';
|
||||
if (b[0] === 0xfe && (b[1] & 0xc0) === 0x80) return 'adresse locale (fe80::/10)';
|
||||
if (b[0] === 0xfe && (b[1] & 0xc0) === 0xc0) return 'adresse locale (fec0::/10)';
|
||||
if (b[0] === 0xff) return 'multicast';
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Forme canonique d'une adresse client : une IPv4 mappée (::ffff:1.2.3.4) redevient 1.2.3.4. */
|
||||
export function normalizeIp(input) {
|
||||
const p = parseIp(input);
|
||||
if (!p) return String(input ?? '').trim();
|
||||
if (p.family === 4) return p.bytes.join('.');
|
||||
const b = p.bytes;
|
||||
if (b.slice(0, 10).every((x) => x === 0) && b[10] === 0xff && b[11] === 0xff) return b.slice(12).join('.');
|
||||
const g = []; for (let i = 0; i < 16; i += 2) g.push(((b[i] << 8) | b[i + 1]).toString(16));
|
||||
return g.join(':');
|
||||
}
|
||||
|
||||
78
src/limits.js
Normal file
78
src/limits.js
Normal file
|
|
@ -0,0 +1,78 @@
|
|||
// Configuration unique des seuils : débit, plafonds des plans, détection d'abus, ports autorisés.
|
||||
// Tout ce qui se règle (fenêtre, nombre de requêtes, plafond d'un plan) se règle ICI et nulle part ailleurs ;
|
||||
// les pages Tarifs et Fonctionnement lisent aussi ces valeurs, pour ne jamais annoncer un chiffre différent du code.
|
||||
|
||||
const MIN = 60_000;
|
||||
const HOUR = 60 * MIN;
|
||||
|
||||
/**
|
||||
* Limitation de débit, en mémoire. Chaque règle donne, par portée, un nombre maximal de requêtes sur une fenêtre glissante.
|
||||
* - `ip` : adresse du client (voir TRUST_PROXY dans la configuration) ;
|
||||
* - `user` : compte connecté.
|
||||
* Une requête passe seulement si toutes les portées de la règle l'acceptent.
|
||||
*/
|
||||
export const RATE_LIMITS = {
|
||||
// Connexion : démarrage (Google, Apple) et retours des fournisseurs
|
||||
auth_start: { ip: { max: 20, windowMs: 10 * MIN } },
|
||||
auth_callback: { ip: { max: 40, windowMs: 10 * MIN } },
|
||||
// Liaison Claude : chaque essai de clé ou de jeton coûte un appel réseau chez Anthropic
|
||||
link: { user: { max: 10, windowMs: 10 * MIN }, ip: { max: 30, windowMs: 10 * MIN } },
|
||||
// Export / import CSV
|
||||
csv: { user: { max: 10, windowMs: 10 * MIN } },
|
||||
// Envois : lancement d'un lot, rapport par mail, notification de test
|
||||
mail_send: { user: { max: 30, windowMs: HOUR } },
|
||||
// Création de projet (clone du dépôt, analyse)
|
||||
project_create: { user: { max: 10, windowMs: HOUR } },
|
||||
// Suppression de compte
|
||||
account_delete: { user: { max: 5, windowMs: HOUR }, ip: { max: 10, windowMs: HOUR } },
|
||||
// Tests de connexion vers les services de l'utilisateur (IMAP, base du récap, SMTP)
|
||||
conn_test: { user: { max: 20, windowMs: 10 * MIN } },
|
||||
// Back-office
|
||||
admin: { user: { max: 120, windowMs: MIN } },
|
||||
};
|
||||
|
||||
/**
|
||||
* Plafonds par plan. `null` = illimité.
|
||||
* - `projects` et `prospects` : totaux du compte ;
|
||||
* - `mails` et `aiJobs` : par mois calendaire, heure de Paris.
|
||||
* Le plan « pro » n'est pas encore défini commercialement : illimité en attendant (voir docs/JOURNAL.md).
|
||||
*/
|
||||
export const PLAN_LIMITS = {
|
||||
free: { projects: 1, prospects: 50, mails: 100, aiJobs: 5 },
|
||||
pro: { projects: null, prospects: null, mails: null, aiJobs: null },
|
||||
admin: { projects: null, prospects: null, mails: null, aiJobs: null },
|
||||
};
|
||||
export const PLAN_LABELS = { free: 'gratuit', pro: 'pro', admin: 'administrateur' };
|
||||
export const PAID_PLANS = ['free', 'pro']; // plans qu'un administrateur peut attribuer depuis le back-office
|
||||
|
||||
/** Détection d'abus à l'envoi : pause du compte quand trop de mails sont rejetés. */
|
||||
export const ABUSE = {
|
||||
minSent: 50, // pas de décision avant ce nombre de prospects contactés
|
||||
maxBounceRate: 0.10, // pause au-dessus de 10 % de rejets
|
||||
windowDays: 30, // fenêtre d'observation
|
||||
};
|
||||
|
||||
/** Comptes inactifs : avertissement avant suppression, durée de conservation du journal d'administration. */
|
||||
export const INACTIVITY = {
|
||||
defaultMonths: 24,
|
||||
warningDays: 30,
|
||||
auditRetentionMonths: 12,
|
||||
};
|
||||
|
||||
/** Pagination du back-office. */
|
||||
export const ADMIN_PAGE_SIZE = 25;
|
||||
|
||||
/**
|
||||
* Ports autorisés pour les hôtes saisis par l'utilisateur. Les ports de services managés connus (DigitalOcean, par exemple)
|
||||
* sont inclus ; tout autre port est refusé, sauf pour un administrateur avec ALLOW_PRIVATE_HOSTS.
|
||||
*/
|
||||
export const ALLOWED_PORTS = {
|
||||
smtp: [25, 465, 587, 2525],
|
||||
imap: [143, 993],
|
||||
mysql: [3306, 3307, 25060],
|
||||
pg: [5432, 5433, 25061],
|
||||
git: [443, 8443],
|
||||
};
|
||||
|
||||
/** Charge serveur : au-delà de ce rapport charge/cœurs, les nouveaux jobs IA attendent (reprise 0,1 plus bas). */
|
||||
export const LOAD = { defaultMax: 0.9, resumeGap: 0.1 };
|
||||
|
|
@ -362,6 +362,64 @@ export const MIGRATIONS = [
|
|||
) ${T}`,
|
||||
],
|
||||
},
|
||||
{
|
||||
// J5 : journal d'usage. Les envois et les jobs IA du mois se comptent ici (et non dans mail_log / jobs) pour qu'un projet
|
||||
// supprimé n'efface pas la consommation du mois. Pas de compteur : on additionne les lignes, rien ne peut dériver.
|
||||
name: 'journal_usage',
|
||||
sqlite: [
|
||||
`CREATE TABLE usage_events (
|
||||
id INTEGER PRIMARY KEY,
|
||||
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
kind TEXT NOT NULL, -- mail | ai_job
|
||||
ref INTEGER, -- ai_job : id du job (il peut disparaître avec son projet, l'événement reste)
|
||||
at INTEGER NOT NULL
|
||||
)`,
|
||||
'CREATE INDEX usage_events_user ON usage_events(user_id, kind, at)',
|
||||
],
|
||||
mysql: [
|
||||
`CREATE TABLE IF NOT EXISTS usage_events (
|
||||
id BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY,
|
||||
user_id BIGINT NOT NULL,
|
||||
kind VARCHAR(20) NOT NULL, -- mail | ai_job
|
||||
ref BIGINT NULL, -- ai_job : id du job (il peut disparaître avec son projet, l'événement reste)
|
||||
at BIGINT NOT NULL,
|
||||
KEY usage_events_user (user_id, kind, at),
|
||||
CONSTRAINT usage_events_user_fk FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
|
||||
) ${T}`,
|
||||
],
|
||||
},
|
||||
{
|
||||
// J5 : journal d'audit des actions d'administration et des décisions automatiques (pause d'envoi, comptes inactifs).
|
||||
// Pas de clé étrangère : le journal survit à la suppression des comptes, qui n'y figurent que par un identifiant et une
|
||||
// adresse masquée (minimisation). Aucune route ne le modifie ni ne l'efface ; un nettoyage périodique retire l'ancien.
|
||||
name: 'journal_audit',
|
||||
sqlite: [
|
||||
`CREATE TABLE admin_audit (
|
||||
id INTEGER PRIMARY KEY,
|
||||
admin_id INTEGER, -- NULL = décision du système (planificateur, détection d'abus)
|
||||
admin_label TEXT,
|
||||
action TEXT NOT NULL,
|
||||
target_id INTEGER,
|
||||
target_label TEXT, -- adresse masquée
|
||||
detail TEXT,
|
||||
created_at INTEGER NOT NULL
|
||||
)`,
|
||||
'CREATE INDEX admin_audit_at ON admin_audit(created_at)',
|
||||
],
|
||||
mysql: [
|
||||
`CREATE TABLE IF NOT EXISTS admin_audit (
|
||||
id BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY,
|
||||
admin_id BIGINT NULL,
|
||||
admin_label VARCHAR(255),
|
||||
action VARCHAR(40) NOT NULL,
|
||||
target_id BIGINT NULL,
|
||||
target_label VARCHAR(255),
|
||||
detail VARCHAR(500),
|
||||
created_at BIGINT NOT NULL,
|
||||
KEY admin_audit_at (created_at)
|
||||
) ${T}`,
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
// ---------- Aides de la migration 2 ----------
|
||||
|
|
|
|||
126
src/netguard.js
Normal file
126
src/netguard.js
Normal file
|
|
@ -0,0 +1,126 @@
|
|||
// Filtrage des hôtes saisis par l'utilisateur (SMTP, IMAP, base du récap, Forgejo) : un compte ne doit pas pouvoir
|
||||
// sonder le réseau interne du serveur (MySQL local, métadonnées cloud, autres sites CloudPanel).
|
||||
//
|
||||
// Principe : on RÉSOUT le nom, on refuse toute adresse privée, puis on SE CONNECTE À L'ADRESSE VÉRIFIÉE (et non au nom).
|
||||
// La vérification porte donc sur l'IP réellement utilisée : un nom dont la réponse DNS change entre la saisie et la
|
||||
// connexion (rebinding) est revérifié à chaque nouvelle connexion, et ne peut pas changer entre la vérification et l'usage.
|
||||
import { isIP } from 'node:net';
|
||||
import dns from 'node:dns/promises';
|
||||
import { HttpError } from './http.js';
|
||||
import { ALLOWED_PORTS } from './limits.js';
|
||||
import { blockedReason } from './ip.js';
|
||||
|
||||
// ---------- Résolution ----------
|
||||
|
||||
/** Résolveur par défaut : getaddrinfo, toutes les adresses (comme le fera la connexion). */
|
||||
export async function defaultResolve(host) {
|
||||
const out = await dns.lookup(host, { all: true, verbatim: true });
|
||||
return out.map((a) => ({ address: a.address, family: a.family }));
|
||||
}
|
||||
|
||||
const HOST_RE = /^(?=.{1,253}$)[A-Za-z0-9]([A-Za-z0-9_-]{0,62})(\.[A-Za-z0-9_-]{1,63})*\.?$/;
|
||||
|
||||
/** Exception de développement : adresses privées autorisées (ALLOW_PRIVATE_HOSTS), en production pour les administrateurs seulement. */
|
||||
export async function privateAllowed(app, userId) {
|
||||
if (!app.cfg.allowPrivateHosts) return false;
|
||||
if (!app.cfg.production) return true;
|
||||
if (userId == null) return false;
|
||||
return !!(await app.db.prepare('SELECT is_admin FROM users WHERE id = ?').get(Number(userId)))?.is_admin;
|
||||
}
|
||||
|
||||
export function assertPort(kind, port, { allowPrivate = false } = {}) {
|
||||
const n = Number(port);
|
||||
if (!Number.isInteger(n) || n < 1 || n > 65535) throw new HttpError(400, 'Port invalide', { expose: true });
|
||||
if (allowPrivate) return n;
|
||||
const allowed = ALLOWED_PORTS[kind];
|
||||
if (!allowed) throw new Error(`Type d'hôte inconnu : ${kind}`);
|
||||
if (!allowed.includes(n)) throw new HttpError(400, `Port ${n} refusé pour ce service (ports acceptés : ${allowed.join(', ')})`, { expose: true });
|
||||
return n;
|
||||
}
|
||||
|
||||
/**
|
||||
* Résout `host` et refuse l'hôte si UNE SEULE de ses adresses est privée (un nom qui répond tantôt public, tantôt interne
|
||||
* ne passe pas). Une IP littérale est contrôlée telle quelle, sans DNS.
|
||||
* @returns {Promise<{address: string, family: 4|6, servername: string|null}>} adresse à utiliser pour la connexion
|
||||
*/
|
||||
export async function resolvePublic(host, { resolve = defaultResolve, allowPrivate = false, lenient = false } = {}) {
|
||||
const name = String(host ?? '').trim().replace(/^\[|\]$/g, '');
|
||||
const literal = isIP(name) ? name : null;
|
||||
if (!literal && !HOST_RE.test(name)) throw new HttpError(400, `Hôte invalide : « ${String(host).slice(0, 80)} »`, { expose: true });
|
||||
let addrs;
|
||||
if (literal) addrs = [{ address: literal, family: isIP(literal) }];
|
||||
else {
|
||||
try { addrs = await resolve(name); }
|
||||
catch {
|
||||
if (lenient) return null; // enregistrement d'un réglage : le nom pourra devenir résolvable plus tard, il sera revérifié à l'usage
|
||||
throw new HttpError(400, `Hôte introuvable : « ${name.slice(0, 80)} » ne répond pas au DNS`, { expose: true });
|
||||
}
|
||||
}
|
||||
if (!addrs?.length) {
|
||||
if (lenient) return null;
|
||||
throw new HttpError(400, `Hôte introuvable : « ${name.slice(0, 80)} » ne répond pas au DNS`, { expose: true });
|
||||
}
|
||||
if (!allowPrivate) {
|
||||
for (const a of addrs) {
|
||||
const why = blockedReason(a.address);
|
||||
if (why) throw new HttpError(400, `Hôte refusé : « ${name.slice(0, 80)} » pointe vers une adresse interne ou réservée (${why}). Seuls les serveurs publics sont acceptés.`, { expose: true });
|
||||
}
|
||||
}
|
||||
return { address: addrs[0].address, family: addrs[0].family || isIP(addrs[0].address), servername: literal ? null : name };
|
||||
}
|
||||
|
||||
/**
|
||||
* Contrôle complet d'une cible saisie par l'utilisateur : port de la liste, résolution, adresses publiques.
|
||||
* `app.resolveHost` permet aux tests d'injecter un résolveur DNS. `lenient` : à l'enregistrement d'un réglage.
|
||||
* @param {'smtp'|'imap'|'mysql'|'pg'|'git'} kind
|
||||
* @returns {Promise<{address: string, family: 4|6, servername: string|null, port: number} | null>} null = hôte non résolu (lenient)
|
||||
*/
|
||||
export async function guardTarget(app, userId, kind, host, port, { lenient = false } = {}) {
|
||||
const allowPrivate = await privateAllowed(app, userId);
|
||||
const checkedPort = assertPort(kind, port, { allowPrivate });
|
||||
const r = await resolvePublic(host, { resolve: app.resolveHost || defaultResolve, allowPrivate, lenient });
|
||||
return r && { ...r, port: checkedPort };
|
||||
}
|
||||
|
||||
// ---------- Cibles « épinglées » : on se connecte à l'adresse vérifiée, pas au nom ----------
|
||||
|
||||
/** SMTP : `host` devient l'IP vérifiée, `servername` garde le nom pour SNI et la vérification du certificat. */
|
||||
export async function pinSmtp(app, userId, smtp, opts) {
|
||||
if (!smtp?.host) return smtp;
|
||||
const t = await guardTarget(app, userId, 'smtp', smtp.host, smtp.port || 587, opts);
|
||||
return t ? { ...smtp, host: t.address, ...(t.servername ? { servername: t.servername } : {}) } : smtp;
|
||||
}
|
||||
|
||||
export async function pinImap(app, userId, imap, opts) {
|
||||
if (!imap?.host) return imap;
|
||||
const t = await guardTarget(app, userId, 'imap', imap.host, imap.port || 993, opts);
|
||||
return t ? { ...imap, host: t.address, ...(t.servername ? { servername: t.servername } : {}) } : imap;
|
||||
}
|
||||
|
||||
/** Base du récap (MySQL ou PostgreSQL). */
|
||||
export async function pinDb(app, userId, cfg, opts) {
|
||||
if (!cfg?.host) return cfg;
|
||||
const kind = cfg.type === 'pg' ? 'pg' : 'mysql';
|
||||
const t = await guardTarget(app, userId, kind, cfg.host, cfg.port || (kind === 'pg' ? 5432 : 3306), opts);
|
||||
return t ? { ...cfg, host: t.address, ...(t.servername ? { servername: t.servername } : {}) } : cfg;
|
||||
}
|
||||
|
||||
/**
|
||||
* Forgejo : vérifie l'hôte de l'URL du dépôt et renvoie ce qu'il faut pour que git se connecte à l'adresse vérifiée
|
||||
* (http.curloptResolve). Une URL qui n'est pas en https est laissée à syncRepo, qui la refuse.
|
||||
* @returns {Promise<{host: string, port: number, address: string, family: 4|6} | null>}
|
||||
*/
|
||||
export async function pinGit(app, userId, url, opts) {
|
||||
let u;
|
||||
try { u = new URL(url); } catch { return null; }
|
||||
if (u.protocol !== 'https:') return null;
|
||||
const t = await guardTarget(app, userId, 'git', u.hostname, u.port || 443, opts);
|
||||
return t ? { host: u.hostname, port: t.port, address: t.address, family: t.family } : null;
|
||||
}
|
||||
|
||||
/** « hôte » ou « hôte:port » saisi dans Réglages (Forgejo) : contrôle à l'enregistrement. */
|
||||
export async function checkForgejoHost(app, userId, value) {
|
||||
const m = /^([^:/]+)(?::(\d{1,5}))?$/.exec(String(value || '').trim());
|
||||
if (!m) throw new HttpError(400, 'Hôte Forgejo invalide (attendu : hôte ou hôte:port)', { expose: true });
|
||||
await guardTarget(app, userId, 'git', m[1], m[2] || 443, { lenient: true });
|
||||
}
|
||||
|
|
@ -2,6 +2,8 @@ import { join } from 'node:path';
|
|||
import { now, getSetting } from './db.js';
|
||||
import { encryptJson, decryptJson, decrypt } from './crypto.js';
|
||||
import { HttpError } from './http.js';
|
||||
import { getUser } from './users.js';
|
||||
import { assertRoom, withUserLock } from './services/plans.js';
|
||||
|
||||
// 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)));
|
||||
|
|
@ -47,8 +49,13 @@ export async function listProjects(app, userId) {
|
|||
}
|
||||
|
||||
export async function createProject(app, { userId, name, gitUrl }) {
|
||||
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);
|
||||
const user = await getUser(app.db, userId);
|
||||
if (!user) throw new HttpError(404, 'Compte introuvable');
|
||||
return withUserLock(user.id, async () => {
|
||||
await assertRoom(app.db, user, 'projects', 1, { note: 'Supprime un projet pour en créer un autre.' });
|
||||
const r = await app.db.prepare('INSERT INTO projects(user_id, name, git_url, created_at) VALUES(?, ?, ?, ?)').run(user.id, name, gitUrl, now());
|
||||
return Number(r.lastInsertRowid);
|
||||
});
|
||||
}
|
||||
|
||||
// Les secrets vides dans le formulaire = on garde l'ancien (le formulaire ne les réaffiche jamais)
|
||||
|
|
|
|||
111
src/ratelimit.js
Normal file
111
src/ratelimit.js
Normal file
|
|
@ -0,0 +1,111 @@
|
|||
// Limitation de débit en mémoire (fenêtre glissante), sans dépendance. Une règle de src/limits.js donne, par portée
|
||||
// (adresse IP, compte), un nombre maximal de requêtes par fenêtre. Les compteurs vivent dans le processus : un redémarrage
|
||||
// les remet à zéro, et plusieurs instances ne les partagent pas (une seule instance en production, voir le cadrage).
|
||||
import { BlockList, isIP } from 'node:net';
|
||||
import { RATE_LIMITS } from './limits.js';
|
||||
import { parseIp, normalizeIp } from './ip.js';
|
||||
import { HttpError } from './http.js';
|
||||
|
||||
// ---------- Adresse du client ----------
|
||||
|
||||
/**
|
||||
* TRUST_PROXY : vide, `false` ou `0` (défaut) = on ne lit jamais X-Forwarded-For ; `true`, `1` ou `loopback` = on le lit
|
||||
* seulement si la connexion arrive d'un proxy local (Nginx sur la même machine) ; sinon une liste d'adresses ou de
|
||||
* plages CIDR séparées par des virgules (`127.0.0.1,10.0.0.0/8`) : les proxys de confiance.
|
||||
* @returns {{trusts: (ip: string) => boolean} | null}
|
||||
*/
|
||||
export function parseTrustProxy(value) {
|
||||
if (value && typeof value === 'object' && typeof value.trusts === 'function') return value;
|
||||
const v = String(value ?? '').trim();
|
||||
if (!v || /^(0|false|off|no|non)$/i.test(v)) return null;
|
||||
const entries = /^(1|true|on|yes|oui|loopback)$/i.test(v) ? ['127.0.0.0/8', '::1'] : v.split(',').map((x) => x.trim()).filter(Boolean);
|
||||
const list = new BlockList();
|
||||
for (const e of entries) {
|
||||
const [addr, bits] = e.split('/');
|
||||
const family = isIP(addr);
|
||||
if (!family || (bits !== undefined && !/^\d{1,3}$/.test(bits))) throw new Error(`TRUST_PROXY : entrée invalide « ${e} » (adresse IP ou plage CIDR attendue)`);
|
||||
const kind = family === 4 ? 'ipv4' : 'ipv6';
|
||||
if (bits === undefined) list.addAddress(addr, kind); else list.addSubnet(addr, Number(bits), kind);
|
||||
}
|
||||
return { trusts: (ip) => { const f = isIP(ip); return f ? list.check(ip, f === 4 ? 'ipv4' : 'ipv6') : false; } };
|
||||
}
|
||||
|
||||
/**
|
||||
* Adresse du client. Sans proxy de confiance, c'est celle de la connexion : un en-tête X-Forwarded-For forgé ne change
|
||||
* rien. Avec TRUST_PROXY, et seulement si la connexion vient d'un proxy de confiance, on lit X-Forwarded-For de droite à
|
||||
* gauche et on garde la première adresse qui n'est pas un proxy de confiance (les entrées de gauche, que le client peut
|
||||
* inventer, ne sont jamais crues).
|
||||
*/
|
||||
export function clientIp(req, trust = null) {
|
||||
const peer = normalizeIp(req.socket?.remoteAddress || '') || 'inconnue';
|
||||
if (!trust || !trust.trusts(peer)) return peer;
|
||||
const raw = [].concat(req.headers['x-forwarded-for'] || []).join(',');
|
||||
const chain = raw.split(',').map((x) => x.trim()).filter(Boolean);
|
||||
for (let i = chain.length - 1; i >= 0; i--) {
|
||||
if (!parseIp(chain[i])) return peer; // entrée illisible : on ne devine pas
|
||||
const ip = normalizeIp(chain[i]);
|
||||
if (!trust.trusts(ip)) return ip;
|
||||
}
|
||||
return peer;
|
||||
}
|
||||
|
||||
// ---------- Limiteur ----------
|
||||
|
||||
const human = (s) => (s < 90 ? `${s} seconde${s > 1 ? 's' : ''}` : s < 5400 ? `${Math.ceil(s / 60)} minutes` : `${Math.ceil(s / 3600)} heures`);
|
||||
|
||||
export class RateLimiter {
|
||||
/** `clock` (ms) est injectable pour les tests. */
|
||||
constructor({ rules = RATE_LIMITS, clock = Date.now, maxKeys = 100_000 } = {}) {
|
||||
this.rules = rules;
|
||||
this.clock = clock;
|
||||
this.maxKeys = maxKeys;
|
||||
this.hits = new Map(); // clé → { times: number[], windowMs }
|
||||
this.calls = 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Compte une requête si la règle l'accepte. Une requête refusée n'est PAS comptée : insister ne prolonge pas l'attente.
|
||||
* @returns {{ok: true} | {ok: false, retryAfter: number, scope: string, rule: string}} retryAfter en secondes
|
||||
*/
|
||||
check(rule, { ip, userId } = {}) {
|
||||
const spec = this.rules[rule];
|
||||
if (!spec) throw new Error(`Règle de débit inconnue : ${rule}`);
|
||||
const t = this.clock();
|
||||
if (++this.calls % 500 === 0 || this.hits.size > this.maxKeys) this.sweep(t);
|
||||
const pending = [];
|
||||
for (const [scope, conf] of Object.entries(spec)) {
|
||||
const id = scope === 'ip' ? ip : userId;
|
||||
if (id == null) continue;
|
||||
const key = `${rule}|${scope}|${id}`;
|
||||
let e = this.hits.get(key);
|
||||
if (!e) e = { times: [], windowMs: conf.windowMs };
|
||||
while (e.times.length && e.times[0] <= t - conf.windowMs) e.times.shift();
|
||||
if (e.times.length >= conf.max) {
|
||||
return { ok: false, rule, scope, retryAfter: Math.max(1, Math.ceil((e.times[0] + conf.windowMs - t) / 1000)) };
|
||||
}
|
||||
pending.push([key, e]);
|
||||
}
|
||||
for (const [key, e] of pending) { e.times.push(t); this.hits.set(key, e); }
|
||||
return { ok: true };
|
||||
}
|
||||
|
||||
/** Refuse (429 avec Retry-After) si la règle est dépassée. */
|
||||
enforce(rule, who) {
|
||||
const r = this.check(rule, who);
|
||||
if (r.ok) return;
|
||||
throw new HttpError(429, `Trop de requêtes : réessaie dans ${human(r.retryAfter)}.`, {
|
||||
expose: true, code: 'rate_limited', headers: { 'Retry-After': String(r.retryAfter) }, data: { retryAfter: r.retryAfter },
|
||||
});
|
||||
}
|
||||
|
||||
/** Efface les compteurs expirés ; si la table reste trop grande, les plus anciens sont oubliés (garde-fou mémoire). */
|
||||
sweep(t = this.clock()) {
|
||||
for (const [key, e] of this.hits) {
|
||||
if (!e.times.length || e.times[e.times.length - 1] <= t - e.windowMs) this.hits.delete(key);
|
||||
}
|
||||
for (const key of this.hits.keys()) {
|
||||
if (this.hits.size <= this.maxKeys) break;
|
||||
this.hits.delete(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
108
src/routes.js
108
src/routes.js
|
|
@ -1,18 +1,22 @@
|
|||
import { now, getSetting, setSetting } from './db.js';
|
||||
import { encrypt, encryptJson, decryptJson, verifyUnsubToken } from './crypto.js';
|
||||
import { html, json, redirect, readBody, HttpError } from './http.js';
|
||||
import { startLogin, finishLogin, destroySession, getSession } from './auth.js';
|
||||
import { deleteUser, normalizeEmail } from './users.js';
|
||||
import { startLogin, finishLogin, destroySession, getSession, checkOrigin } from './auth.js';
|
||||
import { verifyCaptcha } from './captcha.js';
|
||||
import { deleteUser, normalizeEmail, getUser } 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 { registerAdminRoutes } from './adminroutes.js';
|
||||
import { dashboardPage, settingsPage, unsubPage, accountPage, linkPage } from './views.js';
|
||||
import { enqueue, latestJobs, cancelJob, usageSummary } from './services/jobs.js';
|
||||
import { validateGitUrl, removeRepo } from './services/git.js';
|
||||
import { fetchRecap, clearRecapCache, validateSelect } from './services/recap.js';
|
||||
import { sendPause, pauseMessage as pauseMessageOf } from './services/abuse.js';
|
||||
import { guardTarget, pinDb, pinGit, checkForgejoHost } from './netguard.js';
|
||||
import { allowedToSend, EMAIL_RE } from './services/mailer.js';
|
||||
import { cpuTemp } from './services/thermal.js';
|
||||
import { checkInbox } from './services/inbox.js';
|
||||
|
|
@ -22,6 +26,7 @@ import { notify, notifyConfig, EVENTS, WEBHOOK_RE } from './services/notify.js';
|
|||
import { budgetState, AI_JOBS } from './services/budget.js';
|
||||
import { sendWeeklyReport } from './services/report.js';
|
||||
import { exportProspects, importProspects } from './services/csv.js';
|
||||
import { quotaFor, planLimitError, withUserLock, assertRoom, usageView } from './services/plans.js';
|
||||
import { history, saveSnapshot } from './services/metrics.js';
|
||||
import { evolutionHtml } from './services/markdown.js';
|
||||
import {
|
||||
|
|
@ -46,28 +51,45 @@ export function registerRoutes(router, app) {
|
|||
|
||||
// ---------- Public ----------
|
||||
registerSiteRoutes(router, app);
|
||||
registerAdminRoutes(router, app);
|
||||
// Déjà connecté : la page de connexion n'a rien à offrir, on va au tableau de bord
|
||||
router.get('/login', async ({ req, res, url }) => {
|
||||
if (await getSession(db, req)) return redirect(res, '/');
|
||||
html(res, loginPage({ appUrl: cfg.appUrl, error: url.searchParams.get('e'), apple: !!cfg.apple, bye: url.searchParams.has('bye') }));
|
||||
html(res, loginPage({ appUrl: cfg.appUrl, error: url.searchParams.get('e'), apple: !!cfg.apple, bye: url.searchParams.has('bye'), captcha: cfg.recaptcha ? { siteKey: cfg.recaptcha.siteKey } : null }));
|
||||
}, { 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')}`);
|
||||
if (!e.status || (e.status >= 500 && !e.expose)) console.error('[connexion]', e);
|
||||
redirect(res, `/login?e=${encodeURIComponent(e.status && (e.status < 500 || e.expose) ? e.message : 'Connexion impossible, réessaie dans un instant')}`);
|
||||
};
|
||||
router.get('/auth/google', async ({ res }) => startLogin(app, 'google', res), { public: true });
|
||||
// Démarrage : avec reCAPTCHA, seul un POST portant un jeton valide démarre le flux (le GET renvoie vers la page de connexion)
|
||||
const start = (name) => ({
|
||||
get: async ({ res }) => {
|
||||
if (cfg.recaptcha) return redirect(res, `/login?e=${encodeURIComponent('Passe par la vérification anti-robot de la page de connexion')}`);
|
||||
return startLogin(app, name, res);
|
||||
},
|
||||
post: async ({ req, res }) => {
|
||||
try {
|
||||
checkOrigin(req, cfg);
|
||||
await verifyCaptcha(app, (await readBody(req)).captcha);
|
||||
} catch (e) { return loginFailed(res, e); }
|
||||
return startLogin(app, name, res);
|
||||
},
|
||||
});
|
||||
router.get('/auth/google', start('google').get, { public: true, limit: 'auth_start' });
|
||||
router.post('/auth/google', start('google').post, { public: true, limit: 'auth_start' });
|
||||
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 });
|
||||
}, { public: true, limit: 'auth_callback' });
|
||||
// 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.get('/auth/apple', start('apple').get, { public: true, limit: 'auth_start' });
|
||||
router.post('/auth/apple', start('apple').post, { public: true, limit: 'auth_start' });
|
||||
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, limit: 'auth_callback' });
|
||||
|
||||
// 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).
|
||||
|
|
@ -96,7 +118,8 @@ export function registerRoutes(router, app) {
|
|||
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'),
|
||||
email: session.email, projects, forgejoHost: await getSetting(db, userId, 'forgejo_host'), usage: await usageView(db, await getUser(db, userId)),
|
||||
pauseMessage: await sendPause(db, userId).then((p) => (p ? pauseMessageOf(p) : null)),
|
||||
}));
|
||||
});
|
||||
|
||||
|
|
@ -130,7 +153,9 @@ export function registerRoutes(router, app) {
|
|||
const b = await readBody(req);
|
||||
if (b.notify_email && !EMAIL_RE.test(b.notify_email)) throw new HttpError(400, 'Email de réception invalide');
|
||||
await set('notify_email', (b.notify_email || '').trim());
|
||||
await set('forgejo_host', (b.forgejo_host || '').trim().replace(/^https?:\/\//, '').replace(/\/.*$/, ''));
|
||||
const forgejoHost = (b.forgejo_host || '').trim().replace(/^https?:\/\//, '').replace(/\/.*$/, '');
|
||||
if (forgejoHost) await checkForgejoHost(app, userId, forgejoHost);
|
||||
await set('forgejo_host', forgejoHost);
|
||||
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 dmin = int(b.send_delay_min, 5, 3600, 20);
|
||||
|
|
@ -151,6 +176,7 @@ export function registerRoutes(router, app) {
|
|||
if (b.discord_remove === 'on') await set('discord_webhook_enc', null);
|
||||
await set('discord_events', JSON.stringify(Object.keys(EVENTS).filter((k) => b[`ev_${k}`] === 'on')));
|
||||
|
||||
if (b.smtp_host) await guardTarget(app, userId, 'smtp', String(b.smtp_host).trim(), b.smtp_port || 587, { lenient: true });
|
||||
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 };
|
||||
await set('smtp_enc', smtp.host ? encryptJson(cfg.secretKey, smtp) : null);
|
||||
|
|
@ -166,6 +192,7 @@ export function registerRoutes(router, app) {
|
|||
}));
|
||||
});
|
||||
|
||||
const LINK_LIMIT = { limit: 'link' };
|
||||
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 }) => {
|
||||
|
|
@ -179,26 +206,26 @@ export function registerRoutes(router, app) {
|
|||
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/api-key', linkAction((b, s) => linkApiKey(app, s.userId, b.apiKey)), LINK_LIMIT);
|
||||
router.post('/link/subscription', linkAction((b, s) => linkSubscriptionToken(app, s.userId, { token: b.token, accept: b.accept })), LINK_LIMIT);
|
||||
router.post('/link/server', linkAction((b, s) => linkServer(app, s.userId)), LINK_LIMIT);
|
||||
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)}`);
|
||||
});
|
||||
}, LINK_LIMIT);
|
||||
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');
|
||||
});
|
||||
}, LINK_LIMIT);
|
||||
|
||||
// ---------- 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,
|
||||
consent: await lastConsent(db, session.userId), cliModeEnabled, usage: await usageView(db, await getUser(db, session.userId)),
|
||||
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,
|
||||
}));
|
||||
|
|
@ -214,21 +241,21 @@ export function registerRoutes(router, app) {
|
|||
await deleteUser(app, session.userId);
|
||||
await destroySession(db, req, res);
|
||||
redirect(res, '/login?bye=1');
|
||||
});
|
||||
}, { limit: 'account_delete' });
|
||||
|
||||
// ---------- API JSON ----------
|
||||
router.post('/api/report/send', async ({ res, session }) => {
|
||||
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');
|
||||
json(res, { ok: true, channels: r.channels });
|
||||
});
|
||||
}, { limit: 'mail_send' });
|
||||
|
||||
router.post('/api/notify/test', async ({ res, session }) => {
|
||||
if (!(await notifyConfig(app, session.userId)).url) throw new HttpError(400, 'Aucun webhook Discord configuré');
|
||||
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é ?)');
|
||||
json(res, { ok: true });
|
||||
});
|
||||
}, { limit: 'mail_send' });
|
||||
|
||||
// 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)
|
||||
router.get('/api/system', async ({ res, session }) => {
|
||||
|
|
@ -249,7 +276,7 @@ export function registerRoutes(router, app) {
|
|||
runAfter: r.run_after, startedAt: r.started_at, createdAt: r.created_at,
|
||||
}));
|
||||
json(res, {
|
||||
temp: session.user.isAdmin ? cpuTemp() : null, queue, scheduled, jobs, usage: await usageSummary(db, userId), budget: await budgetState(db, userId), thermalMax: cfg.thermalMax,
|
||||
temp: session.user.isAdmin ? cpuTemp() : null, queue, scheduled, jobs, usage: await usageSummary(db, userId), budget: await budgetState(db, userId),
|
||||
claudeRateLimit: rlRaw ? JSON.parse(rlRaw) : null, linkMode: link?.mode ?? null,
|
||||
});
|
||||
});
|
||||
|
|
@ -264,15 +291,19 @@ export function registerRoutes(router, app) {
|
|||
let gitUrl;
|
||||
try { gitUrl = validateGitUrl(String(b.gitUrl || '').trim(), host); }
|
||||
catch (e) { throw new HttpError(400, e.message); }
|
||||
await pinGit(app, userId, gitUrl); // hôte public et port autorisé, sinon refus immédiat
|
||||
// Un même dépôt peut être un projet pour deux comptes différents : l'unicité est par utilisateur
|
||||
const exists = () => db.prepare('SELECT 1 FROM projects WHERE user_id = ? AND git_url = ?').get(userId, gitUrl);
|
||||
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 });
|
||||
});
|
||||
// Plafond de jobs IA atteint : le projet est créé quand même (rien n'est perdu), seule l'analyse attend
|
||||
let notice = null;
|
||||
try { await enqueue(db, { userId, projectId: id, type: 'analyze' }, aiOpts); }
|
||||
catch (e) { if (e.code !== 'plan_limit') throw e; notice = e.message; }
|
||||
json(res, { id, ...(notice ? { notice } : {}) });
|
||||
}, { limit: 'project_create' });
|
||||
|
||||
router.post('/api/projects/:id/delete', async (ctx) => {
|
||||
const p = await project(ctx);
|
||||
|
|
@ -352,7 +383,8 @@ export function registerRoutes(router, app) {
|
|||
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 });
|
||||
});
|
||||
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) }), async (p) => {
|
||||
await assertRoom(db, await getUser(db, p.userId), 'prospects');
|
||||
if (!p.targetValidated) throw new HttpError(400, 'Valide la cible avant de prospecter');
|
||||
}));
|
||||
router.post('/api/projects/:id/evolution', jobRoute('evolution', (b) => ({
|
||||
|
|
@ -363,7 +395,7 @@ export function registerRoutes(router, app) {
|
|||
if (!b.confirm) throw new HttpError(400, 'Confirmation requise');
|
||||
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');
|
||||
}));
|
||||
}), { limit: 'mail_send' });
|
||||
|
||||
router.post('/api/projects/:id/template/save', async (ctx) => {
|
||||
const { req, res } = ctx;
|
||||
|
|
@ -385,6 +417,7 @@ export function registerRoutes(router, app) {
|
|||
const p = await project(ctx);
|
||||
const b = await readBody(req);
|
||||
if (b.fromEmail && !EMAIL_RE.test(b.fromEmail)) throw new HttpError(400, 'Email expéditeur invalide');
|
||||
if (String(b.host || '').trim()) await guardTarget(app, ctx.session.userId, 'smtp', String(b.host).trim(), int(b.port, 1, 65535, 587), { lenient: true });
|
||||
await saveSecretConfig(app, p.id, 'smtp_enc', {
|
||||
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),
|
||||
|
|
@ -403,19 +436,20 @@ export function registerRoutes(router, app) {
|
|||
await db.prepare('UPDATE projects SET imap_enc = NULL, inbox_json = NULL WHERE id = ?').run(p.id);
|
||||
return json(res, { ok: true, disabled: true });
|
||||
}
|
||||
await guardTarget(app, session.userId, 'imap', host, int(b.port, 1, 65535, 993), { lenient: true });
|
||||
await saveSecretConfig(app, p.id, 'imap_enc', {
|
||||
host, port: int(b.port, 1, 65535, 993), user: String(b.user || '').trim(), pass: b.pass || '',
|
||||
}, 'pass');
|
||||
try { json(res, { ok: true, check: await checkInbox(app, session.userId, p.id) }); }
|
||||
catch (e) { json(res, { ok: false, error: e.message }); }
|
||||
});
|
||||
}, { limit: 'conn_test' });
|
||||
|
||||
router.post('/api/projects/:id/inbox/check', async (ctx) => {
|
||||
const { res, session } = ctx;
|
||||
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); }
|
||||
});
|
||||
}, { limit: 'conn_test' });
|
||||
|
||||
router.post('/api/projects/:id/db', async (ctx) => {
|
||||
const { req, res } = ctx;
|
||||
|
|
@ -424,6 +458,7 @@ export function registerRoutes(router, app) {
|
|||
for (const k of ['sql_users', 'sql_clients', 'sql_revenue']) {
|
||||
try { validateSelect(b[k]); } catch (e) { throw new HttpError(400, `${k} : ${e.message}`); }
|
||||
}
|
||||
if (String(b.host || '').trim()) await guardTarget(app, ctx.session.userId, b.type === 'pg' ? 'pg' : 'mysql', String(b.host).trim(), b.port ? int(b.port, 1, 65535, 3306) : (b.type === 'pg' ? 5432 : 3306), { lenient: true });
|
||||
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,
|
||||
database: String(b.database || '').trim(), user: String(b.user || '').trim(), password: b.password || '',
|
||||
|
|
@ -441,11 +476,11 @@ export function registerRoutes(router, app) {
|
|||
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;
|
||||
try {
|
||||
business = await fetchRecap(p.id, p.dbCfg, { force: url.searchParams.has('force') });
|
||||
business = await fetchRecap(p.id, await pinDb(app, ctx.session.userId, p.dbCfg), { force: url.searchParams.has('force') });
|
||||
await saveSnapshot(db, p.id, business); // la consultation alimente aussi la courbe du jour
|
||||
} catch (e) { error = e.message; }
|
||||
json(res, { business, error, stats, aiCostUsd: cost });
|
||||
});
|
||||
}, { limit: 'conn_test' });
|
||||
|
||||
router.get('/api/projects/:id/prospects\\.csv', async (ctx) => {
|
||||
const { res, url } = ctx;
|
||||
|
|
@ -458,15 +493,20 @@ export function registerRoutes(router, app) {
|
|||
'Cache-Control': 'no-store',
|
||||
});
|
||||
res.end(await exportProspects(db, p.id, parseFilters(url.searchParams)));
|
||||
});
|
||||
}, { limit: 'csv' });
|
||||
|
||||
router.post('/api/projects/:id/prospects/import', async (ctx) => {
|
||||
const { req, res } = ctx;
|
||||
const p = await project(ctx);
|
||||
const b = await readBody(req, { max: 1024 * 1024 });
|
||||
try { json(res, await importProspects(db, p.id, String(b.csv || ''))); }
|
||||
catch (e) { throw new HttpError(400, e.message); }
|
||||
});
|
||||
try {
|
||||
json(res, await withUserLock(ctx.session.userId, async () => {
|
||||
const u = await getUser(db, ctx.session.userId);
|
||||
const q = await quotaFor(db, u, 'prospects');
|
||||
return importProspects(db, p.id, String(b.csv || ''), { limit: q.remaining, limitError: q.unlimited ? null : planLimitError(u, q, { wanted: q.remaining + 1, note: "Rien n'a été importé." }) });
|
||||
}));
|
||||
} catch (e) { throw e instanceof HttpError ? e : new HttpError(400, e.message); }
|
||||
}, { limit: 'csv' });
|
||||
|
||||
router.get('/api/projects/:id/history', async (ctx) => {
|
||||
const { res, url } = ctx;
|
||||
|
|
|
|||
|
|
@ -6,6 +6,7 @@ import { fileURLToPath } from 'node:url';
|
|||
import { loadConfig } from './config.js';
|
||||
import { openDb } from './db.js';
|
||||
import { Router, json, redirect, html, HttpError } from './http.js';
|
||||
import { RateLimiter, clientIp } from './ratelimit.js';
|
||||
import { getSession, checkOrigin, purgeExpired } from './auth.js';
|
||||
import { syncAdmins } from './users.js';
|
||||
import { registerRoutes } from './routes.js';
|
||||
|
|
@ -16,7 +17,7 @@ import { notify, notifyJob } from './services/notify.js';
|
|||
import { budgetState, AI_JOBS, quotaState, isQuotaSensitive } from './services/budget.js';
|
||||
import { layout } from './views.js';
|
||||
import { homePage, notFoundPage } from './site/pages.js';
|
||||
import { securityHeaders, robotsHeaderFor } from './site/seo.js';
|
||||
import { securityHeaders, robotsHeaderFor, cspFor } from './site/seo.js';
|
||||
import { hasUsableLink, isLinkExempt, LINK_REQUIRED_MESSAGE } from './claudelink.js';
|
||||
import { sandboxStartupMessages } from './services/sandbox.js';
|
||||
|
||||
|
|
@ -32,14 +33,15 @@ const STATIC = {
|
|||
'/static/app.css': asset('app.css', 'text/css; charset=utf-8', 3600),
|
||||
'/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/captcha.js': asset('captcha.js', 'text/javascript; charset=utf-8', 3600),
|
||||
'/static/favicon.svg': asset('favicon.svg', 'image/svg+xml', 86400),
|
||||
};
|
||||
|
||||
// `fetch`, `validateApiKey`, `validateToken`, `syncRepo` : points d'injection pour les tests (aucun appel réseau réel)
|
||||
export async function createApp(cfg, { db, worker = true, createTransport, fetch, validateApiKey, validateToken, syncRepo } = {}) {
|
||||
// `fetch`, `validateApiKey`, `validateToken`, `syncRepo`, `limiter` : points d'injection pour les tests (aucun appel réseau réel)
|
||||
export async function createApp(cfg, { db, worker = true, createTransport, fetch, validateApiKey, validateToken, syncRepo, limiter, resolveHost } = {}) {
|
||||
db ??= await openDb(cfg.db, { adminEmails: cfg.adminEmails });
|
||||
await syncAdmins(db, cfg.adminEmails || []); // ADMIN_EMAILS fait foi pour le rôle admin
|
||||
const app = { db, cfg, createTransport, fetch, validateApiKey, validateToken, syncRepo };
|
||||
const app = { db, cfg, createTransport, fetch, validateApiKey, validateToken, syncRepo, resolveHost, limiter: limiter || new RateLimiter() };
|
||||
const secHeaders = securityHeaders(cfg.appUrl);
|
||||
const router = new Router();
|
||||
registerRoutes(router, app);
|
||||
|
|
@ -47,6 +49,7 @@ export async function createApp(cfg, { db, worker = true, createTransport, fetch
|
|||
const server = createServer(async (req, res) => {
|
||||
for (const [k, v] of Object.entries(secHeaders)) res.setHeader(k, v);
|
||||
const url = new URL(req.url, cfg.appUrl);
|
||||
res.setHeader('Content-Security-Policy', cspFor(url.pathname, !!cfg.recaptcha));
|
||||
// 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);
|
||||
|
|
@ -66,7 +69,14 @@ export async function createApp(cfg, { db, worker = true, createTransport, fetch
|
|||
if (wantsJson || !isRead) throw new HttpError(404, 'Page introuvable');
|
||||
return html(res, notFoundPage({ appUrl: cfg.appUrl }), 404);
|
||||
}
|
||||
const ip = clientIp(req, cfg.trustProxy);
|
||||
if (route.public && route.limit) app.limiter.enforce(route.limit, { ip });
|
||||
const session = route.public ? null : await getSession(db, req);
|
||||
// Back-office : 404 pour tout autre que les administrateurs (visiteurs compris), sans rien révéler
|
||||
if (route.admin && !session?.user.isAdmin) {
|
||||
if (url.pathname.startsWith('/api/') || !isRead || req.headers.accept?.includes('json')) throw new HttpError(404, 'Page introuvable');
|
||||
return html(res, notFoundPage({ appUrl: cfg.appUrl }), 404);
|
||||
}
|
||||
if (!route.public) {
|
||||
if (!session) {
|
||||
// Visiteur sur la racine : le site public. Connecté, la même adresse mène au tableau de bord.
|
||||
|
|
@ -78,6 +88,7 @@ export async function createApp(cfg, { db, worker = true, createTransport, fetch
|
|||
return redirect(res, '/login');
|
||||
}
|
||||
checkOrigin(req, cfg);
|
||||
if (route.limit) app.limiter.enforce(route.limit, { ip, userId: session.userId });
|
||||
// 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')) {
|
||||
|
|
@ -92,7 +103,8 @@ export async function createApp(cfg, { db, worker = true, createTransport, fetch
|
|||
if (status >= 500 && !e.expose) console.error(`[${req.method} ${url.pathname}]`, e);
|
||||
if (res.headersSent) return res.end();
|
||||
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);
|
||||
for (const [k, v] of Object.entries(e.headers || {})) res.setHeader(k, v);
|
||||
if (url.pathname.startsWith('/api/') || req.headers.accept?.includes('json')) json(res, { error: msg, ...(e.code ? { code: e.code } : {}), ...(e.data || {}) }, 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);
|
||||
}
|
||||
});
|
||||
|
|
@ -105,7 +117,7 @@ export async function createApp(cfg, { db, worker = true, createTransport, fetch
|
|||
let scheduler = null;
|
||||
if (worker) {
|
||||
w = new Worker(db, makeHandlers(app), {
|
||||
thermalMax: cfg.thermalMax, cliModeEnabled: cfg.cliModeEnabled !== false,
|
||||
maxJobs: cfg.maxAiJobs ?? 4, loadMax: cfg.loadMax, cliModeEnabled: cfg.cliModeEnabled !== false,
|
||||
onFinish: (job, r) => notifyJob(app, job, r),
|
||||
budget: (userId) => budgetState(db, userId),
|
||||
isAiJob: (type) => AI_JOBS.has(type),
|
||||
|
|
@ -119,9 +131,9 @@ export async function createApp(cfg, { db, worker = true, createTransport, fetch
|
|||
title: 'Job IA reporté (quota serré)', level: 'warn',
|
||||
description: `${reason[0].toUpperCase()}${reason.slice(1)}. Analyse et évolutions attendent ; prospection et envois continuent.`,
|
||||
}),
|
||||
onThermal: (t, userId) => notify(app, userId, 'thermal', {
|
||||
title: 'Pause thermique', level: 'warn',
|
||||
description: `CPU à ${t} °C : les jobs IA attendent que le Pi redescende sous ${cfg.thermalMax - 5} °C.`,
|
||||
onLoad: (ratio, userId) => notify(app, userId, 'load', {
|
||||
title: 'Serveur très chargé', level: 'warn',
|
||||
description: `Charge du serveur à ${Math.round(ratio * 100)} % : tes jobs attendent un instant, ils repartent tout seuls.`,
|
||||
}),
|
||||
});
|
||||
await w.start();
|
||||
|
|
@ -131,6 +143,7 @@ export async function createApp(cfg, { db, worker = true, createTransport, fetch
|
|||
}
|
||||
let purging = null;
|
||||
const purge = setInterval(() => {
|
||||
app.limiter.sweep();
|
||||
purging = purgeExpired(db).catch((e) => console.error('[purge]', e.message));
|
||||
}, 3600_000);
|
||||
purge.unref();
|
||||
|
|
@ -145,6 +158,7 @@ export async function createApp(cfg, { db, worker = true, createTransport, fetch
|
|||
await db.close();
|
||||
};
|
||||
app.server = server;
|
||||
app.router = router;
|
||||
return app;
|
||||
}
|
||||
|
||||
|
|
@ -152,6 +166,9 @@ if (process.argv[1] === fileURLToPath(import.meta.url)) {
|
|||
const cfg = loadConfig();
|
||||
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);
|
||||
if (cfg.production && cfg.allowPrivateHosts) console.warn('ALLOW_PRIVATE_HOSTS est actif en production : seuls les administrateurs peuvent viser des hôtes privés.');
|
||||
if (cfg.production && !cfg.trustProxy) console.warn("TRUST_PROXY est désactivé : derrière Nginx, tous les visiteurs partagent la même adresse pour la limitation de débit. Pose TRUST_PROXY=true.");
|
||||
if (!cfg.recaptcha) console.warn(`reCAPTCHA désactivé (RECAPTCHA_SITE_KEY / RECAPTCHA_SECRET absentes)${cfg.sandbox.production ? " : à configurer avant l'ouverture au public" : ''}.`);
|
||||
const app = await createApp(cfg);
|
||||
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), (e) => { console.error(e); process.exit(1); });
|
||||
|
|
|
|||
74
src/services/abuse.js
Normal file
74
src/services/abuse.js
Normal file
|
|
@ -0,0 +1,74 @@
|
|||
// Détection d'abus à l'envoi : un compte dont trop de mails sont rejetés (bounces) est mis en pause d'envoi, l'administrateur
|
||||
// est prévenu (journal d'audit, journal du serveur, Discord s'il est configuré) et l'utilisateur voit un message clair.
|
||||
// Le désabonnement et la liste d'opposition globale restent appliqués à chaque envoi, pause ou non (voir handlers.js).
|
||||
// Seuils : src/limits.js (ABUSE).
|
||||
import { now, getSetting, setSetting } from '../db.js';
|
||||
import { ABUSE } from '../limits.js';
|
||||
import { logAudit } from '../audit.js';
|
||||
import { notify } from './notify.js';
|
||||
import { CONTACT_EMAIL } from '../site/layout.js';
|
||||
|
||||
/**
|
||||
* Prospects contactés depuis `since` et, parmi eux, ceux dont le mail a été rejeté (adresse invalide). Un prospect compte une
|
||||
* fois, même relancé. Sont comptés les envois réussis et les rejets définitifs (5xx) ; une panne passagère de SMTP ne pèse pas.
|
||||
*/
|
||||
export async function bounceStats(db, userId, { since }) {
|
||||
const r = await db.prepare(`SELECT COUNT(DISTINCT m.prospect_id) sent,
|
||||
COUNT(DISTINCT CASE WHEN x.status = 'bounced' THEN m.prospect_id END) bounced
|
||||
FROM mail_log m JOIN projects p ON p.id = m.project_id JOIN prospects x ON x.id = m.prospect_id
|
||||
WHERE p.user_id = ? AND m.sent_at >= ? AND (m.error IS NULL OR x.status = 'bounced')`).get(Number(userId), since);
|
||||
const sent = Number(r.sent), bounced = Number(r.bounced);
|
||||
return { sent, bounced, rate: sent ? bounced / sent : 0 };
|
||||
}
|
||||
|
||||
/** Pause d'envoi en cours ({ at, sent, bounced, rate }) ou null. */
|
||||
export async function sendPause(db, userId) {
|
||||
const raw = await getSetting(db, userId, 'send_pause_json');
|
||||
try { return raw ? JSON.parse(raw) : null; } catch { return null; }
|
||||
}
|
||||
|
||||
/** Message affiché à l'utilisateur : pourquoi, que vérifier, comment reprendre. */
|
||||
export function pauseMessage(p) {
|
||||
const pct = Math.round((p.rate || 0) * 100);
|
||||
return `Tes envois sont en pause : ${p.bounced} adresse(s) sur ${p.sent} contactées ont été rejetées (${pct} %, seuil de ${Math.round(ABUSE.maxBounceRate * 100)} %). `
|
||||
+ `Vérifie ta liste de prospects et la configuration de ton domaine d'envoi (SPF, DKIM), puis écris à ${CONTACT_EMAIL} pour reprendre. `
|
||||
+ "Le lien de désinscription et la liste d'opposition restent appliqués.";
|
||||
}
|
||||
|
||||
/**
|
||||
* Évalue la santé des envois d'un compte ; au-delà du seuil (et d'un minimum d'envois), met le compte en pause.
|
||||
* Appelée après chaque lot d'envois et chaque lecture de la boîte (c'est là qu'arrivent les rejets).
|
||||
* Après un rétablissement par l'administrateur, seuls les envois suivants sont comptés.
|
||||
* @returns {Promise<object|null>} la pause (existante ou nouvelle), ou null
|
||||
*/
|
||||
export async function evaluateSending(app, userId, { at = now() } = {}) {
|
||||
const { db } = app;
|
||||
const existing = await sendPause(db, userId);
|
||||
if (existing) return existing;
|
||||
const resumed = Number(await getSetting(db, userId, 'send_resumed_at', '0')) || 0;
|
||||
const since = Math.max(at - ABUSE.windowDays * 86400, resumed);
|
||||
const st = await bounceStats(db, userId, { since });
|
||||
if (st.sent < ABUSE.minSent || st.rate <= ABUSE.maxBounceRate) return null;
|
||||
|
||||
const pause = { at, sent: st.sent, bounced: st.bounced, rate: Math.round(st.rate * 1000) / 1000 };
|
||||
await setSetting(db, userId, 'send_pause_json', JSON.stringify(pause));
|
||||
const user = await db.prepare('SELECT id, email FROM users WHERE id = ?').get(Number(userId));
|
||||
const detail = `${st.bounced} rejets sur ${st.sent} prospects contactés (${Math.round(st.rate * 100)} %)`;
|
||||
await logAudit(db, { action: 'abuse_pause', target: user, detail, at });
|
||||
console.warn(`[abus] envois du compte ${userId} mis en pause : ${detail}`);
|
||||
// L'administrateur est prévenu sur son Discord s'il en a un ; l'utilisateur sur le sien
|
||||
for (const a of await db.prepare("SELECT id FROM users WHERE is_admin = 1 AND status = 'active'").all()) {
|
||||
await notify(app, a.id, 'abuse', {
|
||||
title: 'Compte mis en pause d\'envoi', level: 'warn',
|
||||
description: `Compte n°${userId} : ${detail}. Rétablissement possible depuis /admin.`,
|
||||
}, { force: true });
|
||||
}
|
||||
await notify(app, userId, 'abuse', { title: 'Envois en pause', level: 'warn', description: pauseMessage(pause) });
|
||||
return pause;
|
||||
}
|
||||
|
||||
/** Rétablit les envois (action de l'administrateur) : le décompte repart des envois suivants. */
|
||||
export async function resumeSending(db, userId, { at = now() } = {}) {
|
||||
await setSetting(db, userId, 'send_pause_json', null);
|
||||
await setSetting(db, userId, 'send_resumed_at', String(at));
|
||||
}
|
||||
|
|
@ -75,7 +75,8 @@ const MAX_ROWS = 2000;
|
|||
// Notre propre export préfixe les formules par ' : on l'enlève à la relecture
|
||||
const unformula = (s) => (/^'[=+\-@]/.test(s) ? s.slice(1) : s);
|
||||
|
||||
export async function importProspects(db, projectId, text, { at = now() } = {}) {
|
||||
// `limit` : places restantes dans le plan (null = illimité) ; au-delà, l'import entier est annulé avec `limitError`
|
||||
export async function importProspects(db, projectId, text, { at = now(), limit = null, limitError = null } = {}) {
|
||||
const rows = parseCsv(text);
|
||||
if (rows.length < 2) throw new Error('Fichier vide ou sans en-tête');
|
||||
const header = rows[0].map(norm);
|
||||
|
|
@ -106,6 +107,7 @@ export async function importProspects(db, projectId, text, { at = now() } = {})
|
|||
if (seen.has(email) || await exists.get(projectId, email)) { res.duplicates++; continue; }
|
||||
seen.add(email);
|
||||
if (await optOut.get(email)) { res.blacklisted++; continue; }
|
||||
if (limit != null && res.imported >= limit) throw limitError || new Error('Plafond de prospects atteint');
|
||||
const s = Number(get(r, 'score'));
|
||||
await insert.run(
|
||||
projectId, get(r, 'company') || email.split('@')[1], email, httpUrl(get(r, 'website', 300)), get(r, 'city', 100) || null,
|
||||
|
|
|
|||
|
|
@ -48,8 +48,16 @@ export const GIT_HARDENING = [
|
|||
'-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'];
|
||||
// Épinglage : git se connecte à l'adresse déjà vérifiée (pas de seconde résolution DNS) et ne suit aucune redirection,
|
||||
// qui pourrait mener vers un hôte interne. Nécessite git >= 2.37 pour http.curloptResolve (ignoré sur une version plus ancienne).
|
||||
export function pinArgs(pin) {
|
||||
if (!pin) return [];
|
||||
const addr = pin.family === 6 ? `[${pin.address}]` : pin.address;
|
||||
return ['-c', `http.curloptResolve=${pin.host}:${pin.port}:${addr}`, '-c', 'http.followRedirects=false'];
|
||||
}
|
||||
|
||||
export const cloneArgs = (url, dir, pin = null) => [...GIT_HARDENING, ...pinArgs(pin), 'clone', '--depth', '1', '--single-branch', '--no-tags', '--no-recurse-submodules', url, dir];
|
||||
export const fetchArgs = (pin = null) => [...GIT_HARDENING, ...pinArgs(pin), '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) {
|
||||
|
|
@ -94,12 +102,12 @@ export async function syncRepo(url, dir, token, opts = {}) {
|
|||
// 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`)) {
|
||||
await runGit(fetchArgs(), { token, cwd: dir, watchDir: dir, ...opts });
|
||||
await runGit(fetchArgs(opts.pin), { token, cwd: dir, watchDir: dir, ...opts });
|
||||
await runGit([...GIT_HARDENING, 'reset', '--hard', 'FETCH_HEAD'], { token, cwd: dir, ...opts });
|
||||
} else {
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
mkdirSync(dirname(dir), { recursive: true });
|
||||
try { await runGit(cloneArgs(url, dir), { token, watchDir: dir, ...opts }); }
|
||||
try { await runGit(cloneArgs(url, dir, opts.pin), { token, watchDir: dir, ...opts }); }
|
||||
catch (e) { rmSync(dir, { recursive: true, force: true }); throw e; }
|
||||
}
|
||||
const { stdout } = await runGit([...GIT_HARDENING, 'rev-parse', 'HEAD'], { cwd: dir, ...opts });
|
||||
|
|
|
|||
109
src/services/inactive.js
Normal file
109
src/services/inactive.js
Normal file
|
|
@ -0,0 +1,109 @@
|
|||
// Suppression des comptes inactifs (annoncée dans la politique de confidentialité), lancée par le planificateur.
|
||||
// - inactif = aucune connexion ni job depuis INACTIVE_ACCOUNT_MONTHS mois (24 par défaut) ;
|
||||
// - un mail d'avertissement part 30 jours avant, via le SMTP du serveur (SYSTEM_SMTP_*) ;
|
||||
// - un compte n'est supprimé que s'il a REÇU cet avertissement et qu'il est resté inactif les 30 jours suivants : sans SMTP du
|
||||
// serveur, l'avertissement est seulement journalisé et rien n'est supprimé automatiquement ;
|
||||
// - jamais un administrateur, jamais un compte suspendu (la suspension sert aussi à garder la trace d'un abus).
|
||||
import { now, getSetting, setSetting } from '../db.js';
|
||||
import { INACTIVITY } from '../limits.js';
|
||||
import { logAudit } from '../audit.js';
|
||||
import { deleteUser } from '../users.js';
|
||||
import { createTransport } from './mailer.js';
|
||||
import { pinSmtp } from '../netguard.js';
|
||||
import { CONTACT_EMAIL } from '../site/layout.js';
|
||||
|
||||
const DAY = 86400;
|
||||
|
||||
/** Même instant, `n` mois plus tard (calendrier UTC). */
|
||||
export function addMonths(ts, n) {
|
||||
const d = new Date(ts * 1000);
|
||||
d.setUTCMonth(d.getUTCMonth() + n);
|
||||
return Math.floor(d.getTime() / 1000);
|
||||
}
|
||||
|
||||
/** Dernière activité : connexion, création du compte ou dernier job lancé. */
|
||||
export async function lastActivity(db, user) {
|
||||
const job = await db.prepare('SELECT MAX(created_at) t FROM jobs WHERE user_id = ?').get(Number(user.id));
|
||||
return Math.max(Number(user.last_login_at) || 0, Number(user.created_at) || 0, Number(job?.t) || 0);
|
||||
}
|
||||
|
||||
const dateFr = (ts) => new Date(ts * 1000).toLocaleDateString('fr-FR', { dateStyle: 'long', timeZone: 'Europe/Paris' });
|
||||
|
||||
export function warningMail(cfg, user, deleteAt) {
|
||||
const text = [
|
||||
'Bonjour,',
|
||||
'',
|
||||
`Ton compte AiTools (${user.email}) n'a pas servi depuis longtemps. Conformément à notre politique de confidentialité, il sera supprimé avec toutes ses données (projets, prospects, modèles, réglages) à partir du ${dateFr(deleteAt)}.`,
|
||||
'',
|
||||
`Pour le garder, il suffit de te connecter avant cette date : ${cfg.appUrl}/login`,
|
||||
`Pour récupérer tes prospects avant, exporte-les en CSV depuis le tableau de bord (${cfg.appUrl}/).`,
|
||||
'',
|
||||
`Une question ? ${CONTACT_EMAIL}`,
|
||||
'',
|
||||
"AiTools · message automatique, envoyé une seule fois.",
|
||||
].join('\n');
|
||||
return { subject: 'Ton compte AiTools sera supprimé pour inactivité', text };
|
||||
}
|
||||
|
||||
async function sendWarning(app, user, deleteAt) {
|
||||
const smtp = app.cfg.systemSmtp;
|
||||
if (!smtp) return { sent: false, reason: "SMTP du serveur non configuré (SYSTEM_SMTP_HOST)" };
|
||||
const mail = warningMail(app.cfg, user, deleteAt);
|
||||
const transport = (app.createTransport || createTransport)(await pinSmtp(app, null, smtp));
|
||||
try {
|
||||
await transport.sendMail({ from: smtp.fromEmail, to: user.email, subject: mail.subject, text: mail.text });
|
||||
return { sent: true };
|
||||
} catch (e) {
|
||||
return { sent: false, reason: `envoi impossible (${String(e.message).slice(0, 120)})`, transient: true };
|
||||
} finally { transport.close?.(); }
|
||||
}
|
||||
|
||||
/**
|
||||
* Un passage : avertit les comptes qui approchent de l'échéance, supprime ceux qui l'ont dépassée après avertissement.
|
||||
* `at` est injectable (horloge des tests). months = 0 désactive la suppression.
|
||||
* @returns {{warned: number, deleted: number, unsent: number}}
|
||||
*/
|
||||
export async function runInactiveCleanup(app, { at = now(), months = app.cfg.inactiveMonths ?? INACTIVITY.defaultMonths, log = console } = {}) {
|
||||
const out = { warned: 0, deleted: 0, unsent: 0 };
|
||||
if (!months || months < 1) return out;
|
||||
const { db } = app;
|
||||
const warnSec = INACTIVITY.warningDays * DAY;
|
||||
// Pré-filtre en base : seuls les comptes dont la dernière connexion approche de l'échéance sont examinés un par un
|
||||
const horizon = addMonths(at, -months) + warnSec;
|
||||
const rows = await db.prepare(`SELECT id, email, created_at, last_login_at FROM users
|
||||
WHERE is_admin = 0 AND plan <> 'admin' AND status = 'active' AND COALESCE(last_login_at, created_at) <= ?`).all(horizon);
|
||||
for (const user of rows) {
|
||||
const act = await lastActivity(db, user);
|
||||
const deadline = addMonths(act, months);
|
||||
if (at < deadline - warnSec) continue; // un job récent a repoussé l'échéance
|
||||
const warnedAt = Number(await getSetting(db, user.id, 'inactive_warned_at', '0')) || 0;
|
||||
const warned = warnedAt > act; // un avertissement antérieur à la dernière activité ne compte plus
|
||||
|
||||
if (!warned) {
|
||||
const deleteAt = Math.max(deadline, at + warnSec);
|
||||
const r = await sendWarning(app, user, deleteAt);
|
||||
if (r.sent) {
|
||||
await setSetting(db, user.id, 'inactive_warned_at', String(at));
|
||||
await logAudit(db, { action: 'inactive_warning', target: user, detail: `avertissement envoyé, suppression possible dès le ${dateFr(deleteAt)}`, at });
|
||||
out.warned++;
|
||||
} else {
|
||||
out.unsent++;
|
||||
log.warn?.(`[inactifs] compte ${user.id} : avertissement non envoyé, ${r.reason}. Aucune suppression automatique.`);
|
||||
// Une seule trace au journal d'audit par période d'inactivité (pas à chaque passage du planificateur)
|
||||
const noted = Number(await getSetting(db, user.id, 'inactive_noted_at', '0')) || 0;
|
||||
if (!r.transient && noted <= act) {
|
||||
await setSetting(db, user.id, 'inactive_noted_at', String(at));
|
||||
await logAudit(db, { action: 'inactive_warning', target: user, detail: `avertissement NON envoyé : ${r.reason}. Compte inactif à traiter à la main.`, at });
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (at >= deadline && at >= warnedAt + warnSec) {
|
||||
await logAudit(db, { action: 'inactive_delete', target: user, detail: `inactif depuis le ${dateFr(act)}, avertissement du ${dateFr(warnedAt)}`, at });
|
||||
app.worker?.abortUser(user.id);
|
||||
await deleteUser(app, user.id);
|
||||
out.deleted++;
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
|
@ -3,6 +3,8 @@
|
|||
import { now } from '../db.js';
|
||||
import { getProject } from '../projects.js';
|
||||
import { notify } from './notify.js';
|
||||
import { pinImap } from '../netguard.js';
|
||||
import { evaluateSending } from './abuse.js';
|
||||
|
||||
// Webmails grand public : une réponse d'un autre @gmail.com ne dit rien sur l'entreprise
|
||||
const GENERIC_DOMAINS = new Set([
|
||||
|
|
@ -92,6 +94,7 @@ export async function fetchInbox(creds, state, { since, max = 500 }) {
|
|||
const client = new ImapFlow({
|
||||
host: creds.host, port: creds.port, secure: creds.port === 993,
|
||||
auth: { user: creds.user, pass: creds.pass }, logger: false,
|
||||
...(creds.servername ? { servername: creds.servername } : {}),
|
||||
socketTimeout: 60_000, connectionTimeout: 15_000,
|
||||
});
|
||||
// Sans écouteur, une erreur réseau tardive (timeout après un échec d'auth) ferait planter tout le serveur
|
||||
|
|
@ -153,12 +156,15 @@ export async function checkInbox(app, userId, projectId) {
|
|||
const at = now();
|
||||
const save = (s) => db.prepare('UPDATE projects SET inbox_json = ? WHERE id = ?').run(JSON.stringify(s), project.id);
|
||||
try {
|
||||
const r = await (app.fetchInbox || fetchInbox)(project.imap, state, { since });
|
||||
// Hôte vérifié à CHAQUE lecture et connexion à l'adresse vérifiée (pas de rebinding DNS entre les deux)
|
||||
const imap = await pinImap(app, userId, project.imap);
|
||||
const r = await (app.fetchInbox || fetchInbox)(imap, state, { since });
|
||||
const res = await applyMessages(db, project.id, r.messages, { at });
|
||||
await save({
|
||||
uidValidity: r.uidValidity, lastUid: r.lastUid, lastCheck: at, lastOk: at, lastError: null,
|
||||
replies: (state.replies || 0) + res.replies, bounces: (state.bounces || 0) + res.bounces,
|
||||
});
|
||||
if (res.bounces) await evaluateSending(app, userId); // les rejets arrivent ici : vérifie le taux du compte
|
||||
if (res.replies) {
|
||||
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, userId, 'reply', {
|
||||
|
|
|
|||
|
|
@ -1,10 +1,13 @@
|
|||
// File de jobs en base, UN seul worker : un seul `claude` à la fois.
|
||||
// File de jobs en base : jobs IA simultanés (plafond global), un seul par utilisateur, tourniquet entre utilisateurs.
|
||||
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 { loadRatio } from './load.js';
|
||||
import { LOAD } from '../limits.js';
|
||||
import { assertRoom, recordUsage, withUserLock, MAIL_JOBS } from './plans.js';
|
||||
import { sendPause, pauseMessage } from './abuse.js';
|
||||
|
||||
/**
|
||||
* Met un job en file pour un utilisateur. Point de passage obligé de toutes les routes et tâches de fond :
|
||||
|
|
@ -23,14 +26,28 @@ export async function enqueue(db, { userId, projectId, type, params = {}, runAft
|
|||
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);
|
||||
// Pause d'envoi (trop de rejets) : refus explicite et immédiat, jamais silencieux
|
||||
if (MAIL_JOBS.has(type)) {
|
||||
const pause = await sendPause(db, user.id);
|
||||
if (pause) throw new HttpError(403, pauseMessage(pause), { expose: true, code: 'send_paused' });
|
||||
}
|
||||
// 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 };
|
||||
const r = await db.prepare('INSERT INTO jobs(user_id, project_id, type, params_json, created_at, run_after) VALUES(?, ?, ?, ?, ?, ?)')
|
||||
.run(user.id, projectId ?? null, type, JSON.stringify(params), now(), runAfter);
|
||||
return { id: Number(r.lastInsertRowid), existing: false };
|
||||
// Plafonds du plan : compter puis écrire dans la même section critique (deux requêtes simultanées ne passent pas toutes deux)
|
||||
return withUserLock(user.id, async () => {
|
||||
if (AI_JOBS.has(type)) await assertRoom(db, user, 'aiJobs');
|
||||
if (MAIL_JOBS.has(type)) {
|
||||
await assertRoom(db, user, 'mails');
|
||||
}
|
||||
const r = await db.prepare('INSERT INTO jobs(user_id, project_id, type, params_json, created_at, run_after) VALUES(?, ?, ?, ?, ?, ?)')
|
||||
.run(user.id, projectId ?? null, type, JSON.stringify(params), now(), runAfter);
|
||||
const id = Number(r.lastInsertRowid);
|
||||
if (AI_JOBS.has(type)) await recordUsage(db, user.id, 'ai_job', { ref: id });
|
||||
return { id, existing: false };
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -74,13 +91,27 @@ export async function latestJobs(db, projectId) {
|
|||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* File de jobs équitable et simultanée.
|
||||
* - jusqu'à `maxJobs` jobs en parallèle sur le serveur (MAX_AI_JOBS) ;
|
||||
* - au plus UN job à la fois par utilisateur ;
|
||||
* - prochain job choisi en tourniquet entre utilisateurs (le moins récemment servi d'abord), donc pas de famine ;
|
||||
* à l'intérieur d'un utilisateur, l'ordre des jobs (par id) est conservé, y compris pour les jobs programmés la nuit ;
|
||||
* - réservation atomique : UPDATE conditionnel dont on contrôle le nombre de lignes affectées ;
|
||||
* - nouveaux jobs en pause quand la charge du serveur (charge/cœurs) dépasse `loadMax` ; les jobs en cours continuent.
|
||||
* Budget $ et quota du compte Claude restent évalués par utilisateur.
|
||||
*/
|
||||
export class Worker {
|
||||
constructor(db, handlers, {
|
||||
thermalMax = 75, pollMs = 3000, log = console, clock = now, onFinish, onThermal,
|
||||
maxJobs = 4, loadMax = LOAD.defaultMax, load = loadRatio, pollMs = 3000, log = console, clock = now, onFinish, onLoad,
|
||||
budget, isAiJob, onBudget, quota, isQuotaSensitive, onQuotaHold, cliModeEnabled = true,
|
||||
} = {}) {
|
||||
this.cliModeEnabled = cliModeEnabled;
|
||||
this.clock = clock;
|
||||
this.maxJobs = Math.max(1, Math.floor(Number(maxJobs)) || 1);
|
||||
this.loadMax = loadMax;
|
||||
this.load = load;
|
||||
this.loadPaused = false;
|
||||
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.onBudget = onBudget; // (reason, userId) → une notif quand le blocage commence
|
||||
|
|
@ -90,15 +121,19 @@ export class Worker {
|
|||
this.onQuotaHold = onQuotaHold; // (reason, userId) → une notif quand le report commence
|
||||
this.quotaBlocked = new Set();
|
||||
this.onFinish = onFinish; // (job, {status, result, error}) → notifications
|
||||
this.onThermal = onThermal; // (°C, userId) → une fois par pause
|
||||
this.onLoad = onLoad; // (ratio, userId) → une fois par pause et par utilisateur en attente
|
||||
this.loadNotified = new Set();
|
||||
this.db = db;
|
||||
this.handlers = handlers;
|
||||
this.thermalMax = thermalMax;
|
||||
this.pollMs = pollMs;
|
||||
this.log = log;
|
||||
this.current = null;
|
||||
this.currentJob = null;
|
||||
this.running = new Map(); // id du job → { job, ctrl }
|
||||
this.busyUsers = new Set(); // utilisateurs ayant un job réservé ou en cours (un seul à la fois chacun)
|
||||
this.claiming = 0; // réservations en cours (pour ne jamais dépasser maxJobs)
|
||||
this.served = new Map(); // utilisateur → rang de son dernier service (tourniquet)
|
||||
this.turn = 0;
|
||||
this.stopped = false;
|
||||
this.inflight = new Set(); // jobs lancés par la boucle (attendus à l'arrêt)
|
||||
this.pending = new Set(); // callbacks de notification en vol (attendus à l'arrêt)
|
||||
this.loopDone = null;
|
||||
this.wake = null;
|
||||
|
|
@ -110,23 +145,26 @@ export class Worker {
|
|||
this.loopDone = this.loop();
|
||||
}
|
||||
|
||||
/** Arrête la boucle et attend le job en cours ainsi que les notifications en vol. */
|
||||
/** Arrête la boucle, interrompt TOUS les jobs en cours et les attend, ainsi que les notifications en vol. */
|
||||
async stop() {
|
||||
this.stopped = true;
|
||||
this.current?.abort();
|
||||
for (const { ctrl } of this.running.values()) ctrl.abort();
|
||||
this.wake?.();
|
||||
await this.loopDone;
|
||||
while (this.inflight.size) await Promise.allSettled([...this.inflight]);
|
||||
await this.idle();
|
||||
}
|
||||
|
||||
/** Interrompt le job en cours s'il appartient à cet utilisateur (suppression du compte). */
|
||||
/** Interrompt les jobs en cours de cet utilisateur (suppression du compte, suspension). */
|
||||
abortUser(userId) {
|
||||
if (this.currentJob && Number(this.currentJob.user_id) === Number(userId)) this.current?.abort();
|
||||
for (const { job, ctrl } of this.running.values()) if (Number(job.user_id) === Number(userId)) ctrl.abort();
|
||||
}
|
||||
|
||||
/** Interrompt le job en cours s'il est un job IA de cet utilisateur (déliaison de son accès Claude). */
|
||||
/** Interrompt le job IA en cours 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();
|
||||
for (const { job, ctrl } of this.running.values()) {
|
||||
if (Number(job.user_id) === Number(userId) && this.isAiJob?.(job.type)) ctrl.abort();
|
||||
}
|
||||
}
|
||||
|
||||
/** Attend les callbacks (notifications) lancés par emit(). */
|
||||
|
|
@ -150,73 +188,124 @@ export class Worker {
|
|||
|
||||
async loop() {
|
||||
while (!this.stopped) {
|
||||
let ran = false;
|
||||
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) {
|
||||
try {
|
||||
for (;;) {
|
||||
const job = await this.claim();
|
||||
if (!job) break;
|
||||
this.launch(job);
|
||||
}
|
||||
} catch (e) { this.log.error('[worker]', e.message); } // base indisponible : on réessaie au prochain passage
|
||||
if (!this.stopped) {
|
||||
await new Promise((r) => { this.wake = r; setTimeout(r, this.pollMs).unref(); });
|
||||
this.wake = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
launch(job) {
|
||||
const p = this.runJob(job).catch((e) => this.log.error(`[job ${job.id}]`, e.message)).finally(() => { this.inflight.delete(p); this.wake?.(); });
|
||||
this.inflight.add(p);
|
||||
}
|
||||
|
||||
/** Réserve et exécute un job (jusqu'à sa fin). Renvoie false s'il n'y avait rien à lancer. Utilisé tel quel par les tests. */
|
||||
async tick() {
|
||||
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());
|
||||
if (!due.length) return false;
|
||||
|
||||
// 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 :
|
||||
// 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. Chaque utilisateur a les siens.
|
||||
const budgets = new Map(), quotas = new Map();
|
||||
const perUser = async (cache, fn, userId) => {
|
||||
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}` });
|
||||
if (j.progress_json !== msg) await this.db.prepare('UPDATE jobs SET progress_json = ? WHERE id = ?').run(msg, j.id);
|
||||
};
|
||||
let job = null;
|
||||
const waiting = new Map(), quotaWaiting = new Map();
|
||||
for (const j of due) {
|
||||
// Compte suspendu ou supprimé, job IA sans liaison Claude valide : refusé sans exécution
|
||||
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;
|
||||
break;
|
||||
}
|
||||
for (const [userId, reason] of waiting) if (!this.budgetBlocked.has(userId)) this.emit('onBudget', reason, userId);
|
||||
this.budgetBlocked = new Set(waiting.keys());
|
||||
for (const [userId, reason] of quotaWaiting) if (!this.quotaBlocked.has(userId)) this.emit('onQuotaHold', reason, userId);
|
||||
this.quotaBlocked = new Set(quotaWaiting.keys());
|
||||
const job = await this.claim();
|
||||
if (!job) return false;
|
||||
const handler = this.handlers[job.type];
|
||||
if (!handler) {
|
||||
await this.db.prepare("UPDATE jobs SET status='error', error=?, finished_at=? WHERE id=?").run(`Type inconnu : ${job.type}`, now(), job.id);
|
||||
return true;
|
||||
}
|
||||
await this.runJob(job);
|
||||
return true;
|
||||
}
|
||||
|
||||
let warned = false;
|
||||
await waitCool(this.thermalMax, {
|
||||
onWait: async (t) => {
|
||||
await setProgress(this.db, job.id, { message: `Pause thermique (${t} °C)` });
|
||||
if (!warned) { warned = true; this.emit('onThermal', t, job.user_id); }
|
||||
},
|
||||
});
|
||||
/**
|
||||
* Choisit le prochain job et le réserve atomiquement. Renvoie le job réservé (déjà « running » en base), ou null.
|
||||
* Sûr si appelé en parallèle : un utilisateur n'a jamais deux jobs, le nombre total reste borné.
|
||||
*/
|
||||
async claim() {
|
||||
if (this.stopped || this.running.size + this.claiming >= this.maxJobs) return null;
|
||||
this.claiming++;
|
||||
try {
|
||||
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());
|
||||
if (!due.length) return null;
|
||||
|
||||
await this.db.prepare("UPDATE jobs SET status='running', started_at=? WHERE id=? AND status='queued'").run(now(), job.id);
|
||||
// Budget $ atteint ou quota du compte Claude serré : les jobs concernés restent en file (pas perdus), les autres
|
||||
// passent devant. Le budget met en pause TOUS les jobs IA, le quota ne retarde que les jobs non urgents.
|
||||
const hold = async (j, reason) => {
|
||||
const msg = JSON.stringify({ message: `En attente : ${reason}` });
|
||||
if (j.progress_json !== msg) await this.db.prepare('UPDATE jobs SET progress_json = ? WHERE id = ?').run(msg, j.id);
|
||||
};
|
||||
const byUser = new Map();
|
||||
for (const j of due) {
|
||||
if (!byUser.has(j.user_id)) byUser.set(j.user_id, []);
|
||||
byUser.get(j.user_id).push(j);
|
||||
}
|
||||
const candidates = []; // un seul candidat par utilisateur : son premier job exécutable
|
||||
for (const [userId, jobs] of byUser) {
|
||||
if (this.busyUsers.has(Number(userId))) continue; // déjà un job en cours : les suivants attendent
|
||||
let budgetReason = null, quotaReason = null, cand = null;
|
||||
for (const j of jobs) {
|
||||
// Compte suspendu ou supprimé, job IA sans liaison Claude valide : refusé sans exécution
|
||||
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 b = (await this.budget?.(j.user_id)) || { blocked: false };
|
||||
if (b.blocked && this.isAiJob?.(j.type)) { budgetReason = b.reason; await hold(j, b.reason); continue; }
|
||||
const q = (await this.quota?.(j.user_id)) || { blocked: false };
|
||||
if (q.blocked && this.isQuotaSensitive?.(j.type)) { quotaReason = q.reason; await hold(j, q.reason); continue; }
|
||||
cand = j;
|
||||
break;
|
||||
}
|
||||
if (budgetReason && !this.budgetBlocked.has(userId)) this.emit('onBudget', budgetReason, userId);
|
||||
if (budgetReason) this.budgetBlocked.add(userId); else this.budgetBlocked.delete(userId);
|
||||
if (quotaReason && !this.quotaBlocked.has(userId)) this.emit('onQuotaHold', quotaReason, userId);
|
||||
if (quotaReason) this.quotaBlocked.add(userId); else this.quotaBlocked.delete(userId);
|
||||
if (cand) candidates.push(cand);
|
||||
}
|
||||
if (!candidates.length) return null;
|
||||
|
||||
// Charge du serveur : pause des NOUVEAUX jobs (hystérésis pour éviter le yo-yo)
|
||||
const ratio = await this.load();
|
||||
const limit = this.loadPaused ? this.loadMax - LOAD.resumeGap : this.loadMax;
|
||||
if (ratio >= limit) {
|
||||
this.loadPaused = true;
|
||||
for (const j of candidates) {
|
||||
await hold(j, `charge du serveur élevée (${Math.round(ratio * 100)} %)`);
|
||||
if (!this.loadNotified.has(j.user_id)) { this.loadNotified.add(j.user_id); this.emit('onLoad', ratio, j.user_id); }
|
||||
}
|
||||
return null;
|
||||
}
|
||||
this.loadPaused = false;
|
||||
this.loadNotified.clear();
|
||||
|
||||
// Tourniquet : le moins récemment servi d'abord (jamais servi = en tête), puis l'ordre des jobs
|
||||
candidates.sort((a, b) => (this.served.get(a.user_id) ?? -1) - (this.served.get(b.user_id) ?? -1) || a.id - b.id);
|
||||
for (const job of candidates) {
|
||||
if (this.busyUsers.has(Number(job.user_id))) continue; // pris entre-temps par un claim concurrent
|
||||
if (!(await this.reserve(job))) continue;
|
||||
// Aucun await entre la réservation en base et ces lignes : l'état en mémoire suit toujours la base
|
||||
this.busyUsers.add(Number(job.user_id));
|
||||
this.served.set(job.user_id, ++this.turn);
|
||||
return job;
|
||||
}
|
||||
return null;
|
||||
} finally { this.claiming--; }
|
||||
}
|
||||
|
||||
/**
|
||||
* Passage atomique queued → running. Réussit seulement si le job est encore en file ET si son utilisateur n'a aucun
|
||||
* autre job en cours (la sous-requête passe par une table dérivée : MySQL interdit de lire la table qu'on met à jour).
|
||||
*/
|
||||
async reserve(job) {
|
||||
const r = await this.db.prepare(`UPDATE jobs SET status = 'running', started_at = ? WHERE id = ? AND status = 'queued'
|
||||
AND (SELECT COUNT(*) FROM (SELECT id FROM jobs WHERE user_id = ? AND status = 'running' LIMIT 1) busy) = 0`)
|
||||
.run(now(), job.id, job.user_id);
|
||||
return r.changes === 1;
|
||||
}
|
||||
|
||||
async runJob(job) {
|
||||
const ctrl = new AbortController();
|
||||
this.current = ctrl;
|
||||
this.currentJob = job;
|
||||
this.running.set(job.id, { job, ctrl });
|
||||
const ctx = {
|
||||
job,
|
||||
params: JSON.parse(job.params_json || '{}'),
|
||||
|
|
@ -229,27 +318,32 @@ export class Worker {
|
|||
const watch = setInterval(() => {
|
||||
this.isCancelled(job.id).then((c) => { if (c) ctrl.abort(); }, () => {});
|
||||
}, 2000);
|
||||
|
||||
try {
|
||||
const result = await handler(ctx);
|
||||
if (!(await this.isCancelled(job.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);
|
||||
this.emit('onFinish', job, { status: 'done', result });
|
||||
const handler = this.handlers[job.type];
|
||||
if (!handler) {
|
||||
await this.db.prepare("UPDATE jobs SET status='error', error=?, finished_at=? WHERE id=?").run(`Type inconnu : ${job.type}`, now(), job.id);
|
||||
return;
|
||||
}
|
||||
} catch (e) {
|
||||
this.log.error(`[job ${job.id} ${job.type}]`, e.message);
|
||||
if (!(await this.isCancelled(job.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);
|
||||
this.emit('onFinish', job, { status: 'error', error: e.message });
|
||||
try {
|
||||
const result = await handler(ctx);
|
||||
if (!(await this.isCancelled(job.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);
|
||||
this.emit('onFinish', job, { status: 'done', result });
|
||||
}
|
||||
} catch (e) {
|
||||
this.log.error(`[job ${job.id} ${job.type}]`, e.message);
|
||||
if (!(await this.isCancelled(job.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);
|
||||
this.emit('onFinish', job, { status: 'error', error: e.message });
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
clearInterval(watch);
|
||||
this.current = null;
|
||||
this.currentJob = null;
|
||||
this.running.delete(job.id);
|
||||
this.busyUsers.delete(Number(job.user_id));
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
8
src/services/load.js
Normal file
8
src/services/load.js
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
// Charge du serveur : rapport entre la charge moyenne (1 min) et le nombre de cœurs. Remplace la pause thermique du Raspberry.
|
||||
import os from 'node:os';
|
||||
|
||||
/** 0 = machine au repos, 1 = tous les cœurs occupés. Toujours 0 sous Windows (loadavg y vaut 0). */
|
||||
export function loadRatio() {
|
||||
const cores = Math.max(1, os.availableParallelism?.() ?? os.cpus().length);
|
||||
return os.loadavg()[0] / cores;
|
||||
}
|
||||
|
|
@ -15,6 +15,8 @@ export function createTransport(smtp) {
|
|||
secure: Number(smtp.port) === 465,
|
||||
auth: { user: smtp.user, pass: smtp.pass },
|
||||
pool: false,
|
||||
// Hôte épinglé sur l'IP vérifiée (netguard.js) : le nom reste utilisé pour SNI et la vérification du certificat
|
||||
...(smtp.servername ? { servername: smtp.servername, tls: { servername: smtp.servername } } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@
|
|||
import { now } from '../db.js';
|
||||
import { getProject } from '../projects.js';
|
||||
import { fetchRecap } from './recap.js';
|
||||
import { pinDb } from '../netguard.js';
|
||||
import { parisParts, parisTime, addParisDays } from './paris-time.js';
|
||||
|
||||
const pad = (n) => String(n).padStart(2, '0');
|
||||
|
|
@ -25,7 +26,7 @@ export async function snapshotAll(app, { date = new Date(), log = console } = {}
|
|||
for (const { id, user_id: userId } of todo) {
|
||||
try {
|
||||
const p = await getProject(app, id, { userId, secrets: true });
|
||||
await saveSnapshot(app.db, id, await (app.fetchRecap || fetchRecap)(id, p.dbCfg, { force: true }), { date });
|
||||
await saveSnapshot(app.db, id, await (app.fetchRecap || fetchRecap)(id, await pinDb(app, userId, p.dbCfg), { force: true }), { date });
|
||||
n++;
|
||||
} catch (e) { log.error(`[métriques ${id}]`, e.message); }
|
||||
}
|
||||
|
|
|
|||
|
|
@ -11,7 +11,8 @@ export const EVENTS = {
|
|||
job_error: 'Job en erreur',
|
||||
reply: 'Réponse d\'un prospect',
|
||||
followup: 'Relances envoyées',
|
||||
thermal: 'Pause thermique du Pi',
|
||||
load: 'Serveur très chargé : tes jobs attendent',
|
||||
abuse: 'Envois mis en pause (trop de mails rejetés)',
|
||||
budget: 'Budget IA atteint',
|
||||
quota: 'Quota Claude proche de la limite, ou job reporté',
|
||||
weekly: 'Rapport hebdo',
|
||||
|
|
@ -21,7 +22,7 @@ const COLORS = { ok: 0x15803d, info: 0x2f5bea, warn: 0xb45309, error: 0xb91c1c }
|
|||
const ICONS = { ok: '✅', info: '🔷', warn: '⚠️', error: '⛔' };
|
||||
const FOOTERS = {
|
||||
job_done: 'Job terminé', job_error: 'Job en échec', reply: 'Réponse prospect', followup: 'Relances',
|
||||
thermal: 'Température', budget: 'Budget IA', quota: 'Quota Claude', weekly: 'Rapport hebdo', test: 'Test',
|
||||
load: 'Charge serveur', abuse: 'Envois en pause', budget: 'Budget IA', quota: 'Quota Claude', weekly: 'Rapport hebdo', test: 'Test',
|
||||
};
|
||||
|
||||
/** Barre de progression en caractères (Discord n'affiche pas d'images inline dans un embed sans hébergement). */
|
||||
|
|
@ -36,7 +37,8 @@ export async function notifyConfig(app, userId) {
|
|||
try { url = decrypt(app.cfg.secretKey, await getSetting(app.db, userId, 'discord_webhook_enc')); }
|
||||
catch { url = null; }
|
||||
const raw = await getSetting(app.db, userId, 'discord_events');
|
||||
const events = raw ? JSON.parse(raw) : Object.keys(EVENTS);
|
||||
// « thermal » (ancienne pause du Raspberry) est devenu « load »
|
||||
const events = raw ? JSON.parse(raw).map((e) => (e === 'thermal' ? 'load' : e)) : Object.keys(EVENTS);
|
||||
return { url, events };
|
||||
}
|
||||
|
||||
|
|
|
|||
127
src/services/plans.js
Normal file
127
src/services/plans.js
Normal file
|
|
@ -0,0 +1,127 @@
|
|||
// Plafonds des plans, appliqués côté serveur. Les valeurs vivent dans src/limits.js (PLAN_LIMITS).
|
||||
//
|
||||
// - projets et prospects : totaux du compte, recomptés dans leurs tables ;
|
||||
// - mails et jobs IA : par mois calendaire (heure de Paris), recomptés depuis le journal d'usage (usage_events).
|
||||
// Aucun compteur n'est stocké : chaque consommation est une ligne, et l'usage est une somme. Le journal d'usage survit à la
|
||||
// suppression d'un projet (sinon supprimer puis recréer le projet remettrait le mois à zéro).
|
||||
// Un dépassement refuse l'action avec un message clair et un lien vers /tarifs ; il ne supprime ni ne tronque jamais de données.
|
||||
import { now } from '../db.js';
|
||||
import { HttpError } from '../http.js';
|
||||
import { PLAN_LIMITS, PLAN_LABELS } from '../limits.js';
|
||||
import { parisParts, parisTime } from './paris-time.js';
|
||||
|
||||
export const USAGE_KINDS = ['projects', 'prospects', 'mails', 'aiJobs'];
|
||||
|
||||
const NOUNS = { projects: ['projet', 'projets'], prospects: ['prospect', 'prospects'], mails: ['mail', 'mails'], aiJobs: ['job IA', 'jobs IA'] };
|
||||
export const KIND_LABELS = { projects: 'Projets', prospects: 'Prospects', mails: 'Mails ce mois-ci', aiJobs: 'Jobs IA ce mois-ci' };
|
||||
const MONTHLY = new Set(['mails', 'aiJobs']);
|
||||
|
||||
/** Clé du plan appliqué : un administrateur n'a aucune limite ; un plan inconnu retombe sur « gratuit » (jamais sur illimité). */
|
||||
export function planOf(user) {
|
||||
if (user?.isAdmin || user?.plan === 'admin') return 'admin';
|
||||
return PLAN_LIMITS[user?.plan] ? user.plan : 'free';
|
||||
}
|
||||
export const limitsFor = (user) => PLAN_LIMITS[planOf(user)];
|
||||
|
||||
/** Bornes [début, fin[ du mois calendaire à Paris, en secondes. */
|
||||
export function monthBounds(at = now()) {
|
||||
const p = parisParts(new Date(at * 1000));
|
||||
const [ny, nm] = p.month === 12 ? [p.year + 1, 1] : [p.year, p.month + 1];
|
||||
return {
|
||||
start: Math.floor(parisTime(p.year, p.month, 1, 0).getTime() / 1000),
|
||||
end: Math.floor(parisTime(ny, nm, 1, 0).getTime() / 1000),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Usage d'un compte, recalculé depuis les tables.
|
||||
* Un job IA compte dès sa mise en file, sauf s'il a été annulé ou refusé sans jamais démarrer.
|
||||
*/
|
||||
export async function usageOf(db, userId, { at = now() } = {}) {
|
||||
const { start, end } = monthBounds(at);
|
||||
const n = async (sql, ...p) => Number((await db.prepare(sql).get(...p)).n);
|
||||
const id = Number(userId);
|
||||
return {
|
||||
projects: await n('SELECT COUNT(*) n FROM projects WHERE user_id = ?', id),
|
||||
prospects: await n('SELECT COUNT(*) n FROM prospects x JOIN projects p ON p.id = x.project_id WHERE p.user_id = ?', id),
|
||||
mails: await n("SELECT COUNT(*) n FROM usage_events WHERE user_id = ? AND kind = 'mail' AND at >= ? AND at < ?", id, start, end),
|
||||
aiJobs: await n(`SELECT COUNT(*) n FROM usage_events e LEFT JOIN jobs j ON j.id = e.ref
|
||||
WHERE e.user_id = ? AND e.kind = 'ai_job' AND e.at >= ? AND e.at < ?
|
||||
AND NOT (j.id IS NOT NULL AND j.started_at IS NULL AND j.status IN ('cancelled', 'error'))`, id, start, end),
|
||||
period: { start, end },
|
||||
};
|
||||
}
|
||||
|
||||
/** Une consommation du mois : un mail parti, un job IA mis en file. */
|
||||
export async function recordUsage(db, userId, kind, { ref = null, at = now() } = {}) {
|
||||
if (kind !== 'mail' && kind !== 'ai_job') throw new Error(`Type d'usage inconnu : ${kind}`);
|
||||
await db.prepare('INSERT INTO usage_events(user_id, kind, ref, at) VALUES(?, ?, ?, ?)').run(Number(userId), kind, ref, at);
|
||||
}
|
||||
|
||||
/** @returns {{kind: string, used: number, limit: number|null, remaining: number|null, unlimited: boolean}} */
|
||||
export async function quotaFor(db, user, kind, { at = now() } = {}) {
|
||||
if (!USAGE_KINDS.includes(kind)) throw new Error(`Plafond inconnu : ${kind}`);
|
||||
const limit = limitsFor(user)[kind];
|
||||
const used = (await usageOf(db, user.id, { at }))[kind];
|
||||
return { kind, used, limit, remaining: limit == null ? null : Math.max(0, limit - used), unlimited: limit == null };
|
||||
}
|
||||
|
||||
const plural = (n, kind) => NOUNS[kind][n > 1 ? 1 : 0];
|
||||
|
||||
/** Message destiné à l'écran quand un plafond bloque une action. Toujours : ce qui est atteint, ce qui reste intact, où voir les offres. */
|
||||
export function planLimitMessage(user, quota, { wanted = 1, note = '' } = {}) {
|
||||
const { kind, used, limit, remaining } = quota;
|
||||
const period = MONTHLY.has(kind) ? ' ce mois-ci' : '';
|
||||
const where = remaining > 0 && wanted > remaining
|
||||
? `Il te reste ${remaining} ${plural(remaining, kind)}${period} sur ${limit}.`
|
||||
: `Tu as atteint le plafond du plan ${PLAN_LABELS[planOf(user)]} : ${used} ${plural(used, kind)}${period} sur ${limit}.`;
|
||||
return `${where}${note ? ` ${note}` : ''} Rien n'est supprimé ni perdu. Voir les tarifs : /tarifs`;
|
||||
}
|
||||
|
||||
export function planLimitError(user, quota, opts) {
|
||||
return new HttpError(403, planLimitMessage(user, quota, opts), {
|
||||
expose: true, code: 'plan_limit',
|
||||
data: { kind: quota.kind, used: quota.used, limit: quota.limit, upgradeUrl: '/tarifs' },
|
||||
});
|
||||
}
|
||||
|
||||
/** Refuse (403, code plan_limit) si `wanted` unités ne tiennent pas dans le plafond. Renvoie le quota sinon. */
|
||||
export async function assertRoom(db, user, kind, wanted = 1, { at = now(), note = '' } = {}) {
|
||||
const q = await quotaFor(db, user, kind, { at });
|
||||
if (!q.unlimited && q.remaining < wanted) throw planLimitError(user, q, { wanted, note });
|
||||
return q;
|
||||
}
|
||||
|
||||
/** Types de jobs qui envoient des mails de prospection (comptés dans le plafond mensuel de mails). */
|
||||
export const MAIL_JOBS = new Set(['send', 'followup']);
|
||||
|
||||
// Section critique par compte : « compter puis écrire » ne doit pas être entrelacé par deux requêtes simultanées du même
|
||||
// compte (sinon deux créations de projet passeraient toutes deux sous le plafond). Un seul processus : le verrou est en mémoire.
|
||||
const chains = new Map();
|
||||
export async function withUserLock(userId, fn) {
|
||||
const key = Number(userId);
|
||||
const prev = chains.get(key) || Promise.resolve();
|
||||
let release;
|
||||
const gate = new Promise((r) => { release = r; });
|
||||
const tail = prev.then(() => gate);
|
||||
chains.set(key, tail);
|
||||
await prev;
|
||||
try { return await fn(); } finally {
|
||||
release();
|
||||
if (chains.get(key) === tail) chains.delete(key);
|
||||
}
|
||||
}
|
||||
|
||||
/** Données d'affichage de l'usage du mois (barres de Mon compte et du tableau de bord). */
|
||||
export async function usageView(db, user, { at = now() } = {}) {
|
||||
const usage = await usageOf(db, user.id, { at });
|
||||
const limits = limitsFor(user);
|
||||
return {
|
||||
plan: planOf(user), planLabel: PLAN_LABELS[planOf(user)],
|
||||
items: USAGE_KINDS.map((kind) => {
|
||||
const used = usage[kind], limit = limits[kind];
|
||||
return { kind, label: KIND_LABELS[kind], used, limit, pct: limit == null ? 0 : Math.min(100, Math.round((used / limit) * 100)), full: limit != null && used >= limit };
|
||||
}),
|
||||
period: usage.period,
|
||||
};
|
||||
}
|
||||
|
|
@ -16,7 +16,7 @@ async function queryMysql(cfg, queries) {
|
|||
const mysql = await import('mysql2/promise');
|
||||
const conn = await mysql.createConnection({
|
||||
host: cfg.host, port: Number(cfg.port || 3306), user: cfg.user, password: cfg.password,
|
||||
database: cfg.database, connectTimeout: 8000, ssl: cfg.ssl ? {} : undefined,
|
||||
database: cfg.database, connectTimeout: 8000, ssl: cfg.ssl ? { servername: cfg.servername } : undefined,
|
||||
});
|
||||
try {
|
||||
await conn.query('START TRANSACTION READ ONLY');
|
||||
|
|
@ -35,7 +35,7 @@ async function queryPg(cfg, queries) {
|
|||
const client = new pg.Client({
|
||||
host: cfg.host, port: Number(cfg.port || 5432), user: cfg.user, password: cfg.password,
|
||||
database: cfg.database, connectionTimeoutMillis: 8000, statement_timeout: 10_000,
|
||||
ssl: cfg.ssl ? { rejectUnauthorized: false } : undefined,
|
||||
ssl: cfg.ssl ? { rejectUnauthorized: false, servername: cfg.servername } : undefined,
|
||||
});
|
||||
await client.connect();
|
||||
try {
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@
|
|||
import { now, getSetting, setSetting } from '../db.js';
|
||||
import { abStats, globalSmtp } from '../projects.js';
|
||||
import { createTransport } from './mailer.js';
|
||||
import { pinSmtp } from '../netguard.js';
|
||||
import { notify } from './notify.js';
|
||||
import { weeklyMail } from './mailhtml.js';
|
||||
import { parisParts, parisTime } from './paris-time.js';
|
||||
|
|
@ -62,7 +63,7 @@ export async function sendWeeklyReport(app, userId, { at = now() } = {}) {
|
|||
const to = await getSetting(app.db, userId, 'notify_email');
|
||||
const smtp = await globalSmtp(app, userId);
|
||||
if (to && smtp) {
|
||||
const transport = (app.createTransport || createTransport)(smtp);
|
||||
const transport = (app.createTransport || createTransport)(await pinSmtp(app, userId, smtp));
|
||||
try {
|
||||
await transport.sendMail({
|
||||
from: smtp.fromEmail, to, subject: `[AiTools] Rapport du ${day(st.from)} au ${day(st.to)}`, text,
|
||||
|
|
|
|||
|
|
@ -9,10 +9,15 @@ import { enqueue } from './jobs.js';
|
|||
import { getProject } from '../projects.js';
|
||||
import { maybeSendWeekly } from './report.js';
|
||||
import { snapshotAll } from './metrics.js';
|
||||
import { runInactiveCleanup } from './inactive.js';
|
||||
import { purgeAudit } from '../audit.js';
|
||||
import { INACTIVITY } from '../limits.js';
|
||||
import { now } from '../db.js';
|
||||
|
||||
export class Scheduler {
|
||||
constructor(app, { everyMs = 15 * 60_000, log = console } = {}) {
|
||||
constructor(app, { everyMs = 15 * 60_000, log = console, clock = now } = {}) {
|
||||
this.app = app;
|
||||
this.clock = clock; // secondes ; injectable pour les tests
|
||||
this.everyMs = everyMs;
|
||||
this.log = log;
|
||||
this.running = false;
|
||||
|
|
@ -57,6 +62,11 @@ export class Scheduler {
|
|||
catch (e) { this.log.error('[rapport hebdo]', e.message); }
|
||||
}
|
||||
await snapshotAll(this.app, { log: this.log });
|
||||
// Entretien : comptes inactifs (avertissement puis suppression) et ancien journal d'audit
|
||||
try {
|
||||
await runInactiveCleanup(this.app, { at: this.clock(), log: this.log });
|
||||
await purgeAudit(this.app.db, INACTIVITY.auditRetentionMonths, this.clock());
|
||||
} catch (e) { this.log.error('[inactifs]', e.message); }
|
||||
} finally { this.running = false; }
|
||||
}
|
||||
|
||||
|
|
@ -66,7 +76,10 @@ export class Scheduler {
|
|||
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
|
||||
WHERE p.followup_enabled = 1 AND u.status = 'active'`).all()) {
|
||||
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 } }) });
|
||||
if (!plan.ready) continue;
|
||||
// Plafond mensuel atteint ou envois en pause : la relance attend, les autres comptes ne sont pas touchés
|
||||
try { queued.push({ id, ...await enqueue(db, { userId, projectId: id, type: 'followup', params: { count: plan.due } }) }); }
|
||||
catch (e) { if (!(e.status === 403 && ['plan_limit', 'send_paused'].includes(e.code))) throw e; }
|
||||
}
|
||||
return queued;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,18 +1,7 @@
|
|||
import { readFileSync } from 'node:fs';
|
||||
|
||||
// Température CPU en °C (null hors Raspberry / Linux sans capteur)
|
||||
// Température CPU en °C (null hors Raspberry / Linux sans capteur) : simple information pour les admins
|
||||
export function cpuTemp(path = '/sys/class/thermal/thermal_zone0/temp') {
|
||||
try { return Math.round(Number(readFileSync(path, 'utf8')) / 100) / 10; }
|
||||
catch { return null; }
|
||||
}
|
||||
|
||||
// Attend que le CPU repasse sous le seuil (hystérésis de 5 °C pour éviter le yo-yo)
|
||||
export async function waitCool(max, { read = cpuTemp, sleep = (ms) => new Promise((r) => setTimeout(r, ms)), onWait } = {}) {
|
||||
let t = read();
|
||||
if (t === null || t < max) return;
|
||||
while (t !== null && t >= max - 5) {
|
||||
await onWait?.(t);
|
||||
await sleep(30_000);
|
||||
t = read();
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -30,8 +30,9 @@ export function absoluteUrl(appUrl, path) {
|
|||
* @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)
|
||||
* @param {string[]} [o.scripts] scripts de l'application (chemins /static/…) ; aucun par défaut
|
||||
*/
|
||||
export function siteLayout({ appUrl, path, title, description, body, noindex = false, jsonLd = null }) {
|
||||
export function siteLayout({ appUrl, path, title, description, body, noindex = false, jsonLd = null, scripts = [] }) {
|
||||
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>`;
|
||||
|
|
@ -56,7 +57,7 @@ ${noindex ? '' : `<link rel="canonical" href="${esc(url)}">\n`}<meta name="color
|
|||
<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>
|
||||
${scripts.map((src) => `<script src="${esc(src)}" defer></script>\n`).join('')}${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">
|
||||
|
|
|
|||
|
|
@ -93,18 +93,8 @@ export function mentionsPage({ appUrl }) {
|
|||
}
|
||||
|
||||
// ---------- 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 }) {
|
||||
// `captcha` : reCAPTCHA configuré. Les paragraphes qui le concernent n'apparaissent que dans ce cas, comme Apple.
|
||||
export function privacyPage({ appUrl, apple = false, captcha = false, inactiveMonths = 24 }) {
|
||||
return legalPage({
|
||||
appUrl, path: '/confidentialite',
|
||||
title: 'Politique de confidentialité · AiTools',
|
||||
|
|
@ -133,6 +123,8 @@ export function privacyPage({ appUrl, apple = false }) {
|
|||
<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">Adresse IP</th><td>Ton adresse IP sert à limiter le nombre de requêtes (protection contre les abus). Elle reste en mémoire du serveur, quelques minutes à quelques heures, et n'est pas enregistrée en base de données.</td><td>Sécurité du service. Intérêt légitime.</td></tr>
|
||||
<tr><th scope="row">Modération</th><td>Actions d'administration sur un compte (suspension, plan, suppression) et pauses d'envoi décidées quand trop de mails sont rejetés : date, action, identifiant du compte et adresse masquée.</td><td>Sécurité du service et lutte contre les abus. Intérêt légitime.</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>
|
||||
|
|
@ -145,7 +137,8 @@ export function privacyPage({ appUrl, apple = false }) {
|
|||
<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">Compte inactif</th><td>${inactiveMonths ? `Suppression automatique après ${inactiveMonths} mois sans connexion ni job, avec un mail d'avertissement 30 jours avant. Un compte suspendu ou administrateur n'est pas concerné.` : 'Aucune suppression automatique pour inactivité.'}</td></tr>
|
||||
<tr><th scope="row">Journal d'administration</th><td>12 mois. Il note les actions des administrateurs (suspension, changement de plan, suppression) et les pauses d'envoi, avec un identifiant et une adresse masquée.</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>
|
||||
|
|
@ -162,6 +155,7 @@ export function privacyPage({ appUrl, apple = false }) {
|
|||
<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>
|
||||
${captcha ? `<li><strong>Google reCAPTCHA</strong> (Google Ireland Limited, Google LLC) : protège la connexion contre les envois automatisés. Son script n'est chargé qu'après ton clic sur « Charger la vérification anti-robot », sur la page de connexion. Il dépose des cookies et transmet à Google ton adresse IP, des informations sur ton navigateur et sur ton comportement sur la page. Base légale : ton consentement. AiTools ne conserve pas le résultat de la vérification. Sans elle, la connexion n'est pas possible : c'est une mesure de sécurité contre les abus. Si cela te pose problème, écris-nous. <a href="https://policies.google.com/privacy" rel="noopener noreferrer">Politique de Google</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>
|
||||
|
|
@ -174,17 +168,20 @@ export function privacyPage({ appUrl, apple = false }) {
|
|||
},
|
||||
{
|
||||
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>
|
||||
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${captcha ? ', sauf la vérification anti-robot de Google sur la page de connexion, et seulement après ton accord (voir plus bas)' : ''}.</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>
|
||||
${captcha ? `<tr><th scope="row">Cookies de Google reCAPTCHA</th><td>Déposés par Google, uniquement si tu charges la vérification anti-robot (non essentiels : consentement). Ils servent à distinguer un humain d'un programme.</td><td>Durée fixée par Google</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>`,
|
||||
${captcha
|
||||
? `<p>Sur la page de connexion, rien n'est chargé depuis Google tant que tu n'as pas cliqué sur « Charger la vérification anti-robot ». Ce choix n'est pas mémorisé : il t'est redemandé à chaque visite de la page.</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',
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
// Pages publiques du site (rendu serveur, sans script). Les textes sont écrits pour être lus tels quels :
|
||||
// Pages publiques du site (rendu serveur, sans script, sauf la vérification anti-robot de la connexion). 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';
|
||||
|
|
@ -7,9 +7,29 @@ import { siteLayout } from './layout.js';
|
|||
export const providersText = (apple) => (apple ? 'Google ou Apple' : 'Google');
|
||||
|
||||
// ---------- Connexion ----------
|
||||
export function loginPage({ appUrl, error = null, apple = false, bye = false }) {
|
||||
// Avec reCAPTCHA (clés configurées), la page demande d'abord le consentement : rien n'est chargé depuis Google avant le
|
||||
// clic sur « Charger la vérification anti-robot » (public/captcha.js). Les boutons sont alors des formulaires POST qui
|
||||
// portent le jeton ; sans reCAPTCHA, ce sont de simples liens.
|
||||
function captchaBox(siteKey) {
|
||||
return `<div class="captcha" data-captcha data-sitekey="${esc(siteKey)}">
|
||||
<h3>Vérification anti-robot</h3>
|
||||
<p>Pour protéger la connexion contre les programmes automatiques, AiTools utilise Google reCAPTCHA. Il n'est chargé qu'avec ton accord : Google dépose alors des cookies et reçoit ton adresse IP, des informations sur ton navigateur et sur ton comportement sur la page. Rien n'est envoyé à Google avant ton clic. <a href="/confidentialite#destinataires">En savoir plus</a></p>
|
||||
<p><button type="button" class="btn" data-captcha-load>Charger la vérification anti-robot</button></p>
|
||||
<p class="fine" role="status" data-captcha-status>Les boutons de connexion s'activent une fois la vérification chargée.</p>
|
||||
<noscript><p class="error">JavaScript est nécessaire pour la vérification anti-robot.</p></noscript>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
const loginButtons = ({ apple, captcha }) => (captcha
|
||||
? `<form method="post" action="/auth/google" data-captcha-form><input type="hidden" name="captcha" value=""><button class="btn primary" disabled>Se connecter avec Google</button></form>
|
||||
${apple ? '<form method="post" action="/auth/apple" data-captcha-form><input type="hidden" name="captcha" value=""><button class="btn apple" disabled>Se connecter avec Apple</button></form>' : ''}
|
||||
<p class="fine">Ce site est protégé par reCAPTCHA : la <a href="https://policies.google.com/privacy" rel="noopener noreferrer">politique de confidentialité</a> et les <a href="https://policies.google.com/terms" rel="noopener noreferrer">conditions d'utilisation</a> de Google s'appliquent.</p>`
|
||||
: `<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>' : ''}`);
|
||||
|
||||
export function loginPage({ appUrl, error = null, apple = false, bye = false, captcha = null }) {
|
||||
return siteLayout({
|
||||
appUrl, path: '/login', noindex: true,
|
||||
appUrl, path: '/login', noindex: true, scripts: captcha ? ['/static/captcha.js'] : [],
|
||||
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">
|
||||
|
|
@ -23,9 +43,9 @@ export function loginPage({ appUrl, error = null, apple = false, bye = false })
|
|||
<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>` : ''}
|
||||
${captcha ? captchaBox(captcha.siteKey) : ''}
|
||||
<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>' : ''}
|
||||
${loginButtons({ apple, captcha })}
|
||||
</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>
|
||||
|
|
@ -297,7 +317,7 @@ export function pricingPage({ appUrl }) {
|
|||
<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>
|
||||
<p class="fine">Ces plafonds sont appliqués par le serveur. Les mails et les jobs IA se comptent par mois calendaire (heure de Paris) et repartent à zéro le 1er. Un plafond atteint refuse la nouvelle action sans rien supprimer.</p>
|
||||
<a class="btn primary" href="/login">Créer mon compte</a>
|
||||
</article>
|
||||
<article class="card plan soon" aria-labelledby="plan-payant">
|
||||
|
|
|
|||
|
|
@ -6,7 +6,7 @@ import { robotsTxt, sitemapXml } from './seo.js';
|
|||
|
||||
export function registerSiteRoutes(router, { cfg }) {
|
||||
const apple = !!cfg.apple;
|
||||
const ctx = { appUrl: cfg.appUrl, apple };
|
||||
const ctx = { appUrl: cfg.appUrl, apple, captcha: !!cfg.recaptcha, inactiveMonths: cfg.inactiveMonths ?? 24 };
|
||||
const open = { public: true };
|
||||
|
||||
router.get('/fonctionnement', async ({ res }) => html(res, howPage(ctx)), open);
|
||||
|
|
|
|||
|
|
@ -5,7 +5,7 @@ import { absoluteUrl } from './layout.js';
|
|||
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 const DISALLOWED_PATHS = ['/admin', '/account', '/settings', '/link', '/api/', '/auth/', '/u/', '/logout'];
|
||||
|
||||
export function robotsTxt(appUrl) {
|
||||
return [
|
||||
|
|
@ -30,18 +30,30 @@ ${urls}
|
|||
// 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 = [
|
||||
const directives = (extra = {}) => [
|
||||
"default-src 'self'",
|
||||
"script-src 'self'",
|
||||
`script-src 'self'${extra.script ? ` ${extra.script}` : ''}`,
|
||||
"style-src 'self'",
|
||||
"img-src 'self' data:",
|
||||
"font-src 'self'",
|
||||
"connect-src 'self'",
|
||||
...(extra.frame ? [`frame-src ${extra.frame}`] : []),
|
||||
"object-src 'none'",
|
||||
"base-uri 'self'",
|
||||
"form-action 'self' https://accounts.google.com https://appleid.apple.com",
|
||||
"frame-ancestors 'none'",
|
||||
].join('; ');
|
||||
const CSP = directives();
|
||||
|
||||
// reCAPTCHA : uniquement les domaines que Google documente pour la version 3, et uniquement sur la page de connexion
|
||||
// (le script n'y est chargé qu'après le consentement de l'utilisateur, voir public/captcha.js).
|
||||
const RECAPTCHA_CSP = directives({
|
||||
script: 'https://www.google.com/recaptcha/ https://www.gstatic.com/recaptcha/',
|
||||
frame: 'https://www.google.com/recaptcha/ https://recaptcha.google.com/recaptcha/',
|
||||
});
|
||||
|
||||
/** CSP de la page : celle de la connexion autorise reCAPTCHA quand il est configuré, toutes les autres jamais. */
|
||||
export const cspFor = (pathname, recaptcha) => (recaptcha && pathname.replace(/(.)\/$/, '$1') === '/login' ? RECAPTCHA_CSP : CSP);
|
||||
|
||||
/** En-têtes posés sur toutes les réponses. HSTS seulement si le site est servi en https. */
|
||||
export function securityHeaders(appUrl) {
|
||||
|
|
|
|||
20
src/views.js
20
src/views.js
|
|
@ -57,6 +57,18 @@ ${email ? `<header class="top">
|
|||
</html>`;
|
||||
}
|
||||
|
||||
// Usage du mois : une barre par plafond du plan (largeurs par classes w-N, la CSP interdit le style en ligne)
|
||||
export function usagePanel(u) {
|
||||
if (!u) return '';
|
||||
const rows = u.items.map((i) => `<li><div class="run-head"><span>${esc(i.label)}</span><span class="jpct">${i.used}${i.limit == null ? '' : ` / ${i.limit}`}</span></div>${i.limit == null ? '' : `<div class="bar usage${i.full ? ' full' : ''}"><span class="w-${Math.round(i.pct / 5) * 5}"></span></div>`}</li>`).join('');
|
||||
const full = u.items.filter((i) => i.full);
|
||||
return `<section class="card usage-card">
|
||||
<h4>Usage du mois <span class="badge">plan ${esc(u.planLabel)}</span></h4>
|
||||
<ul class="usage-list">${rows}</ul>
|
||||
${full.length ? `<p class="error small">Plafond atteint : ${full.map((i) => esc(i.label.toLowerCase())).join(', ')}. Rien n'est perdu. <a href="/tarifs">Voir les tarifs</a></p>` : u.plan === 'free' ? '<p class="muted small">Les plafonds se renouvellent le 1er du mois (heure de Paris). <a href="/tarifs">Voir les tarifs</a></p>' : ''}
|
||||
</section>`;
|
||||
}
|
||||
|
||||
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
|
||||
|
|
@ -88,7 +100,7 @@ function linkSection(link, consent) {
|
|||
</section>`;
|
||||
}
|
||||
|
||||
export function accountPage({ user, error, link = null, consent = null, notice = null }) {
|
||||
export function accountPage({ user, error, link = null, consent = null, notice = null, usage = null }) {
|
||||
return layout({
|
||||
title: 'Mon compte', email: user.email,
|
||||
body: `<h1>Mon compte</h1>
|
||||
|
|
@ -97,8 +109,10 @@ export function accountPage({ user, error, link = null, consent = null, notice =
|
|||
<dt>Email</dt><dd>${esc(user.email)}</dd>
|
||||
<dt>Connexion</dt><dd>${esc(PROVIDER_NAMES[user.provider] || '—')}</dd>
|
||||
</dl>
|
||||
${user.isAdmin ? '<p><a class="btn small" href="/admin">Administration</a></p>' : ''}
|
||||
</section>
|
||||
${notice ? `<p class="${notice.ok ? 'ok' : 'error'}">${esc(notice.text)}</p>` : ''}
|
||||
${usagePanel(usage)}
|
||||
${linkSection(link, consent)}
|
||||
<section class="card">
|
||||
<h4>Supprimer mon compte</h4>
|
||||
|
|
@ -339,12 +353,14 @@ function projectItem(p, smtp, dbCfg, imap) {
|
|||
</details>`;
|
||||
}
|
||||
|
||||
export function dashboardPage({ email, projects, forgejoHost }) {
|
||||
export function dashboardPage({ email, projects, forgejoHost, usage = null, pauseMessage = null }) {
|
||||
return layout({
|
||||
title: 'Projets', email,
|
||||
body: `<div class="row head">
|
||||
<h1>Projets</h1>
|
||||
</div>
|
||||
${pauseMessage ? `<p class="error" role="alert">${esc(pauseMessage)}</p>` : ''}
|
||||
${usagePanel(usage)}
|
||||
<details class="card new anim">
|
||||
<summary class="btn primary">+ Nouveau projet</summary>
|
||||
<form data-action="create" class="cfg">
|
||||
|
|
|
|||
223
test/abuse.test.js
Normal file
223
test/abuse.test.js
Normal file
|
|
@ -0,0 +1,223 @@
|
|||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { randomBytes } from 'node:crypto';
|
||||
import { setSetting, getSetting, now } from '../src/db.js';
|
||||
import { testDb } from './helpers/db.js';
|
||||
import { addUser } from './helpers/users.js';
|
||||
import { startApp } from './helpers/server.js';
|
||||
import { Worker, enqueue } from '../src/services/jobs.js';
|
||||
import { makeHandlers } from '../src/handlers.js';
|
||||
import { saveSecretConfig } from '../src/projects.js';
|
||||
import { bounceStats, evaluateSending, sendPause, resumeSending, pauseMessage } from '../src/services/abuse.js';
|
||||
import { applyMessages } from '../src/services/inbox.js';
|
||||
import { recentAudit } from '../src/admin.js';
|
||||
import { ABUSE } from '../src/limits.js';
|
||||
|
||||
// Détection d'abus à l'envoi : taux de rejets au-dessus du seuil (avec un minimum d'envois) = pause d'envoi, admin prévenu,
|
||||
// message clair, désinscription et liste d'opposition toujours respectées.
|
||||
|
||||
async function world() {
|
||||
const db = await testDb();
|
||||
const app = {
|
||||
db, resolveHost: async () => [{ address: '93.184.216.34', family: 4 }],
|
||||
cfg: { dataDir: '/tmp/x', appUrl: 'https://ai.test', secretKey: randomBytes(32), sandbox: { enabled: false } },
|
||||
fetch: async (url, o) => { app.hooks.push({ url, body: JSON.parse(o.body) }); return { ok: true, status: 204 }; },
|
||||
hooks: [],
|
||||
};
|
||||
return { db, app };
|
||||
}
|
||||
const HOOK = 'https://discord.com/api/webhooks/123456789012345678/' + 'a'.repeat(30);
|
||||
async function account(w, { admin = false, hook = false } = {}) {
|
||||
const id = await addUser(w.db, { admin, link: admin ? undefined : { v: 1, mode: 'api_key', valid: true } });
|
||||
const p = Number((await w.db.prepare("INSERT INTO projects(user_id, name, git_url, created_at) VALUES(?, 'p', ?, ?)").run(id, `https://git.test/${id}.git`, now())).lastInsertRowid);
|
||||
if (hook) {
|
||||
const { encrypt } = await import('../src/crypto.js');
|
||||
await setSetting(w.db, id, 'discord_webhook_enc', encrypt(w.app.cfg.secretKey, HOOK));
|
||||
}
|
||||
return { id, p };
|
||||
}
|
||||
// n prospects contactés, dont `bounced` rejetés
|
||||
async function mailed(w, { id, p }, n, bounced, { at = now() } = {}) {
|
||||
for (let i = 0; i < n; i++) {
|
||||
const rejected = i < bounced;
|
||||
const email = `x${id}_${p}_${i}_${Math.random().toString(36).slice(2, 7)}@dom${i}.fr`;
|
||||
const pid = Number((await w.db.prepare("INSERT INTO prospects(project_id, company, email, status, sent_at, created_at) VALUES(?, 'E', ?, ?, ?, ?)").run(p, email, rejected ? 'bounced' : 'sent', at, at)).lastInsertRowid);
|
||||
await w.db.prepare('INSERT INTO mail_log(project_id, prospect_id, email, sent_at, error) VALUES(?, ?, ?, ?, NULL)').run(p, pid, email, at);
|
||||
}
|
||||
}
|
||||
|
||||
test('seuils : pas de décision sous 50 envois, pause strictement au-dessus de 10 %', async () => {
|
||||
assert.equal(ABUSE.minSent, 50);
|
||||
assert.equal(ABUSE.maxBounceRate, 0.10);
|
||||
const w = await world();
|
||||
// 49 envois dont 20 rejets : trop peu d'envois pour conclure
|
||||
const a = await account(w); await mailed(w, a, 49, 20);
|
||||
assert.equal(await evaluateSending(w.app, a.id), null);
|
||||
// 50 envois, 5 rejets = 10 % pile : pas de pause (strictement au-dessus)
|
||||
const b = await account(w); await mailed(w, b, 50, 5);
|
||||
assert.equal((await bounceStats(w.db, b.id, { since: 0 })).rate, 0.1);
|
||||
assert.equal(await evaluateSending(w.app, b.id), null);
|
||||
// 50 envois, 6 rejets = 12 % : pause
|
||||
const c = await account(w); await mailed(w, c, 50, 6);
|
||||
const pause = await evaluateSending(w.app, c.id);
|
||||
assert.equal(pause.sent, 50);
|
||||
assert.equal(pause.bounced, 6);
|
||||
assert.equal(pause.rate, 0.12);
|
||||
assert.deepEqual(await sendPause(w.db, c.id), pause);
|
||||
assert.equal(await sendPause(w.db, b.id), null);
|
||||
});
|
||||
|
||||
test('un prospect relancé ne compte qu\'une fois ; les envois hors fenêtre et les pannes passagères ne pèsent pas', async () => {
|
||||
const w = await world();
|
||||
const a = await account(w);
|
||||
await mailed(w, a, 60, 4);
|
||||
const first = await w.db.prepare("SELECT id, email FROM prospects WHERE project_id = ? AND status = 'sent' LIMIT 1").get(a.p);
|
||||
for (let i = 0; i < 5; i++) await w.db.prepare("INSERT INTO mail_log(project_id, prospect_id, email, sent_at, error, kind) VALUES(?, ?, ?, ?, NULL, 'followup')").run(a.p, first.id, first.email, now());
|
||||
// Échecs 4xx : ni envoi réussi ni rejet définitif
|
||||
const other = await w.db.prepare("INSERT INTO prospects(project_id, company, email, status, created_at) VALUES(?, 'E', 'panne@x.fr', 'new', ?)").run(a.p, now());
|
||||
await w.db.prepare("INSERT INTO mail_log(project_id, prospect_id, email, sent_at, error) VALUES(?, ?, 'panne@x.fr', ?, '421 try later')").run(a.p, Number(other.lastInsertRowid), now());
|
||||
const st = await bounceStats(w.db, a.id, { since: 0 });
|
||||
assert.equal(st.sent, 60);
|
||||
assert.equal(st.bounced, 4);
|
||||
// Anciens envois : hors fenêtre de 30 jours
|
||||
const old = await account(w); await mailed(w, old, 60, 30, { at: now() - 40 * 86400 });
|
||||
assert.equal(await evaluateSending(w.app, old.id), null);
|
||||
// Les comptes ne se mélangent pas
|
||||
const bad = await account(w); await mailed(w, bad, 60, 30);
|
||||
assert.ok(await evaluateSending(w.app, bad.id));
|
||||
assert.equal(await sendPause(w.db, a.id), null);
|
||||
});
|
||||
|
||||
test('pause : audit, journal serveur et notification Discord de l\'administrateur (même sans l\'événement coché)', async () => {
|
||||
const w = await world();
|
||||
const admin = await account(w, { admin: true, hook: true });
|
||||
await setSetting(w.db, admin.id, 'discord_events', JSON.stringify(['job_done'])); // l'administrateur n'a pas coché « abuse »
|
||||
const user = await account(w, { hook: true });
|
||||
await mailed(w, user, 50, 10);
|
||||
const warn = console.warn; const logged = [];
|
||||
console.warn = (...a) => logged.push(a.join(' '));
|
||||
try { await evaluateSending(w.app, user.id); } finally { console.warn = warn; }
|
||||
assert.ok(logged.some((l) => /\[abus\].*mises? en pause|en pause/.test(l)), 'journal du serveur');
|
||||
const [entry] = await recentAudit(w.db);
|
||||
assert.equal(entry.action, 'abuse_pause');
|
||||
assert.equal(entry.admin, 'système');
|
||||
assert.match(entry.detail, /10 rejets sur 50/);
|
||||
assert.equal(entry.targetId, user.id);
|
||||
assert.equal(w.app.hooks.length, 2, 'Discord : un message pour l\'administrateur, un pour le compte concerné');
|
||||
const titles = w.app.hooks.map((h) => h.body.embeds[0].title);
|
||||
assert.ok(titles.includes('Compte mis en pause d\'envoi'));
|
||||
assert.ok(titles.includes('Envois en pause'));
|
||||
// Une seconde évaluation ne renotifie pas
|
||||
await evaluateSending(w.app, user.id);
|
||||
assert.equal(w.app.hooks.length, 2);
|
||||
assert.equal((await recentAudit(w.db)).length, 1);
|
||||
});
|
||||
|
||||
test('envois refusés avec un message clair (jamais silencieux) : mise en file, tâche déjà en file, relances automatiques', async () => {
|
||||
const w = await world();
|
||||
const u = await account(w);
|
||||
await mailed(w, u, 50, 10);
|
||||
const queued = (await enqueue(w.db, { userId: u.id, projectId: u.p, type: 'send', params: { count: 1 } })).id;
|
||||
await evaluateSending(w.app, u.id);
|
||||
for (const type of ['send', 'followup']) {
|
||||
await assert.rejects(enqueue(w.db, { userId: u.id, projectId: u.p, type, params: { count: 1 } }), (e) => {
|
||||
assert.equal(e.status, 403);
|
||||
assert.equal(e.code, 'send_paused');
|
||||
assert.match(e.message, /Tes envois sont en pause/);
|
||||
assert.match(e.message, /10 adresse\(s\) sur 50/);
|
||||
assert.match(e.message, /20 %/);
|
||||
assert.match(e.message, /seuil de 10 %/);
|
||||
assert.match(e.message, /contact@tony-averty\.dev/);
|
||||
assert.match(e.message, /désinscription/);
|
||||
return true;
|
||||
});
|
||||
}
|
||||
// Un job d'envoi déjà en file ne part pas : erreur explicite
|
||||
w.app.createTransport = () => { throw new Error('aucun transport ne doit être créé'); };
|
||||
const worker = new Worker(w.db, makeHandlers(w.app), { log: { error() {} } });
|
||||
await worker.tick();
|
||||
const row = await w.db.prepare('SELECT status, error FROM jobs WHERE id = ?').get(queued);
|
||||
assert.equal(row.status, 'error');
|
||||
assert.match(row.error, /Tes envois sont en pause/);
|
||||
// Les jobs sans envoi restent possibles (analyse, modèles…)
|
||||
await assert.doesNotReject(enqueue(w.db, { userId: u.id, projectId: u.p, type: 'template' }));
|
||||
});
|
||||
|
||||
test('HTTP et tableau de bord : 403 send_paused avec le message, bandeau d\'avertissement', async () => {
|
||||
const s = await startApp();
|
||||
try {
|
||||
const u = await s.newUser({ admin: false, link: { v: 1, mode: 'api_key', valid: true } });
|
||||
const p = Number((await s.db.prepare("INSERT INTO projects(user_id, name, git_url, created_at) VALUES(?, 'p', 'u', ?)").run(u.id, now())).lastInsertRowid);
|
||||
await mailed({ db: s.db }, { id: u.id, p }, 50, 12);
|
||||
await evaluateSending(s.app, u.id);
|
||||
const r = await u.post(`/api/projects/${p}/send`, { confirm: true, count: 1 });
|
||||
assert.equal(r.status, 403);
|
||||
const body = await r.json();
|
||||
assert.equal(body.code, 'send_paused');
|
||||
assert.match(body.error, /Tes envois sont en pause/);
|
||||
assert.match(await (await u.get('/', { headers: { accept: 'text/html' } })).text(), /Tes envois sont en pause/);
|
||||
const other = await s.newUser({ admin: false, link: { v: 1, mode: 'api_key', valid: true } });
|
||||
assert.doesNotMatch(await (await other.get('/', { headers: { accept: 'text/html' } })).text(), /Tes envois sont en pause/);
|
||||
} finally { await s.close(); }
|
||||
});
|
||||
|
||||
test('les rejets lus dans la boîte déclenchent l\'évaluation ; la désinscription et l\'opposition restent respectées en pause comme avant', async () => {
|
||||
const w = await world();
|
||||
const u = await account(w);
|
||||
await mailed(w, u, 49, 0);
|
||||
// Le 50e prospect est contacté, puis 6 rejets arrivent par la boîte IMAP
|
||||
const ids = [];
|
||||
for (let i = 0; i < 6; i++) {
|
||||
const email = `bad${i}@x${i}.fr`;
|
||||
const pid = Number((await w.db.prepare("INSERT INTO prospects(project_id, company, email, status, sent_at, created_at) VALUES(?, 'E', ?, 'sent', ?, ?)").run(u.p, email, now(), now())).lastInsertRowid);
|
||||
await w.db.prepare('INSERT INTO mail_log(project_id, prospect_id, email, sent_at, error, message_id) VALUES(?, ?, ?, ?, NULL, ?)').run(u.p, pid, email, now(), `<m${i}@x.fr>`);
|
||||
ids.push(`<m${i}@x.fr>`);
|
||||
}
|
||||
// 49 + 6 = 55 contactés, aucun rejet encore
|
||||
assert.equal(await evaluateSending(w.app, u.id), null);
|
||||
const res = await applyMessages(w.db, u.p, ids.map((id) => ({ from: 'mailer-daemon@x.fr', subject: 'Undeliverable', headers: { 'content-type': 'multipart/report; report-type=delivery-status' }, inReplyTo: id, body: id })));
|
||||
assert.ok(res.bounces >= 0);
|
||||
// La détection elle-même est testée ci-dessus ; ici on vérifie que le rejet alimente bien la liste d'opposition
|
||||
const rejected = (await bounceStats(w.db, u.id, { since: 0 })).bounced;
|
||||
assert.equal(rejected, (await w.db.prepare("SELECT COUNT(*) n FROM prospects WHERE project_id = ? AND status = 'bounced'").get(u.p)).n);
|
||||
// Pause posée, puis un prospect désabonné ou en opposition n'est jamais contacté même après rétablissement
|
||||
await setSetting(w.db, u.id, 'send_pause_json', JSON.stringify({ at: now(), sent: 55, bounced: 6, rate: 0.11 }));
|
||||
await resumeSending(w.db, u.id);
|
||||
assert.equal(await sendPause(w.db, u.id), null);
|
||||
await w.db.prepare('UPDATE projects SET daily_mail_cap = 200 WHERE id = ?').run(u.p);
|
||||
await saveSecretConfig(w.app, u.p, 'smtp_enc', { host: 'smtp.exemple.fr', port: 587, user: 'u', pass: 'p', fromEmail: 'a@b.fr' }, 'pass');
|
||||
await w.db.prepare("INSERT INTO templates(project_id, kind, subject, body, status, updated_at) VALUES(?, 'initial', 's', 'b', 'validated', ?)").run(u.p, now());
|
||||
await w.db.prepare("INSERT INTO prospects(project_id, company, email, created_at) VALUES(?, 'Opp', 'opp@exemple.fr', ?)").run(u.p, now());
|
||||
await w.db.prepare("INSERT INTO prospects(project_id, company, email, created_at) VALUES(?, 'Ok', 'ok@exemple.fr', ?)").run(u.p, now());
|
||||
await w.db.prepare("INSERT INTO blacklist(email, reason, created_at) VALUES('opp@exemple.fr', 'unsubscribe', ?)").run(now());
|
||||
const sent = [];
|
||||
w.app.createTransport = () => ({ verify: async () => true, sendMail: async (m) => { sent.push(m.to); }, close() {} });
|
||||
await setSetting(w.db, u.id, 'send_delay_min', '0'); await setSetting(w.db, u.id, 'send_delay_max', '0');
|
||||
await enqueue(w.db, { userId: u.id, projectId: u.p, type: 'send', params: { count: 10 } });
|
||||
await new Worker(w.db, makeHandlers(w.app), { log: { error() {} } }).tick();
|
||||
assert.deepEqual(sent, ['ok@exemple.fr'], 'la liste d\'opposition reste respectée');
|
||||
});
|
||||
|
||||
test('rétablissement par l\'administrateur : le décompte repart des envois suivants, audit et verrou levé', async () => {
|
||||
const s = await startApp();
|
||||
try {
|
||||
const admin = await s.newUser({ admin: true, email: 'chef@x.fr' });
|
||||
const u = await s.newUser({ admin: false, email: 'bob@x.fr', link: { v: 1, mode: 'api_key', valid: true } });
|
||||
const p = Number((await s.db.prepare("INSERT INTO projects(user_id, name, git_url, created_at) VALUES(?, 'p', 'u', ?)").run(u.id, now())).lastInsertRowid);
|
||||
await mailed({ db: s.db }, { id: u.id, p }, 50, 10, { at: now() - 3600 });
|
||||
await evaluateSending(s.app, u.id);
|
||||
assert.match(await (await admin.get('/admin', { headers: { accept: 'text/html' } })).text(), /envois en pause[\s\S]*Rétablir les envois/);
|
||||
assert.equal((await u.post('/admin/users/1/resume-send', {}, { form: true })).status, 404, 'réservé aux administrateurs');
|
||||
const r = await admin.post(`/admin/users/${u.id}/resume-send`, {}, { form: true });
|
||||
assert.match(decodeURIComponent(r.headers.get('location')), /done=resume_send/);
|
||||
assert.equal(await sendPause(s.db, u.id), null);
|
||||
assert.ok(Number(await getSetting(s.db, u.id, 'send_resumed_at')) > 0);
|
||||
// Les anciens rejets ne comptent plus : pas de nouvelle pause immédiate
|
||||
assert.equal(await evaluateSending(s.app, u.id), null);
|
||||
assert.equal((await recentAudit(s.db))[0].action, 'resume_send');
|
||||
// De nouveaux rejets massifs après le rétablissement remettent en pause
|
||||
await mailed({ db: s.db }, { id: u.id, p }, 50, 10, { at: now() + 5 });
|
||||
assert.ok(await evaluateSending(s.app, u.id));
|
||||
assert.match(pauseMessage(await sendPause(s.db, u.id)), /20 %/);
|
||||
} finally { await s.close(); }
|
||||
});
|
||||
255
test/admin.test.js
Normal file
255
test/admin.test.js
Normal file
|
|
@ -0,0 +1,255 @@
|
|||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFileSync, readdirSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { now } from '../src/db.js';
|
||||
import { encrypt } from '../src/crypto.js';
|
||||
import { maskEmail, logAudit, purgeAudit, recentAudit } from '../src/admin.js';
|
||||
import { getSession } from '../src/auth.js';
|
||||
import { ADMIN_PAGE_SIZE } from '../src/limits.js';
|
||||
import { Worker, enqueue } from '../src/services/jobs.js';
|
||||
import { startApp } from './helpers/server.js';
|
||||
|
||||
// Back-office : réservé aux administrateurs (404 pour les autres), actions journalisées, garde-fous sur les administrateurs,
|
||||
// aucune donnée métier.
|
||||
|
||||
const html = { headers: { accept: 'text/html' } };
|
||||
const ADMIN_ROUTES = [
|
||||
['GET', '/admin'], ['GET', '/admin?page=2&q=x'], ['POST', '/admin/users/1/suspend'], ['POST', '/admin/users/1/reactivate'],
|
||||
['POST', '/admin/users/1/plan'], ['POST', '/admin/users/1/delete'], ['POST', '/admin/users/1/resume-send'],
|
||||
];
|
||||
const form = (u, path, body = {}, o = {}) => u.post(path, body, { form: true, ...o });
|
||||
const where = (r) => decodeURIComponent(r.headers.get('location') || '');
|
||||
|
||||
test('non-admin, visiteur et administrateur : 404 sauf pour l\'administrateur, pour toutes les routes', async () => {
|
||||
const s = await startApp();
|
||||
try {
|
||||
const user = await s.newUser({ admin: false });
|
||||
const admin = await s.newUser({ admin: true });
|
||||
for (const [method, path] of ADMIN_ROUTES) {
|
||||
for (const [who, c] of [['visiteur', s.anon], ['utilisateur', user]]) {
|
||||
const r = method === 'GET' ? await c.get(path, html) : await form(c, path);
|
||||
assert.equal(r.status, 404, `${who} ${method} ${path}`);
|
||||
const j = method === 'GET' ? await c.get(path) : await c.post(path, {});
|
||||
assert.equal(j.status, 404, `${who} ${method} ${path} (JSON)`);
|
||||
assert.equal(r.headers.get('location'), null, 'aucune redirection vers la connexion (rien n\'est révélé)');
|
||||
}
|
||||
}
|
||||
// Aucune trace de la page dans la réponse 404, et l'administrateur la voit
|
||||
const denied = await (await user.get('/admin', html)).text();
|
||||
assert.doesNotMatch(denied, /Administration|Journal d'audit/);
|
||||
assert.equal((await admin.get('/admin', html)).status, 200);
|
||||
// Un utilisateur sans liaison Claude mais admin y accède aussi (pas de redirection vers /link)
|
||||
const bare = await s.newUser({ admin: true, link: null });
|
||||
assert.equal((await bare.get('/admin', html)).status, 200);
|
||||
// Le lien « Administration » n'est visible que des administrateurs
|
||||
assert.match(await (await admin.get('/account', html)).text(), /href="\/admin"/);
|
||||
assert.doesNotMatch(await (await user.get('/account', html)).text(), /href="\/admin"/);
|
||||
// Jamais indexé ni exploré
|
||||
assert.match(await (await s.anon.get('/robots.txt')).text(), /Disallow: \/admin\n/);
|
||||
} finally { await s.close(); }
|
||||
});
|
||||
|
||||
test('administration : une origine étrangère est refusée (anti-CSRF) et le débit est limité', async () => {
|
||||
const s = await startApp({ rateLimit: true });
|
||||
try {
|
||||
const admin = await s.newUser({ admin: true });
|
||||
const target = await s.newUser({ admin: false });
|
||||
const r = await form(admin, `/admin/users/${target.id}/suspend`, {}, { origin: 'https://evil.example' });
|
||||
assert.equal(r.status, 403);
|
||||
assert.equal((await s.db.prepare('SELECT status FROM users WHERE id = ?').get(target.id)).status, 'active');
|
||||
for (let i = 0; i < 120; i++) await admin.get('/admin', html);
|
||||
assert.equal((await admin.get('/admin', html)).status, 429);
|
||||
} finally { await s.close(); }
|
||||
});
|
||||
|
||||
test('liste des comptes : identité, plan, statut, dates, mode de liaison et usage ; jamais un secret ni une donnée métier', async () => {
|
||||
const s = await startApp();
|
||||
try {
|
||||
const admin = await s.newUser({ admin: true, email: 'tony@x.fr' });
|
||||
const SECRET = 'sk-ant-api03-SECRETSECRETSECRETSECRET1234';
|
||||
const link = { v: 1, mode: 'api_key', valid: true, last4: '1234', secret_enc: encrypt(s.app.cfg.secretKey, SECRET) };
|
||||
const bob = await s.newUser({ admin: false, email: 'bob@exemple.fr', link });
|
||||
await s.db.prepare('UPDATE users SET last_login_at = ? WHERE id = ?').run(1_800_000_000, bob.id);
|
||||
const pid = Number((await s.db.prepare("INSERT INTO projects(user_id, name, git_url, profile_json, created_at) VALUES(?, 'ProjetConfidentiel', 'https://git.test/b/secret.git', ?, ?)").run(bob.id, JSON.stringify({ resume: 'RESUMEPRIVE' }), now())).lastInsertRowid);
|
||||
await s.db.prepare("INSERT INTO prospects(project_id, company, email, hook, created_at) VALUES(?, 'EntreprisePrivee', 'client@prive.fr', 'ACCROCHEPRIVEE', ?)").run(pid, now());
|
||||
const prospect = (await s.db.prepare('SELECT id FROM prospects WHERE project_id = ?').get(pid)).id;
|
||||
await s.db.prepare("INSERT INTO prospect_notes(prospect_id, body, created_at) VALUES(?, 'NOTEPRIVEE', ?)").run(prospect, now());
|
||||
await s.db.prepare("INSERT INTO mail_log(project_id, prospect_id, email, sent_at, subject) VALUES(?, ?, 'client@prive.fr', ?, 'OBJETPRIVE')").run(pid, prospect, now());
|
||||
await s.db.prepare("INSERT INTO user_settings(user_id, `key`, value) VALUES(?, 'smtp_enc', 'SMTPCHIFFRE')").run(bob.id);
|
||||
|
||||
const page = await (await admin.get('/admin', html)).text();
|
||||
for (const f of ['bob@exemple.fr', 'tony@x.fr', 'Google', 'gratuit', 'actif', 'Clé API Anthropic', 'P 1/1', 'Pr 1/50', 'M 0/100', 'IA 0/5', '15/01/2027']) assert.ok(page.includes(f), f);
|
||||
for (const secret of [SECRET, 'SECRETSECRET', '1234</', 'secret_enc', link.secret_enc, 'SMTPCHIFFRE', 'ProjetConfidentiel', 'secret.git', 'RESUMEPRIVE', 'EntreprisePrivee', 'client@prive.fr', 'ACCROCHEPRIVEE', 'NOTEPRIVEE', 'OBJETPRIVE']) {
|
||||
assert.ok(!page.includes(secret), `la page d'administration ne doit pas contenir « ${secret} »`);
|
||||
}
|
||||
// Les administrateurs figurent avec « Administrateur (ADMIN_EMAILS) » et sans bouton d'action sur leur propre ligne
|
||||
assert.match(page, /Ton compte/);
|
||||
// Seules routes /admin : aucune ne renvoie de donnée métier
|
||||
const paths = s.app.router.routes.filter((r) => /admin/.test(r.re.source)).map((r) => r.re.source);
|
||||
assert.ok(paths.length >= 6);
|
||||
for (const p of paths) assert.doesNotMatch(p, /prospect|mail|note|project/i);
|
||||
} finally { await s.close(); }
|
||||
});
|
||||
|
||||
test('liste paginée et recherche par email (caractères spéciaux neutralisés)', async () => {
|
||||
const s = await startApp();
|
||||
try {
|
||||
const admin = await s.newUser({ admin: true });
|
||||
for (let i = 0; i < ADMIN_PAGE_SIZE + 5; i++) await s.newUser({ admin: false, email: `membre${String(i).padStart(2, '0')}@liste.fr` });
|
||||
await s.newUser({ admin: false, email: '100%_vrai@liste.fr' });
|
||||
const rows = (h) => (h.match(/<tr>\s*<td>[^<]*@/g) || []).length;
|
||||
const p1 = await (await admin.get('/admin', html)).text();
|
||||
assert.equal(rows(p1), ADMIN_PAGE_SIZE);
|
||||
assert.match(p1, /page 1 \/ 2/);
|
||||
assert.match(p1, /href="\/admin\?page=2"/);
|
||||
const p2 = await (await admin.get('/admin?page=2', html)).text();
|
||||
assert.equal(rows(p2), 1 + ADMIN_PAGE_SIZE + 5 + 1 - ADMIN_PAGE_SIZE);
|
||||
assert.match(p2, /Précédent/);
|
||||
assert.equal(rows(await (await admin.get('/admin?page=99', html)).text()), rows(p2), 'page hors bornes ramenée à la dernière');
|
||||
assert.equal(rows(await (await admin.get('/admin?page=abc', html)).text()), ADMIN_PAGE_SIZE);
|
||||
const found = await (await admin.get('/admin?q=membre07', html)).text();
|
||||
assert.equal(rows(found), 1);
|
||||
assert.ok(found.includes('membre07@liste.fr'));
|
||||
const special = await (await admin.get('/admin?q=' + encodeURIComponent('100%_'), html)).text();
|
||||
assert.equal(rows(special), 1, '% et _ sont cherchés littéralement');
|
||||
assert.equal(rows(await (await admin.get('/admin?q=%25', html)).text()), 1);
|
||||
} finally { await s.close(); }
|
||||
});
|
||||
|
||||
test('suspendre : sessions fermées, connexion refusée, jobs en file refusés, audit ; réactiver rétablit', async () => {
|
||||
const s = await startApp();
|
||||
try {
|
||||
const admin = await s.newUser({ admin: true, email: 'chef@x.fr' });
|
||||
const bob = await s.newUser({ admin: false, email: 'bob@x.fr', link: { v: 1, mode: 'api_key', valid: true } });
|
||||
const pid = Number((await s.db.prepare("INSERT INTO projects(user_id, name, git_url, created_at) VALUES(?, 'p', 'u', ?)").run(bob.id, now())).lastInsertRowid);
|
||||
const job = (await enqueue(s.db, { userId: bob.id, projectId: pid, type: 'template' })).id;
|
||||
assert.ok(await getSession(s.db, { headers: { cookie: bob.cookie } }));
|
||||
const r = await form(admin, `/admin/users/${bob.id}/suspend`, { page: '1' });
|
||||
assert.equal(r.status, 303);
|
||||
assert.match(where(r), /^\/admin\?page=1&done=suspend$/);
|
||||
assert.equal((await s.db.prepare('SELECT status FROM users WHERE id = ?').get(bob.id)).status, 'suspended');
|
||||
assert.equal(await getSession(s.db, { headers: { cookie: bob.cookie } }), null, 'sa session est fermée');
|
||||
assert.equal((await bob.get('/api/system')).status, 401);
|
||||
// Son job en file ne s'exécute pas
|
||||
const w = new Worker(s.db, { template: async () => { throw new Error('ne doit pas tourner'); } }, { log: { error() {} } });
|
||||
await w.tick();
|
||||
assert.equal((await s.db.prepare('SELECT status, error FROM jobs WHERE id = ?').get(job)).error, 'Compte suspendu');
|
||||
await assert.rejects(enqueue(s.db, { userId: bob.id, projectId: pid, type: 'prospect' }), { status: 403 });
|
||||
// La page le montre, puis la réactivation
|
||||
assert.match(await (await admin.get('/admin?done=suspend', html)).text(), /suspendu/);
|
||||
assert.equal((await form(admin, `/admin/users/${bob.id}/reactivate`)).status, 303);
|
||||
assert.equal((await s.db.prepare('SELECT status FROM users WHERE id = ?').get(bob.id)).status, 'active');
|
||||
const log = await recentAudit(s.db);
|
||||
assert.deepEqual(log.map((l) => l.action), ['reactivate', 'suspend']);
|
||||
assert.equal(log[1].admin, 'chef@x.fr');
|
||||
assert.equal(log[1].target, 'b***@x.fr', 'adresse masquée dans le journal');
|
||||
assert.equal(log[1].targetId, bob.id);
|
||||
} finally { await s.close(); }
|
||||
});
|
||||
|
||||
test('un administrateur ne peut ni se suspendre, ni se supprimer, ni toucher un autre administrateur', async () => {
|
||||
const s = await startApp();
|
||||
try {
|
||||
const a = await s.newUser({ admin: true, email: 'a@x.fr' });
|
||||
const b = await s.newUser({ admin: true, email: 'b@x.fr' });
|
||||
await s.newUser({ admin: false, email: 'u@x.fr' });
|
||||
const refusals = [
|
||||
[a.id, 'suspend', {}, /propre compte/], [a.id, 'delete', { confirm: 'a@x.fr' }, /propre compte/], [a.id, 'plan', { plan: 'free' }, /propre compte/],
|
||||
[b.id, 'suspend', {}, /administrateur/], [b.id, 'delete', { confirm: 'b@x.fr' }, /administrateur/], [b.id, 'plan', { plan: 'pro' }, /administrateur/],
|
||||
];
|
||||
for (const [id, action, body, re] of refusals) {
|
||||
const r = await form(a, `/admin/users/${id}/${action}`, body);
|
||||
assert.equal(r.status, 303, action);
|
||||
const loc = where(r);
|
||||
assert.match(loc, /[?&]e=/, `${action} sur ${id} : ${loc}`);
|
||||
assert.match(loc, re, `${action} sur ${id}`);
|
||||
}
|
||||
for (const id of [a.id, b.id]) {
|
||||
const row = await s.db.prepare('SELECT status FROM users WHERE id = ?').get(id);
|
||||
assert.equal(row?.status, 'active', `compte ${id} intact`);
|
||||
}
|
||||
assert.deepEqual(await recentAudit(s.db), [], 'un refus n\'est pas une action : rien au journal');
|
||||
assert.equal(await getSession(s.db, { headers: { cookie: a.cookie } }) !== null, true, 'la session de l\'admin reste ouverte');
|
||||
} finally { await s.close(); }
|
||||
});
|
||||
|
||||
test('plan : gratuit / pro attribuables, rien d\'autre ; le plan pro lève les plafonds', async () => {
|
||||
const s = await startApp();
|
||||
try {
|
||||
const admin = await s.newUser({ admin: true });
|
||||
const bob = await s.newUser({ admin: false });
|
||||
assert.equal((await form(admin, `/admin/users/${bob.id}/plan`, { plan: 'pro' })).status, 303);
|
||||
assert.equal((await s.db.prepare('SELECT plan FROM users WHERE id = ?').get(bob.id)).plan, 'pro');
|
||||
for (const bad of ['admin', 'enterprise', '', 'PRO ']) {
|
||||
const loc = where(await form(admin, `/admin/users/${bob.id}/plan`, { plan: bad }));
|
||||
assert.match(loc, /Plan inconnu/, bad);
|
||||
}
|
||||
assert.equal((await s.db.prepare('SELECT plan FROM users WHERE id = ?').get(bob.id)).plan, 'pro');
|
||||
await form(admin, `/admin/users/${bob.id}/plan`, { plan: 'free' });
|
||||
assert.deepEqual((await recentAudit(s.db)).map((l) => l.action), ['plan_free', 'plan_pro']);
|
||||
assert.match(await (await admin.get('/admin?done=plan', html)).text(), /Plan modifié/);
|
||||
assert.equal(where(await form(admin, '/admin/users/99999/plan', { plan: 'pro' })).includes('introuvable'), true);
|
||||
} finally { await s.close(); }
|
||||
});
|
||||
|
||||
test('suppression : confirmation par saisie de l\'email, mêmes effets que la suppression du compte, audit conservé', async () => {
|
||||
const s = await startApp();
|
||||
try {
|
||||
const admin = await s.newUser({ admin: true });
|
||||
const bob = await s.newUser({ admin: false, email: 'bob@exemple.fr' });
|
||||
const pid = Number((await s.db.prepare("INSERT INTO projects(user_id, name, git_url, created_at) VALUES(?, 'p', 'u', ?)").run(bob.id, now())).lastInsertRowid);
|
||||
await s.db.prepare("INSERT INTO prospects(project_id, company, email, created_at) VALUES(?, 'E', 'e@x.fr', ?)").run(pid, now());
|
||||
await s.db.prepare("INSERT INTO blacklist(email, reason, created_at) VALUES('opp@x.fr', 'unsubscribe', ?)").run(now());
|
||||
for (const bad of ['', 'autre@exemple.fr', 'bob@exemple.f']) {
|
||||
assert.match(where(await form(admin, `/admin/users/${bob.id}/delete`, { confirm: bad })), /ne correspond pas/, bad);
|
||||
}
|
||||
assert.ok(await s.db.prepare('SELECT 1 x FROM users WHERE id = ?').get(bob.id), 'toujours là sans la bonne saisie');
|
||||
const ok = await form(admin, `/admin/users/${bob.id}/delete`, { confirm: ' Bob@Exemple.fr ' });
|
||||
assert.match(where(ok), /done=delete/);
|
||||
for (const [t, col] of [['users', 'id'], ['projects', 'user_id'], ['sessions', 'user_id'], ['jobs', 'user_id']]) {
|
||||
assert.equal((await s.db.prepare(`SELECT COUNT(*) n FROM ${t} WHERE ${col} = ?`).get(bob.id)).n, 0, t);
|
||||
}
|
||||
assert.equal((await s.db.prepare('SELECT COUNT(*) n FROM prospects WHERE project_id = ?').get(pid)).n, 0);
|
||||
assert.equal((await s.db.prepare('SELECT COUNT(*) n FROM blacklist').get()).n, 1, 'la liste d\'opposition est conservée, comme à la suppression du compte');
|
||||
const [entry] = await recentAudit(s.db);
|
||||
assert.equal(entry.action, 'delete');
|
||||
assert.equal(entry.target, 'b***@exemple.fr');
|
||||
assert.ok(!JSON.stringify(entry).includes('bob@exemple.fr'), 'l\'adresse complète n\'est pas gardée');
|
||||
} finally { await s.close(); }
|
||||
});
|
||||
|
||||
test('journal d\'audit : en lecture seule, aucune route ni requête ne le modifie, purge des lignes anciennes', async () => {
|
||||
const s = await startApp();
|
||||
try {
|
||||
const admin = await s.newUser({ admin: true });
|
||||
const target = { id: 5, email: 'jean@exemple.fr' };
|
||||
await logAudit(s.db, { admin: { id: admin.id, email: 'a@x.fr' }, action: 'suspend', target, at: now() - 400 * 86400 });
|
||||
await logAudit(s.db, { action: 'abuse_pause', target, detail: 'x'.repeat(900), at: now() });
|
||||
await assert.rejects(logAudit(s.db, { action: 'inconnue', target }), /inconnue/);
|
||||
const page = await (await admin.get('/admin', html)).text();
|
||||
assert.match(page, /Journal d'audit/);
|
||||
assert.match(page, /Envois mis en pause/);
|
||||
assert.match(page, /système/);
|
||||
assert.doesNotMatch(page, /jean@exemple\.fr/);
|
||||
assert.equal((await recentAudit(s.db)).find((l) => l.action === 'abuse_pause').detail.length, 500, 'détail borné');
|
||||
// La section du journal ne propose aucun formulaire
|
||||
const section = page.slice(page.indexOf("Journal d'audit"));
|
||||
assert.doesNotMatch(section, /<form|<button/);
|
||||
// Aucune route d'écriture sur le journal
|
||||
assert.ok(!s.app.router.routes.some((r) => /audit/.test(r.re.source)));
|
||||
// Dans le code, seule la purge ancienne supprime des lignes ; rien ne les met à jour
|
||||
const files = [];
|
||||
const walk = (d) => { for (const e of readdirSync(d, { withFileTypes: true })) { const p = join(d, e.name); e.isDirectory() ? walk(p) : p.endsWith('.js') && files.push(p); } };
|
||||
walk('src');
|
||||
const src = files.map((f) => [f, readFileSync(f, 'utf8')]);
|
||||
for (const [f, text] of src) {
|
||||
assert.doesNotMatch(text, /UPDATE\s+admin_audit/i, f);
|
||||
if (!f.endsWith('audit.js')) assert.doesNotMatch(text, /DELETE\s+FROM\s+admin_audit/i, f);
|
||||
}
|
||||
await purgeAudit(s.db, 12);
|
||||
assert.deepEqual((await recentAudit(s.db)).map((l) => l.action), ['abuse_pause'], 'la ligne de plus de 12 mois est retirée');
|
||||
assert.equal(maskEmail('a@b.fr'), 'a***@b.fr');
|
||||
assert.equal(maskEmail('sans-arobase'), 's***');
|
||||
} finally { await s.close(); }
|
||||
});
|
||||
|
|
@ -51,7 +51,7 @@ test('budget atteint : les jobs IA attendent (pas perdus), les envois passent, u
|
|||
const alerts = [];
|
||||
const h = (name) => async () => { ran.push(name); };
|
||||
const w = new Worker(s.db, { prospect: h('prospect'), evolution: h('evolution'), send: h('send') }, {
|
||||
thermalMax: 999, log: { error() {} },
|
||||
log: { error() {} },
|
||||
budget: (u) => budgetState(s.db, u), isAiJob: (t) => AI_JOBS.has(t), onBudget: (r) => alerts.push(r),
|
||||
});
|
||||
await enqueue(s.db, { userId: s.u, projectId: 1, type: 'prospect' });
|
||||
|
|
@ -105,7 +105,7 @@ test('quota serré : analyse/évolution attendent, la prospection et l\'envoi co
|
|||
const alerts = [];
|
||||
const h = (name) => async () => { ran.push(name); };
|
||||
const w = new Worker(s.db, { prospect: h('prospect'), evolution: h('evolution'), analyze: h('analyze') }, {
|
||||
thermalMax: 999, log: { error() {} },
|
||||
log: { error() {} },
|
||||
quota: (u) => quotaState(s.db, u), isQuotaSensitive, onQuotaHold: (r) => alerts.push(r),
|
||||
});
|
||||
await enqueue(s.db, { userId: s.u, projectId: 1, type: 'evolution' });
|
||||
|
|
|
|||
291
test/captcha.test.js
Normal file
291
test/captcha.test.js
Normal file
|
|
@ -0,0 +1,291 @@
|
|||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import vm from 'node:vm';
|
||||
import { verifyCaptcha } from '../src/captcha.js';
|
||||
import { loadConfig } from '../src/config.js';
|
||||
import { startApp, APP_URL } from './helpers/server.js';
|
||||
|
||||
// reCAPTCHA v3 : vérification serveur (jeton absent, invalide, score bas…), consentement avant tout chargement de Google,
|
||||
// CSP limitée à la page de connexion. Aucun appel réel à Google : tout passe par app.fetch.
|
||||
|
||||
const SITE = 'site-key-test';
|
||||
const SECRET = 'secret-key-test';
|
||||
const RC = { siteKey: SITE, secret: SECRET, minScore: 0.5 };
|
||||
const HOST = new URL(APP_URL).hostname;
|
||||
const answer = (o = {}) => ({ success: true, score: 0.9, action: 'login', hostname: HOST, ...o });
|
||||
|
||||
const fakeFetch = (reply, calls = []) => async (url, opts = {}) => {
|
||||
calls.push({ url, body: Object.fromEntries(new URLSearchParams(opts.body)) });
|
||||
if (reply instanceof Error) throw reply;
|
||||
return { ok: reply.ok ?? true, status: reply.status ?? 200, json: async () => reply.data ?? reply };
|
||||
};
|
||||
const appWith = (reply, calls, rc = RC) => ({ cfg: { recaptcha: rc, appUrl: APP_URL }, fetch: fakeFetch(reply, calls) });
|
||||
|
||||
// ---------- Vérification ----------
|
||||
|
||||
test('sans clés configurées, reCAPTCHA est désactivé (et n\'appelle jamais Google)', async () => {
|
||||
const calls = [];
|
||||
const app = { cfg: { recaptcha: null, appUrl: APP_URL }, fetch: fakeFetch(answer(), calls) };
|
||||
assert.deepEqual(await verifyCaptcha(app, undefined), { skipped: true });
|
||||
assert.equal(calls.length, 0);
|
||||
});
|
||||
|
||||
test('jeton absent : refus 400 sans appel à Google', async () => {
|
||||
for (const token of [undefined, null, '', ' ', 42, {}, []]) {
|
||||
const calls = [];
|
||||
await assert.rejects(verifyCaptcha(appWith(answer(), calls), token), { status: 400, code: 'captcha_missing' }, String(token));
|
||||
assert.equal(calls.length, 0);
|
||||
}
|
||||
});
|
||||
|
||||
test('jeton invalide ou rejeté par Google : refus 403', async () => {
|
||||
await assert.rejects(verifyCaptcha(appWith({ success: false, 'error-codes': ['invalid-input-response'] }), 'tok'), { status: 403, code: 'captcha_invalid' });
|
||||
await assert.rejects(verifyCaptcha(appWith({ success: false, 'error-codes': ['timeout-or-duplicate'] }), 'tok'), { status: 403 });
|
||||
await assert.rejects(verifyCaptcha(appWith(answer(), []), 'x'.repeat(5000)), { status: 403 }, 'jeton démesuré');
|
||||
await assert.rejects(verifyCaptcha(appWith({}), 'tok'), { status: 403 }, 'réponse vide');
|
||||
});
|
||||
|
||||
test('score bas : refus ; le seuil est inclus (0,5 passe, 0,49 non) et réglable', async () => {
|
||||
await assert.rejects(verifyCaptcha(appWith(answer({ score: 0.3 })), 'tok'), { status: 403, code: 'captcha_low_score' });
|
||||
await assert.rejects(verifyCaptcha(appWith(answer({ score: 0.49 })), 'tok'), { status: 403, code: 'captcha_low_score' });
|
||||
await assert.rejects(verifyCaptcha(appWith(answer({ score: undefined })), 'tok'), { status: 403 }, 'pas de score : refus');
|
||||
assert.deepEqual(await verifyCaptcha(appWith(answer({ score: 0.5 })), 'tok'), { score: 0.5 });
|
||||
await assert.rejects(verifyCaptcha(appWith(answer({ score: 0.7 }), [], { ...RC, minScore: 0.8 }), 'tok'), { status: 403 });
|
||||
assert.deepEqual(await verifyCaptcha(appWith(answer({ score: 0.1 }), [], { ...RC, minScore: 0 }), 'tok'), { score: 0.1 });
|
||||
});
|
||||
|
||||
test('jeton produit pour une autre action ou un autre site : refus', async () => {
|
||||
await assert.rejects(verifyCaptcha(appWith(answer({ action: 'homepage' })), 'tok'), { status: 403 });
|
||||
await assert.rejects(verifyCaptcha(appWith(answer({ action: undefined })), 'tok'), { status: 403 });
|
||||
await assert.rejects(verifyCaptcha(appWith(answer({ hostname: 'evil.example' })), 'tok'), { status: 403 });
|
||||
await assert.rejects(verifyCaptcha(appWith(answer({ hostname: undefined })), 'tok'), { status: 403 });
|
||||
});
|
||||
|
||||
test('Google injoignable ou en erreur : 503, jamais un passage faute de réponse', async () => {
|
||||
await assert.rejects(verifyCaptcha(appWith(new Error('ECONNRESET')), 'tok'), { status: 503, code: 'captcha_unavailable' });
|
||||
await assert.rejects(verifyCaptcha(appWith({ ok: false, status: 500, data: answer() }), 'tok'), { status: 503 });
|
||||
});
|
||||
|
||||
test('jeton valide : la requête vers Google porte le secret et le jeton, sans adresse IP', async () => {
|
||||
const calls = [];
|
||||
assert.deepEqual(await verifyCaptcha(appWith(answer({ score: 0.9 }), calls), 'le-jeton'), { score: 0.9 });
|
||||
assert.equal(calls.length, 1);
|
||||
assert.equal(calls[0].url, 'https://www.google.com/recaptcha/api/siteverify');
|
||||
assert.deepEqual(calls[0].body, { secret: SECRET, response: 'le-jeton' });
|
||||
});
|
||||
|
||||
// ---------- Configuration ----------
|
||||
|
||||
test('configuration : les deux clés ensemble, seuil par défaut 0,5, aucun contournement', () => {
|
||||
const base = { APP_URL: 'https://x.fr', SECRET_KEY: 'a'.repeat(64), GOOGLE_CLIENT_ID: 'g', GOOGLE_CLIENT_SECRET: 's', DB_DRIVER: 'sqlite' };
|
||||
const keep = { ...process.env };
|
||||
const withEnv = (extra, fn) => {
|
||||
for (const k of ['RECAPTCHA_SITE_KEY', 'RECAPTCHA_SECRET', 'RECAPTCHA_MIN_SCORE']) delete process.env[k];
|
||||
Object.assign(process.env, base, extra);
|
||||
try { return fn(); } finally {
|
||||
for (const k of Object.keys(process.env)) if (!(k in keep)) delete process.env[k];
|
||||
Object.assign(process.env, keep);
|
||||
}
|
||||
};
|
||||
assert.equal(withEnv({}, () => loadConfig().recaptcha), null);
|
||||
assert.deepEqual(withEnv({ RECAPTCHA_SITE_KEY: 'a', RECAPTCHA_SECRET: 'b' }, () => loadConfig().recaptcha), { siteKey: 'a', secret: 'b', minScore: 0.5 });
|
||||
assert.equal(withEnv({ RECAPTCHA_SITE_KEY: 'a', RECAPTCHA_SECRET: 'b', RECAPTCHA_MIN_SCORE: '0.7' }, () => loadConfig().recaptcha.minScore), 0.7);
|
||||
assert.throws(() => withEnv({ RECAPTCHA_SITE_KEY: 'a' }, loadConfig), /vont ensemble/);
|
||||
assert.throws(() => withEnv({ RECAPTCHA_SECRET: 'b' }, loadConfig), /vont ensemble/);
|
||||
assert.throws(() => withEnv({ RECAPTCHA_SITE_KEY: 'a', RECAPTCHA_SECRET: 'b', RECAPTCHA_MIN_SCORE: '2' }, loadConfig), /entre 0 et 1/);
|
||||
assert.throws(() => withEnv({ RECAPTCHA_SITE_KEY: 'a', RECAPTCHA_SECRET: 'b', RECAPTCHA_MIN_SCORE: 'abc' }, loadConfig), /entre 0 et 1/);
|
||||
// Aucune variable ne désactive la vérification quand les clés sont là
|
||||
const src = readFileSync('src/captcha.js', 'utf8') + readFileSync('src/config.js', 'utf8').match(/function recaptchaConfig[\s\S]*?\n}\n/)[0];
|
||||
assert.doesNotMatch(src, /process\.env|env\.(RECAPTCHA_)?(DISABLE|SKIP|BYPASS)/i);
|
||||
});
|
||||
|
||||
// ---------- Page de connexion et démarrage du flux ----------
|
||||
|
||||
test('page de connexion : consentement d\'abord, rien de Google dans la page, boutons inactifs', async () => {
|
||||
const s = await startApp({ cfg: { recaptcha: RC, apple: { teamId: 't', keyId: 'k', clientId: 'c', privateKey: 'p' } } });
|
||||
try {
|
||||
const r = await s.anon.get('/login', { headers: { accept: 'text/html' } });
|
||||
const h = await r.text();
|
||||
assert.match(h, /data-captcha/);
|
||||
assert.match(h, new RegExp(`data-sitekey="${SITE}"`));
|
||||
assert.match(h, /Charger la vérification anti-robot/);
|
||||
assert.match(h, /Rien n'est envoyé à Google avant ton clic/);
|
||||
// Un seul script, celui de l'application ; aucune URL de script, de cadre ou d'image vers Google
|
||||
assert.deepEqual([...h.matchAll(/<script[^>]*\ssrc="([^"]+)"/g)].map((m) => m[1]), ['/static/captcha.js']);
|
||||
assert.doesNotMatch(h, /<(script|iframe|img|link)[^>]*(gstatic|google\.com\/recaptcha)/i);
|
||||
assert.doesNotMatch(h, /recaptcha\/api\.js/);
|
||||
assert.doesNotMatch(h, /<script(?![^>]*src=)/i, 'aucun script en ligne (CSP)');
|
||||
// Les boutons sont des formulaires POST désactivés, pour Google et pour Apple
|
||||
const forms = [...h.matchAll(/<form method="post" action="(\/auth\/\w+)" data-captcha-form>[\s\S]*?<button[^>]*disabled/g)].map((m) => m[1]);
|
||||
assert.deepEqual(forms, ['/auth/google', '/auth/apple']);
|
||||
assert.doesNotMatch(h, /<a [^>]*href="\/auth\//, 'plus de lien direct vers /auth');
|
||||
// Mentions exigées par Google quand le badge est masqué
|
||||
assert.match(h, /policies\.google\.com\/privacy/);
|
||||
assert.match(h, /policies\.google\.com\/terms/);
|
||||
// Sans reCAPTCHA, la page reste sans script et avec de simples liens
|
||||
const plain = await startApp();
|
||||
try {
|
||||
const p = await (await plain.anon.get('/login', { headers: { accept: 'text/html' } })).text();
|
||||
assert.doesNotMatch(p, /<script|data-captcha/);
|
||||
assert.match(p, /href="\/auth\/google"/);
|
||||
} finally { await plain.close(); }
|
||||
} finally { await s.close(); }
|
||||
});
|
||||
|
||||
test('CSP : les domaines reCAPTCHA ne sont autorisés que sur la page de connexion, et seulement s\'il est configuré', async () => {
|
||||
const on = await startApp({ cfg: { recaptcha: RC } });
|
||||
const off = await startApp();
|
||||
try {
|
||||
const csp = async (s, path) => (await s.anon.get(path, { headers: { accept: 'text/html' } })).headers.get('content-security-policy');
|
||||
const login = await csp(on, '/login');
|
||||
assert.match(login, /script-src 'self' https:\/\/www\.google\.com\/recaptcha\/ https:\/\/www\.gstatic\.com\/recaptcha\//);
|
||||
assert.match(login, /frame-src https:\/\/www\.google\.com\/recaptcha\/ https:\/\/recaptcha\.google\.com\/recaptcha\//);
|
||||
assert.match(login, /default-src 'self'/);
|
||||
assert.match(login, /frame-ancestors 'none'/);
|
||||
assert.doesNotMatch(login, /unsafe-inline|unsafe-eval|\*/);
|
||||
assert.equal((await csp(on, '/login?e=x')), login, 'la page d\'erreur de connexion aussi');
|
||||
for (const p of ['/', '/tarifs', '/confidentialite', '/cgu', '/fonctionnement', '/inexistant', '/static/captcha.js']) {
|
||||
const c = await csp(on, p);
|
||||
assert.doesNotMatch(c, /recaptcha|gstatic|recaptcha.google/i, `${p} : pas de domaine reCAPTCHA`);
|
||||
assert.match(c, /script-src 'self'; /, p);
|
||||
assert.doesNotMatch(c, /frame-src/, p);
|
||||
}
|
||||
assert.doesNotMatch(await csp(off, '/login'), /recaptcha|gstatic|frame-src/i, 'sans clés : aucune ouverture');
|
||||
} finally { await on.close(); await off.close(); }
|
||||
});
|
||||
|
||||
test('POST /auth/google : jeton absent, invalide ou score bas = aucun flux démarré ; jeton valide = redirection vers Google', async () => {
|
||||
const s = await startApp({ cfg: { recaptcha: RC } });
|
||||
try {
|
||||
const calls = [];
|
||||
const states = async () => (await s.db.prepare('SELECT COUNT(*) n FROM oauth_states').get()).n;
|
||||
const post = (body, headers = {}) => fetch(`${s.base}/auth/google`, {
|
||||
method: 'POST', redirect: 'manual',
|
||||
headers: { 'content-type': 'application/x-www-form-urlencoded', origin: APP_URL, ...headers }, body: new URLSearchParams(body).toString(),
|
||||
});
|
||||
const failure = (r) => decodeURIComponent(new URL(r.headers.get('location'), s.base).searchParams.get('e') || '');
|
||||
|
||||
s.app.fetch = fakeFetch(answer(), calls);
|
||||
let r = await post({});
|
||||
assert.equal(r.status, 303);
|
||||
assert.match(r.headers.get('location'), /^\/login\?e=/);
|
||||
assert.match(failure(r), /Vérification anti-robot manquante/);
|
||||
assert.equal(await states(), 0);
|
||||
assert.equal(calls.length, 0, 'pas d\'appel à Google sans jeton');
|
||||
|
||||
s.app.fetch = fakeFetch({ success: false });
|
||||
r = await post({ captcha: 'faux' });
|
||||
assert.match(failure(r), /refusée/);
|
||||
s.app.fetch = fakeFetch(answer({ score: 0.2 }));
|
||||
r = await post({ captcha: 'bot' });
|
||||
assert.match(failure(r), /suspecte/);
|
||||
s.app.fetch = fakeFetch(new Error('réseau coupé'));
|
||||
r = await post({ captcha: 'tok' });
|
||||
assert.match(failure(r), /indisponible/);
|
||||
assert.equal(await states(), 0, 'aucun état OAuth créé pour un refus');
|
||||
assert.deepEqual(r.headers.getSetCookie().filter((c) => c.startsWith('oauth_b=')), [], 'pas de cookie de liaison');
|
||||
|
||||
// Origine étrangère ou absente : refus (le jeton ne suffit pas)
|
||||
s.app.fetch = fakeFetch(answer());
|
||||
r = await post({ captcha: 'ok' }, { origin: 'https://evil.example' });
|
||||
assert.match(failure(r), /Origine refusée/);
|
||||
assert.equal(await states(), 0);
|
||||
|
||||
r = await post({ captcha: 'ok' });
|
||||
assert.equal(r.status, 303);
|
||||
const loc = new URL(r.headers.get('location'));
|
||||
assert.equal(loc.origin + loc.pathname, 'https://accounts.google.com/o/oauth2/v2/auth');
|
||||
assert.equal(await states(), 1);
|
||||
assert.ok(r.headers.getSetCookie().some((c) => c.startsWith('oauth_b=')));
|
||||
|
||||
// Le lien direct (GET) ne démarre plus rien tant que reCAPTCHA est actif
|
||||
r = await fetch(`${s.base}/auth/google`, { redirect: 'manual' });
|
||||
assert.equal(r.status, 303);
|
||||
assert.match(r.headers.get('location'), /^\/login\?e=/);
|
||||
assert.equal(await states(), 1);
|
||||
} finally { await s.close(); }
|
||||
});
|
||||
|
||||
test('POST /auth/apple : mêmes règles ; sans reCAPTCHA, le démarrage reste direct', async () => {
|
||||
const apple = { teamId: 't', keyId: 'k', clientId: 'c', privateKey: 'p' };
|
||||
const s = await startApp({ cfg: { recaptcha: RC, apple } });
|
||||
const plain = await startApp({ cfg: { apple } });
|
||||
try {
|
||||
const post = (base, body) => fetch(`${base}/auth/apple`, {
|
||||
method: 'POST', redirect: 'manual', headers: { 'content-type': 'application/x-www-form-urlencoded', origin: APP_URL }, body: new URLSearchParams(body).toString(),
|
||||
});
|
||||
s.app.fetch = fakeFetch(answer({ score: 0.1 }));
|
||||
assert.match((await post(s.base, { captcha: 'x' })).headers.get('location'), /^\/login\?e=/);
|
||||
s.app.fetch = fakeFetch(answer());
|
||||
const ok = await post(s.base, { captcha: 'x' });
|
||||
assert.match(ok.headers.get('location'), /^https:\/\/appleid\.apple\.com\/auth\/authorize\?/);
|
||||
// Pas de clés : le lien direct fonctionne comme avant (développement)
|
||||
const direct = await fetch(`${plain.base}/auth/apple`, { redirect: 'manual' });
|
||||
assert.match(direct.headers.get('location'), /^https:\/\/appleid\.apple\.com\/auth\/authorize\?/);
|
||||
} finally { await s.close(); await plain.close(); }
|
||||
});
|
||||
|
||||
// ---------- Script de la page : rien avant le clic ----------
|
||||
|
||||
test('captcha.js : aucun chargement de Google avant le clic ; après, le script officiel puis le jeton dans le formulaire', async () => {
|
||||
const s = await startApp({ cfg: { recaptcha: RC } });
|
||||
try {
|
||||
const src = await (await s.anon.get('/static/captcha.js')).text();
|
||||
assert.match(src, /api\.js\?render=/);
|
||||
assert.ok(src.indexOf("addEventListener('click'") < src.indexOf('recaptcha/api.js'), 'l\'adresse de Google n\'apparaît que dans le gestionnaire de clic');
|
||||
|
||||
// Faux DOM minimal
|
||||
const handlers = { load: {}, forms: [] };
|
||||
const el = (extra = {}) => ({ dataset: {}, hidden: false, disabled: false, textContent: '', listeners: {}, addEventListener(n, f) { this.listeners[n] = f; }, ...extra });
|
||||
const status = el(), load = el();
|
||||
const box = el({ dataset: { sitekey: SITE }, querySelector: (q) => (q === '[data-captcha-status]' ? status : load) });
|
||||
const mkForm = () => {
|
||||
const button = el(), input = el({ value: '' });
|
||||
const f = el({ submitted: 0, submit() { this.submitted++; }, querySelector: (q) => (q === 'button' ? button : input) });
|
||||
f.button = button; f.input = input; return f;
|
||||
};
|
||||
const forms = [mkForm(), mkForm()];
|
||||
const appended = [];
|
||||
const grecaptcha = { ready: (cb) => cb(), execute: async (k, o) => { grecaptcha.last = [k, o]; return 'jeton-xyz'; } };
|
||||
const window = { grecaptcha };
|
||||
const document = {
|
||||
querySelector: (q) => (q === '[data-captcha]' ? box : null), querySelectorAll: () => forms,
|
||||
createElement: () => ({}), head: { append: (n) => appended.push(n) },
|
||||
};
|
||||
vm.runInNewContext(src, { document, window, encodeURIComponent });
|
||||
|
||||
assert.equal(appended.length, 0, 'rien n\'est chargé au chargement de la page');
|
||||
assert.ok(forms.every((f) => f.listeners.submit));
|
||||
load.listeners.click();
|
||||
assert.equal(appended.length, 1);
|
||||
assert.equal(appended[0].src, `https://www.google.com/recaptcha/api.js?render=${SITE}`);
|
||||
appended[0].onload();
|
||||
assert.ok(forms.every((f) => f.button.disabled === false), 'boutons actifs une fois chargé');
|
||||
let prevented = 0;
|
||||
await forms[0].listeners.submit({ preventDefault: () => prevented++ });
|
||||
await new Promise((r) => setImmediate(r));
|
||||
assert.equal(prevented, 1);
|
||||
assert.deepEqual(JSON.parse(JSON.stringify(grecaptcha.last)), [SITE, { action: 'login' }]);
|
||||
assert.equal(forms[0].input.value, 'jeton-xyz');
|
||||
assert.equal(forms[0].submitted, 1);
|
||||
} finally { await s.close(); }
|
||||
});
|
||||
|
||||
// ---------- Pages légales ----------
|
||||
|
||||
test('confidentialité : le paragraphe reCAPTCHA, ses cookies et le consentement n\'apparaissent que s\'il est configuré', async () => {
|
||||
const on = await startApp({ cfg: { recaptcha: RC } });
|
||||
const off = await startApp();
|
||||
try {
|
||||
const page = async (s) => (await s.anon.get('/confidentialite', { headers: { accept: 'text/html' } })).text();
|
||||
const a = await page(on);
|
||||
for (const f of ['Google reCAPTCHA', 'Charger la vérification anti-robot', 'Base légale : ton consentement', 'Cookies de Google reCAPTCHA', 'redemandé à chaque visite']) {
|
||||
assert.ok(a.includes(f), f);
|
||||
}
|
||||
assert.doesNotMatch(a, /<!--/);
|
||||
assert.match(a, /Adresse IP/);
|
||||
const b = await page(off);
|
||||
assert.doesNotMatch(b, /reCAPTCHA/);
|
||||
} finally { await on.close(); await off.close(); }
|
||||
});
|
||||
|
|
@ -283,7 +283,7 @@ test('garde « compte relié » à chaque couche : route, enqueue, worker, wrapp
|
|||
|
||||
// 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() {} } });
|
||||
const w = new Worker(s.db, Object.fromEntries([...AI_JOBS, 'send'].map((t) => [t, async () => { ran.push(t); return {}; }])), { 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']);
|
||||
|
|
@ -391,12 +391,12 @@ test('délier un job IA en cours : il est interrompu', async () => {
|
|||
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) });
|
||||
}, { 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));
|
||||
for (let i = 0; i < 50 && !w.running.size; i++) await new Promise((r) => setTimeout(r, 20));
|
||||
assert.equal((await u.post('/link/unlink', {})).status, 200);
|
||||
await tick;
|
||||
assert.equal(aborted, true);
|
||||
|
|
@ -437,7 +437,7 @@ test('serveur complet (worker démarré par createApp) : job d\'un compte relié
|
|||
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));
|
||||
for (let i = 0; i < 100 && (['queued', 'running'].includes((await status(jl)).status) || ['queued', 'running'].includes((await status(jb)).status)); 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);
|
||||
|
|
|
|||
|
|
@ -49,7 +49,7 @@ test('un utilisateur ne lance jamais un job avec le secret d\'un autre (secret r
|
|||
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() {} } });
|
||||
const w = new Worker(s.db, makeHandlers(s.app), { 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 */ }
|
||||
|
|
@ -69,7 +69,7 @@ test('id de projet ou de job manipulé : le job d\'A ne touche jamais au projet
|
|||
}
|
||||
// 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() {} } });
|
||||
const w = new Worker(s.db, makeHandlers(s.app), { 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');
|
||||
|
|
@ -141,7 +141,7 @@ test('le secret n\'apparaît ni dans les erreurs du CLI, ni dans le job en erreu
|
|||
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() {} } });
|
||||
const w = new Worker(s.db, { template: async () => { await makeClaude(s.app)(a.id, { prompt: 'LEAK' }); } }, { 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);
|
||||
|
|
@ -312,7 +312,7 @@ test('quota : chaque utilisateur voit le sien, celui du CLI de A n\'apparaît ja
|
|||
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),
|
||||
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' });
|
||||
|
|
@ -328,7 +328,7 @@ test('quota : chaque utilisateur voit le sien, celui du CLI de A n\'apparaît ja
|
|||
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),
|
||||
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' });
|
||||
|
|
|
|||
6
test/fixtures/fake-claude.js
vendored
6
test/fixtures/fake-claude.js
vendored
|
|
@ -3,6 +3,11 @@
|
|||
const prompt = process.argv[process.argv.indexOf('-p') + 1] || '';
|
||||
const out = (o) => process.stdout.write(JSON.stringify(o) + '\n');
|
||||
out({ type: 'system', subtype: 'init', args: process.argv.slice(2) });
|
||||
// Concurrence : FAKE_LOG = fichier où noter début et fin (clé de l'utilisateur), FAKE_DELAY_MS = durée simulée du travail
|
||||
const who = (process.env.ANTHROPIC_API_KEY || process.env.CLAUDE_CODE_OAUTH_TOKEN || '').slice(-4);
|
||||
const trace = async (what) => { if (process.env.FAKE_LOG) (await import('node:fs')).appendFileSync(process.env.FAKE_LOG, what + ' ' + who + ' ' + Date.now() + String.fromCharCode(10)); };
|
||||
await trace('start');
|
||||
if (process.env.FAKE_DELAY_MS) await new Promise((r) => setTimeout(r, Number(process.env.FAKE_DELAY_MS)));
|
||||
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); }
|
||||
|
|
@ -29,4 +34,5 @@ out({ type: 'rate_limit_event', rate_limit_info: { status: 'allowed', unifiedWin
|
|||
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 },
|
||||
} } });
|
||||
await trace('end');
|
||||
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 } });
|
||||
|
|
|
|||
|
|
@ -40,7 +40,7 @@ async function setup() {
|
|||
const tmp = mkdtempSync(join(tmpdir(), 'aitools-fu-'));
|
||||
const db = await testDb();
|
||||
const sentMails = [];
|
||||
const app = {
|
||||
const app = { resolveHost: async () => [{ address: '93.184.216.34', family: 4 }],
|
||||
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() {} }),
|
||||
isBusinessHours: () => true, // horloge figée : le test ne dépend pas de l'heure à laquelle on le lance
|
||||
|
|
@ -64,7 +64,7 @@ async function setup() {
|
|||
.run(id, pid, email, t, `Une idée pour ${email}`, `<orig-${pid}@codebzh.fr>`);
|
||||
return pid;
|
||||
};
|
||||
const worker = new Worker(db, makeHandlers(app), { thermalMax: 999, log: { error() {} } });
|
||||
const worker = new Worker(db, makeHandlers(app), { log: { error() {} } });
|
||||
const scheduler = new Scheduler(app, { log: { error() {} } });
|
||||
return { tmp, db, app, id, userId, add, inboxOk, worker, scheduler, sentMails };
|
||||
}
|
||||
|
|
|
|||
|
|
@ -27,7 +27,7 @@ async function setup() {
|
|||
execFileSync('git', ['-C', src, '-c', 'user.name=t', '-c', 'user.email=t@t', 'commit', '-qm', 'readme']);
|
||||
const db = await testDb();
|
||||
const sentMails = [];
|
||||
const app = {
|
||||
const app = { resolveHost: async () => [{ address: '93.184.216.34', family: 4 }],
|
||||
db,
|
||||
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
|
||||
|
|
@ -42,7 +42,7 @@ async function setup() {
|
|||
await setSetting(db, userId, 'send_delay_min', '0');
|
||||
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), { log: { error: (...a) => console.error(...a) } });
|
||||
return { tmp, db, app, id, userId, worker, sentMails };
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -7,28 +7,40 @@ import { now } from '../../src/db.js';
|
|||
import { createApp } from '../../src/server.js';
|
||||
import { testDb } from './db.js';
|
||||
import { addUser } from './users.js';
|
||||
import { RateLimiter } from '../../src/ratelimit.js';
|
||||
import { RATE_LIMITS } from '../../src/limits.js';
|
||||
|
||||
export const APP_URL = 'https://ai.tony-averty.dev';
|
||||
|
||||
export async function startApp({ cfg = {}, worker = false } = {}) {
|
||||
// Limiteur sans plafond réaliste : les tests qui répètent des requêtes ne butent pas sur le débit. `rateLimit: true` rétablit
|
||||
// les seuils réels de src/limits.js ; un objet { clock } les garde avec une horloge injectée.
|
||||
// Résolveur DNS des tests : tout nom pointe vers une adresse publique (aucune requête DNS réelle)
|
||||
export const PUBLIC_DNS = async () => [{ address: '93.184.216.34', family: 4 }];
|
||||
|
||||
const unlimited = () => new RateLimiter({
|
||||
rules: Object.fromEntries(Object.entries(RATE_LIMITS).map(([k, v]) => [k, Object.fromEntries(Object.entries(v).map(([sc, c]) => [sc, { ...c, max: 1e9 }]))])),
|
||||
});
|
||||
|
||||
export async function startApp({ cfg = {}, worker = false, rateLimit = false, createTransport, resolveHost } = {}) {
|
||||
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,
|
||||
secretKey: randomBytes(32), dataDir: tmp, claudeBin: 'claude', cliModeEnabled: true,
|
||||
sandbox: { enabled: false, production: false, roBinds: [], serverHome: tmp }, ...cfg,
|
||||
};
|
||||
const app = await createApp(config, { db: await testDb(), worker });
|
||||
const limiter = rateLimit ? new RateLimiter(rateLimit === true ? {} : rateLimit) : unlimited();
|
||||
const app = await createApp(config, { db: await testDb(), worker, limiter, createTransport, resolveHost: resolveHost || PUBLIC_DNS });
|
||||
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, {
|
||||
post: (p, body = {}, { origin = APP_URL, form = false, headers = {} } = {}) => 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',
|
||||
'content-type': form ? 'application/x-www-form-urlencoded' : 'application/json', ...headers,
|
||||
},
|
||||
body: form ? new URLSearchParams(body).toString() : JSON.stringify(body),
|
||||
}),
|
||||
|
|
|
|||
|
|
@ -17,7 +17,7 @@ before(async () => {
|
|||
tmp = mkdtempSync(join(tmpdir(), 'aitools-http-'));
|
||||
const cfg = {
|
||||
appUrl: APP_URL, google: { clientId: 'cid', clientSecret: 'cs' }, apple: null, adminEmails: ['me@gmail.com'],
|
||||
secretKey: randomBytes(32), dataDir: tmp, claudeBin: 'claude', thermalMax: 75, sandbox: { enabled: false, production: false },
|
||||
secretKey: randomBytes(32), dataDir: tmp, claudeBin: 'claude', sandbox: { enabled: false, production: false },
|
||||
};
|
||||
app = await createApp(cfg, { db: await testDb(), worker: false });
|
||||
await new Promise((r) => app.server.listen(0, '127.0.0.1', r));
|
||||
|
|
|
|||
237
test/inactive.test.js
Normal file
237
test/inactive.test.js
Normal file
|
|
@ -0,0 +1,237 @@
|
|||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { randomBytes } from 'node:crypto';
|
||||
import { getSetting, now } from '../src/db.js';
|
||||
import { testDb } from './helpers/db.js';
|
||||
import { addUser } from './helpers/users.js';
|
||||
import { startApp } from './helpers/server.js';
|
||||
import { addMonths, runInactiveCleanup, warningMail } from '../src/services/inactive.js';
|
||||
import { Scheduler } from '../src/services/scheduler.js';
|
||||
import { recentAudit } from '../src/admin.js';
|
||||
import { loadConfig } from '../src/config.js';
|
||||
|
||||
// Suppression des comptes inactifs avec une horloge injectée : avertissement 30 jours avant, suppression seulement après
|
||||
// avertissement reçu, jamais un administrateur.
|
||||
|
||||
const DAY = 86400;
|
||||
const T0 = Date.parse('2025-01-15T10:00:00Z') / 1000; // date de dernière connexion de référence
|
||||
const at = (months, days = 0) => addMonths(T0, months) + days * DAY;
|
||||
|
||||
async function world({ smtp = true, months = 24 } = {}) {
|
||||
const db = await testDb();
|
||||
const mails = [];
|
||||
const app = {
|
||||
db, resolveHost: async () => [{ address: '93.184.216.34', family: 4 }],
|
||||
cfg: {
|
||||
dataDir: '/tmp/aitools-inactive', appUrl: 'https://ai.test', secretKey: randomBytes(32), inactiveMonths: months,
|
||||
systemSmtp: smtp ? { host: 'smtp.serveur.fr', port: 587, user: 'u', pass: 'p', fromEmail: 'noreply@ai.test' } : null,
|
||||
},
|
||||
createTransport: (cfg) => ({ sendMail: async (m) => { mails.push({ ...m, via: cfg.host }); }, close() {} }),
|
||||
};
|
||||
const log = { warns: [], warn: (...a) => log.warns.push(a.join(' ')), error() {} };
|
||||
return { db, app, mails, log };
|
||||
}
|
||||
async function member(w, o = {}) {
|
||||
const id = await addUser(w.db, { admin: false, email: o.email || `m${Math.random().toString(36).slice(2, 8)}@ex.fr`, ...o });
|
||||
await w.db.prepare('UPDATE users SET created_at = ?, last_login_at = ? WHERE id = ?').run(o.createdAt ?? T0 - 10 * DAY, o.lastLogin ?? T0, id);
|
||||
return id;
|
||||
}
|
||||
const exists = async (w, id) => !!(await w.db.prepare('SELECT 1 x FROM users WHERE id = ?').get(id));
|
||||
const run = (w, when, extra = {}) => runInactiveCleanup(w.app, { at: when, log: w.log, ...extra });
|
||||
|
||||
test('chronologie : rien avant 23 mois, avertissement à J-30, suppression à J0 si avertissement reçu et resté inactif', async () => {
|
||||
const w = await world();
|
||||
const id = await member(w, { email: 'ada@ex.fr' });
|
||||
assert.deepEqual(await run(w, at(23)), { warned: 0, deleted: 0, unsent: 0 }, '23 mois : rien');
|
||||
assert.equal(w.mails.length, 0);
|
||||
assert.deepEqual(await run(w, at(24, -31)), { warned: 0, deleted: 0, unsent: 0 }, 'à 31 jours de l\'échéance : encore rien');
|
||||
|
||||
// 30 jours avant l'échéance : un avertissement, via le SMTP du serveur, jamais de suppression ce jour-là
|
||||
const warnDay = at(24, -30);
|
||||
assert.deepEqual(await run(w, warnDay), { warned: 1, deleted: 0, unsent: 0 });
|
||||
assert.equal(w.mails.length, 1);
|
||||
assert.equal(w.mails[0].to, 'ada@ex.fr');
|
||||
assert.equal(w.mails[0].from, 'noreply@ai.test');
|
||||
assert.equal(w.mails[0].via, '93.184.216.34', 'le SMTP du serveur passe aussi par le filtre SSRF');
|
||||
assert.match(w.mails[0].text, /supprimé avec toutes ses données/);
|
||||
assert.match(w.mails[0].text, /https:\/\/ai\.test\/login/);
|
||||
assert.match(w.mails[0].text, /15 janvier 2027/);
|
||||
assert.equal(await exists(w, id), true);
|
||||
// Passages suivants (toutes les 15 min) : ni second mail, ni suppression avant l'échéance
|
||||
assert.deepEqual(await run(w, warnDay + 900), { warned: 0, deleted: 0, unsent: 0 });
|
||||
assert.deepEqual(await run(w, at(24, -1)), { warned: 0, deleted: 0, unsent: 0 });
|
||||
assert.equal(w.mails.length, 1, 'un seul avertissement');
|
||||
assert.equal(await exists(w, id), true);
|
||||
// Échéance atteinte (24 mois) : supprimé
|
||||
assert.deepEqual(await run(w, at(24, 0)), { warned: 0, deleted: 1, unsent: 0 });
|
||||
assert.equal(await exists(w, id), false);
|
||||
const log = await recentAudit(w.db);
|
||||
assert.deepEqual(log.map((l) => l.action), ['inactive_delete', 'inactive_warning']);
|
||||
assert.equal(log[0].target, 'a***@ex.fr');
|
||||
assert.equal(log[0].admin, 'système');
|
||||
});
|
||||
|
||||
test('un avertissement tardif ne permet pas de supprimer tout de suite : 30 jours de délai après le mail', async () => {
|
||||
const w = await world();
|
||||
const id = await member(w);
|
||||
const late = at(30); // inactif depuis 30 mois, mais premier passage seulement maintenant
|
||||
assert.deepEqual(await run(w, late), { warned: 1, deleted: 0, unsent: 0 });
|
||||
assert.equal(await exists(w, id), true);
|
||||
assert.match(w.mails[0].text, new RegExp(String(new Date((late + 30 * DAY) * 1000).getUTCFullYear())));
|
||||
assert.deepEqual(await run(w, late + 29 * DAY), { warned: 0, deleted: 0, unsent: 0 });
|
||||
assert.equal(await exists(w, id), true);
|
||||
assert.deepEqual(await run(w, late + 30 * DAY), { warned: 0, deleted: 1, unsent: 0 });
|
||||
assert.equal(await exists(w, id), false);
|
||||
});
|
||||
|
||||
test('une connexion après l\'avertissement sauve le compte ; l\'ancien avertissement ne vaut plus', async () => {
|
||||
const w = await world();
|
||||
const id = await member(w);
|
||||
await run(w, at(24, -30));
|
||||
assert.equal(w.mails.length, 1);
|
||||
await w.db.prepare('UPDATE users SET last_login_at = ? WHERE id = ?').run(at(24, -10), id); // il se reconnecte
|
||||
assert.deepEqual(await run(w, at(24, 5)), { warned: 0, deleted: 0, unsent: 0 });
|
||||
assert.equal(await exists(w, id), true);
|
||||
// 24 mois après sa nouvelle connexion : il faut un nouvel avertissement avant toute suppression
|
||||
const later = addMonths(at(24, -10), 24);
|
||||
assert.deepEqual(await run(w, later), { warned: 1, deleted: 0, unsent: 0 });
|
||||
assert.equal(w.mails.length, 2);
|
||||
assert.equal(await exists(w, id), true);
|
||||
});
|
||||
|
||||
test('un job récent compte comme activité', async () => {
|
||||
const w = await world();
|
||||
const id = await member(w);
|
||||
await w.db.prepare("INSERT INTO jobs(user_id, type, status, created_at) VALUES(?, 'send', 'done', ?)").run(id, at(20));
|
||||
assert.deepEqual(await run(w, at(24, -20)), { warned: 0, deleted: 0, unsent: 0 }, 'dernière activité il y a 4 mois seulement');
|
||||
assert.equal(w.mails.length, 0);
|
||||
});
|
||||
|
||||
test('jamais un administrateur, ni un compte suspendu, ni un compte actif', async () => {
|
||||
const w = await world();
|
||||
const admin = await addUser(w.db, { admin: true });
|
||||
await w.db.prepare('UPDATE users SET created_at = ?, last_login_at = ? WHERE id = ?').run(T0 - 3000 * DAY, T0 - 3000 * DAY, admin);
|
||||
const planAdmin = await member(w); await w.db.prepare("UPDATE users SET plan = 'admin' WHERE id = ?").run(planAdmin);
|
||||
const suspended = await member(w, { status: 'suspended' });
|
||||
const active = await member(w, { lastLogin: at(40) });
|
||||
const never = await member(w, { createdAt: at(40), lastLogin: null });
|
||||
await w.db.prepare('UPDATE users SET last_login_at = NULL WHERE id = ?').run(never);
|
||||
const when = at(60);
|
||||
assert.deepEqual(await run(w, when), { warned: 0, deleted: 0, unsent: 0 });
|
||||
assert.deepEqual(await run(w, when + 31 * DAY), { warned: 0, deleted: 0, unsent: 0 });
|
||||
assert.equal(w.mails.length, 0);
|
||||
for (const id of [admin, planAdmin, suspended, active, never]) assert.equal(await exists(w, id), true, `compte ${id}`);
|
||||
});
|
||||
|
||||
test('sans SMTP du serveur : avertissement journalisé, JAMAIS de suppression automatique', async () => {
|
||||
const w = await world({ smtp: false });
|
||||
const id = await member(w);
|
||||
const r = await run(w, at(30));
|
||||
assert.deepEqual(r, { warned: 0, deleted: 0, unsent: 1 });
|
||||
assert.ok(w.log.warns.some((l) => /avertissement non envoyé/.test(l) && /SYSTEM_SMTP_HOST/.test(l)));
|
||||
const [entry] = await recentAudit(w.db);
|
||||
assert.equal(entry.action, 'inactive_warning');
|
||||
assert.match(entry.detail, /NON envoyé/);
|
||||
// Passages suivants : toujours rien de supprimé, et une seule trace au journal d'audit
|
||||
for (let i = 1; i <= 5; i++) await run(w, at(30) + i * 900);
|
||||
await run(w, at(40));
|
||||
assert.equal(await exists(w, id), true);
|
||||
assert.equal((await recentAudit(w.db)).length, 1);
|
||||
});
|
||||
|
||||
test('SMTP du serveur en panne : réessai au passage suivant, pas de suppression, pas de bruit dans le journal d\'audit', async () => {
|
||||
const w = await world();
|
||||
const id = await member(w);
|
||||
let fail = true;
|
||||
w.app.createTransport = () => ({ sendMail: async (m) => { if (fail) throw new Error('421 indisponible'); w.mails.push(m); }, close() {} });
|
||||
assert.deepEqual(await run(w, at(30)), { warned: 0, deleted: 0, unsent: 1 });
|
||||
assert.deepEqual(await run(w, at(30) + 900), { warned: 0, deleted: 0, unsent: 1 });
|
||||
assert.equal((await recentAudit(w.db)).length, 0);
|
||||
assert.equal(await getSetting(w.db, id, 'inactive_warned_at'), null);
|
||||
fail = false;
|
||||
assert.deepEqual(await run(w, at(30) + 1800), { warned: 1, deleted: 0, unsent: 0 });
|
||||
assert.equal(w.mails.length, 1);
|
||||
});
|
||||
|
||||
test('durée réglable (INACTIVE_ACCOUNT_MONTHS) et désactivable (0)', async () => {
|
||||
const w = await world({ months: 12 });
|
||||
const id = await member(w);
|
||||
assert.equal((await run(w, at(12, -30))).warned, 1);
|
||||
assert.equal((await run(w, at(12))).deleted, 1);
|
||||
assert.equal(await exists(w, id), false);
|
||||
const off = await world({ months: 0 });
|
||||
const kept = await member(off);
|
||||
assert.deepEqual(await run(off, at(100)), { warned: 0, deleted: 0, unsent: 0 });
|
||||
assert.equal(await exists(off, kept), true);
|
||||
});
|
||||
|
||||
test('la suppression a les mêmes effets que celle du compte : données effacées, liste d\'opposition conservée', async () => {
|
||||
const w = await world();
|
||||
const id = await member(w);
|
||||
const p = Number((await w.db.prepare("INSERT INTO projects(user_id, name, git_url, created_at) VALUES(?, 'p', 'u', ?)").run(id, T0)).lastInsertRowid);
|
||||
await w.db.prepare("INSERT INTO prospects(project_id, company, email, created_at) VALUES(?, 'E', 'e@x.fr', ?)").run(p, T0);
|
||||
await w.db.prepare("INSERT INTO blacklist(email, reason, created_at) VALUES('opp@x.fr', 'unsubscribe', ?)").run(T0);
|
||||
await w.db.prepare("INSERT INTO sessions(id, user_id, created_at, expires_at) VALUES('s1', ?, ?, ?)").run(id, T0, T0 + 99);
|
||||
await run(w, at(24, -30));
|
||||
await run(w, at(24));
|
||||
assert.equal((await w.db.prepare('SELECT COUNT(*) n FROM projects WHERE user_id = ?').get(id)).n, 0);
|
||||
assert.equal((await w.db.prepare('SELECT COUNT(*) n FROM prospects WHERE project_id = ?').get(p)).n, 0);
|
||||
assert.equal((await w.db.prepare('SELECT COUNT(*) n FROM sessions WHERE user_id = ?').get(id)).n, 0);
|
||||
assert.equal((await w.db.prepare('SELECT COUNT(*) n FROM blacklist').get()).n, 1);
|
||||
});
|
||||
|
||||
test('le planificateur lance le nettoyage avec son horloge injectable', async () => {
|
||||
const w = await world();
|
||||
const id = await member(w);
|
||||
let clock = at(24, -30);
|
||||
const sch = new Scheduler(w.app, { log: w.log, clock: () => clock });
|
||||
w.app.fetchRecap = async () => ({});
|
||||
await sch.tick();
|
||||
assert.equal(w.mails.length, 1);
|
||||
clock = at(24, 1);
|
||||
await sch.tick();
|
||||
assert.equal(await exists(w, id), false);
|
||||
await sch.stop();
|
||||
});
|
||||
|
||||
test('configuration : INACTIVE_ACCOUNT_MONTHS (24 par défaut) et SMTP du serveur toutes variables ensemble', () => {
|
||||
const base = { APP_URL: 'https://x.fr', SECRET_KEY: 'a'.repeat(64), GOOGLE_CLIENT_ID: 'g', GOOGLE_CLIENT_SECRET: 's', DB_DRIVER: 'sqlite' };
|
||||
const keep = { ...process.env };
|
||||
const withEnv = (extra, fn) => {
|
||||
for (const k of Object.keys(process.env)) if (/^(INACTIVE_|SYSTEM_SMTP)/.test(k)) delete process.env[k];
|
||||
Object.assign(process.env, base, extra);
|
||||
try { return fn(); } finally { for (const k of Object.keys(process.env)) if (!(k in keep)) delete process.env[k]; Object.assign(process.env, keep); }
|
||||
};
|
||||
assert.equal(withEnv({}, () => loadConfig().inactiveMonths), 24);
|
||||
assert.equal(withEnv({ INACTIVE_ACCOUNT_MONTHS: '18' }, () => loadConfig().inactiveMonths), 18);
|
||||
assert.equal(withEnv({ INACTIVE_ACCOUNT_MONTHS: '0' }, () => loadConfig().inactiveMonths), 0);
|
||||
assert.throws(() => withEnv({ INACTIVE_ACCOUNT_MONTHS: '-1' }, loadConfig), /INACTIVE_ACCOUNT_MONTHS/);
|
||||
assert.throws(() => withEnv({ INACTIVE_ACCOUNT_MONTHS: 'deux ans' }, loadConfig), /INACTIVE_ACCOUNT_MONTHS/);
|
||||
assert.equal(withEnv({}, () => loadConfig().systemSmtp), null);
|
||||
const full = { SYSTEM_SMTP_HOST: 'smtp.x.fr', SYSTEM_SMTP_USER: 'u', SYSTEM_SMTP_PASSWORD: 'p', SYSTEM_SMTP_FROM: 'n@x.fr' };
|
||||
assert.deepEqual(withEnv(full, () => loadConfig().systemSmtp), { host: 'smtp.x.fr', port: 587, user: 'u', pass: 'p', fromEmail: 'n@x.fr' });
|
||||
assert.throws(() => withEnv({ SYSTEM_SMTP_HOST: 'smtp.x.fr' }, loadConfig), /incomplètes/);
|
||||
});
|
||||
|
||||
test('politique de confidentialité : la suppression automatique est annoncée comme en place, avec la durée configurée', async () => {
|
||||
const s = await startApp({ cfg: { inactiveMonths: 18 } });
|
||||
const off = await startApp({ cfg: { inactiveMonths: 0 } });
|
||||
try {
|
||||
const page = async (x) => (await x.anon.get('/confidentialite', { headers: { accept: 'text/html' } })).text();
|
||||
const h = await page(s);
|
||||
assert.match(h, /Suppression automatique après 18 mois sans connexion ni job, avec un mail d'avertissement 30 jours avant/);
|
||||
assert.doesNotMatch(h, /pas encore en place|prévue/);
|
||||
assert.match(h, /Journal d'administration/);
|
||||
assert.match(await page(off), /Aucune suppression automatique pour inactivité/);
|
||||
const def = await startApp();
|
||||
try { assert.match(await page(def), /après 24 mois/); } finally { await def.close(); }
|
||||
} finally { await s.close(); await off.close(); }
|
||||
});
|
||||
|
||||
test('mail d\'avertissement : jamais le mot de passe ni de donnée métier, lien de connexion et d\'export', () => {
|
||||
const m = warningMail({ appUrl: 'https://ai.test' }, { email: 'ada@ex.fr' }, T0);
|
||||
assert.match(m.subject, /supprimé pour inactivité/);
|
||||
assert.match(m.text, /ada@ex\.fr/);
|
||||
assert.match(m.text, /export/i);
|
||||
assert.ok(m.text.includes('contact@tony-averty.dev'));
|
||||
});
|
||||
|
|
@ -10,7 +10,7 @@ import { createProject, saveSecretConfig, getProject, imapCredentials } from '..
|
|||
|
||||
async function setup() {
|
||||
const db = await testDb();
|
||||
const app = { db, cfg: { secretKey: randomBytes(32) } };
|
||||
const app = { resolveHost: async () => [{ address: '93.184.216.34', family: 4 }], db, cfg: { secretKey: randomBytes(32) } };
|
||||
const userId = await addUser(db);
|
||||
const id = await createProject(app, { userId, name: 'P', gitUrl: 'https://git.x/T/P.git' });
|
||||
const add = async (company, email, msgId, status = 'sent') => {
|
||||
|
|
|
|||
|
|
@ -10,7 +10,7 @@ const ts = (iso) => Math.floor(Date.parse(iso) / 1000);
|
|||
|
||||
async function setup() {
|
||||
const db = await testDb();
|
||||
const app = { db, cfg: { secretKey: randomBytes(32) } };
|
||||
const app = { resolveHost: async () => [{ address: '93.184.216.34', family: 4 }], db, cfg: { secretKey: randomBytes(32) } };
|
||||
const userId = await addUser(db);
|
||||
const id = await createProject(app, { userId, name: 'MEP', gitUrl: 'https://g/T/M.git' });
|
||||
return { db, app, id, userId };
|
||||
|
|
|
|||
266
test/netguard.test.js
Normal file
266
test/netguard.test.js
Normal file
|
|
@ -0,0 +1,266 @@
|
|||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { createTransport } from '../src/services/mailer.js';
|
||||
import { pinArgs, cloneArgs, fetchArgs } from '../src/services/git.js';
|
||||
import { blockedReason, normalizeIp } from '../src/ip.js';
|
||||
import { resolvePublic, guardTarget, pinSmtp, pinImap, pinDb, pinGit, assertPort } from '../src/netguard.js';
|
||||
import { ALLOWED_PORTS } from '../src/limits.js';
|
||||
import { loadConfig } from '../src/config.js';
|
||||
import { Worker, enqueue } from '../src/services/jobs.js';
|
||||
import { makeHandlers } from '../src/handlers.js';
|
||||
import { checkInbox } from '../src/services/inbox.js';
|
||||
import { saveSecretConfig } from '../src/projects.js';
|
||||
import { now } from '../src/db.js';
|
||||
import { startApp } from './helpers/server.js';
|
||||
|
||||
// Filtrage des hôtes saisis par l'utilisateur (SSRF) : adresses, résolution, ports, rebinding, branchement sur chaque service.
|
||||
// Aucune requête DNS ni connexion réelle : le résolveur est injecté.
|
||||
|
||||
const PUBLIC = '93.184.216.34';
|
||||
const dns = (map) => async (host) => {
|
||||
const v = map[host];
|
||||
if (v instanceof Error) throw v;
|
||||
if (!v) throw Object.assign(new Error('ENOTFOUND'), { code: 'ENOTFOUND' });
|
||||
return [].concat(v).map((address) => ({ address, family: address.includes(':') ? 6 : 4 }));
|
||||
};
|
||||
|
||||
// ---------- Adresses ----------
|
||||
|
||||
test('adresses refusées : boucle locale, privées, link-local (métadonnées), CGNAT, IPv6 locales, IPv4 mappées ou encapsulées', () => {
|
||||
const blocked = [
|
||||
'127.0.0.1', '127.255.255.254', '10.0.0.1', '10.255.255.255', '172.16.0.1', '172.31.255.255', '192.168.0.1', '192.168.255.255',
|
||||
'169.254.169.254', '169.254.0.1', '0.0.0.0', '100.64.0.1', '224.0.0.1', '255.255.255.255', '192.0.2.5',
|
||||
'::1', '::', 'fc00::1', 'fdff:ffff::1', 'fe80::1', 'febf::1', 'ff02::1', '2001:db8::1',
|
||||
'::ffff:127.0.0.1', '::ffff:7f00:1', '::ffff:10.1.2.3', '::ffff:169.254.169.254', '::ffff:a9fe:a9fe', '::127.0.0.1',
|
||||
'64:ff9b::7f00:1', '64:ff9b::a9fe:a9fe', '2002:7f00:1::', '2002:a9fe:a9fe::1', '[::1]', 'fe80::1%eth0',
|
||||
];
|
||||
for (const ip of blocked) assert.ok(blockedReason(ip), `${ip} devrait être refusée`);
|
||||
const open = ['8.8.8.8', '93.184.216.34', '172.15.255.255', '172.32.0.1', '192.169.0.1', '11.0.0.1', '100.63.255.255', '100.128.0.1',
|
||||
'2606:4700:4700::1111', '2a00:1450:4007:80b::200e', '::ffff:8.8.8.8', '::ffff:5db8:d822', '64:ff9b::808:808'];
|
||||
for (const ip of open) assert.equal(blockedReason(ip), null, `${ip} devrait passer`);
|
||||
assert.ok(blockedReason('pas-une-ip'));
|
||||
assert.equal(normalizeIp('::ffff:127.0.0.1'), '127.0.0.1');
|
||||
});
|
||||
|
||||
// ---------- Résolution ----------
|
||||
|
||||
test('résolution : IP littérales, noms vers des adresses privées, réponse mixte, formes numériques trompeuses', async () => {
|
||||
const resolve = dns({
|
||||
'mail.exemple.fr': PUBLIC, 'interne.exemple.fr': '10.0.0.5', 'local.exemple.fr': '127.0.0.1', 'meta.exemple.fr': '169.254.169.254',
|
||||
'mixte.exemple.fr': [PUBLIC, '192.168.1.10'], 'v6.exemple.fr': '::1', 'mappe.exemple.fr': '::ffff:127.0.0.1',
|
||||
localhost: '127.0.0.1', '2130706433': '127.0.0.1', '127.1': '127.0.0.1', '0x7f.1': '127.0.0.1',
|
||||
});
|
||||
assert.deepEqual(await resolvePublic('mail.exemple.fr', { resolve }), { address: PUBLIC, family: 4, servername: 'mail.exemple.fr' });
|
||||
const refused = async (host) => assert.rejects(resolvePublic(host, { resolve }), (e) => e.status === 400 && /refusé|invalide|introuvable/.test(e.message), host);
|
||||
for (const h of ['127.0.0.1', '169.254.169.254', '10.0.0.1', '192.168.1.1', '::1', '[::1]', '::ffff:127.0.0.1',
|
||||
'interne.exemple.fr', 'local.exemple.fr', 'meta.exemple.fr', 'mixte.exemple.fr', 'v6.exemple.fr', 'mappe.exemple.fr',
|
||||
'localhost', '2130706433', '127.1', '0x7f.1']) await refused(h);
|
||||
// Une IP publique littérale passe, sans DNS
|
||||
assert.deepEqual(await resolvePublic('8.8.8.8', { resolve: () => { throw new Error('pas de DNS'); } }), { address: '8.8.8.8', family: 4, servername: null });
|
||||
// Hôtes mal formés
|
||||
for (const h of ['', ' ', 'a b', 'exemple.fr/chemin', 'http://exemple.fr', 'exemple.fr:25', 'x'.repeat(300), 'ex@mple.fr', 'a;b']) await refused(h);
|
||||
// Introuvable : refus, sauf à l'enregistrement (lenient) où le nom pourra devenir résolvable
|
||||
await assert.rejects(resolvePublic('absent.exemple.fr', { resolve }), /introuvable/);
|
||||
assert.equal(await resolvePublic('absent.exemple.fr', { resolve, lenient: true }), null);
|
||||
// Mais lenient ne laisse jamais passer une adresse privée
|
||||
await assert.rejects(resolvePublic('local.exemple.fr', { resolve, lenient: true }), /refusé/);
|
||||
// Exception de développement
|
||||
assert.equal((await resolvePublic('local.exemple.fr', { resolve, allowPrivate: true })).address, '127.0.0.1');
|
||||
});
|
||||
|
||||
test('le message de refus n\'affiche pas l\'adresse interne trouvée', async () => {
|
||||
await assert.rejects(resolvePublic('x.fr', { resolve: dns({ 'x.fr': '10.9.8.7' }) }), (e) => !e.message.includes('10.9.8.7') && /interne ou réservée/.test(e.message));
|
||||
});
|
||||
|
||||
// ---------- Ports ----------
|
||||
|
||||
test('ports : liste par type de service, tout le reste est refusé', () => {
|
||||
for (const [kind, ports] of Object.entries(ALLOWED_PORTS)) {
|
||||
for (const p of ports) assert.equal(assertPort(kind, p), p);
|
||||
}
|
||||
for (const [kind, p] of [['smtp', 22], ['smtp', 3306], ['imap', 25], ['mysql', 6379], ['mysql', 80], ['pg', 3306], ['git', 22], ['git', 80], ['git', 8080]]) {
|
||||
assert.throws(() => assertPort(kind, p), (e) => e.status === 400 && /refusé/.test(e.message), `${kind}:${p}`);
|
||||
}
|
||||
for (const bad of [0, -1, 70000, 'abc', 1.5, null]) assert.throws(() => assertPort('smtp', bad), /Port invalide/);
|
||||
assert.equal(assertPort('smtp', 1025, { allowPrivate: true }), 1025, 'exception de développement');
|
||||
});
|
||||
|
||||
// ---------- ALLOW_PRIVATE_HOSTS ----------
|
||||
|
||||
test('ALLOW_PRIVATE_HOSTS : désactivé par défaut ; en production réservé aux administrateurs', async () => {
|
||||
const s = await startApp();
|
||||
try {
|
||||
const user = await s.newUser({ admin: false });
|
||||
const admin = await s.newUser({ admin: true });
|
||||
const resolveHost = dns({ 'local.test': '127.0.0.1' });
|
||||
const app = (cfg) => ({ db: s.db, cfg, resolveHost });
|
||||
const ok = (a, u) => guardTarget(a, u.id, 'smtp', 'local.test', 2525);
|
||||
// Drapeau absent : personne, admin compris
|
||||
await assert.rejects(ok(app({}), admin), /refusé/);
|
||||
// Développement (hors production) : tout le monde
|
||||
assert.equal((await ok(app({ allowPrivateHosts: true, production: false }), user)).address, '127.0.0.1');
|
||||
// Production : l'administrateur seulement
|
||||
await assert.rejects(ok(app({ allowPrivateHosts: true, production: true }), user), /refusé/);
|
||||
assert.equal((await ok(app({ allowPrivateHosts: true, production: true }), admin)).address, '127.0.0.1');
|
||||
// Les ports hors liste passent aussi avec l'exception
|
||||
assert.equal((await guardTarget(app({ allowPrivateHosts: true, production: false }), user.id, 'smtp', 'local.test', 1025)).port, 1025);
|
||||
await assert.rejects(guardTarget(app({}), user.id, 'smtp', 'public.test', 1025), /Port 1025 refusé/);
|
||||
// Configuration
|
||||
const base = { APP_URL: 'https://x.fr', SECRET_KEY: 'a'.repeat(64), GOOGLE_CLIENT_ID: 'g', GOOGLE_CLIENT_SECRET: 's', DB_DRIVER: 'sqlite' };
|
||||
const keep = { ...process.env };
|
||||
try {
|
||||
delete process.env.ALLOW_PRIVATE_HOSTS; Object.assign(process.env, base);
|
||||
assert.equal(loadConfig().allowPrivateHosts, false);
|
||||
process.env.ALLOW_PRIVATE_HOSTS = 'true';
|
||||
assert.equal(loadConfig().allowPrivateHosts, true);
|
||||
} finally { for (const k of Object.keys(process.env)) if (!(k in keep)) delete process.env[k]; Object.assign(process.env, keep); }
|
||||
} finally { await s.close(); }
|
||||
});
|
||||
|
||||
// ---------- Rebinding DNS : on se connecte à l'adresse vérifiée, et on revérifie à chaque connexion ----------
|
||||
|
||||
test('DNS qui change entre deux résolutions : la 2e connexion est refusée, la 1re utilise l\'IP vérifiée', async () => {
|
||||
const s = await startApp();
|
||||
try {
|
||||
const u = await s.newUser({ admin: false });
|
||||
let answers = [[PUBLIC], ['127.0.0.1'], ['169.254.169.254']];
|
||||
s.app.resolveHost = async () => answers.shift().map((address) => ({ address, family: 4 }));
|
||||
const smtp = { host: 'smtp.rebind.fr', port: 587, user: 'u', pass: 'p', fromEmail: 'a@b.fr' };
|
||||
// 1re connexion : nom public → on se connecte à l'IP vérifiée, le nom ne sert qu'à SNI / certificat
|
||||
const pinned = await pinSmtp(s.app, u.id, smtp);
|
||||
assert.equal(pinned.host, PUBLIC);
|
||||
assert.equal(pinned.servername, 'smtp.rebind.fr');
|
||||
const transport = createTransport(pinned);
|
||||
assert.equal(transport.options.host, PUBLIC, 'le transport vise l\'IP, pas le nom (aucune seconde résolution possible)');
|
||||
assert.equal(transport.options.servername, 'smtp.rebind.fr');
|
||||
assert.equal(transport.options.tls.servername, 'smtp.rebind.fr');
|
||||
transport.close();
|
||||
// Le DNS répond maintenant 127.0.0.1, puis l'adresse des métadonnées : refus à chaque nouvelle connexion
|
||||
await assert.rejects(pinSmtp(s.app, u.id, smtp), /refusé/);
|
||||
await assert.rejects(pinSmtp(s.app, u.id, smtp), /refusé/);
|
||||
// Les autres services passent par le même contrôle
|
||||
answers = [['127.0.0.1'], ['127.0.0.1'], ['127.0.0.1']];
|
||||
await assert.rejects(pinImap(s.app, u.id, { host: 'imap.rebind.fr', port: 993 }), /refusé/);
|
||||
await assert.rejects(pinDb(s.app, u.id, { host: 'db.rebind.fr', type: 'mysql' }), /refusé/);
|
||||
await assert.rejects(pinGit(s.app, u.id, 'https://git.rebind.fr/a/b.git'), /refusé/);
|
||||
} finally { await s.close(); }
|
||||
});
|
||||
|
||||
test('épinglage git : http.curloptResolve vers l\'adresse vérifiée, aucune redirection suivie', async () => {
|
||||
const pin = { host: 'git.exemple.fr', port: 443, address: PUBLIC, family: 4 };
|
||||
assert.deepEqual(pinArgs(pin), ['-c', `http.curloptResolve=git.exemple.fr:443:${PUBLIC}`, '-c', 'http.followRedirects=false']);
|
||||
assert.deepEqual(pinArgs({ ...pin, address: '2606:4700::1', family: 6 }).slice(1, 2), ['http.curloptResolve=git.exemple.fr:443:[2606:4700::1]']);
|
||||
assert.deepEqual(pinArgs(null), []);
|
||||
const clone = cloneArgs('https://git.exemple.fr/a/b.git', '/d', pin);
|
||||
assert.ok(clone.includes(`http.curloptResolve=git.exemple.fr:443:${PUBLIC}`));
|
||||
assert.ok(clone.indexOf('clone') > clone.indexOf('http.followRedirects=false'), 'options avant la sous-commande');
|
||||
assert.ok(fetchArgs(pin).includes('http.followRedirects=false'));
|
||||
assert.equal(cloneArgs('https://x/a/b.git', '/d').includes('http.followRedirects=false'), false);
|
||||
const s = await startApp();
|
||||
try {
|
||||
const u = await s.newUser({ admin: false });
|
||||
s.app.resolveHost = dns({ 'git.exemple.fr': PUBLIC });
|
||||
assert.deepEqual(await pinGit(s.app, u.id, 'https://git.exemple.fr/a/b.git'), pin);
|
||||
assert.deepEqual(await pinGit(s.app, u.id, 'https://git.exemple.fr:8443/a/b.git'), { ...pin, port: 8443 });
|
||||
await assert.rejects(pinGit(s.app, u.id, 'https://git.exemple.fr:22/a/b.git'), /Port 22 refusé/);
|
||||
assert.equal(await pinGit(s.app, u.id, 'file:///tmp/depot'), null, 'les URL non https sont refusées plus loin par syncRepo');
|
||||
} finally { await s.close(); }
|
||||
});
|
||||
|
||||
// ---------- Branchement sur les enregistrements (réponse immédiate) ----------
|
||||
|
||||
test('enregistrement : SMTP, IMAP, base du récap, Forgejo et dépôt vers des adresses internes ou des ports interdits = 400', async () => {
|
||||
const s = await startApp();
|
||||
try {
|
||||
s.app.resolveHost = dns({ 'ok.exemple.fr': PUBLIC, 'prive.exemple.fr': '10.0.0.8', 'meta.exemple.fr': '169.254.169.254' });
|
||||
const u = await s.newUser({ admin: false, link: { v: 1, mode: 'api_key', valid: true } });
|
||||
const pid = Number((await s.db.prepare("INSERT INTO projects(user_id, name, git_url, created_at) VALUES(?, 'p', 'https://ok.exemple.fr/a/b.git', 1)").run(u.id)).lastInsertRowid);
|
||||
const refused = async (res, re, label) => { const b = await res.json(); assert.equal(res.status, 400, `${label} : ${JSON.stringify(b)}`); assert.match(b.error, re, label); };
|
||||
|
||||
await refused(await u.post(`/api/projects/${pid}/smtp`, { host: 'prive.exemple.fr', port: 587 }), /interne ou réservée/, 'SMTP privé');
|
||||
await refused(await u.post(`/api/projects/${pid}/smtp`, { host: '169.254.169.254', port: 25 }), /interne ou réservée/, 'SMTP métadonnées');
|
||||
await refused(await u.post(`/api/projects/${pid}/smtp`, { host: '127.0.0.1', port: 587 }), /interne ou réservée/, 'SMTP loopback');
|
||||
await refused(await u.post(`/api/projects/${pid}/smtp`, { host: 'ok.exemple.fr', port: 3306 }), /Port 3306 refusé/, 'SMTP port MySQL');
|
||||
assert.equal((await u.post(`/api/projects/${pid}/smtp`, { host: 'ok.exemple.fr', port: 587, user: 'u', pass: 'p' })).status, 200);
|
||||
// Hôte pas encore résolvable : enregistré (il sera revérifié à l'usage)
|
||||
assert.equal((await u.post(`/api/projects/${pid}/smtp`, { host: 'futur.exemple.fr', port: 587 })).status, 200);
|
||||
|
||||
await refused(await u.post(`/api/projects/${pid}/imap`, { host: 'meta.exemple.fr', port: 993 }), /interne ou réservée/, 'IMAP métadonnées');
|
||||
await refused(await u.post(`/api/projects/${pid}/imap`, { host: 'ok.exemple.fr', port: 22 }), /Port 22 refusé/, 'IMAP port SSH');
|
||||
|
||||
const db = { sql_users: '', sql_clients: '', sql_revenue: '' };
|
||||
await refused(await u.post(`/api/projects/${pid}/db`, { ...db, host: '127.0.0.1', port: 3306 }), /interne ou réservée/, 'BDD loopback');
|
||||
await refused(await u.post(`/api/projects/${pid}/db`, { ...db, type: 'pg', host: 'prive.exemple.fr' }), /interne ou réservée/, 'PostgreSQL privé');
|
||||
await refused(await u.post(`/api/projects/${pid}/db`, { ...db, host: 'ok.exemple.fr', port: 6379 }), /Port 6379 refusé/, 'BDD port Redis');
|
||||
assert.equal((await u.post(`/api/projects/${pid}/db`, { ...db, host: 'ok.exemple.fr', port: 3306 })).status, 200);
|
||||
|
||||
for (const [host, re] of [['prive.exemple.fr', /interne ou réservée/], ['localhost:3000', /interne|introuvable|Port/], ['ok.exemple.fr:22', /Port 22 refusé/]]) {
|
||||
const r = await u.post('/settings', { forgejo_host: host }, { form: true });
|
||||
assert.equal(r.status, 400, host);
|
||||
assert.match((await r.json()).error, re, host);
|
||||
}
|
||||
const sm = await u.post('/settings', { forgejo_host: 'ok.exemple.fr', smtp_host: 'prive.exemple.fr', smtp_port: '587' }, { form: true });
|
||||
assert.equal(sm.status, 400);
|
||||
assert.equal((await u.post('/settings', { forgejo_host: 'ok.exemple.fr' }, { form: true })).status, 303);
|
||||
|
||||
// Création de projet : le dépôt doit être sur l'hôte Forgejo enregistré, et cet hôte est revérifié
|
||||
await s.db.prepare("UPDATE user_settings SET value = 'prive.exemple.fr' WHERE user_id = ? AND `key` = 'forgejo_host'").run(u.id);
|
||||
await refused(await u.post('/api/projects', { name: 'X', gitUrl: 'https://prive.exemple.fr/a/x.git' }), /interne ou réservée/, 'dépôt privé');
|
||||
} finally { await s.close(); }
|
||||
});
|
||||
|
||||
// ---------- Branchement à l'usage (jobs, lecture IMAP, récap) ----------
|
||||
|
||||
test('à l\'usage : un hôte devenu interne fait échouer l\'envoi, la lecture IMAP et la synchronisation, sans connexion', async () => {
|
||||
const s = await startApp();
|
||||
try {
|
||||
const u = await s.newUser({ admin: true });
|
||||
s.app.resolveHost = dns({ 'smtp.exemple.fr': PUBLIC, 'imap.exemple.fr': PUBLIC, 'git.exemple.fr': PUBLIC });
|
||||
const calls = { transport: 0, imap: 0, sync: 0 };
|
||||
s.app.createTransport = () => { calls.transport++; return { verify: async () => true, sendMail: async () => {}, close() {} }; };
|
||||
s.app.fetchInbox = async () => { calls.imap++; return { messages: [], uidValidity: '1', lastUid: 0 }; };
|
||||
s.app.syncRepo = async (url, dir, token, opts) => { calls.sync++; calls.pin = opts.pin; return 'abc'; };
|
||||
const p = Number((await s.db.prepare("INSERT INTO projects(user_id, name, git_url, target_validated, created_at) VALUES(?, 'p', 'https://git.exemple.fr/a/b.git', 1, ?)").run(u.id, now())).lastInsertRowid);
|
||||
await saveSecretConfig(s.app, p, 'smtp_enc', { host: 'smtp.exemple.fr', port: 587, user: 'u', pass: 'p', fromEmail: 'a@b.fr' }, 'pass');
|
||||
await saveSecretConfig(s.app, p, 'imap_enc', { host: 'imap.exemple.fr', port: 993 }, 'pass');
|
||||
await s.db.prepare("INSERT INTO templates(project_id, kind, subject, body, status, updated_at) VALUES(?, 'initial', 's', 'b', 'validated', ?)").run(p, now());
|
||||
await s.db.prepare("INSERT INTO prospects(project_id, company, email, created_at) VALUES(?, 'E', 'e@x.fr', ?)").run(p, now());
|
||||
const worker = new Worker(s.db, makeHandlers(s.app), { log: { error() {} } });
|
||||
|
||||
// Tout est public : les pièces reçoivent l'adresse vérifiée
|
||||
await checkInbox(s.app, u.id, p);
|
||||
assert.equal(calls.imap, 1);
|
||||
const sentWith = [];
|
||||
s.app.createTransport = (smtp) => { sentWith.push(smtp); return { verify: async () => true, sendMail: async () => {}, close() {} }; };
|
||||
await enqueue(s.db, { userId: u.id, projectId: p, type: 'send', params: { count: 1 } });
|
||||
await worker.tick();
|
||||
assert.equal(sentWith[0].host, PUBLIC);
|
||||
assert.equal(sentWith[0].servername, 'smtp.exemple.fr');
|
||||
await enqueue(s.db, { userId: u.id, projectId: p, type: 'analyze' });
|
||||
await worker.tick();
|
||||
assert.deepEqual(calls.pin, { host: 'git.exemple.fr', port: 443, address: PUBLIC, family: 4 });
|
||||
|
||||
// Le DNS bascule vers le réseau interne : plus rien ne part, plus rien ne se connecte
|
||||
s.app.resolveHost = dns({ 'smtp.exemple.fr': '127.0.0.1', 'imap.exemple.fr': '10.0.0.3', 'git.exemple.fr': '169.254.169.254' });
|
||||
const before = { ...calls }; const sentBefore = sentWith.length;
|
||||
await s.db.prepare("INSERT INTO prospects(project_id, company, email, created_at) VALUES(?, 'F', 'f@y.fr', ?)").run(p, now());
|
||||
const send = (await enqueue(s.db, { userId: u.id, projectId: p, type: 'send', params: { count: 1 } })).id;
|
||||
await worker.tick();
|
||||
const job = await s.db.prepare('SELECT status, error FROM jobs WHERE id = ?').get(send);
|
||||
assert.equal(job.status, 'error');
|
||||
assert.match(job.error, /interne ou réservée/);
|
||||
assert.equal(sentWith.length, sentBefore, 'aucun transport créé');
|
||||
await assert.rejects(checkInbox(s.app, u.id, p), /interne ou réservée/);
|
||||
assert.equal(calls.imap, before.imap, 'fetchInbox n\'est pas appelé');
|
||||
const an = (await enqueue(s.db, { userId: u.id, projectId: p, type: 'template' })).id;
|
||||
await s.db.prepare("UPDATE jobs SET type = 'analyze' WHERE id = ?").run(an);
|
||||
await worker.tick();
|
||||
assert.equal((await s.db.prepare('SELECT status FROM jobs WHERE id = ?').get(an)).status, 'error');
|
||||
assert.equal(calls.sync, before.sync, 'syncRepo n\'est pas appelé');
|
||||
// Récap : l'accès BDD est revérifié
|
||||
await saveSecretConfig(s.app, p, 'db_enc', { type: 'mysql', host: 'db.exemple.fr', sql_users: 'select 1' }, 'password');
|
||||
s.app.resolveHost = dns({ 'db.exemple.fr': '192.168.1.5' });
|
||||
const r = await (await u.get(`/api/projects/${p}/recap?force=1`)).json();
|
||||
assert.match(r.error, /interne ou réservée/);
|
||||
} finally { await s.close(); }
|
||||
});
|
||||
|
|
@ -31,7 +31,7 @@ test('le worker ne démarre pas un job programmé avant son heure', async () =>
|
|||
let clock = now();
|
||||
const ran = [];
|
||||
const w = new Worker(db, { prospect: async () => { ran.push('prospect'); }, evolution: async () => { ran.push('evolution'); } },
|
||||
{ thermalMax: 999, log: { error() {} }, clock: () => clock });
|
||||
{ log: { error() {} }, clock: () => clock });
|
||||
const u = await addUser(db);
|
||||
await db.prepare("INSERT INTO projects(user_id, name, git_url, created_at) VALUES(?, 'p', 'u', ?)").run(u, now());
|
||||
await enqueue(db, { userId: u, projectId: 1, type: 'prospect', runAfter: clock + 3600 });
|
||||
|
|
|
|||
|
|
@ -15,7 +15,7 @@ const HOOK = 'https://discord.com/api/webhooks/123456789012345678/abcdefghijklmn
|
|||
async function setup({ events } = {}) {
|
||||
const db = await testDb();
|
||||
const sent = [];
|
||||
const app = {
|
||||
const app = { resolveHost: async () => [{ address: '93.184.216.34', family: 4 }],
|
||||
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 }; },
|
||||
};
|
||||
|
|
@ -82,7 +82,7 @@ test('le worker notifie en fin de job, et un callback qui plante ne le bloque pa
|
|||
const s = await setup();
|
||||
const seen = [];
|
||||
const w = new Worker(s.db, { prospect: async () => ({ found: 2, requested: 5 }), evolution: async () => { throw new Error('boom'); } }, {
|
||||
thermalMax: 999, log: { error() {} },
|
||||
log: { error() {} },
|
||||
onFinish: (job, r) => { seen.push(`${job.type}:${r.status}`); if (job.type === 'evolution') throw new Error('callback cassé'); },
|
||||
});
|
||||
await enqueue(s.db, { userId: s.userId, projectId: s.id, type: 'prospect' });
|
||||
|
|
|
|||
251
test/plans.test.js
Normal file
251
test/plans.test.js
Normal file
|
|
@ -0,0 +1,251 @@
|
|||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { randomBytes } from 'node:crypto';
|
||||
import { setSetting, now } from '../src/db.js';
|
||||
import { testDb } from './helpers/db.js';
|
||||
import { addUser } from './helpers/users.js';
|
||||
import { Worker, enqueue, cancelJob } from '../src/services/jobs.js';
|
||||
import { makeHandlers } from '../src/handlers.js';
|
||||
import { createProject, saveSecretConfig } from '../src/projects.js';
|
||||
import { getUser } from '../src/users.js';
|
||||
import { PLAN_LIMITS } from '../src/limits.js';
|
||||
import { monthBounds, usageOf, quotaFor, assertRoom, recordUsage, planOf, usageView } from '../src/services/plans.js';
|
||||
import { encrypt } from '../src/crypto.js';
|
||||
import { importProspects } from '../src/services/csv.js';
|
||||
import { startApp } from './helpers/server.js';
|
||||
|
||||
// Plafonds du plan gratuit appliqués côté serveur : à la limite exacte, sans compteur qui dérive, sans perte de données.
|
||||
|
||||
const LINK = { v: 1, mode: 'api_key', valid: true };
|
||||
const free = (db, extra = {}) => addUser(db, { admin: false, link: LINK, ...extra });
|
||||
|
||||
async function world() {
|
||||
const db = await testDb();
|
||||
const sent = [];
|
||||
const app = { resolveHost: async () => [{ address: '93.184.216.34', family: 4 }],
|
||||
db, cfg: { dataDir: '/tmp/x', appUrl: 'https://ai.test', secretKey: randomBytes(32), sandbox: { enabled: false } },
|
||||
createTransport: () => ({ verify: async () => true, sendMail: async (m) => { sent.push(m); }, close() {} }),
|
||||
};
|
||||
return { db, app, sent };
|
||||
}
|
||||
const proj = async (w, userId, n = 1) => Number((await w.db.prepare('INSERT INTO projects(user_id, name, git_url, created_at) VALUES(?, ?, ?, ?)').run(userId, `p${n}`, `https://git.test/u${userId}/r${n}.git`, now())).lastInsertRowid);
|
||||
|
||||
test('les limites viennent d\'un seul module et reprennent le cadrage', () => {
|
||||
assert.deepEqual(PLAN_LIMITS.free, { projects: 1, prospects: 50, mails: 100, aiJobs: 5 });
|
||||
});
|
||||
|
||||
test('mois calendaire à l\'heure de Paris, changement d\'heure compris', () => {
|
||||
const iso = (t) => new Date(t * 1000).toISOString();
|
||||
// 31 oct. 2026 23:30 UTC = 1er nov. 00:30 à Paris (heure d'hiver depuis le 25 oct.) : c'est déjà novembre
|
||||
let b = monthBounds(Date.parse('2026-10-31T23:30:00Z') / 1000);
|
||||
assert.equal(iso(b.start), '2026-10-31T23:00:00.000Z');
|
||||
assert.equal(iso(b.end), '2026-11-30T23:00:00.000Z');
|
||||
// 31 oct. 22:30 UTC = 23:30 à Paris : encore octobre (heure d'été jusqu'au 25 oct. : décalage +1 h seulement après)
|
||||
b = monthBounds(Date.parse('2026-10-31T22:30:00Z') / 1000);
|
||||
assert.equal(iso(b.start), '2026-09-30T22:00:00.000Z');
|
||||
assert.equal(iso(b.end), '2026-10-31T23:00:00.000Z');
|
||||
b = monthBounds(Date.parse('2026-12-15T12:00:00Z') / 1000);
|
||||
assert.equal(iso(b.end), '2026-12-31T23:00:00.000Z');
|
||||
});
|
||||
|
||||
test('plan : un administrateur n\'a pas de limite, un plan inconnu retombe sur gratuit', async () => {
|
||||
const w = await world();
|
||||
const a = await getUser(w.db, await addUser(w.db, { admin: true }));
|
||||
const f = await getUser(w.db, await free(w.db));
|
||||
assert.equal(planOf(a), 'admin');
|
||||
assert.equal(planOf(f), 'free');
|
||||
assert.equal(planOf({ ...f, plan: 'invente' }), 'free');
|
||||
assert.equal(planOf({ ...f, plan: 'admin' }), 'admin', 'plan « admin » explicite');
|
||||
assert.equal((await quotaFor(w.db, a, 'mails')).unlimited, true);
|
||||
await assert.doesNotReject(assertRoom(w.db, a, 'projects', 1000));
|
||||
});
|
||||
|
||||
test('projets : le 2e est refusé (403 plan_limit, lien /tarifs), un admin crée sans limite, créations simultanées bornées', async () => {
|
||||
const w = await world();
|
||||
const u = await free(w.db);
|
||||
await createProject(w.app, { userId: u, name: 'A', gitUrl: 'https://git.test/a/a.git' });
|
||||
await assert.rejects(createProject(w.app, { userId: u, name: 'B', gitUrl: 'https://git.test/a/b.git' }), (e) => {
|
||||
assert.equal(e.status, 403);
|
||||
assert.equal(e.code, 'plan_limit');
|
||||
assert.equal(e.data.upgradeUrl, '/tarifs');
|
||||
assert.match(e.message, /plafond du plan gratuit/);
|
||||
assert.match(e.message, /Rien n'est supprimé ni perdu/);
|
||||
assert.match(e.message, /\/tarifs/);
|
||||
return true;
|
||||
});
|
||||
assert.equal((await w.db.prepare('SELECT COUNT(*) n FROM projects WHERE user_id = ?').get(u)).n, 1, 'aucun projet supprimé');
|
||||
const admin = await addUser(w.db, { admin: true });
|
||||
for (let i = 0; i < 3; i++) await createProject(w.app, { userId: admin, name: `P${i}`, gitUrl: `https://git.test/z/${i}.git` });
|
||||
const u2 = await free(w.db);
|
||||
const res = await Promise.allSettled([1, 2, 3, 4].map((i) => createProject(w.app, { userId: u2, name: `C${i}`, gitUrl: `https://git.test/c/${i}.git` })));
|
||||
assert.equal(res.filter((r) => r.status === 'fulfilled').length, 1, 'une seule création passe malgré la simultanéité');
|
||||
});
|
||||
|
||||
test('jobs IA : 5 par mois, le 6e est refusé ; annulé sans démarrer = rendu ; projet supprimé = toujours compté', async () => {
|
||||
const w = await world();
|
||||
const u = await free(w.db);
|
||||
const p = await proj(w, u);
|
||||
const types = ['analyze', 'prospect', 'template', 'followup_template', 'evolution'];
|
||||
const ids = [];
|
||||
for (const type of types) ids.push((await enqueue(w.db, { userId: u, projectId: p, type })).id);
|
||||
assert.equal((await usageOf(w.db, u)).aiJobs, 5);
|
||||
await assert.rejects(enqueue(w.db, { userId: u, projectId: p, type: 'analyze' }).then(() => enqueue(w.db, { userId: u, projectId: null, type: 'analyze' })), { status: 403, code: 'plan_limit' });
|
||||
// Le même job déjà en file n'est pas recompté (dédoublonnage)
|
||||
assert.equal((await enqueue(w.db, { userId: u, projectId: p, type: 'template' })).existing, true);
|
||||
// Annulé avant de démarrer : rendu
|
||||
await cancelJob(w.db, u, ids[0]);
|
||||
assert.equal((await usageOf(w.db, u)).aiJobs, 4);
|
||||
await enqueue(w.db, { userId: u, projectId: p, type: 'analyze' });
|
||||
await assert.rejects(enqueue(w.db, { userId: u, projectId: null, type: 'template' }), { code: 'plan_limit' }, 'à la limite exacte');
|
||||
// Supprimer le projet efface ses jobs, pas la consommation du mois
|
||||
await w.db.prepare('DELETE FROM projects WHERE id = ?').run(p);
|
||||
assert.equal((await w.db.prepare('SELECT COUNT(*) n FROM jobs WHERE user_id = ?').get(u)).n, 0);
|
||||
assert.ok((await usageOf(w.db, u)).aiJobs >= 5, 'pas de contournement par suppression du projet (le job annulé, disparu avec le projet, compte par prudence)');
|
||||
const p2 = await proj(w, u, 2);
|
||||
await assert.rejects(enqueue(w.db, { userId: u, projectId: p2, type: 'evolution' }), { code: 'plan_limit' });
|
||||
// Le mois suivant, tout repart de zéro
|
||||
const next = monthBounds().end + 3600;
|
||||
assert.equal((await usageOf(w.db, u, { at: next })).aiJobs, 0);
|
||||
// Les jobs sans IA (envoi) ne consomment pas de job IA
|
||||
const admin = await addUser(w.db, { admin: true });
|
||||
for (let i = 0; i < 8; i++) await recordUsage(w.db, admin, 'ai_job', { ref: null });
|
||||
await assert.doesNotReject(assertRoom(w.db, await getUser(w.db, admin), 'aiJobs'));
|
||||
});
|
||||
|
||||
test('jobs IA : le plafond d\'un compte ne touche pas un autre compte', async () => {
|
||||
const w = await world();
|
||||
const a = await free(w.db), b = await free(w.db);
|
||||
const pa = await proj(w, a), pb = await proj(w, b);
|
||||
for (const type of ['analyze', 'prospect', 'template', 'followup_template', 'evolution']) await enqueue(w.db, { userId: a, projectId: pa, type });
|
||||
await assert.doesNotReject(enqueue(w.db, { userId: b, projectId: pb, type: 'analyze' }));
|
||||
});
|
||||
|
||||
test('mails : 100 par mois, le 101e refusé à la limite exacte ; un lot est tronqué à ce qui reste, sans perte', async () => {
|
||||
const w = await world();
|
||||
const u = await free(w.db);
|
||||
const user = await getUser(w.db, u);
|
||||
for (let i = 0; i < 99; i++) await recordUsage(w.db, u, 'mail');
|
||||
assert.equal((await quotaFor(w.db, user, 'mails')).remaining, 1);
|
||||
await assert.doesNotReject(assertRoom(w.db, user, 'mails', 1));
|
||||
await assert.rejects(assertRoom(w.db, user, 'mails', 2), (e) => /Il te reste 1 mail ce mois-ci sur 100/.test(e.message));
|
||||
await recordUsage(w.db, u, 'mail');
|
||||
await assert.rejects(assertRoom(w.db, user, 'mails', 1), (e) => e.code === 'plan_limit' && /100 mails ce mois-ci sur 100/.test(e.message));
|
||||
|
||||
// Lot réel : 98 déjà envoyés, 5 demandés → 2 partent, 3 prospects restent à contacter, le suivant est refusé
|
||||
const w2 = await world();
|
||||
const v = await free(w2.db);
|
||||
await setSetting(w2.db, v, 'send_delay_min', '0'); await setSetting(w2.db, v, 'send_delay_max', '0');
|
||||
const p = await proj(w2, v);
|
||||
await saveSecretConfig(w2.app, p, 'smtp_enc', { host: 'smtp.test', port: 587, user: 'u', pass: 'p', fromEmail: 'a@b.fr' }, 'pass');
|
||||
await w2.db.prepare("INSERT INTO templates(project_id, kind, subject, body, status, updated_at) VALUES(?, 'initial', 's', 'b {{entreprise}}', 'validated', ?)").run(p, now());
|
||||
for (let i = 0; i < 5; i++) await w2.db.prepare("INSERT INTO prospects(project_id, company, email, created_at) VALUES(?, ?, ?, ?)").run(p, `E${i}`, `e${i}@x${i}.fr`, now());
|
||||
for (let i = 0; i < 98; i++) await recordUsage(w2.db, v, 'mail');
|
||||
const worker = new Worker(w2.db, makeHandlers(w2.app), { log: { error() {} } });
|
||||
const { id } = await enqueue(w2.db, { userId: v, projectId: p, type: 'send', params: { count: 5 } });
|
||||
await worker.tick();
|
||||
const job = await w2.db.prepare('SELECT status, result_json FROM jobs WHERE id = ?').get(id);
|
||||
assert.equal(job.status, 'done');
|
||||
assert.equal(JSON.parse(job.result_json).sent, 2);
|
||||
assert.equal(w2.sent.length, 2);
|
||||
assert.equal((await w2.db.prepare("SELECT COUNT(*) n FROM prospects WHERE project_id = ? AND status = 'new'").get(p)).n, 3, 'rien de perdu');
|
||||
await assert.rejects(enqueue(w2.db, { userId: v, projectId: p, type: 'send', params: { count: 1 } }), { code: 'plan_limit' });
|
||||
await assert.rejects(enqueue(w2.db, { userId: v, projectId: p, type: 'followup', params: { count: 1 } }), { code: 'plan_limit' });
|
||||
});
|
||||
|
||||
test('prospects : 50 au total, l\'import est refusé en entier (rien importé) au-delà, accepté à la limite exacte', async () => {
|
||||
const w = await world();
|
||||
const u = await free(w.db);
|
||||
const user = await getUser(w.db, u);
|
||||
const p = await proj(w, u);
|
||||
const csv = (from, n) => 'email,entreprise\n' + Array.from({ length: n }, (_, i) => `c${from + i}@dom${from + i}.fr,E${from + i}`).join('\n');
|
||||
const q = () => quotaFor(w.db, user, 'prospects');
|
||||
const imp = async (text) => {
|
||||
const quota = await q();
|
||||
return importProspects(w.db, p, text, { limit: quota.remaining, limitError: new Error(`plafond : il reste ${quota.remaining}`) });
|
||||
};
|
||||
assert.equal((await imp(csv(0, 49))).imported, 49);
|
||||
await assert.rejects(imp(csv(100, 2)), /il reste 1/);
|
||||
assert.equal((await q()).used, 49, 'l\'import refusé n\'a rien écrit (tout ou rien)');
|
||||
assert.equal((await imp(csv(200, 1))).imported, 1, '50e prospect : accepté');
|
||||
await assert.rejects(imp(csv(300, 1)), /il reste 0/);
|
||||
assert.equal((await q()).used, 50);
|
||||
});
|
||||
|
||||
test('prospection : les prospects trouvés au-delà du plafond ne sont pas enregistrés, le job signale le plafond', async () => {
|
||||
const w = await world();
|
||||
const u = await free(w.db, { link: { v: 1, mode: 'api_key', valid: true, secret_enc: encrypt(w.app.cfg.secretKey, 'sk-ant-' + 'a'.repeat(30)) } });
|
||||
const p = await proj(w, u);
|
||||
await w.db.prepare('UPDATE projects SET profile_json = ?, target_json = ?, target_validated = 1 WHERE id = ?').run(JSON.stringify({ resume: 'r', proposition_valeur: 'v' }), JSON.stringify({ description: 'd', secteurs: ['s'] }), p);
|
||||
for (let i = 0; i < 49; i++) await w.db.prepare('INSERT INTO prospects(project_id, company, email, created_at) VALUES(?, ?, ?, ?)').run(p, `E${i}`, `e${i}@d${i}.fr`, now());
|
||||
const { resolve } = await import('node:path');
|
||||
w.app.cfg.claudeBin = resolve('test/fixtures/fake-claude.js');
|
||||
const worker = new Worker(w.db, makeHandlers(w.app), { log: { error() {} } });
|
||||
const { id } = await enqueue(w.db, { userId: u, projectId: p, type: 'prospect', params: { count: 3 } });
|
||||
await worker.tick();
|
||||
const job = await w.db.prepare('SELECT status, error, result_json FROM jobs WHERE id = ?').get(id);
|
||||
assert.equal(job.status, 'done', job.error);
|
||||
const r = JSON.parse(job.result_json);
|
||||
assert.equal(r.found, 1);
|
||||
assert.equal(r.capped, true);
|
||||
assert.equal((await w.db.prepare('SELECT COUNT(*) n FROM prospects WHERE project_id = ?').get(p)).n, 50);
|
||||
});
|
||||
|
||||
test('HTTP : refus explicite avec code plan_limit et lien /tarifs ; le projet est créé même si l\'analyse est refusée', async () => {
|
||||
const s = await startApp();
|
||||
try {
|
||||
const u = await s.newUser({ admin: false, link: LINK });
|
||||
await s.db.prepare("INSERT INTO user_settings(user_id, `key`, value) VALUES(?, 'forgejo_host', 'git.test')").run(u.id);
|
||||
for (let i = 0; i < 5; i++) await recordUsage(s.db, u.id, 'ai_job');
|
||||
const ok = await u.post('/api/projects', { name: 'Un', gitUrl: 'https://git.test/a/un.git' });
|
||||
assert.equal(ok.status, 200);
|
||||
const body = await ok.json();
|
||||
assert.ok(body.id);
|
||||
assert.match(body.notice, /plafond du plan gratuit/, 'le projet existe, seule l\'analyse attend');
|
||||
const second = await u.post('/api/projects', { name: 'Deux', gitUrl: 'https://git.test/a/deux.git' });
|
||||
assert.equal(second.status, 403);
|
||||
const e = await second.json();
|
||||
assert.equal(e.code, 'plan_limit');
|
||||
assert.equal(e.upgradeUrl, '/tarifs');
|
||||
assert.match(e.error, /\/tarifs/);
|
||||
const analyze = await u.post(`/api/projects/${body.id}/analyze`, {});
|
||||
assert.equal(analyze.status, 403);
|
||||
assert.equal((await analyze.json()).code, 'plan_limit');
|
||||
} finally { await s.close(); }
|
||||
});
|
||||
|
||||
test('Mon compte et tableau de bord : barres d\'usage du mois, plafond atteint signalé ; admin sans barre de plafond', async () => {
|
||||
const s = await startApp();
|
||||
try {
|
||||
const u = await s.newUser({ admin: false, link: LINK });
|
||||
const pid = await proj({ db: s.db }, u.id);
|
||||
for (let i = 0; i < 100; i++) await recordUsage(s.db, u.id, 'mail');
|
||||
for (const page of ['/account', '/']) {
|
||||
const h = await (await u.get(page, { headers: { accept: 'text/html' } })).text();
|
||||
assert.match(h, /Usage du mois/, page);
|
||||
assert.match(h, /plan gratuit/, page);
|
||||
assert.match(h, /Mails ce mois-ci<\/span><span class="jpct">100 \/ 100/, page);
|
||||
assert.match(h, /<div class="bar usage full"><span class="w-100">/, page);
|
||||
assert.match(h, /<span class="w-100">/);
|
||||
assert.match(h, /Plafond atteint : .*mails ce mois-ci/, page);
|
||||
assert.match(h, /Projets<\/span><span class="jpct">1 \/ 1/, page);
|
||||
assert.doesNotMatch(h, /style="/, 'pas de style en ligne (CSP)');
|
||||
}
|
||||
assert.ok(pid);
|
||||
const a = await s.newUser({ admin: true });
|
||||
const h = await (await a.get('/account', { headers: { accept: 'text/html' } })).text();
|
||||
assert.match(h, /plan administrateur/);
|
||||
assert.doesNotMatch(h, /class="bar usage/);
|
||||
const view = await usageView(s.db, await getUser(s.db, u.id));
|
||||
assert.deepEqual(view.items.map((i) => i.limit), [1, 50, 100, 5]);
|
||||
} finally { await s.close(); }
|
||||
});
|
||||
|
||||
test('Tarifs : plus de « pas encore appliqués », chiffres identiques à la configuration', async () => {
|
||||
const s = await startApp();
|
||||
try {
|
||||
const h = await (await s.anon.get('/tarifs', { headers: { accept: 'text/html' } })).text();
|
||||
assert.doesNotMatch(h, /pas encore appliqu/);
|
||||
assert.match(h, /appliqués par le serveur/);
|
||||
for (const n of Object.values(PLAN_LIMITS.free)) assert.ok(h.includes(`<strong>${n}</strong>`), String(n));
|
||||
} finally { await s.close(); }
|
||||
});
|
||||
247
test/queue.test.js
Normal file
247
test/queue.test.js
Normal file
|
|
@ -0,0 +1,247 @@
|
|||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { mkdtempSync, mkdirSync, readFileSync, rmSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { now } from '../src/db.js';
|
||||
import { encrypt } from '../src/crypto.js';
|
||||
import { testDb } from './helpers/db.js';
|
||||
import { addUser } from './helpers/users.js';
|
||||
import { startApp } from './helpers/server.js';
|
||||
import { makeClaudeBin } from './helpers/claude-bin.js';
|
||||
import { Worker, enqueue } from '../src/services/jobs.js';
|
||||
import { makeHandlers } from '../src/handlers.js';
|
||||
import { loadConfig } from '../src/config.js';
|
||||
|
||||
// File de jobs équitable et simultanée : plafond global, un job à la fois par utilisateur, tourniquet,
|
||||
// réservation atomique, pause de charge, arrêt propre. Les jobs « prospect » et « evolution » des tests sont de simples
|
||||
// fonctions instrumentées ; le dernier test lance le vrai circuit avec le CLI simulé.
|
||||
|
||||
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
||||
const log = { error() {} };
|
||||
|
||||
async function world(n = 3) {
|
||||
const db = await testDb();
|
||||
const users = [];
|
||||
for (let i = 0; i < n; i++) {
|
||||
const id = await addUser(db);
|
||||
const p = Number((await db.prepare("INSERT INTO projects(user_id, name, git_url, created_at) VALUES(?, 'p', ?, ?)").run(id, `https://git.test/${id}.git`, now())).lastInsertRowid);
|
||||
users.push({ id, p });
|
||||
}
|
||||
return { db, users };
|
||||
}
|
||||
const q = (db, u, type) => enqueue(db, { userId: u.id, projectId: u.p, type }).then((r) => r.id);
|
||||
async function until(fn, ms = 5000) {
|
||||
const t0 = Date.now();
|
||||
while (!(await fn())) { if (Date.now() - t0 > ms) throw new Error('délai dépassé'); await sleep(10); }
|
||||
}
|
||||
|
||||
test('plafond global : jamais plus de maxJobs en parallèle, jamais deux jobs du même utilisateur', async () => {
|
||||
const { db, users } = await world(3);
|
||||
let cur = 0, max = 0;
|
||||
const perUser = new Map(); let perUserMax = 0;
|
||||
const starts = [];
|
||||
const handler = async (ctx) => {
|
||||
cur++; max = Math.max(max, cur);
|
||||
const n = (perUser.get(ctx.job.user_id) || 0) + 1; perUser.set(ctx.job.user_id, n); perUserMax = Math.max(perUserMax, n);
|
||||
starts.push(ctx.job.user_id);
|
||||
await sleep(40);
|
||||
cur--; perUser.set(ctx.job.user_id, n - 1);
|
||||
return {};
|
||||
};
|
||||
for (const u of users) { await q(db, u, 'prospect'); await q(db, u, 'evolution'); }
|
||||
const w = new Worker(db, { prospect: handler, evolution: handler }, { maxJobs: 2, pollMs: 10, log });
|
||||
await w.start();
|
||||
await until(async () => (await db.prepare("SELECT COUNT(*) n FROM jobs WHERE status IN ('queued','running')").get()).n === 0);
|
||||
await w.stop();
|
||||
assert.equal(max, 2, 'deux jobs en parallèle, pas plus');
|
||||
assert.equal(perUserMax, 1, 'jamais deux jobs du même utilisateur en même temps');
|
||||
assert.equal(starts.length, 6);
|
||||
// Tourniquet : le 3e utilisateur démarre avant que le 1er ne reçoive son 2e job
|
||||
const [a, b, c] = users.map((u) => u.id);
|
||||
assert.deepEqual(starts.slice(0, 3), [a, b, c]);
|
||||
assert.deepEqual(starts.slice(3), [a, b, c]);
|
||||
});
|
||||
|
||||
test('un seul utilisateur avec beaucoup de jobs ne prend qu\'un emplacement, les autres passent', async () => {
|
||||
const { db, users } = await world(2);
|
||||
const order = [];
|
||||
const w = new Worker(db, {
|
||||
prospect: async (ctx) => { order.push(`${ctx.job.user_id}:${ctx.job.type}`); await sleep(60); return {}; },
|
||||
evolution: async (ctx) => { order.push(`${ctx.job.user_id}:${ctx.job.type}`); await sleep(60); return {}; },
|
||||
template: async (ctx) => { order.push(`${ctx.job.user_id}:${ctx.job.type}`); await sleep(60); return {}; },
|
||||
}, { maxJobs: 4, pollMs: 10, log });
|
||||
const [a, b] = users;
|
||||
await q(db, a, 'prospect'); await q(db, a, 'evolution'); await q(db, a, 'template');
|
||||
await q(db, b, 'prospect');
|
||||
await w.start();
|
||||
await until(async () => (await db.prepare("SELECT COUNT(*) n FROM jobs WHERE status IN ('queued','running')").get()).n === 0);
|
||||
await w.stop();
|
||||
assert.equal(order[0], `${a.id}:prospect`);
|
||||
assert.equal(order[1], `${b.id}:prospect`, 'B part tout de suite, malgré la file de A et 4 emplacements libres');
|
||||
assert.deepEqual(order.filter((x) => x.startsWith(`${a.id}:`)), [`${a.id}:prospect`, `${a.id}:evolution`, `${a.id}:template`], 'ordre propre à l\'utilisateur conservé');
|
||||
});
|
||||
|
||||
test('réservation atomique : deux workers sur la même base, un job n\'est réservé qu\'une fois', async () => {
|
||||
const { db, users } = await world(1);
|
||||
const [u] = users;
|
||||
const id = await q(db, u, 'prospect');
|
||||
const w1 = new Worker(db, {}, { log }), w2 = new Worker(db, {}, { log });
|
||||
const [j1, j2] = await Promise.all([w1.claim(), w2.claim()]);
|
||||
assert.equal([j1, j2].filter(Boolean).length, 1, 'un seul worker obtient le job');
|
||||
assert.equal((await db.prepare('SELECT status FROM jobs WHERE id = ?').get(id)).status, 'running');
|
||||
// Le second job du même utilisateur ne peut pas être réservé tant que le premier tourne (garde en base, pas seulement en mémoire)
|
||||
const id2 = await q(db, u, 'evolution');
|
||||
const intruder = (await db.prepare('SELECT * FROM jobs WHERE id = ?').get(id2));
|
||||
assert.equal(await new Worker(db, {}, { log }).reserve(intruder), false);
|
||||
assert.equal((await db.prepare('SELECT status FROM jobs WHERE id = ?').get(id2)).status, 'queued');
|
||||
// Et un job déjà réservé ne l'est pas deux fois
|
||||
assert.equal(await new Worker(db, {}, { log }).reserve({ id, user_id: 999 }), false);
|
||||
});
|
||||
|
||||
test('claim() appelé en rafale : le plafond et l\'unicité par utilisateur tiennent', async () => {
|
||||
const { db, users } = await world(5);
|
||||
for (const u of users) { await q(db, u, 'prospect'); await q(db, u, 'evolution'); }
|
||||
const w = new Worker(db, {}, { maxJobs: 3, log });
|
||||
const got = (await Promise.all(Array.from({ length: 12 }, () => w.claim()))).filter(Boolean);
|
||||
assert.equal(got.length, 3);
|
||||
assert.equal(new Set(got.map((j) => j.user_id)).size, 3, 'trois utilisateurs différents');
|
||||
assert.equal((await db.prepare("SELECT COUNT(*) n FROM jobs WHERE status = 'running'").get()).n, 3);
|
||||
});
|
||||
|
||||
test('jobs programmés : ni avant l\'heure, ni dans le désordre ; l\'ordre par id est conservé après', async () => {
|
||||
const { db, users } = await world(2);
|
||||
const [a, b] = users;
|
||||
let clock = 1000;
|
||||
const night = 5000;
|
||||
const ids = {};
|
||||
ids.a = (await enqueue(db, { userId: a.id, projectId: a.p, type: 'prospect', runAfter: night })).id;
|
||||
ids.b = (await enqueue(db, { userId: b.id, projectId: b.p, type: 'prospect', runAfter: night })).id;
|
||||
ids.a2 = (await enqueue(db, { userId: a.id, projectId: a.p, type: 'evolution' })).id;
|
||||
const w = new Worker(db, {}, { maxJobs: 4, clock: () => clock, log });
|
||||
const first = await w.claim();
|
||||
assert.equal(first.id, ids.a2, 'seul le job sans heure est dû');
|
||||
assert.equal(await w.claim(), null, 'le job de nuit d\'A attend, et A est déjà occupé');
|
||||
clock = night;
|
||||
const second = await w.claim();
|
||||
assert.equal(second.id, ids.b, 'B (jamais servi) avant A');
|
||||
await db.prepare("UPDATE jobs SET status = 'done' WHERE id = ?").run(ids.a2);
|
||||
w.busyUsers.delete(a.id);
|
||||
assert.equal((await w.claim()).id, ids.a);
|
||||
});
|
||||
|
||||
test('pause de charge : les nouveaux jobs attendent (message clair), reprise avec hystérésis, jobs en cours épargnés', async () => {
|
||||
const { db, users } = await world(2);
|
||||
const [a, b] = users;
|
||||
let ratio = 0.95;
|
||||
const notified = [];
|
||||
const w = new Worker(db, {}, { maxJobs: 4, loadMax: 0.9, load: () => ratio, log, onLoad: (r, uid) => notified.push(uid) });
|
||||
const ja = await q(db, a, 'prospect');
|
||||
assert.equal(await w.claim(), null);
|
||||
const prog = JSON.parse((await db.prepare('SELECT progress_json FROM jobs WHERE id = ?').get(ja)).progress_json);
|
||||
assert.match(prog.message, /charge du serveur élevée \(95 %\)/);
|
||||
assert.equal((await db.prepare('SELECT status FROM jobs WHERE id = ?').get(ja)).status, 'queued');
|
||||
await w.claim(); await w.idle();
|
||||
assert.deepEqual(notified, [a.id], 'une seule notification par pause');
|
||||
ratio = 0.85; // sous 0,9 mais pas sous 0,8 : on reste en pause
|
||||
assert.equal(await w.claim(), null);
|
||||
ratio = 0.79;
|
||||
assert.equal((await w.claim()).id, ja);
|
||||
// Charge de nouveau élevée : le job de B attend, celui de A (en cours) n'est pas touché
|
||||
ratio = 0.99;
|
||||
await q(db, b, 'prospect');
|
||||
assert.equal(await w.claim(), null);
|
||||
assert.equal((await db.prepare('SELECT status FROM jobs WHERE id = ?').get(ja)).status, 'running');
|
||||
});
|
||||
|
||||
test('arrêt propre : tous les jobs en cours sont interrompus ET attendus', async () => {
|
||||
const { db, users } = await world(3);
|
||||
let started = 0;
|
||||
const finished = [];
|
||||
const handler = (ctx) => new Promise((_, reject) => {
|
||||
started++;
|
||||
ctx.signal.addEventListener('abort', () => setTimeout(() => { finished.push(ctx.job.id); reject(new Error('Annulé')); }, 30), { once: true });
|
||||
});
|
||||
for (const u of users) await q(db, u, 'prospect');
|
||||
const w = new Worker(db, { prospect: handler }, { maxJobs: 3, pollMs: 10, log });
|
||||
await w.start();
|
||||
await until(() => started === 3);
|
||||
await w.stop();
|
||||
assert.equal(finished.length, 3, 'les trois jobs ont fini avant le retour de stop()');
|
||||
assert.equal(w.running.size, 0);
|
||||
assert.equal(w.busyUsers.size, 0);
|
||||
assert.equal((await db.prepare("SELECT COUNT(*) n FROM jobs WHERE status = 'error'").get()).n, 3);
|
||||
assert.equal(await w.claim(), null, 'plus rien ne démarre après l\'arrêt');
|
||||
});
|
||||
|
||||
test('suppression d\'un compte et déliaison n\'interrompent que les jobs de ce compte', async () => {
|
||||
const { db, users } = await world(2);
|
||||
const aborted = [];
|
||||
const handler = (ctx) => new Promise((resolve) => {
|
||||
ctx.signal.addEventListener('abort', () => { aborted.push(ctx.job.user_id); resolve({}); }, { once: true });
|
||||
setTimeout(resolve, 300);
|
||||
});
|
||||
for (const u of users) await q(db, u, 'prospect');
|
||||
const w = new Worker(db, { prospect: handler }, { maxJobs: 2, pollMs: 10, log, isAiJob: () => true });
|
||||
await w.start();
|
||||
await until(() => w.running.size === 2);
|
||||
w.abortUser(users[0].id);
|
||||
w.abortUserAi(users[1].id);
|
||||
await until(() => aborted.length === 2);
|
||||
assert.deepEqual(aborted.sort(), users.map((u) => u.id).sort());
|
||||
await w.stop();
|
||||
});
|
||||
|
||||
test('configuration : MAX_AI_JOBS (4 par défaut) et LOAD_MAX validés', () => {
|
||||
const base = { APP_URL: 'https://x.fr', SECRET_KEY: 'a'.repeat(64), GOOGLE_CLIENT_ID: 'g', GOOGLE_CLIENT_SECRET: 's', DB_DRIVER: 'sqlite' };
|
||||
const keep = { ...process.env };
|
||||
const withEnv = (extra, fn) => {
|
||||
delete process.env.MAX_AI_JOBS; delete process.env.LOAD_MAX;
|
||||
Object.assign(process.env, base, extra);
|
||||
try { return fn(); } finally {
|
||||
for (const k of Object.keys(process.env)) if (!(k in keep)) delete process.env[k];
|
||||
Object.assign(process.env, keep);
|
||||
}
|
||||
};
|
||||
assert.equal(withEnv({}, () => loadConfig().maxAiJobs), 4);
|
||||
assert.equal(withEnv({}, () => loadConfig().loadMax), 0.9);
|
||||
assert.equal(withEnv({ MAX_AI_JOBS: '2', LOAD_MAX: '1.2' }, () => loadConfig().maxAiJobs), 2);
|
||||
assert.throws(() => withEnv({ MAX_AI_JOBS: '0' }, loadConfig), /MAX_AI_JOBS/);
|
||||
assert.throws(() => withEnv({ MAX_AI_JOBS: 'beaucoup' }, loadConfig), /MAX_AI_JOBS/);
|
||||
assert.throws(() => withEnv({ LOAD_MAX: '0' }, loadConfig), /LOAD_MAX/);
|
||||
});
|
||||
|
||||
test('avec le CLI simulé : deux utilisateurs tournent en parallèle, jamais deux processus pour le même utilisateur', async () => {
|
||||
const tmp = mkdtempSync(join(tmpdir(), 'aitools-q-'));
|
||||
const trace = join(tmp, 'trace.log');
|
||||
const s = await startApp({ cfg: { claudeBin: makeClaudeBin(tmp, { env: { FAKE_LOG: trace.split('\\').join('/'), FAKE_DELAY_MS: '350' } }) } });
|
||||
try {
|
||||
const key = (c) => `sk-ant-api03-${'x'.repeat(30)}${c.repeat(4)}`;
|
||||
const mk = async (c) => {
|
||||
const u = await s.newUser({ admin: false, link: { v: 1, mode: 'api_key', valid: true, last4: c, secret_enc: encrypt(s.app.cfg.secretKey, key(c)) } });
|
||||
const p = Number((await s.db.prepare('INSERT INTO projects(user_id, name, git_url, profile_json, target_json, target_validated, created_at) VALUES(?, ?, ?, ?, ?, 1, ?)')
|
||||
.run(u.id, 'P', `https://git.test/${c}.git`, JSON.stringify({ resume: 'x', proposition_valeur: 'y' }), JSON.stringify({ description: 'd', secteurs: ['s'] }), now())).lastInsertRowid);
|
||||
return { ...u, p };
|
||||
};
|
||||
const [A, B, C] = [await mk('A'), await mk('B'), await mk('C')];
|
||||
for (const u of [A, B, C]) { await enqueue(s.db, { userId: u.id, projectId: u.p, type: 'template' }); await enqueue(s.db, { userId: u.id, projectId: u.p, type: 'followup_template' }); }
|
||||
mkdirSync(join(tmp, 'x'), { recursive: true });
|
||||
const w = new Worker(s.db, makeHandlers(s.app), { maxJobs: 2, pollMs: 20, log });
|
||||
await w.start();
|
||||
await until(async () => (await s.db.prepare("SELECT COUNT(*) n FROM jobs WHERE status IN ('queued','running')").get()).n === 0, 20000);
|
||||
await w.stop();
|
||||
const bad = await s.db.prepare("SELECT error FROM jobs WHERE status = 'error'").all(); assert.deepEqual(bad, []);
|
||||
assert.equal((await s.db.prepare("SELECT COUNT(*) n FROM jobs WHERE status = 'done'").get()).n, 6);
|
||||
|
||||
const events = readFileSync(trace, 'utf8').trim().split('\n').map((l) => { const [what, who, t] = l.split(' '); return { what, who, t: Number(t) }; }).sort((x, y) => x.t - y.t);
|
||||
let open = 0, maxOpen = 0; const live = new Set(); let sameUser = false;
|
||||
for (const e of events) {
|
||||
if (e.what === 'start') { if (live.has(e.who)) sameUser = true; live.add(e.who); open++; maxOpen = Math.max(maxOpen, open); }
|
||||
else { live.delete(e.who); open--; }
|
||||
}
|
||||
assert.equal(maxOpen, 2, 'deux processus simultanés (maxJobs = 2), pas trois');
|
||||
assert.equal(sameUser, false, 'jamais deux processus du même utilisateur');
|
||||
assert.equal(events.filter((e) => e.what === 'start').length, 6);
|
||||
// L'ordre d'équité est vérifié de façon déterministe plus haut : l'horodatage de démarrage des processus dépend de leur lancement
|
||||
} finally { await s.close(); rmSync(tmp, { recursive: true, force: true }); }
|
||||
});
|
||||
212
test/ratelimit.test.js
Normal file
212
test/ratelimit.test.js
Normal file
|
|
@ -0,0 +1,212 @@
|
|||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { RateLimiter, parseTrustProxy, clientIp } from '../src/ratelimit.js';
|
||||
import { RATE_LIMITS } from '../src/limits.js';
|
||||
import { loadConfig } from '../src/config.js';
|
||||
import { startApp } from './helpers/server.js';
|
||||
|
||||
// Limitation de débit : le limiteur, la lecture de l'adresse du client, et son effet sur les vraies routes.
|
||||
|
||||
const RULES = { demo: { ip: { max: 3, windowMs: 10_000 }, user: { max: 2, windowMs: 60_000 } } };
|
||||
|
||||
test('limiteur : fenêtre glissante, Retry-After exact, une requête refusée n\'est pas comptée', () => {
|
||||
let t = 1_000_000;
|
||||
const rl = new RateLimiter({ rules: { r: { ip: { max: 2, windowMs: 10_000 } } }, clock: () => t });
|
||||
assert.ok(rl.check('r', { ip: 'a' }).ok);
|
||||
t += 4000;
|
||||
assert.ok(rl.check('r', { ip: 'a' }).ok);
|
||||
const blocked = rl.check('r', { ip: 'a' });
|
||||
assert.equal(blocked.ok, false);
|
||||
assert.equal(blocked.retryAfter, 6, 'la 1re requête sort de la fenêtre dans 6 s');
|
||||
t += 3000;
|
||||
assert.equal(rl.check('r', { ip: 'a' }).retryAfter, 3, 'insister ne prolonge pas l\'attente');
|
||||
t += 3000; // 10 s après la 1re requête
|
||||
assert.ok(rl.check('r', { ip: 'a' }).ok, 'la fenêtre a glissé');
|
||||
assert.ok(rl.check('r', { ip: 'b' }).ok, 'une autre adresse a son propre compteur');
|
||||
assert.throws(() => rl.check('inconnue', {}), /Règle de débit inconnue/);
|
||||
});
|
||||
|
||||
test('limiteur : portées IP et compte indépendantes, refus dès qu\'une portée est dépassée', () => {
|
||||
const rl = new RateLimiter({ rules: RULES, clock: () => 1000 });
|
||||
assert.ok(rl.check('demo', { ip: '1.1.1.1', userId: 7 }).ok);
|
||||
assert.ok(rl.check('demo', { ip: '2.2.2.2', userId: 7 }).ok);
|
||||
const r = rl.check('demo', { ip: '3.3.3.3', userId: 7 });
|
||||
assert.equal(r.ok, false);
|
||||
assert.equal(r.scope, 'user', 'changer d\'adresse ne contourne pas la limite du compte');
|
||||
assert.ok(rl.check('demo', { ip: '3.3.3.3', userId: 8 }).ok, 'un autre compte n\'est pas touché');
|
||||
// Le refus par le compte n'a pas consommé le quota de l'adresse 4.4.4.4
|
||||
assert.equal([1, 2, 3].filter(() => rl.check('demo', { ip: '4.4.4.4' }).ok).length, 3);
|
||||
});
|
||||
|
||||
test('limiteur : les compteurs expirés sont libérés, la table reste bornée', () => {
|
||||
let t = 0;
|
||||
const rl = new RateLimiter({ rules: { r: { ip: { max: 1, windowMs: 1000 } } }, clock: () => t, maxKeys: 50 });
|
||||
for (let i = 0; i < 40; i++) rl.check('r', { ip: `10.0.0.${i}` });
|
||||
assert.equal(rl.hits.size, 40);
|
||||
t = 5000;
|
||||
rl.sweep();
|
||||
assert.equal(rl.hits.size, 0, 'tout a expiré');
|
||||
for (let i = 0; i < 200; i++) rl.check('r', { ip: `10.1.0.${i}` });
|
||||
rl.sweep();
|
||||
assert.ok(rl.hits.size <= 50, 'plafond mémoire');
|
||||
});
|
||||
|
||||
// ---------- Adresse du client ----------
|
||||
|
||||
const req = (remote, xff) => ({ socket: { remoteAddress: remote }, headers: xff === undefined ? {} : { 'x-forwarded-for': xff } });
|
||||
|
||||
test('adresse du client : sans TRUST_PROXY, X-Forwarded-For forgé est ignoré', () => {
|
||||
assert.equal(clientIp(req('203.0.113.9', '1.2.3.4')), '203.0.113.9');
|
||||
assert.equal(clientIp(req('::ffff:203.0.113.9', '1.2.3.4'), parseTrustProxy('false')), '203.0.113.9');
|
||||
assert.equal(clientIp(req('127.0.0.1', '1.2.3.4'), null), '127.0.0.1', 'même venu d\'un proxy local, sans TRUST_PROXY on ne lit rien');
|
||||
});
|
||||
|
||||
test('adresse du client : avec TRUST_PROXY, lecture de droite à gauche, seulement depuis un proxy de confiance', () => {
|
||||
const trust = parseTrustProxy('true');
|
||||
assert.equal(clientIp(req('127.0.0.1', '198.51.100.7'), trust), '198.51.100.7');
|
||||
assert.equal(clientIp(req('::1', '198.51.100.7'), trust), '198.51.100.7');
|
||||
assert.equal(clientIp(req('::ffff:127.0.0.1', '198.51.100.7'), trust), '198.51.100.7');
|
||||
// Le client écrit « 9.9.9.9 » à gauche ; Nginx ajoute SON adresse à droite : seule celle-ci compte
|
||||
assert.equal(clientIp(req('127.0.0.1', '9.9.9.9, 198.51.100.7'), trust), '198.51.100.7');
|
||||
assert.equal(clientIp(req('127.0.0.1', '9.9.9.9, 198.51.100.7, 127.0.0.1'), trust), '198.51.100.7', 'un 2e proxy local est sauté');
|
||||
// Une connexion directe (pas du proxy) qui envoie l'en-tête n'est pas crue
|
||||
assert.equal(clientIp(req('203.0.113.9', '1.2.3.4'), trust), '203.0.113.9');
|
||||
assert.equal(clientIp(req('127.0.0.1', undefined), trust), '127.0.0.1');
|
||||
assert.equal(clientIp(req('127.0.0.1', 'pas-une-ip'), trust), '127.0.0.1');
|
||||
});
|
||||
|
||||
test('adresse du client : liste de proxys et plages CIDR, entrée invalide refusée', () => {
|
||||
const trust = parseTrustProxy('10.0.0.0/8, 192.0.2.1');
|
||||
assert.equal(clientIp(req('10.4.5.6', '198.51.100.7'), trust), '198.51.100.7');
|
||||
assert.equal(clientIp(req('192.0.2.1', '198.51.100.7'), trust), '198.51.100.7');
|
||||
assert.equal(clientIp(req('127.0.0.1', '198.51.100.7'), trust), '127.0.0.1', 'le loopback n\'est pas dans cette liste');
|
||||
assert.throws(() => parseTrustProxy('10.0.0.0/8, nimporte'), /TRUST_PROXY/);
|
||||
assert.throws(() => parseTrustProxy('10.0.0.0/x'), /TRUST_PROXY/);
|
||||
assert.equal(parseTrustProxy(''), null);
|
||||
assert.equal(parseTrustProxy(undefined), null);
|
||||
});
|
||||
|
||||
test('TRUST_PROXY : désactivé par défaut dans la configuration', () => {
|
||||
const env = { APP_URL: 'https://x.fr', SECRET_KEY: 'a'.repeat(64), GOOGLE_CLIENT_ID: 'g', GOOGLE_CLIENT_SECRET: 's', DB_DRIVER: 'sqlite' };
|
||||
const keep = { ...process.env };
|
||||
try {
|
||||
Object.assign(process.env, env); delete process.env.TRUST_PROXY;
|
||||
assert.equal(loadConfig().trustProxy, null);
|
||||
process.env.TRUST_PROXY = 'true';
|
||||
assert.ok(loadConfig().trustProxy.trusts('127.0.0.1'));
|
||||
} finally {
|
||||
for (const k of Object.keys(process.env)) if (!(k in keep)) delete process.env[k];
|
||||
Object.assign(process.env, keep);
|
||||
}
|
||||
});
|
||||
|
||||
// ---------- Sur les vraies routes ----------
|
||||
|
||||
test('connexion : au-delà du seuil, 429 avec Retry-After ; un X-Forwarded-For forgé ne donne pas un compteur neuf', async () => {
|
||||
const s = await startApp({ rateLimit: true });
|
||||
try {
|
||||
const max = RATE_LIMITS.auth_start.ip.max;
|
||||
for (let i = 0; i < max; i++) {
|
||||
const r = await fetch(`${s.base}/auth/google`, { redirect: 'manual', headers: { 'x-forwarded-for': `203.0.113.${i + 1}` } });
|
||||
assert.equal(r.status, 303, `requête ${i + 1}`);
|
||||
}
|
||||
// L'essai suivant arrive avec une adresse « neuve » dans X-Forwarded-For : sans TRUST_PROXY, c'est le même client
|
||||
const r = await fetch(`${s.base}/auth/google`, { redirect: 'manual', headers: { 'x-forwarded-for': '198.51.100.99' } });
|
||||
assert.equal(r.status, 429);
|
||||
const wait = Number(r.headers.get('retry-after'));
|
||||
assert.ok(wait >= 1 && wait <= RATE_LIMITS.auth_start.ip.windowMs / 1000, `Retry-After = ${wait}`);
|
||||
assert.match(await r.text(), /Trop de requêtes/);
|
||||
// Les pages publiques restent libres
|
||||
assert.equal((await fetch(`${s.base}/tarifs`)).status, 200);
|
||||
const json = await fetch(`${s.base}/auth/google`, { headers: { accept: 'application/json', 'x-forwarded-for': '198.51.100.100' }, redirect: 'manual' });
|
||||
assert.equal(json.status, 429);
|
||||
const body = await json.json();
|
||||
assert.equal(body.code, 'rate_limited');
|
||||
assert.ok(body.retryAfter >= 1);
|
||||
} finally { await s.close(); }
|
||||
});
|
||||
|
||||
test('connexion : avec TRUST_PROXY, l\'adresse lue dans X-Forwarded-For (proxy local) sépare les compteurs', async () => {
|
||||
const s = await startApp({ rateLimit: true, cfg: { trustProxy: parseTrustProxy('true') } });
|
||||
try {
|
||||
const max = RATE_LIMITS.auth_start.ip.max;
|
||||
const go = (ip) => fetch(`${s.base}/auth/google`, { redirect: 'manual', headers: { 'x-forwarded-for': ip } });
|
||||
for (let i = 0; i < max; i++) assert.equal((await go('198.51.100.1')).status, 303);
|
||||
assert.equal((await go('198.51.100.1')).status, 429, 'ce client est limité');
|
||||
assert.equal((await go('198.51.100.2')).status, 303, 'un autre client derrière le même proxy ne l\'est pas');
|
||||
// L'attaquant qui ajoute des adresses à GAUCHE reste sur le même compteur : seule l'entrée du proxy (à droite) compte
|
||||
assert.equal((await go('7.7.7.7, 198.51.100.1')).status, 429);
|
||||
} finally { await s.close(); }
|
||||
});
|
||||
|
||||
test('retours des fournisseurs (Google, Apple) : limités par adresse', async () => {
|
||||
const s = await startApp({ rateLimit: true, cfg: { apple: { teamId: 't', keyId: 'k', clientId: 'c', privateKey: 'p' } } });
|
||||
try {
|
||||
const max = RATE_LIMITS.auth_callback.ip.max;
|
||||
for (let i = 0; i < max; i++) {
|
||||
const r = await fetch(`${s.base}/auth/google/callback?state=x&code=y`, { redirect: 'manual' });
|
||||
assert.equal(r.status, 303, 'refus de connexion ordinaire (redirection vers /login)');
|
||||
}
|
||||
assert.equal((await fetch(`${s.base}/auth/google/callback?state=x&code=y`, { redirect: 'manual' })).status, 429);
|
||||
// La règle est commune aux deux retours
|
||||
const apple = await fetch(`${s.base}/auth/apple/callback`, { method: 'POST', redirect: 'manual', headers: { 'content-type': 'application/x-www-form-urlencoded' }, body: 'state=x' });
|
||||
assert.equal(apple.status, 429);
|
||||
} finally { await s.close(); }
|
||||
});
|
||||
|
||||
test('liaison : essais de clé limités par compte, un autre compte n\'est pas pénalisé', async () => {
|
||||
const s = await startApp({ rateLimit: true });
|
||||
try {
|
||||
const a = await s.newUser({ admin: false, link: null });
|
||||
const b = await s.newUser({ admin: false, link: null });
|
||||
const max = RATE_LIMITS.link.user.max;
|
||||
for (let i = 0; i < max; i++) {
|
||||
const r = await a.post('/link/api-key', { apiKey: 'pas-une-cle' });
|
||||
assert.equal(r.status, 400, `essai ${i + 1}`);
|
||||
}
|
||||
const blocked = await a.post('/link/api-key', { apiKey: 'pas-une-cle' });
|
||||
assert.equal(blocked.status, 429);
|
||||
assert.ok(Number(blocked.headers.get('retry-after')) >= 1);
|
||||
for (const p of ['/link/subscription', '/link/test', '/link/unlink', '/link/server']) assert.equal((await a.post(p, {})).status, 429, p);
|
||||
assert.equal((await b.post('/link/api-key', { apiKey: 'pas-une-cle' })).status, 400);
|
||||
} finally { await s.close(); }
|
||||
});
|
||||
|
||||
test('export, import, création de projet, suppression de compte, tests de connexion : tous limités', async () => {
|
||||
const s = await startApp({ rateLimit: true });
|
||||
try {
|
||||
const u = await s.newUser({ admin: true });
|
||||
const pid = Number((await s.db.prepare("INSERT INTO projects(user_id, name, git_url, created_at) VALUES(?, 'p', 'https://git.test/a/b.git', 1)").run(u.id)).lastInsertRowid);
|
||||
const hit = async (rule, call) => {
|
||||
const conf = RATE_LIMITS[rule].user;
|
||||
for (let i = 0; i < conf.max; i++) assert.notEqual((await call()).status, 429, `${rule} #${i + 1}`);
|
||||
assert.equal((await call()).status, 429, `${rule} au-delà du seuil`);
|
||||
};
|
||||
await hit('csv', () => u.get(`/api/projects/${pid}/prospects.csv`));
|
||||
await hit('conn_test', () => u.get(`/api/projects/${pid}/recap`));
|
||||
await hit('project_create', () => u.post('/api/projects', {}));
|
||||
await hit('account_delete', () => u.post('/account/delete', { confirm: 'autre@x.fr' }, { form: true }));
|
||||
await hit('mail_send', () => u.post('/api/report/send', {}));
|
||||
// L'import CSV partage la règle « csv » de l'export : déjà épuisée ci-dessus
|
||||
assert.equal((await u.post(`/api/projects/${pid}/prospects/import`, { csv: 'email\na@b.fr' })).status, 429);
|
||||
} finally { await s.close(); }
|
||||
});
|
||||
|
||||
test('chaque règle citée par une route existe, et les points sensibles sont tous couverts', async () => {
|
||||
const s = await startApp();
|
||||
try {
|
||||
const routes = s.app.router.routes;
|
||||
const used = new Set(routes.map((r) => r.limit).filter(Boolean));
|
||||
for (const rule of used) assert.ok(RATE_LIMITS[rule], `règle ${rule} absente de src/limits.js`);
|
||||
// « admin » n'est branchée qu'avec le back-office
|
||||
for (const rule of Object.keys(RATE_LIMITS).filter((r) => r !== 'admin')) assert.ok(used.has(rule), `règle ${rule} sans route`);
|
||||
const find = (method, path) => routes.find((r) => r.method === method && r.re.test(path));
|
||||
for (const [m, p] of [
|
||||
['GET', '/auth/google'], ['GET', '/auth/apple'], ['GET', '/auth/google/callback'], ['POST', '/auth/apple/callback'],
|
||||
['POST', '/link/api-key'], ['POST', '/link/subscription'], ['POST', '/link/server'], ['POST', '/link/test'], ['POST', '/link/unlink'],
|
||||
['GET', '/api/projects/1/prospects.csv'], ['POST', '/api/projects/1/prospects/import'], ['POST', '/api/projects/1/send'],
|
||||
['POST', '/api/report/send'], ['POST', '/api/notify/test'], ['POST', '/api/projects'], ['POST', '/account/delete'],
|
||||
['POST', '/api/projects/1/imap'], ['POST', '/api/projects/1/inbox/check'], ['GET', '/api/projects/1/recap'],
|
||||
]) assert.ok(find(m, p)?.limit, `${m} ${p} sans limite`);
|
||||
} finally { await s.close(); }
|
||||
});
|
||||
|
|
@ -11,7 +11,7 @@ import { createProject } from '../src/projects.js';
|
|||
async function setup() {
|
||||
const db = await testDb();
|
||||
const mails = [], hooks = [];
|
||||
const app = {
|
||||
const app = { resolveHost: async () => [{ address: '93.184.216.34', family: 4 }],
|
||||
db, cfg: { secretKey: randomBytes(32), appUrl: 'https://ai.test' },
|
||||
createTransport: () => ({ sendMail: async (m) => { mails.push(m); }, close() {} }),
|
||||
fetch: async (url, o) => { hooks.push(JSON.parse(o.body)); return { ok: true }; },
|
||||
|
|
|
|||
|
|
@ -55,7 +55,7 @@ function parseDdl(statements) {
|
|||
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 NOT_OWNED = new Set(['blacklist', 'oauth_states', 'users', 'admin_audit']);
|
||||
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', () => {
|
||||
|
|
|
|||
|
|
@ -2,7 +2,6 @@ import { test } from 'node:test';
|
|||
import assert from 'node:assert/strict';
|
||||
import { resolve } from 'node:path';
|
||||
import { runClaude, extractJson, rateLimitWindows } from '../src/services/claude.js';
|
||||
import { waitCool } from '../src/services/thermal.js';
|
||||
import { now } from '../src/db.js';
|
||||
import { testDb } from './helpers/db.js';
|
||||
import { addUser } from './helpers/users.js';
|
||||
|
|
@ -49,14 +48,6 @@ test('extractJson gère texte, fences et accolades dans les chaînes', () => {
|
|||
assert.throws(() => extractJson('rien'), /Aucun JSON/);
|
||||
});
|
||||
|
||||
test('waitCool attend la redescente avec hystérésis', async () => {
|
||||
const temps = [80, 78, 72, 69];
|
||||
let waits = 0;
|
||||
await waitCool(75, { read: () => temps.shift(), sleep: async () => {}, onWait: () => waits++ });
|
||||
assert.equal(waits, 3);
|
||||
await waitCool(75, { read: () => null });
|
||||
});
|
||||
|
||||
test('worker : exécution, dédoublonnage, erreurs, annulation, conso', async () => {
|
||||
const db = await testDb();
|
||||
const u = await addUser(db);
|
||||
|
|
@ -67,7 +58,7 @@ test('worker : exécution, dédoublonnage, erreurs, annulation, conso', async ()
|
|||
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é'); },
|
||||
};
|
||||
const w = new Worker(db, handlers, { thermalMax: 999, log: { error() {} } });
|
||||
const w = new Worker(db, handlers, { log: { error() {} } });
|
||||
assert.equal(await w.tick(), true);
|
||||
await enqueue(db, { userId: u, projectId: 1, type: 'boom' });
|
||||
await w.tick();
|
||||
|
|
|
|||
|
|
@ -201,7 +201,8 @@ test('textes : faits réels du statut, tarifs sans prix inventé, aucun terme in
|
|||
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, /appliqués par le serveur/);
|
||||
assert.doesNotMatch(tarifs, /pas encore appliqu/);
|
||||
assert.match(tarifs, /suspendu ou fermé/);
|
||||
|
||||
const cgu = await text('/cgu');
|
||||
|
|
|
|||
|
|
@ -22,12 +22,12 @@ test('start puis stop : la boucle s\'arrête, le job en cours est annulé et att
|
|||
started();
|
||||
ctx.signal.addEventListener('abort', () => reject(new Error('Annulé')), { once: true });
|
||||
}),
|
||||
}, { thermalMax: 999, pollMs: 10, log: { error() {} } });
|
||||
}, { 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);
|
||||
assert.equal(w.running.size, 0);
|
||||
const job = (await latestJobs(db, 1)).prospect;
|
||||
assert.equal(job.status, 'error');
|
||||
assert.match(job.error, /Annulé/);
|
||||
|
|
@ -38,7 +38,7 @@ test('stop attend les notifications en vol, et un callback qui échoue est journ
|
|||
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(' ')) },
|
||||
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}`);
|
||||
|
|
@ -57,7 +57,7 @@ test('stop attend les notifications en vol, et un callback qui échoue est journ
|
|||
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() {} } });
|
||||
const w = new Worker(db, {}, { pollMs: 10, log: { error() {} } });
|
||||
await w.start();
|
||||
await w.stop();
|
||||
const job = (await latestJobs(db, 1)).analyze;
|
||||
|
|
|
|||
Loading…
Reference in a new issue