feat: init repo
deploy / deploy (push) Canceled after 0s

This commit is contained in:
2026-11-10 19:56:03 +01:00
commit 858d862fed
166 changed files with 13336 additions and 0 deletions
+174
View File
@@ -0,0 +1,174 @@
# CRM — modèle de données
Entreprises, prospects, référentiel des pays. Le runtime **existe** : API Hono
dans `src/`, 18 routes sous `/api/crm`, front React séparé. Le détail des
endpoints, du déploiement et de la sécurité est dans
[`../../docs/api.md`](../../docs/api.md),
[`../../docs/deployment.md`](../../docs/deployment.md) et
[`../../docs/security.md`](../../docs/security.md).
## Modèle de données
```mermaid
erDiagram
users ||--o{ password_reset_tokens : "possede"
users ||--o{ organizations : "pilote"
users ||--o{ contacts : "pilote"
users ||--o{ deals : "pilote"
users ||--o{ tasks : "assignee"
users ||--o{ audit_logs : "trace"
countries ||--o{ organizations : "situee"
countries ||--o{ contacts : "situe"
organizations ||--o{ contacts : "emploie"
organizations ||--o{ deals : "concerne"
contacts ||--o{ deals : "interlocuteur"
pipeline_stages ||--o{ deals : "etape"
pipeline_stages ||--o{ deal_stage_history : "transitions"
deals ||--o{ deal_stage_history : "parcourt"
deals ||--o{ activities : "genere"
deals ||--o{ tasks : "genere"
contacts ||--o{ activities : "genere"
contacts ||--o{ tasks : "genere"
contacts ||--o{ contact_tags : "etiquette"
tags ||--o{ contact_tags : "attribue"
```
La table `roles` n'apparaît plus : supprimée par `007_no_roles.sql`.
## Tables
| Table | Rôle | Exposée par l'API |
|---|---|---|
| `users` | Comptes utilisateurs (plus de `role_id`) | `/auth/*` |
| `user_sessions` | Sessions persistées (`005`) | interne |
| `password_reset_tokens` | Jetons de réinitialisation hachés | non (aucune route) |
| `countries` | Référentiel ISO 3166 | `/countries` |
| `organizations` | Entreprises | `/organizations` |
| `contacts` | Interlocuteurs | `/contacts` |
| `tags` / `contact_tags` | Étiquetage | non |
| `pipeline_stages` | Étapes du pipeline | non |
| `deals` | Affaires | non |
| `deal_stage_history` | Historique des transitions | non |
| `activities` | Appels, e-mails, réunions, notes | non |
| `tasks` | Actions à mener | non |
| `settings` | Configuration clé-valeur | non |
| `audit_logs` | Piste d'audit | non |
| `schema_migrations` | Versions appliquées | non |
16 tables après `007` (17 avant : la table `roles` ayant disparu). Seules celles
marquées « `/…` » sont atteignables depuis le front.
## Conventions
| Sujet | Choix | Raison |
|---|---|---|
| Noms de tables | pluriel `snake_case`, sans préfixe | les tables vivent dans une base dédiée, le préfixe serait redondant |
| Noms de colonnes | `snake_case` | cohérent du DDL jusqu'au JSON |
| Types d'horodatage | `DATETIME`, `DATETIME(3)` pour l'audit | évite la conversion de fuseau de `TIMESTAMP` et la limite de 2038 |
| Durées de vie | `created_at`, `updated_at` sur toute table mutable | `ON UPDATE CURRENT_TIMESTAMP` garantit la fraîcheur sans code applicatif |
| Suppression | `deleted_at`, jamais de `DELETE` métier | conserver l'historique et éviter les suppressions en cascade destructrices |
| Identifiants | `CHAR(36)` pour les entités, `INT UNSIGNED` pour les référentiels | UUID stables hors base, entiers compacts pour les tables de référence |
| Encodage | `utf8mb4` / `utf8mb4_unicode_ci` | accents et emoji, collation correcte |
| Listes fermées | `CHECK` plutôt que table, sauf le pipeline | le jeu de valeurs est stable et court ; `pipeline_stages` reste une table car le nombre d'étapes varie selon les usages |
Trois tables ne portent volontairement pas `updated_at` : `audit_logs`,
`deal_stage_history` et `password_reset_tokens`. Elles sont en ajout seul. Une
piste d'audit modifiable n'est plus une piste d'audit.
Exception à la règle « jamais de `DELETE` » : **`countries` est supprimée en dur**.
Référentiel fini, aucune entreprise ne peut pointer dessus (FK `SET NULL`), et
un pays de trop poserait plus de problèmes qu'il n'en résout.
## Ce qui a été repris du CRM de référence
| Décision | Origine |
|---|---|
| Le pipeline en table, pas en `ENUM` | la référence compte plus de vingt étapes réelles ; un `ENUM` aurait été ingérable |
| Clé externe `UNIQUE` pour les imports | évite les doublons à l'ingestion et permet un `upsert` au `COALESCE` qui n'écrase jamais une saisie humaine |
| `settings` en clé naturelle, sans surrogate | la clé est la donnée |
| `snake_case` homogène DDL, TypeScript, JSON | seule chose réellement bien tenue de la référence |
| Organisation en référentiel plutôt qu'en valeur figée | un rôle unique dans une colonne texte avait produit trois vocabulaires contradictoires |
## Ce qui a été corrigé
| Défaut de la référence | Correction ici |
|---|---|
| Aucun `updated_at` | ajouté partout, maintenu par la base |
| Suppressions dures, `ON DELETE CASCADE` sur l'audit | soft delete, et l'audit survit à la suppression d'un utilisateur (`ON DELETE SET NULL` + instantané `user_email`) |
| `users.role` en texte libre | table `roles` + FK `RESTRICT` (`003`), **puis suppression totale des rôles par `007`** — choix assumé, voir ci-dessous |
| Historique de statut limité à un niveau | `deal_stage_history` conserve toutes les transitions avec auteur et horodatage |
| Aucun index de performance, filtrage et tri faits dans le navigateur | index composites `(deleted_at, …)` dimensionnés pour la pagination serveur |
| `tokens.token` ni indexé ni haché | `token_hash CHAR(64)` indexé, le jeton en clair n'est jamais stocké |
| Clé de déduplication d'envoi sans contrainte en base | contrainte composite en base plutôt qu'en application |
| Aucune société, affaire, activité ni tâche | le modèle en tient compte dès le départ |
| `int(11)` | `INT` ou `INT UNSIGNED` selon le cas |
## Migrations
Les fichiers sont numérotés et appliqués dans l'ordre. Une migration déjà
appliquée ne se modifie jamais : une correction passe par un nouveau fichier.
| Fichier | Contenu |
|---|---|
| `000_schema_migrations.sql` | table de suivi des versions |
| `001_initial_schema.sql` | 15 tables, 30 clés étrangères, 7 `CHECK` |
| `002_reference_data.sql` | rôles, étapes, pays, réglages, étiquettes |
| `003_integrity_backstop.sql` | clé étrangère `users.role_id` manquante, `CHECK` sur les champs obligatoires |
| `004_audit_precision.sql` | millisecondes sur les colonnes d'audit |
| `005_user_sessions.sql` | table `user_sessions` : sans elle, aucune session n'est possible |
| `006_active_identity.sql` | colonnes générées `active_email` / `active_name` |
| `007_no_roles.sql` | **suppression des rôles** : `DROP FOREIGN KEY fk_users_role`, `DROP COLUMN role_id`, `DROP TABLE roles` |
Notes :
- `003` existe parce que `001` avait été livrée avec la clé étrangère
`users.role_id` absente alors que l'index était présent. Le cas a été trouvé en
interrogeant la base, pas en relisant le SQL : c'est pourquoi chaque migration
est validée par des inserts qui doivent échouer, pas seulement par une
exécution sans erreur.
- `005` a été nécessaire pour réutiliser `@cohaise/server` tel quel : le code
partagé attend `user_sessions`, absente du modèle initial.
- `006` corrige un oubli — `uq_contacts_email` et `uq_organizations_name`
portaient sur la colonne brute, ce qui interdisait de réutiliser une adresse
ou un nom après une suppression logique. Corrections en colonnes générées, à
l'image du Cloud ; `001` n'a pas été retouché.
- `007` annule `003` et vide `002` de son sens, sans les réécrire : c'est le
principe même du fichier scellé. Le code, lui, a été vidé de `requireRole` et
de `role_slug` en même temps. **Tout compte authentifié a tous les droits.**
## Sécurité (couche modèle)
- Suppression d'un pays, d'un tag, d'une société référencée : `ON DELETE SET
NULL` ou `RESTRICT`, la donnée métier survit.
- Les identifiants d'organisation et de contact sont des UUID, non devinables
dans les URL.
- `audit_logs` est en ajout seul par convention applicative ; les colonnes
portent la contrainte `JSON_VALID`.
- Sessions : `user_sessions.token_hash` indexé, le jeton en clair n'est jamais
stocké.
Sessions, mots de passe, en-têtes et **absence de cloisonnement** :
[`../../docs/security.md`](../../docs/security.md).
## Limites actuelles
Seules les entités demandées sont exposées : `/auth/{login,logout,me,change-password}`,
`/countries`, `/organizations`, `/contacts`. **Aucune route n'est protégée par un
rôle** — le middleware `requireRole` n'existe plus dans le code.
- **`owner_id` ne cloisonne rien** : la colonne est écrite et retournée dans les
réponses, mais jamais filtrée. Toute ligne est visible et modifiable par tout
compte authentifié.
- Le premier compte se crée par `cohaise-crm-admin`
(`make admin ARGS="--email … --first … --last …"`), jamais par une route
publique. **Il n'existe pas d'option `--role`** : un compte créé a tous les
droits.
- `countries` ne compte que 19 entrées sur les ~250 de la norme ISO ; à
compléter si l'usage le justifie.
- Le pipeline (`deals`, `activities`, `tasks`, `tags`, `pipeline_stages`) existe
en base mais **n'a ni route ni interface**.
- Pas de journalisation des transitions en base : l'écriture dans
`deal_stage_history` relève de l'application, à faire dans la même transaction
que le changement d'étape.
- `password_reset_tokens` est créée mais aucune route ne l'utilise.
- Pas de rate limiting sur la connexion.
@@ -0,0 +1,5 @@
CREATE TABLE IF NOT EXISTS schema_migrations (
version VARCHAR(64) NOT NULL,
applied_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (version)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
@@ -0,0 +1,295 @@
CREATE TABLE roles (
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
slug VARCHAR(50) NOT NULL,
name VARCHAR(100) NOT NULL,
description VARCHAR(255) NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (id),
UNIQUE KEY uq_roles_slug (slug)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE users (
id CHAR(36) NOT NULL,
email VARCHAR(255) NOT NULL,
password_hash VARCHAR(255) NOT NULL,
first_name VARCHAR(100) NOT NULL,
last_name VARCHAR(100) NOT NULL,
role_id INT UNSIGNED NOT NULL,
is_active TINYINT(1) NOT NULL DEFAULT 1,
must_change_password TINYINT(1) NOT NULL DEFAULT 0,
last_login_at DATETIME NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
deleted_at DATETIME NULL,
PRIMARY KEY (id),
UNIQUE KEY uq_users_email (email),
KEY idx_users_role (role_id),
KEY idx_users_deleted (deleted_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE password_reset_tokens (
id CHAR(36) NOT NULL,
user_id CHAR(36) NOT NULL,
token_hash CHAR(64) NOT NULL,
expires_at DATETIME NOT NULL,
used_at DATETIME NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (id),
UNIQUE KEY uq_prt_hash (token_hash),
KEY idx_prt_user (user_id),
KEY idx_prt_expiry (expires_at),
CONSTRAINT fk_prt_user FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE countries (
id SMALLINT UNSIGNED NOT NULL AUTO_INCREMENT,
code CHAR(2) NOT NULL,
name VARCHAR(100) NOT NULL,
phone_code VARCHAR(8) NULL,
PRIMARY KEY (id),
UNIQUE KEY uq_countries_code (code)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE tags (
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
name VARCHAR(60) NOT NULL,
slug VARCHAR(60) NOT NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
deleted_at DATETIME NULL,
PRIMARY KEY (id),
UNIQUE KEY uq_tags_name (name),
UNIQUE KEY uq_tags_slug (slug)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE organizations (
id CHAR(36) NOT NULL,
name VARCHAR(255) NOT NULL,
slug VARCHAR(255) NOT NULL,
website VARCHAR(255) NULL,
industry VARCHAR(100) NULL,
phone VARCHAR(50) NULL,
email VARCHAR(255) NULL,
address_line1 VARCHAR(255) NULL,
address_line2 VARCHAR(255) NULL,
postal_code VARCHAR(20) NULL,
city VARCHAR(100) NULL,
country_id SMALLINT UNSIGNED NULL,
description TEXT NULL,
owner_id CHAR(36) NULL,
created_by CHAR(36) NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
deleted_at DATETIME NULL,
PRIMARY KEY (id),
UNIQUE KEY uq_organizations_name (name),
KEY idx_organizations_slug (slug),
KEY idx_organizations_owner (owner_id),
KEY idx_organizations_country (country_id),
KEY idx_organizations_deleted (deleted_at),
KEY idx_organizations_list (deleted_at, created_at, id),
CONSTRAINT fk_organizations_country FOREIGN KEY (country_id) REFERENCES countries (id) ON DELETE SET NULL,
CONSTRAINT fk_organizations_owner FOREIGN KEY (owner_id) REFERENCES users (id) ON DELETE SET NULL,
CONSTRAINT fk_organizations_creator FOREIGN KEY (created_by) REFERENCES users (id) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE contacts (
id CHAR(36) NOT NULL,
organization_id CHAR(36) NULL,
first_name VARCHAR(100) NOT NULL,
last_name VARCHAR(100) NOT NULL,
email VARCHAR(255) NULL,
phone VARCHAR(50) NULL,
mobile VARCHAR(50) NULL,
job_title VARCHAR(150) NULL,
country_id SMALLINT UNSIGNED NULL,
external_source VARCHAR(50) NULL,
external_id VARCHAR(100) NULL,
description TEXT NULL,
owner_id CHAR(36) NULL,
created_by CHAR(36) NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
deleted_at DATETIME NULL,
PRIMARY KEY (id),
UNIQUE KEY uq_contacts_email (email),
UNIQUE KEY uq_contacts_external (external_source, external_id),
KEY idx_contacts_organization (organization_id),
KEY idx_contacts_owner (owner_id),
KEY idx_contacts_country (country_id),
KEY idx_contacts_deleted (deleted_at),
KEY idx_contacts_list (deleted_at, created_at, id),
KEY idx_contacts_name (last_name, first_name),
CONSTRAINT fk_contacts_organization FOREIGN KEY (organization_id) REFERENCES organizations (id) ON DELETE SET NULL,
CONSTRAINT fk_contacts_country FOREIGN KEY (country_id) REFERENCES countries (id) ON DELETE SET NULL,
CONSTRAINT fk_contacts_owner FOREIGN KEY (owner_id) REFERENCES users (id) ON DELETE SET NULL,
CONSTRAINT fk_contacts_creator FOREIGN KEY (created_by) REFERENCES users (id) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE contact_tags (
contact_id CHAR(36) NOT NULL,
tag_id INT UNSIGNED NOT NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (contact_id, tag_id),
KEY idx_contact_tags_tag (tag_id),
CONSTRAINT fk_contact_tags_contact FOREIGN KEY (contact_id) REFERENCES contacts (id) ON DELETE CASCADE,
CONSTRAINT fk_contact_tags_tag FOREIGN KEY (tag_id) REFERENCES tags (id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE pipeline_stages (
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
name VARCHAR(100) NOT NULL,
slug VARCHAR(100) NOT NULL,
position INT UNSIGNED NOT NULL,
probability TINYINT UNSIGNED NOT NULL DEFAULT 0,
is_system TINYINT(1) NOT NULL DEFAULT 0,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
deleted_at DATETIME NULL,
PRIMARY KEY (id),
UNIQUE KEY uq_stages_slug (slug),
KEY idx_stages_position (position),
CONSTRAINT chk_stages_probability CHECK (probability <= 100)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE deals (
id CHAR(36) NOT NULL,
title VARCHAR(255) NOT NULL,
organization_id CHAR(36) NULL,
primary_contact_id CHAR(36) NULL,
stage_id INT UNSIGNED NOT NULL,
value_amount DECIMAL(15,2) NULL,
currency CHAR(3) NOT NULL DEFAULT 'EUR',
probability TINYINT UNSIGNED NOT NULL DEFAULT 0,
expected_close_date DATE NULL,
description TEXT NULL,
lost_reason VARCHAR(255) NULL,
owner_id CHAR(36) NULL,
created_by CHAR(36) NULL,
stage_changed_at DATETIME NULL,
won_at DATETIME NULL,
lost_at DATETIME NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
deleted_at DATETIME NULL,
PRIMARY KEY (id),
KEY idx_deals_stage (stage_id),
KEY idx_deals_organization (organization_id),
KEY idx_deals_contact (primary_contact_id),
KEY idx_deals_owner (owner_id),
KEY idx_deals_deleted (deleted_at),
KEY idx_deals_pipeline (deleted_at, stage_id, updated_at),
KEY idx_deals_close_date (expected_close_date),
KEY idx_deals_list (deleted_at, created_at, id),
CONSTRAINT chk_deals_probability CHECK (probability <= 100),
CONSTRAINT chk_deals_amount CHECK (value_amount IS NULL OR value_amount >= 0),
CONSTRAINT fk_deals_stage FOREIGN KEY (stage_id) REFERENCES pipeline_stages (id) ON DELETE RESTRICT,
CONSTRAINT fk_deals_organization FOREIGN KEY (organization_id) REFERENCES organizations (id) ON DELETE SET NULL,
CONSTRAINT fk_deals_contact FOREIGN KEY (primary_contact_id) REFERENCES contacts (id) ON DELETE SET NULL,
CONSTRAINT fk_deals_owner FOREIGN KEY (owner_id) REFERENCES users (id) ON DELETE SET NULL,
CONSTRAINT fk_deals_creator FOREIGN KEY (created_by) REFERENCES users (id) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE deal_stage_history (
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
deal_id CHAR(36) NOT NULL,
from_stage_id INT UNSIGNED NULL,
to_stage_id INT UNSIGNED NOT NULL,
changed_by CHAR(36) NULL,
changed_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (id),
KEY idx_dsh_deal (deal_id, changed_at),
KEY idx_dsh_to (to_stage_id),
CONSTRAINT fk_dsh_deal FOREIGN KEY (deal_id) REFERENCES deals (id) ON DELETE CASCADE,
CONSTRAINT fk_dsh_from FOREIGN KEY (from_stage_id) REFERENCES pipeline_stages (id) ON DELETE SET NULL,
CONSTRAINT fk_dsh_to FOREIGN KEY (to_stage_id) REFERENCES pipeline_stages (id) ON DELETE RESTRICT,
CONSTRAINT fk_dsh_user FOREIGN KEY (changed_by) REFERENCES users (id) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE activities (
id CHAR(36) NOT NULL,
type VARCHAR(20) NOT NULL,
subject VARCHAR(255) NOT NULL,
body TEXT NULL,
occurred_at DATETIME NOT NULL,
organization_id CHAR(36) NULL,
contact_id CHAR(36) NULL,
deal_id CHAR(36) NULL,
owner_id CHAR(36) NULL,
created_by CHAR(36) NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
deleted_at DATETIME NULL,
PRIMARY KEY (id),
KEY idx_activities_contact (contact_id, occurred_at),
KEY idx_activities_deal (deal_id, occurred_at),
KEY idx_activities_org (organization_id, occurred_at),
KEY idx_activities_owner (owner_id, occurred_at),
KEY idx_activities_deleted (deleted_at),
KEY idx_activities_list (deleted_at, created_at, id),
CONSTRAINT chk_activities_type CHECK (type IN ('call', 'email', 'meeting', 'note', 'demo', 'other')),
CONSTRAINT fk_activities_org FOREIGN KEY (organization_id) REFERENCES organizations (id) ON DELETE CASCADE,
CONSTRAINT fk_activities_contact FOREIGN KEY (contact_id) REFERENCES contacts (id) ON DELETE CASCADE,
CONSTRAINT fk_activities_deal FOREIGN KEY (deal_id) REFERENCES deals (id) ON DELETE CASCADE,
CONSTRAINT fk_activities_owner FOREIGN KEY (owner_id) REFERENCES users (id) ON DELETE SET NULL,
CONSTRAINT fk_activities_creator FOREIGN KEY (created_by) REFERENCES users (id) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE tasks (
id CHAR(36) NOT NULL,
title VARCHAR(255) NOT NULL,
description TEXT NULL,
status VARCHAR(20) NOT NULL DEFAULT 'open',
priority VARCHAR(20) NOT NULL DEFAULT 'normal',
due_at DATETIME NULL,
completed_at DATETIME NULL,
assigned_to CHAR(36) NULL,
organization_id CHAR(36) NULL,
contact_id CHAR(36) NULL,
deal_id CHAR(36) NULL,
created_by CHAR(36) NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
deleted_at DATETIME NULL,
PRIMARY KEY (id),
KEY idx_tasks_assignee (assigned_to, status, due_at),
KEY idx_tasks_deal (deal_id),
KEY idx_tasks_contact (contact_id),
KEY idx_tasks_org (organization_id),
KEY idx_tasks_deleted (deleted_at),
KEY idx_tasks_due (deleted_at, due_at),
CONSTRAINT chk_tasks_status CHECK (status IN ('open', 'in_progress', 'done', 'cancelled')),
CONSTRAINT chk_tasks_priority CHECK (priority IN ('low', 'normal', 'high', 'urgent')),
CONSTRAINT fk_tasks_assignee FOREIGN KEY (assigned_to) REFERENCES users (id) ON DELETE SET NULL,
CONSTRAINT fk_tasks_org FOREIGN KEY (organization_id) REFERENCES organizations (id) ON DELETE CASCADE,
CONSTRAINT fk_tasks_contact FOREIGN KEY (contact_id) REFERENCES contacts (id) ON DELETE CASCADE,
CONSTRAINT fk_tasks_deal FOREIGN KEY (deal_id) REFERENCES deals (id) ON DELETE CASCADE,
CONSTRAINT fk_tasks_creator FOREIGN KEY (created_by) REFERENCES users (id) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE settings (
setting_key VARCHAR(64) NOT NULL,
setting_value VARCHAR(255) NOT NULL,
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (setting_key)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE audit_logs (
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
user_id CHAR(36) NULL,
user_email VARCHAR(255) NULL,
action VARCHAR(50) NOT NULL,
resource VARCHAR(50) NOT NULL,
resource_id VARCHAR(64) NULL,
details LONGTEXT NULL,
ip_address VARCHAR(45) NULL,
user_agent VARCHAR(255) NULL,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (id),
KEY idx_audit_created (created_at),
KEY idx_audit_user (user_id),
KEY idx_audit_resource (resource, resource_id),
CONSTRAINT chk_audit_details CHECK (details IS NULL OR JSON_VALID(details)),
CONSTRAINT fk_audit_user FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
@@ -0,0 +1,47 @@
INSERT INTO roles (id, slug, name, description) VALUES
(1, 'admin', 'Administrateur', 'Accès complet, y compris la gestion des utilisateurs et des parametres.'),
(2, 'manager', 'Responsable', 'Acces a toutes les donnees commerciales et a leur modification.'),
(3, 'agent', 'Commercial', 'Acces limite aux donnees qui lui sont attribuees.');
INSERT INTO pipeline_stages (id, name, slug, position, probability, is_system) VALUES
(1, 'Nouveau', 'nouveau', 1, 10, 1),
(2, 'Qualifie', 'qualifie', 2, 25, 1),
(3, 'Découvert', 'decouvert', 3, 40, 1),
(4, 'Proposition envoyée', 'proposition-envoyee', 4, 60, 1),
(5, 'Négociation', 'negociation', 5, 75, 1),
(6, 'Gagné', 'gagne', 6, 100, 1),
(7, 'Perdu', 'perdu', 7, 0, 1);
INSERT INTO countries (id, code, name, phone_code) VALUES
(1, 'FR', 'France', '+33'),
(2, 'BE', 'Belgique', '+32'),
(3, 'CH', 'Suisse', '+41'),
(4, 'LU', 'Luxembourg', '+352'),
(5, 'DE', 'Allemagne', '+49'),
(6, 'ES', 'Espagne', '+34'),
(7, 'IT', 'Italie', '+39'),
(8, 'GB', 'Royaume-Uni', '+44'),
(9, 'IE', 'Irlande', '+353'),
(10, 'NL', 'Pays-Bas', '+31'),
(11, 'PT', 'Portugal', '+351'),
(12, 'CA', 'Canada', '+1'),
(13, 'US', 'Etats-Unis', '+1'),
(14, 'MA', 'Maroc', '+212'),
(15, 'DZ', 'Algerie', '+213'),
(16, 'TN', 'Tunisie', '+216'),
(17, 'SN', 'Senegal', '+221'),
(18, 'CI', "Cote d'Ivoire", '+225'),
(19, 'CM', 'Cameroun', '+237');
INSERT INTO settings (setting_key, setting_value) VALUES
('password_reset_enabled', 'true'),
('default_currency', 'EUR'),
('default_deal_stage', '1'),
('pagination_limit', '25');
INSERT INTO tags (id, name, slug) VALUES
(1, 'Prioritaire', 'prioritaire'),
(2, 'Partenaire', 'partenaire'),
(3, 'Presse', 'presse'),
(4, 'Salon', 'salon'),
(5, 'Relance', 'relance');
@@ -0,0 +1,18 @@
ALTER TABLE users
ADD CONSTRAINT fk_users_role FOREIGN KEY (role_id) REFERENCES roles (id) ON DELETE RESTRICT,
ADD CONSTRAINT chk_users_names CHECK (CHAR_LENGTH(first_name) > 0 AND CHAR_LENGTH(last_name) > 0);
ALTER TABLE contacts
ADD CONSTRAINT chk_contacts_names CHECK (CHAR_LENGTH(first_name) > 0 AND CHAR_LENGTH(last_name) > 0);
ALTER TABLE organizations
ADD CONSTRAINT chk_organizations_name CHECK (CHAR_LENGTH(name) > 0);
ALTER TABLE deals
ADD CONSTRAINT chk_deals_title CHECK (CHAR_LENGTH(title) > 0);
ALTER TABLE tags
ADD CONSTRAINT chk_tags_name CHECK (CHAR_LENGTH(name) > 0);
ALTER TABLE pipeline_stages
ADD CONSTRAINT chk_stages_name CHECK (CHAR_LENGTH(name) > 0);
@@ -0,0 +1,23 @@
ALTER TABLE audit_logs
MODIFY created_at DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3);
ALTER TABLE deal_stage_history
MODIFY changed_at DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3);
ALTER TABLE deals
MODIFY stage_changed_at DATETIME(3) NULL,
MODIFY won_at DATETIME(3) NULL,
MODIFY lost_at DATETIME(3) NULL;
ALTER TABLE activities
MODIFY occurred_at DATETIME(3) NOT NULL;
ALTER TABLE tasks
MODIFY due_at DATETIME(3) NULL,
MODIFY completed_at DATETIME(3) NULL;
ALTER TABLE users
MODIFY last_login_at DATETIME(3) NULL;
ALTER TABLE password_reset_tokens
MODIFY expires_at DATETIME(3) NOT NULL;
@@ -0,0 +1,32 @@
-- 005_user_sessions.sql
--
-- Le CRM n'avait aucun support de session : l'authentification etait
-- impossible sans introduire une table. Miroir exact de celle du Cloud
-- (cohaise_cloud.user_sessions), pour que le code partage de
-- @cohaise/server travaille sur les deux bases sans adaptation.
--
-- Le jeton brut ne quitte jamais le serveur : seul son empreinte SHA-256 est
-- stockee, donc une copie de la base ne fournit aucune session ouvrable.
CREATE TABLE user_sessions (
id CHAR(36) NOT NULL,
user_id CHAR(36) NOT NULL,
token_hash CHAR(64) NOT NULL,
ip_address VARCHAR(45) DEFAULT NULL,
user_agent VARCHAR(255) DEFAULT NULL,
created_at DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
last_seen_at DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
expires_at DATETIME(3) NOT NULL,
revoked_at DATETIME(3) DEFAULT NULL,
PRIMARY KEY (id),
UNIQUE KEY uq_user_sessions_hash (token_hash),
KEY idx_user_sessions_user (user_id, revoked_at),
KEY idx_user_sessions_expiry (expires_at),
CONSTRAINT fk_user_sessions_user
FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- La purge des jetons expires n'est pas confiee a un EVENT MariaDB : elle
-- depend du planificateur, desactive par defaut, et une migration qui echoue
-- au milieu n'est pas enregistree. Le service appelle purgeExpiredSessions()
-- au demarrage, comme le Cloud.
@@ -0,0 +1,35 @@
-- 006_active_identity.sql
--
-- uq_contacts_email et uq_organizations_name portent sur la colonne brute :
-- une suppression logique laisse la ligne en place, donc l'index voit encore
-- la valeur et interdit toute reutilisation. Un prospect rendu inactif
-- bloquait ainsi sa propre reimportation.
--
-- Meme mecanisme que cohaise_cloud : une colonne generatee ne vaut rien quand
-- deleted_at n'est pas NULL, et en SQL plusieurs NULL ne sont pas egaux, donc
-- l'index ne voit plus la ligne supprimee. La contrainte d'origine est
-- conservee sous un autre nom pour que le controle reste explicable en base.
--
-- 001 n'est pas modifie : la correction passe par un fichier nouveau.
ALTER TABLE contacts
DROP INDEX uq_contacts_email,
ADD COLUMN active_email VARCHAR(255)
GENERATED ALWAYS AS (IF(deleted_at IS NULL, email, NULL)) STORED,
ADD UNIQUE KEY uq_contacts_active_email (active_email);
ALTER TABLE organizations
DROP INDEX uq_organizations_name,
ADD COLUMN active_name VARCHAR(255)
GENERATED ALWAYS AS (IF(deleted_at IS NULL, name, NULL)) STORED,
ADD UNIQUE KEY uq_organizations_active_name (active_name);
-- Deux contacts actifs ne peuvent pas porter la meme adresse, meme si elle
-- est saisie avec des casse differentes : la collation s'en charge deja, mais
-- la cle garantit que le controle ne depend pas du moteur.
INSERT INTO audit_logs (action, resource, details)
VALUES (
'schema.migration',
'migration',
JSON_OBJECT('version', '006_active_identity', 'portee', 'contacts.email, organizations.name')
);
+13
View File
@@ -0,0 +1,13 @@
-- Les roles disparaissent : le CRM n'a qu'un compte principal et un compte de
-- secours, tous deux avec les memes droits. requireRole et role_slug partent
-- en meme temps du code, la base reste le dernier recours.
--
-- 001, 002 et 003 ne sont pas retouches : la correction passe par ce fichier,
-- comme pour toute migration deja appliquee.
ALTER TABLE users DROP FOREIGN KEY fk_users_role;
ALTER TABLE users DROP COLUMN role_id;
-- L'index idx_users_role part avec la colonne.
DROP TABLE roles;
+24
View File
@@ -0,0 +1,24 @@
{
"name": "@cohaise/crm",
"version": "0.0.0",
"private": true,
"type": "module",
"scripts": {
"build": "tsc --build",
"clean": "node --eval \"import('node:fs').then(fs => { fs.rmSync('dist', { recursive: true, force: true }); fs.rmSync('tsconfig.tsbuildinfo', { force: true }); })\"",
"typecheck": "tsc --noEmit",
"start": "node dist/index.js",
"admin": "node dist/admin.js"
},
"dependencies": {
"@cohaise/server": "*",
"zod": "^4.6.5"
},
"devDependencies": {
"@types/node": "^24.0.0",
"typescript": "^7.0.2"
},
"bin": {
"cohaise-crm-admin": "./dist/admin.js"
}
}
+172
View File
@@ -0,0 +1,172 @@
#!/usr/bin/env node
import { randomUUID } from "node:crypto";
import { ConfigError, loadDbConfig, hashPassword, AppError, toSafeError } from "@cohaise/server";
/**
* Creation et reinitialisation des comptes CRM, hors requete HTTP.
*
* Meme principe que cohaise-admin : cette commande ne lit que les variables
* DB, pour pouvoir creer le premier administrateur alors que l'API n'a pas
* encore le droit de demarrer.
*
* node dist/admin.js --email [email protected] --first Jean --last Dupont
* node dist/admin.js --email [email protected] --reset
*
* Mot de passe : ADMIN_PASSWORD dans l'environnement, sinon --password,
* sinon un mot de passe aleatoire est genere et affiche une seule fois.
*/
const USAGE = `Utilisation : cohaise-crm-admin --email <adr> --first <prenom> --last <nom> [options]
--email <adr> Adresse du compte (obligatoire)
--first <nom> Prenom (obligatoire a la creation)
--last <nom> Nom (obligatoire a la creation)
--password <mdp> Mot de passe, sinon variable ADMIN_PASSWORD
--reset Reinitialise le mot de passe d'un compte existant
--help Cette aide`;
interface Args {
email: string;
first: string;
last: string;
password?: string;
reset: boolean;
help: boolean;
}
const parseArgs = (argv: string[]): Args => {
const args: Args = {
email: "",
first: "",
last: "",
reset: false,
help: false,
};
const value = (index: number): string => {
const next = argv[index + 1];
if (next === undefined || next.startsWith("--")) {
throw AppError.badRequest(`Valeur manquante pour ${argv[index]}`);
}
return next;
};
for (let index = 0; index < argv.length; index += 1) {
const arg = argv[index];
if (arg === undefined) continue;
if (arg === "--email") args.email = value(index++);
else if (arg === "--first") args.first = value(index++);
else if (arg === "--last") args.last = value(index++);
else if (arg === "--password") args.password = value(index++);
else if (arg === "--reset") args.reset = true;
else if (arg === "--help" || arg === "-h") args.help = true;
else throw AppError.badRequest(`Argument inconnu : ${arg}`);
}
return args;
};
/** Mot de passe aleatoire, lisible a la frappe, sans caractere ambigu. */
const generatePassword = (): string => {
const alphabet = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789";
const bytes = new Uint8Array(18);
globalThis.crypto.getRandomValues(bytes);
let out = "";
for (const byte of bytes) out += alphabet[byte % alphabet.length];
return out;
};
const main = async (argv: string[]): Promise<number> => {
let args: Args;
try {
args = parseArgs(argv);
} catch (error) {
console.error(` ${toSafeError(error).message}\n\n${USAGE}`);
return 2;
}
if (args.help) {
console.log(USAGE);
return 0;
}
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(args.email)) {
console.error(" Adresse e-mail invalide.");
return 2;
}
let config;
try {
config = loadDbConfig();
} catch (error) {
if (error instanceof ConfigError) {
console.error(` Configuration invalide :\n - ${error.issues.join("\n - ")}`);
return 2;
}
throw error;
}
const { Db } = await import("@cohaise/server");
const db = new Db(config);
try {
// Pas de colonne active_email ici : le CRM n'a pas de migration qui
// neutralise les lignes supprimees sur la table users. On regarde donc
// deleted_at explicitement.
const existing = await db.one<{ id: string; deleted_at: string | null }>(
"SELECT id, deleted_at FROM users WHERE email = ?",
[args.email],
);
if (existing && !args.reset && existing.deleted_at === null) {
console.error(` Ce compte existe deja : ${args.email}`);
console.error(" Utilisez --reset pour reinitialiser son mot de passe.");
return 1;
}
const password = args.password ?? process.env.ADMIN_PASSWORD ?? generatePassword();
if (Buffer.byteLength(password) < 8) {
console.error(" Le mot de passe doit contenir au moins 8 caracteres.");
return 2;
}
const hash = await hashPassword(password);
if (existing) {
const assignments = ["password_hash = ?", "must_change_password = 1", "is_active = 1", "deleted_at = NULL"];
const values: unknown[] = [hash, existing.id];
await db.exec(`UPDATE users SET ${assignments.join(", ")} WHERE id = ?`, values);
console.log(` Mot de passe reinitialise pour ${args.email}`);
console.log(` Mot de passe : ${password}`);
console.log(" Un changement de mot de passe sera demande a la premiere connexion.");
return 0;
}
if (!args.first || !args.last) {
console.error(" --first et --last sont obligatoires a la creation.");
console.error(`\n${USAGE}`);
return 2;
}
const id = randomUUID();
await db.exec(
`INSERT INTO users (id, email, first_name, last_name, password_hash, must_change_password)
VALUES (?, ?, ?, ?, ?, 1)`,
[id, args.email, args.first, args.last, hash],
);
console.log(` Compte cree : ${args.email}`);
console.log(` Mot de passe : ${password}`);
console.log(" Un changement de mot de passe sera demande a la premiere connexion.");
return 0;
} catch (error) {
const safe = toSafeError(error);
console.error(` Echec : ${safe.code} — ${safe.message}`);
return 1;
} finally {
await db.close().catch(() => undefined);
}
};
main(process.argv.slice(2)).then(
(code) => process.exit(code),
(error) => {
console.error(` Erreur inattendue : ${error instanceof Error ? error.message : String(error)}`);
process.exit(1);
},
);
+25
View File
@@ -0,0 +1,25 @@
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
import { purgeExpiredSessions, startService } from "@cohaise/server";
import { registerAuthRoutes } from "./routes/auth.js";
import { registerCountryRoutes } from "./routes/countries.js";
import { registerOrganizationRoutes } from "./routes/organizations.js";
import { registerContactRoutes } from "./routes/contacts.js";
import { registerLeadRoutes } from "./routes/leads.js";
const migrationsDir = join(dirname(fileURLToPath(import.meta.url)), "../migrations");
void startService({
service: "crm",
migrationsDir,
routes: (app, { db, config }) => {
registerAuthRoutes(app, db, config);
registerCountryRoutes(app, db);
registerOrganizationRoutes(app, db);
registerContactRoutes(app, db);
registerLeadRoutes(app, db);
// Les jetons expires n'ont rien a faire en base : purge au demarrage
// plutot qu'un EVENT, qui dependrait du planificateur MariaDB.
void purgeExpiredSessions(db);
},
});
+151
View File
@@ -0,0 +1,151 @@
import { z } from "zod";
import {
AppError,
attachUser,
clearSessionCookie,
createSession,
currentUser,
hashPassword,
isHttpsRequest,
requireAuth,
revokeSession,
setSessionCookie,
sha256,
verifyPassword,
type App,
type Config,
type Db,
} from "@cohaise/server";
const credentials = z.object({
email: z.string().trim().toLowerCase().email().max(255),
password: z.string().min(1).max(1024),
});
const changePassword = z.object({
current: z.string().min(1).max(1024),
next: z.string().min(8).max(1024),
});
interface UserRow {
id: string;
email: string;
password_hash: string;
first_name: string;
last_name: string;
is_active: number;
must_change_password: number;
}
const SELECT_USER = `
SELECT u.id, u.email, u.password_hash, u.first_name, u.last_name,
u.is_active, u.must_change_password
FROM users u`;
/**
* Empreinte de repli, calculee pour n'importe quelle chaine : une adresse
* inconnue doit prendre exactement le meme temps qu'une adresse connue avec
* un mauvais mot de passe, sinon l'API devient un annuaire.
*/
const DUMMY_HASH_PROMISE = hashPassword("placeholder-for-anti-enumeration").catch(() => null);
void DUMMY_HASH_PROMISE;
const publicUser = (row: UserRow) => ({
id: row.id,
email: row.email,
first_name: row.first_name,
last_name: row.last_name,
must_change_password: row.must_change_password === 1,
});
export const registerAuthRoutes = (app: App, db: Db, config: Config): void => {
app.use("/api/crm/auth/*", attachUser(db));
app.post("/api/crm/auth/login", async (context) => {
const parsed = credentials.safeParse(await context.req.json().catch(() => null));
if (!parsed.success) {
throw AppError.badRequest("Identifiants invalides.");
}
const row = await db.one<UserRow>(
`${SELECT_USER} WHERE u.email = ? AND u.deleted_at IS NULL`,
[parsed.data.email],
);
const stored = row?.password_hash ?? (await DUMMY_HASH_PROMISE) ?? "";
const valid = stored ? await verifyPassword(parsed.data.password, stored) : false;
if (!row || !valid) throw AppError.unauthorized("Identifiants invalides.");
if (row.is_active !== 1) throw AppError.unauthorized("Compte desactive.");
const { token, expiresAt } = await createSession(
db,
row.id,
{
ipAddress: context.req.header("x-forwarded-for")?.split(",")[0]?.trim() ?? null,
userAgent: context.req.header("user-agent") ?? null,
},
config.SESSION_TTL_HOURS,
);
await db.exec("UPDATE users SET last_login_at = UTC_TIMESTAMP(3) WHERE id = ?", [row.id]);
// Le schema reel de la requete, pas PUBLIC_ORIGIN : voir isHttpsRequest.
const secure = isHttpsRequest(context, config.TRUST_PROXY);
setSessionCookie(context, token, expiresAt, secure);
return context.json({ user: publicUser(row) });
});
app.post("/api/crm/auth/logout", requireAuth, async (context) => {
const token = context.get("token") as string | undefined;
if (token) await revokeSession(db, token);
clearSessionCookie(context);
return context.json({ ok: true });
});
app.get("/api/crm/auth/me", requireAuth, async (context) => {
const session = currentUser(context);
const row = await db.one<UserRow>(`${SELECT_USER} WHERE u.id = ? AND u.deleted_at IS NULL`, [
session.id,
]);
if (!row) throw AppError.unauthorized();
return context.json({ user: publicUser(row) });
});
app.post("/api/crm/auth/change-password", requireAuth, async (context) => {
const session = currentUser(context);
const parsed = changePassword.safeParse(await context.req.json().catch(() => null));
if (!parsed.success) {
throw AppError.badRequest("Le nouveau mot de passe doit contenir au moins 8 caracteres.");
}
const row = await db.one<{ password_hash: string }>(
"SELECT password_hash FROM users WHERE id = ? AND deleted_at IS NULL",
[session.id],
);
if (!row) throw AppError.unauthorized();
if (!(await verifyPassword(parsed.data.current, row.password_hash))) {
throw AppError.unauthorized("Mot de passe actuel incorrect.");
}
if (parsed.data.current === parsed.data.next) {
throw AppError.badRequest("Le nouveau mot de passe doit differer de l'actuel.");
}
const hash = await hashPassword(parsed.data.next);
// Pas de password_changed_at ici : cette colonne appartient au modele du
// Cloud. Le CRM n'a pas de notion de confirmation d'identite a celebrer.
await db.exec("UPDATE users SET password_hash = ?, must_change_password = 0 WHERE id = ?", [
hash,
session.id,
]);
// La session courante est conservee, toutes les autres sont revoquees.
await db.exec(
`UPDATE user_sessions
SET revoked_at = UTC_TIMESTAMP()
WHERE user_id = ? AND revoked_at IS NULL AND token_hash <> ?`,
[session.id, sha256(context.get("token") ?? "")],
);
return context.json({ ok: true });
});
};
+274
View File
@@ -0,0 +1,274 @@
import { randomUUID } from "node:crypto";
import { z } from "zod";
import {
AppError,
attachUser,
currentUser,
requireAuth,
type App,
type Db,
} from "@cohaise/server";
const uuid = z
.string()
.regex(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i, "Identifiant invalide.");
const createContact = z.object({
firstName: z.string().trim().min(1).max(100),
lastName: z.string().trim().min(1).max(100),
organizationId: z.string().regex(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i).nullish(),
email: z.string().trim().max(255).nullish(),
phone: z.string().trim().max(50).nullish(),
mobile: z.string().trim().max(50).nullish(),
jobTitle: z.string().trim().max(150).nullish(),
countryId: z.coerce.number().int().positive().nullish(),
externalSource: z.string().trim().max(50).nullish(),
externalId: z.string().trim().max(100).nullish(),
description: z.string().trim().max(4000).nullish(),
});
const updateContact = createContact.partial();
interface ContactRow {
id: string;
first_name: string;
last_name: string;
organization_id: string | null;
organization_name: string | null;
email: string | null;
phone: string | null;
mobile: string | null;
job_title: string | null;
country_id: number | null;
country_name: string | null;
country_code: string | null;
external_source: string | null;
external_id: string | null;
description: string | null;
owner_id: string | null;
owner_name: string | null;
created_at: string;
updated_at: string;
}
const SELECT_CONTACT = `
SELECT ct.id, ct.first_name, ct.last_name, ct.organization_id,
o.name AS organization_name, ct.email, ct.phone, ct.mobile, ct.job_title,
ct.country_id, c.name AS country_name, c.code AS country_code,
ct.external_source, ct.external_id, ct.description, ct.owner_id,
CONCAT(u.first_name, ' ', u.last_name) AS owner_name,
ct.created_at, ct.updated_at
FROM contacts ct
LEFT JOIN organizations o ON o.id = ct.organization_id AND o.deleted_at IS NULL
LEFT JOIN countries c ON c.id = ct.country_id
LEFT JOIN users u ON u.id = ct.owner_id`;
const publicContact = (row: ContactRow) => ({
id: row.id,
first_name: row.first_name,
last_name: row.last_name,
organization_id: row.organization_id,
organization_name: row.organization_name,
email: row.email,
phone: row.phone,
mobile: row.mobile,
job_title: row.job_title,
country_id: row.country_id,
country_name: row.country_name,
country_code: row.country_code,
external_source: row.external_source,
external_id: row.external_id,
description: row.description,
owner_id: row.owner_id,
owner_name: row.owner_name,
created_at: row.created_at,
updated_at: row.updated_at,
});
/** Un e-mail absent ne doit pas heurter l'index actif : NULL passe partout. */
const emailOrNull = (value: string | null | undefined): string | null =>
value ? value.toLowerCase() : null;
export const registerContactRoutes = (app: App, db: Db): void => {
app.use("/api/crm/contacts/*", attachUser(db));
app.use("/api/crm/contacts", attachUser(db));
app.get("/api/crm/contacts", requireAuth, async (context) => {
const search = context.req.query("q")?.trim() ?? "";
const organizationId = context.req.query("organizationId")?.trim() ?? "";
const page = Math.max(1, Number(context.req.query("page") ?? 1) || 1);
const limit = Math.min(100, Math.max(1, Number(context.req.query("limit") ?? 25) || 25));
const offset = (page - 1) * limit;
const clauses = ["ct.deleted_at IS NULL"];
const params: unknown[] = [];
if (search) {
clauses.push(
"(ct.first_name LIKE ? OR ct.last_name LIKE ? OR ct.email LIKE ? OR o.name LIKE ?)",
);
const term = `%${search}%`;
params.push(term, term, term, term);
}
if (uuid.safeParse(organizationId).success) {
clauses.push("ct.organization_id = ?");
params.push(organizationId);
}
const where = `WHERE ${clauses.join(" AND ")}`;
const totalRows = await db.query<{ total: number }>(
`SELECT COUNT(*) AS total
FROM contacts ct
LEFT JOIN organizations o ON o.id = ct.organization_id AND o.deleted_at IS NULL
${where}`,
params,
);
const total = Number(totalRows[0]?.total ?? 0);
const rows = await db.query<ContactRow>(
`${SELECT_CONTACT} ${where} ORDER BY ct.last_name, ct.first_name LIMIT ${limit} OFFSET ${offset}`,
params,
);
return context.json({
total,
page,
limit,
contacts: rows.map(publicContact),
});
});
app.get("/api/crm/contacts/:id", requireAuth, async (context) => {
const id = context.req.param("id");
if (!uuid.safeParse(id).success) throw AppError.notFound("Prospect introuvable.");
const row = await db.one<ContactRow>(
`${SELECT_CONTACT} WHERE ct.id = ? AND ct.deleted_at IS NULL`,
[id],
);
if (!row) throw AppError.notFound("Prospect introuvable.");
return context.json({ contact: publicContact(row) });
});
app.post(
"/api/crm/contacts",
requireAuth,
async (context) => {
const user = currentUser(context);
const parsed = createContact.safeParse(await context.req.json().catch(() => null));
if (!parsed.success) {
const issue = parsed.error.issues[0];
throw AppError.badRequest(issue ? `${issue.path.join(".") || "corps"} : ${issue.message}` : "Corps invalide.");
}
const data = parsed.data;
const id = randomUUID();
try {
await db.exec(
`INSERT INTO contacts
(id, first_name, last_name, organization_id, email, phone, mobile, job_title,
country_id, external_source, external_id, description, owner_id, created_by)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
[
id,
data.firstName,
data.lastName,
data.organizationId ?? null,
emailOrNull(data.email),
data.phone ?? null,
data.mobile ?? null,
data.jobTitle ?? null,
data.countryId ?? null,
data.externalSource ?? null,
data.externalId ?? null,
data.description ?? null,
user.id,
user.id,
],
);
} catch (error) {
if ((error as { errno?: number }).errno === 1062) {
throw AppError.conflict("Un prospect actif porte deja cette adresse.");
}
if ((error as { errno?: number }).errno === 1452) {
throw AppError.badRequest("L'entreprise ou le pays reference n'existe pas.");
}
throw error;
}
const created = await db.required<ContactRow>(`${SELECT_CONTACT} WHERE ct.id = ?`, [id]);
return context.json({ contact: publicContact(created) }, 201);
},
);
app.patch(
"/api/crm/contacts/:id",
requireAuth,
async (context) => {
const id = context.req.param("id");
if (!uuid.safeParse(id).success) throw AppError.notFound("Prospect introuvable.");
const parsed = updateContact.safeParse(await context.req.json().catch(() => null));
if (!parsed.success) throw AppError.badRequest("Corps invalide.");
const existing = await db.one<{ id: string }>(
"SELECT id FROM contacts WHERE id = ? AND deleted_at IS NULL",
[id],
);
if (!existing) throw AppError.notFound("Prospect introuvable.");
const columns: Record<string, unknown> = {
first_name: parsed.data.firstName,
last_name: parsed.data.lastName,
organization_id: parsed.data.organizationId,
email: parsed.data.email === undefined ? undefined : emailOrNull(parsed.data.email),
phone: parsed.data.phone,
mobile: parsed.data.mobile,
job_title: parsed.data.jobTitle,
country_id: parsed.data.countryId,
external_source: parsed.data.externalSource,
external_id: parsed.data.externalId,
description: parsed.data.description,
};
const assignments = Object.keys(columns)
.filter((key) => columns[key] !== undefined)
.map((key) => `${key} = ?`);
if (assignments.length === 0) throw AppError.badRequest("Aucune modification fournie.");
const values = Object.keys(columns)
.filter((key) => columns[key] !== undefined)
.map((key) => columns[key]);
try {
await db.exec(
`UPDATE contacts SET ${assignments.join(", ")} WHERE id = ? AND deleted_at IS NULL`,
[...values, id],
);
} catch (error) {
if ((error as { errno?: number }).errno === 1062) {
throw AppError.conflict("Un prospect actif porte deja cette adresse.");
}
if ((error as { errno?: number }).errno === 1452) {
throw AppError.badRequest("L'entreprise ou le pays reference n'existe pas.");
}
throw error;
}
const updated = await db.required<ContactRow>(`${SELECT_CONTACT} WHERE ct.id = ?`, [id]);
return context.json({ contact: publicContact(updated) });
},
);
app.delete(
"/api/crm/contacts/:id",
requireAuth,
async (context) => {
const id = context.req.param("id");
if (!uuid.safeParse(id).success) throw AppError.notFound("Prospect introuvable.");
const result = await db.exec(
"UPDATE contacts SET deleted_at = UTC_TIMESTAMP() WHERE id = ? AND deleted_at IS NULL",
[id],
);
if (result.affectedRows === 0) throw AppError.notFound("Prospect introuvable.");
return context.json({ ok: true });
},
);
};
+150
View File
@@ -0,0 +1,150 @@
import { z } from "zod";
import {
AppError,
attachUser,
requireAuth,
type App,
type Db,
} from "@cohaise/server";
const createCountry = z.object({
code: z
.string()
.trim()
.toUpperCase()
.regex(/^[A-Z]{2}$/, "Code ISO 3166-1 alpha-2 attendu, deux lettres."),
name: z.string().trim().min(1).max(100),
phoneCode: z
.string()
.trim()
.regex(/^\+?[0-9]{1,7}$/, "Indicatif telephonique attendu.")
.nullish(),
});
const updateCountry = createCountry.partial();
interface CountryRow {
id: number;
code: string;
name: string;
phone_code: string | null;
}
const publicCountry = (row: CountryRow) => ({
id: row.id,
code: row.code,
name: row.name,
phone_code: row.phone_code,
});
export const registerCountryRoutes = (app: App, db: Db): void => {
app.use("/api/crm/countries/*", attachUser(db));
app.use("/api/crm/countries", attachUser(db));
// Referentiel : lecture ouverte a tout le monde authentifie, ecriture
// reservee. Le tri est collationnel, donc sans accent ni casse douteuse.
app.get("/api/crm/countries", requireAuth, async (context) => {
const search = context.req.query("q")?.trim() ?? "";
const where = search ? "WHERE name LIKE ? OR code = ?" : "";
const params = search ? [`%${search}%`, search.toUpperCase()] : [];
const rows = await db.query<CountryRow>(
`SELECT id, code, name, phone_code FROM countries ${where} ORDER BY name`,
params,
);
return context.json({ countries: rows.map(publicCountry) });
});
app.post(
"/api/crm/countries",
requireAuth,
async (context) => {
const parsed = createCountry.safeParse(await context.req.json().catch(() => null));
if (!parsed.success) {
const issue = parsed.error.issues[0];
throw AppError.badRequest(issue?.message ?? "Corps invalide.");
}
try {
await db.exec("INSERT INTO countries (code, name, phone_code) VALUES (?, ?, ?)", [
parsed.data.code,
parsed.data.name,
parsed.data.phoneCode ?? null,
]);
} catch (error) {
if ((error as { errno?: number }).errno === 1062) {
throw AppError.conflict("Ce pays existe deja.");
}
throw error;
}
const created = await db.required<CountryRow>(
"SELECT id, code, name, phone_code FROM countries WHERE code = ?",
[parsed.data.code],
);
return context.json({ country: publicCountry(created) }, 201);
},
);
app.patch(
"/api/crm/countries/:id",
requireAuth,
async (context) => {
const id = Number(context.req.param("id"));
if (!Number.isInteger(id) || id <= 0) throw AppError.notFound("Pays introuvable.");
const parsed = updateCountry.safeParse(await context.req.json().catch(() => null));
if (!parsed.success) throw AppError.badRequest("Corps invalide.");
const columns: Record<string, unknown> = {
code: parsed.data.code,
name: parsed.data.name,
phone_code: parsed.data.phoneCode,
};
const assignments = Object.keys(columns)
.filter((key) => columns[key] !== undefined)
.map((key) => `${key} = ?`);
if (assignments.length === 0) throw AppError.badRequest("Aucune modification fournie.");
const values = Object.keys(columns)
.filter((key) => columns[key] !== undefined)
.map((key) => columns[key]);
try {
const result = await db.exec(
`UPDATE countries SET ${assignments.join(", ")} WHERE id = ?`,
[...values, id],
);
if (result.affectedRows === 0) throw AppError.notFound("Pays introuvable.");
} catch (error) {
if ((error as { errno?: number }).errno === 1062) {
throw AppError.conflict("Ce code de pays existe deja.");
}
throw error;
}
const updated = await db.required<CountryRow>(
"SELECT id, code, name, phone_code FROM countries WHERE id = ?",
[id],
);
return context.json({ country: publicCountry(updated) });
},
);
app.delete(
"/api/crm/countries/:id",
requireAuth,
async (context) => {
const id = Number(context.req.param("id"));
if (!Number.isInteger(id) || id <= 0) throw AppError.notFound("Pays introuvable.");
try {
const result = await db.exec("DELETE FROM countries WHERE id = ?", [id]);
if (result.affectedRows === 0) throw AppError.notFound("Pays introuvable.");
} catch (error) {
if ((error as { errno?: number }).errno === 1451) {
throw AppError.conflict("Des entreprises ou contacts referencent ce pays.");
}
throw error;
}
return context.json({ ok: true });
},
);
};
+146
View File
@@ -0,0 +1,146 @@
import { randomUUID } from "node:crypto";
import { z } from "zod";
import { AppError, type App, type Db } from "@cohaise/server";
/**
* Point d'entrée public du formulaire de contact de la vitrine.
*
* Route volontairement sans `requireAuth` : n'importe quel visiteur de
* cohaise.dev peut creer un prospect. Protection anti-abus a deux etages :
* - un honeypot (champ invisible que seuls les robots remplissent) ;
* - un rate-limit simple en memoire, par IP (Cloudflare reste la 1re ligne).
* Le lead est pose dans `contacts` avec `external_source = 'cohaise-web'`,
* non assigne, pour apparaitre dans la liste des prospects du CRM.
*/
const leadSchema = z.object({
firstName: z.string().trim().min(1).max(100),
lastName: z.string().trim().min(1).max(100),
email: z.string().trim().min(1).max(255),
organization: z.string().trim().min(1).max(255).nullish(),
phone: z.string().trim().max(50).nullish(),
message: z.string().trim().max(4000).nullish(),
// Honeypot : vide chez un humain, rempli par un robot.
website: z.string().max(255).nullish(),
});
const slugify = (value: string): string =>
value
.normalize("NFD")
.replace(/[\u0300-\u036f]/g, "")
.toLowerCase()
.replace(/[^a-z0-9]+/g, "-")
.replace(/^-+|-+$/g, "")
.slice(0, 255);
/** Un e-mail absent ne doit pas heurter l'index unique : NULL passe partout. */
const emailOrNull = (value: string): string | null => value.toLowerCase();
/** Retrouve l'entreprise par son nom, ou la cree (nom unique en base). */
const findOrCreateOrganization = async (db: Db, name: string): Promise<string> => {
const existing = await db.one<{ id: string }>(
"SELECT id FROM organizations WHERE name = ? AND deleted_at IS NULL",
[name],
);
if (existing) return existing.id;
const id = randomUUID();
try {
await db.exec("INSERT INTO organizations (id, name, slug) VALUES (?, ?, ?)", [
id,
name,
slugify(name),
]);
} catch (error) {
if ((error as { errno?: number }).errno === 1062) {
// Course : une autre requete vient de creer le meme nom. On la rejoint.
const raced = await db.one<{ id: string }>(
"SELECT id FROM organizations WHERE name = ? AND deleted_at IS NULL",
[name],
);
if (raced) return raced.id;
}
throw error;
}
return id;
};
// Rate-limit en memoire : suffisant pour une instance CRM unique. Derriere
// nginx/Cloudflare, l'IP vient de x-forwarded-for.
const RATE_WINDOW_MS = 15 * 60 * 1000;
const RATE_MAX = 5;
const attempts = new Map<string, number[]>();
const isAllowed = (ip: string): boolean => {
const now = Date.now();
const recent = (attempts.get(ip) ?? []).filter((t) => now - t < RATE_WINDOW_MS);
if (recent.length >= RATE_MAX) {
attempts.set(ip, recent);
return false;
}
recent.push(now);
attempts.set(ip, recent);
return true;
};
export const registerLeadRoutes = (app: App, db: Db): void => {
app.post("/api/crm/leads", async (context) => {
const forwarded = context.req.header("x-forwarded-for");
const ip =
forwarded?.split(",")[0]?.trim() ?? context.req.header("x-real-ip") ?? "unknown";
if (!isAllowed(ip)) throw AppError.tooManyRequests();
const parsed = leadSchema.safeParse(await context.req.json().catch(() => null));
if (!parsed.success) {
const issue = parsed.error.issues[0];
throw AppError.badRequest(
issue ? `${issue.path.join(".") || "corps"} : ${issue.message}` : "Corps invalide.",
);
}
const data = parsed.data;
// Honeypot rempli : robot. On feint la reussite pour ne pas se trahir.
if (data.website) {
return context.json({ ok: true, id: randomUUID() }, 201);
}
const organizationId = data.organization
? await findOrCreateOrganization(db, data.organization)
: null;
const id = randomUUID();
try {
await db.exec(
`INSERT INTO contacts
(id, first_name, last_name, organization_id, email, phone, job_title,
country_id, external_source, external_id, description, owner_id, created_by)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
[
id,
data.firstName,
data.lastName,
organizationId,
emailOrNull(data.email),
data.phone ?? null,
null,
null,
"cohaise-web",
null,
data.message ?? null,
null,
null,
],
);
} catch (error) {
if ((error as { errno?: number }).errno === 1062) {
throw AppError.conflict("Cette adresse a deja ete enregistree.");
}
if ((error as { errno?: number }).errno === 1452) {
throw AppError.badRequest("L'entreprise referencee n'existe pas.");
}
throw error;
}
return context.json({ ok: true, id }, 201);
});
};
+277
View File
@@ -0,0 +1,277 @@
import { randomUUID } from "node:crypto";
import { z } from "zod";
import {
AppError,
attachUser,
currentUser,
requireAuth,
type App,
type Db,
} from "@cohaise/server";
const uuid = z
.string()
.regex(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i, "Identifiant invalide.");
const writable = z.string().trim().min(1).max(255);
const optionalText = z.string().trim().max(255).nullish();
const optionalLong = z.string().trim().max(4000).nullish();
const createOrganization = z.object({
name: writable,
website: optionalText,
industry: z.string().trim().max(100).nullish(),
phone: z.string().trim().max(50).nullish(),
email: z.string().trim().max(255).nullish(),
addressLine1: optionalText,
addressLine2: optionalText,
postalCode: z.string().trim().max(20).nullish(),
city: z.string().trim().max(100).nullish(),
countryId: z.coerce.number().int().positive().nullish(),
description: optionalLong,
});
const updateOrganization = createOrganization.partial();
interface OrganizationRow {
id: string;
name: string;
slug: string;
website: string | null;
industry: string | null;
phone: string | null;
email: string | null;
address_line1: string | null;
address_line2: string | null;
postal_code: string | null;
city: string | null;
country_id: number | null;
country_name: string | null;
country_code: string | null;
description: string | null;
owner_id: string | null;
owner_name: string | null;
created_at: string;
updated_at: string;
}
const SELECT_ORGANIZATION = `
SELECT o.id, o.name, o.slug, o.website, o.industry, o.phone, o.email,
o.address_line1, o.address_line2, o.postal_code, o.city, o.country_id,
c.name AS country_name, c.code AS country_code,
o.description, o.owner_id,
CONCAT(u.first_name, ' ', u.last_name) AS owner_name,
o.created_at, o.updated_at
FROM organizations o
LEFT JOIN countries c ON c.id = o.country_id
LEFT JOIN users u ON u.id = o.owner_id`;
const publicOrganization = (row: OrganizationRow) => ({
id: row.id,
name: row.name,
slug: row.slug,
website: row.website,
industry: row.industry,
phone: row.phone,
email: row.email,
address_line1: row.address_line1,
address_line2: row.address_line2,
postal_code: row.postal_code,
city: row.city,
country_id: row.country_id,
country_name: row.country_name,
country_code: row.country_code,
description: row.description,
owner_id: row.owner_id,
owner_name: row.owner_name,
created_at: row.created_at,
updated_at: row.updated_at,
});
/** Normalise un nom en slug lisible, sans accent ni punctuation. */
const slugify = (value: string): string =>
value
.normalize("NFD")
.replace(/[\u0300-\u036f]/g, "")
.toLowerCase()
.replace(/[^a-z0-9]+/g, "-")
.replace(/^-+|-+$/g, "")
.slice(0, 255);
export const registerOrganizationRoutes = (app: App, db: Db): void => {
app.use("/api/crm/organizations/*", attachUser(db));
app.use("/api/crm/organizations", attachUser(db));
app.get("/api/crm/organizations", requireAuth, async (context) => {
const search = context.req.query("q")?.trim() ?? "";
const page = Math.max(1, Number(context.req.query("page") ?? 1) || 1);
const limit = Math.min(100, Math.max(1, Number(context.req.query("limit") ?? 25) || 25));
const offset = (page - 1) * limit;
const where = search
? "WHERE o.deleted_at IS NULL AND (o.name LIKE ? OR o.city LIKE ? OR o.industry LIKE ?)"
: "WHERE o.deleted_at IS NULL";
const term = `%${search}%`;
const params = search ? [term, term, term] : [];
const [{ total }, rows] = await Promise.all([
db
.query<{ total: number }>(`SELECT COUNT(*) AS total FROM organizations o ${where}`, params)
.then((result) => ({ total: Number(result[0]?.total ?? 0) })),
db.query<OrganizationRow>(
`${SELECT_ORGANIZATION} ${where} ORDER BY o.name LIMIT ${limit} OFFSET ${offset}`,
params,
),
]);
return context.json({
total,
page,
limit,
organizations: rows.map(publicOrganization),
});
});
app.get("/api/crm/organizations/:id", requireAuth, async (context) => {
const id = context.req.param("id");
if (!uuid.safeParse(id).success) throw AppError.notFound("Entreprise introuvable.");
const row = await db.one<OrganizationRow>(
`${SELECT_ORGANIZATION} WHERE o.id = ? AND o.deleted_at IS NULL`,
[id],
);
if (!row) throw AppError.notFound("Entreprise introuvable.");
return context.json({ organization: publicOrganization(row) });
});
app.post(
"/api/crm/organizations",
requireAuth,
async (context) => {
const user = currentUser(context);
const parsed = createOrganization.safeParse(await context.req.json().catch(() => null));
if (!parsed.success) {
const issue = parsed.error.issues[0];
throw AppError.badRequest(
issue ? `${issue.path.join(".") || "corps"} : ${issue.message}` : "Corps invalide.",
);
}
const data = parsed.data;
const id = randomUUID();
try {
await db.exec(
`INSERT INTO organizations
(id, name, slug, website, industry, phone, email, address_line1, address_line2,
postal_code, city, country_id, description, owner_id, created_by)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
[
id,
data.name,
slugify(data.name),
data.website ?? null,
data.industry ?? null,
data.phone ?? null,
data.email ?? null,
data.addressLine1 ?? null,
data.addressLine2 ?? null,
data.postalCode ?? null,
data.city ?? null,
data.countryId ?? null,
data.description ?? null,
user.id,
user.id,
],
);
} catch (error) {
if ((error as { errno?: number }).errno === 1062) {
throw AppError.conflict("Une entreprise porte deja ce nom.");
}
throw error;
}
const created = await db.required<OrganizationRow>(
`${SELECT_ORGANIZATION} WHERE o.id = ?`,
[id],
);
return context.json({ organization: publicOrganization(created) }, 201);
},
);
app.patch(
"/api/crm/organizations/:id",
requireAuth,
async (context) => {
const id = context.req.param("id");
if (!uuid.safeParse(id).success) throw AppError.notFound("Entreprise introuvable.");
const parsed = updateOrganization.safeParse(await context.req.json().catch(() => null));
if (!parsed.success) throw AppError.badRequest("Corps invalide.");
const existing = await db.one<{ id: string }>(
"SELECT id FROM organizations WHERE id = ? AND deleted_at IS NULL",
[id],
);
if (!existing) throw AppError.notFound("Entreprise introuvable.");
const columns: Record<string, unknown> = {
website: parsed.data.website,
industry: parsed.data.industry,
phone: parsed.data.phone,
email: parsed.data.email,
address_line1: parsed.data.addressLine1,
address_line2: parsed.data.addressLine2,
postal_code: parsed.data.postalCode,
city: parsed.data.city,
country_id: parsed.data.countryId,
description: parsed.data.description,
};
if (parsed.data.name !== undefined) {
columns.name = parsed.data.name;
columns.slug = slugify(parsed.data.name);
}
const assignments = Object.keys(columns)
.filter((key) => columns[key] !== undefined)
.map((key) => `${key} = ?`);
if (assignments.length === 0) throw AppError.badRequest("Aucune modification fournie.");
const values = Object.keys(columns)
.filter((key) => columns[key] !== undefined)
.map((key) => columns[key]);
try {
await db.exec(
`UPDATE organizations SET ${assignments.join(", ")} WHERE id = ? AND deleted_at IS NULL`,
[...values, id],
);
} catch (error) {
if ((error as { errno?: number }).errno === 1062) {
throw AppError.conflict("Une entreprise porte deja ce nom.");
}
throw error;
}
const updated = await db.required<OrganizationRow>(
`${SELECT_ORGANIZATION} WHERE o.id = ?`,
[id],
);
return context.json({ organization: publicOrganization(updated) });
},
);
app.delete(
"/api/crm/organizations/:id",
requireAuth,
async (context) => {
const id = context.req.param("id");
if (!uuid.safeParse(id).success) throw AppError.notFound("Entreprise introuvable.");
const result = await db.exec(
"UPDATE organizations SET deleted_at = UTC_TIMESTAMP() WHERE id = ? AND deleted_at IS NULL",
[id],
);
if (result.affectedRows === 0) throw AppError.notFound("Entreprise introuvable.");
return context.json({ ok: true });
},
);
};
+17
View File
@@ -0,0 +1,17 @@
{
"$schema": "https://json.schemastore.org/tsconfig",
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"module": "NodeNext",
"moduleResolution": "NodeNext",
"lib": ["ES2023"],
"types": ["node"],
"rootDir": "src",
"outDir": "dist",
"composite": true,
"declaration": true,
"sourceMap": true
},
"include": ["src/**/*.ts"],
"references": [{ "path": "../shared" }]
}
+33
View File
@@ -0,0 +1,33 @@
{
"name": "@cohaise/server",
"version": "0.0.0",
"private": true,
"type": "module",
"exports": {
".": {
"types": "./dist/index.d.ts",
"default": "./dist/index.js"
}
},
"files": [
"dist"
],
"scripts": {
"build": "tsc --build",
"clean": "node --eval \"import('node:fs').then(fs => { fs.rmSync('dist', { recursive: true, force: true }); fs.rmSync('tsconfig.tsbuildinfo', { force: true }); })\"",
"typecheck": "tsc --noEmit"
},
"devDependencies": {
"@types/node": "^24.0.0",
"typescript": "^7.0.2"
},
"dependencies": {
"@hono/node-server": "^2.1.3",
"hono": "^4.13.13",
"mysql2": "^3.24.5",
"zod": "^4.6.5"
},
"bin": {
"cohaise-migrate": "./dist/cli.js"
}
}
+224
View File
@@ -0,0 +1,224 @@
import { createHash, randomBytes, randomUUID, scrypt as scryptCallback, timingSafeEqual } from "node:crypto";
import { promisify } from "node:util";
import type { Context, Next } from "hono";
import { getCookie, setCookie, deleteCookie } from "hono/cookie";
import type { Db } from "./db.js";
import { AppError } from "./errors.js";
const scrypt = promisify(scryptCallback) as (
password: string | Buffer,
salt: Buffer,
keylen: number,
options: { N: number; r: number; p: number; maxmem?: number },
) => Promise<Buffer>;
/**
* scrypt du module natif, pas une dependance externe. Une lib native a compiler
* est la facon la plus rapide de casser un build sur une machine cible : argon2
* ou bcrypt produisent un binaire qui n'est pas portable sans outilchain.
* node:crypto est deja la, et scrypt est un KDF defini par RFC 7914.
*/
const SCRYPT = { N: 16384, r: 8, p: 1, keylen: 64, maxmem: 32 * 1024 * 1024 };
export const hashPassword = async (password: string): Promise<string> => {
if (Buffer.byteLength(password) < 8) {
throw AppError.badRequest("Le mot de passe doit contenir au moins 8 caracteres.");
}
const salt = randomBytes(16);
const derived = await scrypt(password, salt, SCRYPT.keylen, SCRYPT);
return `scrypt$${SCRYPT.N}$${SCRYPT.r}$${SCRYPT.p}$${salt.toString("base64")}$${derived.toString("base64")}`;
};
export const verifyPassword = async (password: string, stored: string): Promise<boolean> => {
const parts = stored.split("$");
if (parts.length !== 6 || parts[0] !== "scrypt") return false;
const [, n, r, p, saltB64, hashB64] = parts;
const salt = Buffer.from(saltB64 ?? "", "base64");
const expected = Buffer.from(hashB64 ?? "", "base64");
if (expected.length === 0) return false;
const derived = await scrypt(password, salt, expected.length, {
N: Number(n),
r: Number(r),
p: Number(p),
maxmem: SCRYPT.maxmem,
});
return derived.length === expected.length && timingSafeEqual(derived, expected);
};
export const sha256 = (value: string): string => createHash("sha256").update(value).digest("hex");
/**
* Portrait de l'utilisateur porte par la session.
*
* Les budgets de stockage n'y figurent pas : une valeur figee dans un cookie
* serait fausse des la premiere ecriture, et le CRM n'a pas de notion de
* quota. Chaque route qui en a besoin relit les colonnes en base au moment
* de l'usage.
*/
export interface SessionUser {
id: string;
email: string;
first_name: string;
last_name: string;
role_slug: string;
role_name: string;
is_active: number;
must_change_password: number;
}
export interface SessionMeta {
ipAddress?: string | null | undefined;
userAgent?: string | null | undefined;
}
export const SESSION_COOKIE = "cohaise_session";
/**
* Le jeton brut part dans le cookie, son empreinte SHA-256 dans la base.
* Une copie de la base ne donne donc aucune session ouvrable : il faudrait
* en plus la table des cookies, qui n'existe pas.
*/
export const createSession = async (
db: Db,
userId: string,
meta: SessionMeta,
ttlHours: number,
): Promise<{ token: string; expiresAt: Date }> => {
const token = randomBytes(32).toString("base64url");
const expiresAt = new Date(Date.now() + ttlHours * 3600_000);
await db.exec(
`INSERT INTO user_sessions (id, user_id, token_hash, ip_address, user_agent, expires_at)
VALUES (?, ?, ?, ?, ?, ?)`,
[
randomUUID(),
userId,
sha256(token),
meta.ipAddress ?? null,
meta.userAgent?.slice(0, 255) ?? null,
expiresAt,
],
);
return { token, expiresAt };
};
export const resolveSession = async (db: Db, token: string): Promise<SessionUser | null> => {
const row = await db.one<SessionUser & { last_seen_at: string }>(
`SELECT u.id, u.email, u.first_name, u.last_name,
r.slug AS role_slug, r.name AS role_name,
u.is_active, u.must_change_password,
s.last_seen_at
FROM user_sessions s
JOIN users u ON u.id = s.user_id
JOIN roles r ON r.id = u.role_id
WHERE s.token_hash = ?
AND s.revoked_at IS NULL
AND s.expires_at > UTC_TIMESTAMP()
AND u.deleted_at IS NULL
AND u.is_active = 1`,
[sha256(token)],
);
if (!row) return null;
// Etat vu, avec un decalage de 60 s pour ne pas ecrire a chaque requete.
await db.exec(
"UPDATE user_sessions SET last_seen_at = UTC_TIMESTAMP() WHERE token_hash = ? AND last_seen_at < UTC_TIMESTAMP(3) - INTERVAL 60 SECOND",
[sha256(token)],
);
return row;
};
export const revokeSession = async (db: Db, token: string): Promise<void> => {
await db.exec("UPDATE user_sessions SET revoked_at = UTC_TIMESTAMP() WHERE token_hash = ?", [
sha256(token),
]);
};
export const purgeExpiredSessions = async (db: Db): Promise<number> => {
const result = await db.exec("DELETE FROM user_sessions WHERE expires_at < UTC_TIMESTAMP()");
return result.affectedRows;
};
/**
* Secure depend du schema reel de la requete, pas d'une origine configuree.
*
* Deriver Secure de PUBLIC_ORIGIN rendait tout test local impossible : le
* navigateur rejette en HTTP un cookie marque Secure, donc la connexion
* echouait sans message exploitable. A l'inverse, un cookie non Secure servi en
* HTTPS laisserait le jeton circuler en clair.
*
* X-Forwarded-Proto n'est pris en compte que si le service fait confiance a son
* proxy ; sinon la connexion parle d'elle-meme.
*/
export const isHttpsRequest = (context: Context, trustProxy: boolean): boolean => {
if (trustProxy) {
const forwarded = context.req.header("x-forwarded-proto");
if (forwarded) return forwarded.split(",")[0]?.trim() === "https";
}
return context.req.raw.url.startsWith("https:");
};
export const setSessionCookie = (
context: Context,
token: string,
expiresAt: Date,
secure: boolean,
): void => {
setCookie(context, SESSION_COOKIE, token, {
httpOnly: true,
sameSite: "Lax",
secure,
path: "/",
expires: expiresAt,
});
};
export const clearSessionCookie = (context: Context): void => {
deleteCookie(context, SESSION_COOKIE, { path: "/" });
};
export interface AuthState {
user: SessionUser;
token: string;
}
/** Lit le cookie et attache l'utilisateur, sans exiger qu'il existe. */
export const attachUser =
(db: Db) =>
async (context: Context, next: Next): Promise<void> => {
const token = getCookie(context, SESSION_COOKIE);
if (token) {
const user = await resolveSession(db, token);
if (user) {
context.set("user", user);
context.set("token", token);
} else {
clearSessionCookie(context);
}
}
await next();
};
export const requireAuth = async (context: Context, next: Next): Promise<void> => {
const user = context.get("user") as SessionUser | undefined;
if (!user) throw AppError.unauthorized();
await next();
};
/** Le role est impose en base, jamais en entete, donc ni cacheable ni falsifiable. */
export const requireRole =
(...slugs: string[]) =>
async (context: Context, next: Next): Promise<void> => {
const user = context.get("user") as SessionUser | undefined;
if (!user) throw AppError.unauthorized();
if (!slugs.includes(user.role_slug)) {
throw AppError.forbidden(`Action reservee au role : ${slugs.join(", ")}.`);
}
await next();
};
export const currentUser = (context: Context): SessionUser => {
const user = context.get("user") as SessionUser | undefined;
if (!user) throw AppError.unauthorized();
return user;
};
+137
View File
@@ -0,0 +1,137 @@
#!/usr/bin/env node
import { pathToFileURL } from "node:url";
import { resolve } from "node:path";
import { ConfigError, loadDbConfig } from "./config.js";
import { Db } from "./db.js";
import { AppError, toSafeError } from "./errors.js";
import { listMigrations, runMigrations } from "./migrate.js";
/**
* Point d'entree des migrations : `node dist/cli.js --dir <dossier>`.
*
* Le conteneur de migration n'a besoin d'aucun secret lisible a la main :
* les variables sont resolues par Docker depuis .env au lancement.
*
* Codes de sortie :
* 0 tout est applique, ou rien a faire
* 1 erreur (connexion, SQL, migration) OU derive detectee
* 2 configuration incomplete
*/
interface Options {
dir: string;
dryRun: boolean;
check: boolean;
help: boolean;
}
const USAGE = `Utilisation : cohaise-migrate --dir <dossier> [--dry-run] [--check]
--dir <dossier> Dossier contenant les fichiers NNN_nom.sql (obligatoire)
--dry-run Analyse sans ecrire en base
--check Echoue s'il reste une migration a appliquer
--help Cette aide`;
const parseArgs = (argv: string[]): Options => {
const options: Options = { dir: "", dryRun: false, check: false, help: false };
for (let index = 0; index < argv.length; index += 1) {
const arg = argv[index];
if (arg === undefined) continue;
if (arg === "--dry-run") options.dryRun = true;
else if (arg === "--check") options.check = true;
else if (arg === "--help" || arg === "-h") options.help = true;
else if (arg === "--dir") {
options.dir = argv[index + 1] ?? "";
index += 1;
} else if (arg.startsWith("--dir=")) {
options.dir = arg.slice("--dir=".length);
} else {
throw AppError.badRequest(`Argument inconnu : ${arg}`, { argument: arg });
}
}
return options;
};
const main = async (argv: string[]): Promise<number> => {
let options: Options;
try {
options = parseArgs(argv);
} catch (error) {
const safe = toSafeError(error);
console.error(` ${safe.message}\n\n${USAGE}`);
return 2;
}
if (options.help) {
console.log(USAGE);
return 0;
}
if (!options.dir) {
console.error(` --dir est obligatoire\n\n${USAGE}`);
return 2;
}
let config;
try {
config = loadDbConfig();
} catch (error) {
if (error instanceof ConfigError) {
console.error(` Configuration invalide :\n - ${error.issues.join("\n - ")}`);
return 2;
}
throw error;
}
const dir = resolve(options.dir);
const db = new Db(config);
try {
const migrations = await listMigrations(dir);
if (migrations.length === 0) {
console.log(` Aucune migration trouvee dans ${dir}`);
return 0;
}
const result = await runMigrations(db, dir, { dryRun: options.dryRun });
const prefix = options.dryRun ? "[dry-run] " : "";
console.log(
`${prefix}${migrations.length} migration(s) · ${result.applied.length} appliquee(s) · ` +
`${result.skipped.length} deja en place · ${result.drifted.length} derivee(s)`,
);
for (const version of result.applied) console.log(` + ${version}`);
for (const drift of result.drifted) {
console.error(` ! ${drift.version} modifiee depuis son execution (checksum attendu ${drift.recorded.slice(0, 12)}…, trouve ${drift.current.slice(0, 12)}…)`);
}
if (result.drifted.length > 0) return 1;
if (options.check && result.applied.length > 0) return 1;
return 0;
} catch (error) {
const safe = toSafeError(error);
console.error(` Echec : ${safe.code} — ${safe.message}`);
if (error instanceof AppError && error.status >= 500 && error.message.includes("migree")) {
console.error(" Appliquez d'abord les migrations : cohaise-migrate --dir <dossier>");
}
return 1;
} finally {
await db.close().catch(() => undefined);
}
};
const isDirectRun =
process.argv[1] !== undefined &&
import.meta.url === pathToFileURL(process.argv[1]).href;
if (isDirectRun) {
main(process.argv.slice(2)).then(
(code) => process.exit(code),
(error) => {
console.error(` Erreur inattendue : ${error instanceof Error ? error.message : String(error)}`);
process.exit(1);
},
);
}
export { main, parseArgs };
+95
View File
@@ -0,0 +1,95 @@
import { z } from "zod";
/**
* Configuration lue une seule fois au demarrage. L'objet est fige :
* si une variable manque ou est mal formee, le processus s'arrete avant
* d'ouvrir le moindre port, avec la liste exacte de ce qui pose probleme.
* Une API qui demarre puis echoue sur la premiere requete est un defaut de
* deploiement, pas un defaut d'ecriture de code.
*/
const bool = (fallback: boolean) =>
z
.string()
.optional()
.transform((value) => {
if (value === undefined || value === "") return fallback;
return !["0", "false", "no", "off"].includes(value.toLowerCase());
});
const port = (fallback: number) =>
z.coerce.number().int().min(1).max(65535).default(fallback);
const positiveInt = (fallback: number) =>
z.coerce.number().int().positive().default(fallback);
const schema = z.object({
NODE_ENV: z.enum(["development", "production", "test"]).default("development"),
LOG_LEVEL: z.enum(["silent", "error", "warn", "info", "debug"]).default("info"),
PORT: port(3000),
PUBLIC_ORIGIN: z.url().optional().transform((v) => v ?? null),
DB_HOST: z.string().min(1),
DB_PORT: port(3306),
DB_USER: z.string().min(1),
DB_PASSWORD: z.string().min(1),
DB_NAME: z.string().min(1),
DB_CONNECTION_LIMIT: positiveInt(8),
DB_CONNECT_TIMEOUT_MS: positiveInt(10_000),
MEDIA_DIR: z.string().min(1).default("/data/media/originals"),
VARIANT_DIR: z.string().min(1).default("/data/media/variants"),
SESSION_SECRET: z.string().min(32),
SESSION_TTL_HOURS: positiveInt(24 * 14),
TRUST_PROXY: bool(false),
CORS_ORIGIN: z.string().optional().transform((v) => v ?? null),
});
export type Config = Readonly<z.infer<typeof schema>>;
export class ConfigError extends Error {
readonly issues: string[];
constructor(issues: string[]) {
super(`Configuration invalide (${issues.length}) :\n - ${issues.join("\n - ")}`);
this.name = "ConfigError";
this.issues = issues;
}
}
export const loadConfig = (env: NodeJS.ProcessEnv = process.env): Config => {
const parsed = schema.safeParse(env);
if (!parsed.success) throw new ConfigError(issuesOf(parsed.error));
return Object.freeze(parsed.data);
};
/** Sous-ensemble DB, pour les outils qui n'ouvrent aucun port (migrations, CLI). */
const dbSchema = z.object({
NODE_ENV: z.enum(["development", "production", "test"]).default("development"),
LOG_LEVEL: z.enum(["silent", "error", "warn", "info", "debug"]).default("info"),
DB_HOST: z.string().min(1),
DB_PORT: port(3306),
DB_USER: z.string().min(1),
DB_PASSWORD: z.string().min(1),
DB_NAME: z.string().min(1),
DB_CONNECTION_LIMIT: positiveInt(8),
DB_CONNECT_TIMEOUT_MS: positiveInt(10_000),
});
export type DbConfig = Readonly<z.infer<typeof dbSchema>>;
export const loadDbConfig = (env: NodeJS.ProcessEnv = process.env): DbConfig => {
const parsed = dbSchema.safeParse(env);
if (!parsed.success) throw new ConfigError(issuesOf(parsed.error));
return Object.freeze(parsed.data);
};
const issuesOf = (error: z.ZodError): string[] =>
error.issues.map((issue) => {
const path = issue.path.join(".") || "(racine)";
const missing = issue.code === "invalid_type" && issue.input === undefined;
return missing ? `${path} : variable absente` : `${path} : ${issue.message}`;
});
+107
View File
@@ -0,0 +1,107 @@
import mysql, { type Pool, type PoolConnection, type ResultSetHeader, type RowDataPacket } from "mysql2/promise";
import type { DbConfig } from "./config.js";
export interface QueryError {
code: string;
errno: number;
sqlMessage?: string;
}
export class Db {
readonly pool: Pool;
constructor(config: DbConfig) {
this.pool = mysql.createPool({
host: config.DB_HOST,
port: config.DB_PORT,
user: config.DB_USER,
password: config.DB_PASSWORD,
database: config.DB_NAME,
waitForConnections: true,
connectionLimit: config.DB_CONNECTION_LIMIT,
connectTimeout: config.DB_CONNECT_TIMEOUT_MS,
timezone: "Z",
charset: "utf8mb4_unicode_ci",
decimalNumbers: true,
// Porte refermee sur les requetes empilees : sans cet option, une
// contamination d'une lecture echappait en INSERT ou en DROP. Les valeurs
// sont toujours transmises en parametres, jamais concatenees dans le SQL.
multipleStatements: false,
namedPlaceholders: false,
});
}
/** Lecture en protocole prepare : les valeurs sont binaires, jamais des chains de texte. */
async query<T = RowDataPacket>(sql: string, params: unknown[] = []): Promise<T[]> {
const [rows] = await this.pool.execute(sql, params as never);
return rows as T[];
}
/** Requete brute, sans parametres, reservee au DDL des migrations.
Certains etats DDL ne passent pas le protocole prepare de MariaDB. */
async raw(sql: string): Promise<void> {
await this.pool.query(sql);
}
async one<T = RowDataPacket>(sql: string, params: unknown[] = []): Promise<T | null> {
const rows = await this.query<RowDataPacket>(sql, params);
return (rows[0] as T | undefined) ?? null;
}
/** Le premier resultat, ou une erreur explicite plutot qu'un undefined silencieux. */
async required<T = RowDataPacket>(sql: string, params: unknown[] = []): Promise<T> {
const row = await this.one<T>(sql, params);
if (row === null) {
throw Object.assign(new Error("Ligne introuvable"), { status: 404, code: "NOT_FOUND" });
}
return row;
}
async exec(sql: string, params: unknown[] = []): Promise<ResultSetHeader> {
const [result] = await this.pool.execute(sql, params as never);
return result as ResultSetHeader;
}
async transaction<T>(fn: (connection: PoolConnection) => Promise<T>): Promise<T> {
const connection = await this.pool.getConnection();
try {
await connection.beginTransaction();
const result = await fn(connection);
await connection.commit();
return result;
} catch (error) {
await connection.rollback();
throw error;
} finally {
connection.release();
}
}
/** Forme courte des erreurs de contrainte, pour les repondre en 409 et non en 500. */
static classify(error: unknown): { status: number; message: string } {
const errno = (error as { errno?: number })?.errno;
const sqlMessage = (error as { sqlMessage?: string })?.sqlMessage ?? "";
switch (errno) {
case 1062:
return { status: 409, message: "Cette valeur existe deja." };
case 1451:
case 1452:
return { status: 409, message: "Operation impossible : des enregistrements en referent encore." };
case 1406:
return { status: 422, message: "Valeur trop longue pour la colonne." };
case 1146:
return { status: 503, message: "Table absente : la base n'est peut-etre pas migree." };
case 1045:
return { status: 503, message: "Acces refuse par la base de donnees." };
case 1040:
case 1203:
return { status: 503, message: "Trop de connexions a la base de donnees." };
default:
return errno === undefined ? { status: 500, message: "Erreur interne." } : { status: 500, message: sqlMessage || "Erreur de base de donnees." };
}
}
async close(): Promise<void> {
await this.pool.end();
}
}
+100
View File
@@ -0,0 +1,100 @@
/**
* Erreurs portees par un code HTTP. Une erreur qui n'en porte pas est
* consideree interne : on journalise le detail, on ne le rend jamais au
* client, parce que le message d'une exception ne doit pas decrire le schema.
*/
export class AppError extends Error {
readonly status: number;
readonly code: string;
readonly details?: Record<string, unknown>;
constructor(status: number, code: string, message: string, details?: Record<string, unknown>) {
super(message);
this.name = "AppError";
this.status = status;
this.code = code;
if (details !== undefined) this.details = details;
}
static badRequest(message: string, details?: Record<string, unknown>) {
return new AppError(400, "BAD_REQUEST", message, details);
}
static unauthorized(message = "Authentification requise.") {
return new AppError(401, "UNAUTHORIZED", message);
}
static forbidden(message = "Vous ne pouvez pas effectuer cette action.") {
return new AppError(403, "FORBIDDEN", message);
}
static notFound(message = "Ressource introuvable.") {
return new AppError(404, "NOT_FOUND", message);
}
static conflict(message: string) {
return new AppError(409, "CONFLICT", message);
}
static payloadTooLarge(message = "Fichier trop volumineux.") {
return new AppError(413, "PAYLOAD_TOO_LARGE", message);
}
static unprocessable(message: string, details?: Record<string, unknown>) {
return new AppError(422, "UNPROCESSABLE", message, details);
}
static tooManyRequests(message = "Trop de requetes. Reessayez plus tard.") {
return new AppError(429, "TOO_MANY_REQUESTS", message);
}
static serviceUnavailable(message = "Service momentanement indisponible.") {
return new AppError(503, "UNAVAILABLE", message);
}
}
export interface SafeError {
status: number;
code: string;
message: string;
details?: Record<string, unknown>;
}
export const toSafeError = (error: unknown): SafeError => {
if (error instanceof AppError) {
return error.details !== undefined
? { status: error.status, code: error.code, message: error.message, details: error.details }
: { status: error.status, code: error.code, message: error.message };
}
const status = (error as { status?: number })?.status;
const code = (error as { code?: string })?.code;
if (typeof status === "number" && status >= 400 && status < 500) {
return { status, code: code ?? "BAD_REQUEST", message: (error as Error).message };
}
// Une erreur MariaDB connue est un probleme d'exploitation, pas un crash.
const errno = (error as { errno?: number })?.errno;
if (errno !== undefined) {
const { status: dbStatus, message } = classifyDbError(errno);
return { status: dbStatus, code: errno === 1146 ? "NOT_MIGRATED" : "DATABASE", message };
}
return { status: 500, code: "INTERNAL", message: "Erreur interne." };
};
const classifyDbError = (errno: number): { status: number; message: string } => {
switch (errno) {
case 1062:
return { status: 409, message: "Cette valeur existe deja." };
case 1451:
case 1452:
return { status: 409, message: "Operation impossible : des enregistrements en referent encore." };
case 1406:
return { status: 422, message: "Valeur trop longue pour la colonne." };
case 1146:
return { status: 503, message: "Base non migree. Lancez les migrations avant de servir." };
case 1045:
return { status: 503, message: "Acces refuse par la base de donnees." };
case 1040:
case 1203:
return { status: 503, message: "Trop de connexions a la base de donnees." };
case 1053:
return { status: 503, message: "Base de donnees en cours d'initialisation." };
default:
return { status: 503, message: "Base de donnees indisponible." };
}
};
+154
View File
@@ -0,0 +1,154 @@
import { randomUUID } from "node:crypto";
import { Hono, type Context, type Next } from "hono";
import { cors } from "hono/cors";
import type { SessionUser } from "./auth.js";
import type { Config } from "./config.js";
import type { Db } from "./db.js";
import { AppError, toSafeError } from "./errors.js";
export interface Logger {
level: Config["LOG_LEVEL"];
info: (message: string, fields?: Record<string, unknown>) => void;
warn: (message: string, fields?: Record<string, unknown>) => void;
error: (message: string, fields?: Record<string, unknown>) => void;
debug: (message: string, fields?: Record<string, unknown>) => void;
}
const ORDER: Record<Config["LOG_LEVEL"], number> = {
silent: 0,
error: 1,
warn: 2,
info: 3,
debug: 4,
};
export const createLogger = (level: Config["LOG_LEVEL"], service: string): Logger => {
const emit = (name: keyof typeof ORDER, message: string, fields?: Record<string, unknown>) => {
if (ORDER[name] > ORDER[level]) return;
const line = JSON.stringify({
ts: new Date().toISOString(),
level: name,
service,
msg: message,
...fields,
});
if (name === "error") console.error(line);
else console.log(line);
};
return {
level,
info: (message, fields) => emit("info", message, fields),
warn: (message, fields) => emit("warn", message, fields),
error: (message, fields) => emit("error", message, fields),
debug: (message, fields) => emit("debug", message, fields),
};
};
/** Variables transportees par chaque requete : tracee d'identification. */
export interface AppEnv {
Variables: {
requestId: string;
/** Posee par attachUser quand le cookie de session est valide. */
user?: SessionUser;
token?: string;
};
}
/** Type public d'une application CoHaiSe, impose aux routes metier. */
export type App = Hono<AppEnv>;
/** Dependances remises aux routes metier au montage. */
export interface RouteDeps {
db: Db;
config: Config;
logger: Logger;
}
export interface AppOptions {
service: string;
config: Config;
db: Db;
logger: Logger;
/** Routes metier, montees sous /api/<service> dans le routing. */
routes: (app: App, deps: RouteDeps) => void;
/** Vrai quand l'API doit repondre a /healthz avec l'etat de la base. */
probeDb?: boolean;
}
export const createApp = ({ service, config, db, logger, routes, probeDb = true }: AppOptions): App => {
const app = new Hono<AppEnv>();
app.use("*", async (context: Context, next: Next) => {
const requestId = context.req.header("x-request-id") ?? randomUUID();
context.set("requestId", requestId);
context.res.headers.set("x-request-id", requestId);
context.res.headers.set("x-content-type-options", "nosniff");
context.res.headers.set("referrer-policy", "same-origin");
context.res.headers.set("x-frame-options", "DENY");
const started = performance.now();
await next();
const duration = Math.round(performance.now() - started);
if (context.req.method !== "OPTIONS") {
logger.debug("requete", {
requestId,
method: context.req.method,
path: new URL(context.req.url).pathname,
status: context.res.status,
durationMs: duration,
});
}
});
if (config.CORS_ORIGIN) {
app.use(
"*",
cors({
origin: config.CORS_ORIGIN.split(",").map((value) => value.trim()),
credentials: true,
maxAge: 600,
}),
);
}
app.get("/healthz", async (context) => {
if (!probeDb) return context.json({ status: "ok", service }, 200);
const started = performance.now();
try {
await db.query("SELECT 1");
return context.json(
{ status: "ok", service, db: "up", latencyMs: Math.round(performance.now() - started) },
200,
);
} catch (error) {
logger.error("sante base en echec", { error: String(error) });
return context.json({ status: "degraded", service, db: "down" }, 503);
}
});
routes(app, { db, config, logger });
app.notFound((context) =>
context.json({ error: { status: 404, code: "NOT_FOUND", message: "Route introuvable." } }, 404),
);
app.onError((error, context) => {
const safe = toSafeError(error);
const requestId = context.get("requestId");
if (safe.status >= 500) {
logger.error("erreur non geree", {
requestId,
code: safe.code,
message: error instanceof Error ? error.message : String(error),
stack: error instanceof Error ? error.stack : undefined,
});
} else {
logger.debug("refus", { requestId, code: safe.code, status: safe.status });
}
return context.json({ error: { ...safe, requestId } }, safe.status as 500);
});
return app;
};
export { AppError };
+47
View File
@@ -0,0 +1,47 @@
export {
loadConfig,
loadDbConfig,
ConfigError,
type Config,
type DbConfig,
} from "./config.js";
export { Db } from "./db.js";
export { AppError, toSafeError, type SafeError } from "./errors.js";
export {
createApp,
createLogger,
type App,
type AppEnv,
type AppOptions,
type Logger,
type RouteDeps,
} from "./http.js";
export {
attachUser,
clearSessionCookie,
createSession,
currentUser,
isHttpsRequest,
hashPassword,
requireAuth,
requireRole,
purgeExpiredSessions,
revokeSession,
SESSION_COOKIE,
setSessionCookie,
sha256,
verifyPassword,
type SessionUser,
} from "./auth.js";
export {
listMigrations,
runMigrations,
assertNoDrift,
type MigrationResult,
} from "./migrate.js";
export {
prepareService,
startService,
type Service,
type ServiceOptions,
} from "./service.js";
+144
View File
@@ -0,0 +1,144 @@
import { createHash } from "node:crypto";
import { readdir, readFile } from "node:fs/promises";
import path from "node:path";
import type { Db } from "./db.js";
/**
* Applique les fichiers NNN_nom.sql dans l'ordre lexical, et uniquement ceux
* qui ne sont pas encore marques comme appliques. Idempotent : un second appel
* ne reexecute rien.
*
* Limite connue et assumee : le DDL MariaDB n'est pas transactionnel. Un fichier
* echoue au milieu, le reste des statements n'est pas applique et le fichier
* n'est pas enregistre. Le repasser reprend depuis son debut. C'est pourquoi
* chaque migration part de la ou la precedente a fini, et pourquoi une migration
* en desordre doit etre reparue et pas seulement sauvegardee depuis sa moitie.
*/
export interface MigrationFile {
version: string;
file: string;
sql: string;
checksum: string;
}
export interface MigrationResult {
applied: string[];
skipped: string[];
/** Migrations deja appliquees dont le contenu du fichier a change depuis. */
drifted: { version: string; recorded: string; current: string }[];
}
// Les deux bases utilisent un prefixe a trois chiffres (000, 001, …) ;
// quatre est accepte pour ne pas interdire le passage a un dossier plus large.
const FILE_PATTERN = /^(\d{3,4}_[a-z0-9_]+)\.sql$/;
export const listMigrations = async (dir: string): Promise<MigrationFile[]> => {
const entries = await readdir(dir);
const files = entries.filter((entry) => FILE_PATTERN.test(entry)).sort();
return Promise.all(
files.map(async (file) => {
const sql = await readFile(path.join(dir, file), "utf8");
return {
version: FILE_PATTERN.exec(file)?.[1] ?? file,
file,
sql,
checksum: createHash("sha256").update(sql).digest("hex"),
};
}),
);
};
const ensureLedger = async (db: Db): Promise<void> => {
await db.raw(`
CREATE TABLE IF NOT EXISTS schema_migrations (
version VARCHAR(64) NOT NULL,
applied_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (version)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
`);
// Creer la colonne ici plutot que dans une migration : ajouter une ligne a un
// registre qui enregistre lui-meme les lignes ajoutees boucle sur lui-meme.
await db.raw(
"ALTER TABLE schema_migrations ADD COLUMN IF NOT EXISTS checksum CHAR(64) NULL AFTER applied_at",
);
};
export const runMigrations = async (
db: Db,
dir: string,
options: { dryRun?: boolean } = {},
): Promise<MigrationResult> => {
const files = await listMigrations(dir);
await ensureLedger(db);
const applied = new Map<string, { checksum: string | null }>();
const rows = await db.query<{ version: string; checksum: string | null }>(
"SELECT version, checksum FROM schema_migrations",
);
for (const row of rows) applied.set(row.version, { checksum: row.checksum });
const result: MigrationResult = { applied: [], skipped: [], drifted: [] };
for (const migration of files) {
const record = applied.get(migration.version);
if (record) {
result.skipped.push(migration.version);
if (record.checksum && record.checksum !== migration.checksum) {
result.drifted.push({
version: migration.version,
recorded: record.checksum,
current: migration.checksum,
});
}
continue;
}
if (options.dryRun) {
result.applied.push(migration.version);
continue;
}
// Un statement par un statement : un filet de faille reste visible et le
// point d'arret reste reproductible plutot qu'un bloc de 400 lignes perdu.
//
// Les lignes de commentaire sont retirees, pas le statement entier : un
// en-tete de fichier ou une legende au-dessus d'un INSERT ne doit pas
// faire sauter la requete, et encore moins la faire sauter en silence
// pendant que la version est enregistree comme appliquee.
const statements = migration.sql
.split(/;\s*(?:\r?\n|$)/)
.map((statement) =>
statement
.split(/\r?\n/)
.filter((line) => !line.trim().startsWith("--"))
.join("\n")
.trim(),
)
.filter((statement) => statement.length > 0);
for (const statement of statements) await db.raw(statement);
await db.exec("INSERT INTO schema_migrations (version, checksum) VALUES (?, ?)", [
migration.version,
migration.checksum,
]);
result.applied.push(migration.version);
}
return result;
};
export const assertNoDrift = (result: MigrationResult): void => {
if (result.drifted.length === 0) return;
const lines = result.drifted.map(
(d) => ` ${d.version} : appliquee ${d.recorded.slice(0, 12)}, fichier ${d.current.slice(0, 12)}`,
);
throw new Error(
`Migrations deja appliquees modifiees depuis leur execution (${result.drifted.length}) :\n` +
`${lines.join("\n")}\n` +
"Une migration appliquee ne se modifie pas : creez un nouveau fichier.",
);
};
+135
View File
@@ -0,0 +1,135 @@
import { createServer, type Server } from "node:http";
import { type AddressInfo } from "node:net";
import { getRequestListener } from "@hono/node-server";
import { ConfigError, loadConfig, type Config } from "./config.js";
import { AppError } from "./errors.js";
import { Db } from "./db.js";
import {
createLogger,
createApp,
type App,
type AppOptions,
type Logger,
type RouteDeps,
} from "./http.js";
import { assertNoDrift, runMigrations } from "./migrate.js";
export interface ServiceOptions {
service: string;
/** Dossier contenant les fichiers NNN_nom.sql de cette application. */
migrationsDir?: string;
routes: (app: App, deps: RouteDeps) => void;
probeDb?: boolean;
}
export interface Service {
config: Config;
db: Db;
logger: Logger;
app: App;
}
const fail = (error: unknown): never => {
if (error instanceof ConfigError) {
console.error(`\n [${new Date().toISOString()}] Demarrage refuse\n`);
console.error(error.message);
console.error(
"\n Verifiez .env (ou les variables du conteneur). .env.example recense l'ensemble du format attendu.\n",
);
} else {
console.error(
`\n [${new Date().toISOString()}] Demarrage refuse : ${
error instanceof Error ? error.message : String(error)
}\n`,
);
if (error instanceof Error && error.stack) console.error(error.stack);
}
process.exit(1);
};
/**
* Prepare le service sans lancer d'ecoute. Utile pour la CLI de migration et
* pour les tests, qui n'ont pas besoin d'un port.
*/
export const prepareService = async (options: ServiceOptions): Promise<Service> => {
const config = loadConfig();
const logger = createLogger(config.LOG_LEVEL, options.service);
const db = new Db(config);
if (options.migrationsDir) {
const result = await runMigrations(db, options.migrationsDir);
assertNoDrift(result);
if (result.applied.length > 0) {
logger.info("migrations appliquees", { versions: result.applied });
}
if (result.drifted.length > 0) {
logger.warn("migrations modifiees depuis leur execution", {
versions: result.drifted.map((d) => d.version),
});
}
}
const app = createApp({
service: options.service,
config,
db,
logger,
routes: options.routes,
probeDb: options.probeDb ?? true,
});
return { config, db, logger, app };
};
/** Demarre, ecoute, et s'arrete proprement. */
export const startService = async (options: ServiceOptions): Promise<Server> => {
let prepared: Service;
try {
prepared = await prepareService(options);
} catch (error) {
return fail(error);
}
const { config, db, logger, app } = prepared;
const server: Server = createServer(getRequestListener(app.fetch));
server.keepAliveTimeout = 65_000;
server.headersTimeout = 70_000;
const shutdown = async (signal: string) => {
logger.info("arret demande", { signal });
// Le SIGTERM de docker stop a un delai limite : fermer d'abord l'ecoute
// evite de nouvelles requetes, puis attendre les requetes en cours.
server.close(async () => {
await db.close().catch((error: unknown) => logger.error("fermeture base", { error: String(error) }));
logger.info("arret termine");
process.exit(0);
});
setTimeout(() => {
logger.warn("arret force apres delai");
process.exit(1);
}, 10_000).unref();
};
process.on("SIGTERM", () => void shutdown("SIGTERM"));
process.on("SIGINT", () => void shutdown("SIGINT"));
process.on("unhandledRejection", (reason) => {
logger.error("rejet de promesse non gere", { reason: String(reason) });
});
await new Promise<void>((resolve) => {
server.listen(config.PORT, "0.0.0.0", () => resolve());
});
const address = server.address() as AddressInfo;
logger.info("api prete", {
port: address.port,
env: config.NODE_ENV,
db: `${config.DB_HOST}:${config.DB_PORT}/${config.DB_NAME}`,
});
return server;
};
export { AppError, ConfigError, Db, createApp, createLogger, loadConfig, runMigrations };
export type { AppOptions, Config, Logger, RouteDeps };
+17
View File
@@ -0,0 +1,17 @@
{
"$schema": "https://json.schemastore.org/tsconfig",
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"module": "NodeNext",
"moduleResolution": "NodeNext",
"lib": ["ES2023"],
"types": ["node"],
"rootDir": "src",
"outDir": "dist",
"composite": true,
"declaration": true,
"declarationMap": true,
"sourceMap": true
},
"include": ["src/**/*.ts"]
}