raiton 6.5.0-beta.13 → 6.6.0-beta.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/build/bin/index.mjs +1278 -1222
  3. package/docs/contributors/framework/plugins/csrf.md +277 -0
  4. package/docs/contributors/framework/plugins/security.md +40 -6
  5. package/docs/user-guide/README.md +7 -4
  6. package/docs/user-guide/best-practices.md +1 -0
  7. package/docs/user-guide/csrf.md +557 -0
  8. package/docs/user-guide/decorators/README.md +2 -0
  9. package/docs/user-guide/decorators/health-check.md +125 -0
  10. package/docs/user-guide/health-check.md +117 -0
  11. package/docs/user-guide/security.md +8 -2
  12. package/package.json +1 -1
  13. package/source/core/application.ts +1 -1
  14. package/source/core/controller/builder.ts +23 -0
  15. package/source/core/thread.ts +5 -1
  16. package/source/framework/artifacts.ts +3 -0
  17. package/source/framework/constants/decorators.constant.ts +2 -0
  18. package/source/framework/decorators/csrf-guard.decorator.ts +60 -0
  19. package/source/framework/decorators/csrf-token.decorator.ts +20 -0
  20. package/source/framework/decorators/health-check.decorator.ts +50 -0
  21. package/source/framework/decorators/index.ts +3 -0
  22. package/source/framework/enums/csrf.enum.ts +4 -0
  23. package/source/framework/enums/index.ts +2 -1
  24. package/source/framework/health-check.ts +137 -0
  25. package/source/framework/index.ts +1 -0
  26. package/source/framework/plugins/security/csrf.ts +145 -0
  27. package/source/framework/plugins/security/index.ts +2 -0
  28. package/source/framework/utilities/artifact.util.ts +4 -0
  29. package/source/framework/utilities/csrf.util.ts +162 -0
  30. package/source/framework/utilities/index.ts +2 -1
  31. package/source/types/application.ts +1 -1
  32. package/source/types/csrf.ts +38 -0
  33. package/source/types/index.ts +2 -1
  34. package/source/types/runtime.ts +1 -1
  35. /package/source/framework/utilities/{https.ts → https.util.ts} +0 -0
  36. /package/source/framework/utilities/{url.ts → url.util.ts} +0 -0
@@ -0,0 +1,277 @@
1
+ # Plugin CSRF
2
+
3
+ **Fichiers :**
4
+ - `source/framework/plugins/security/csrf.ts` — Plugin middleware principal
5
+ - `source/framework/utilities/csrf.util.ts` — Utilitaire de génération/validation
6
+ - `source/framework/decorators/csrf-guard.decorator.ts` — Decorator route-level
7
+ - `source/framework/decorators/csrf-token.decorator.ts` — Decorator injection token
8
+ - `source/types/csrf.ts` — Types et interfaces
9
+
10
+ **Import :** `import { Security, CsrfGuard, CsrfToken } from "raiton/framework"`
11
+
12
+ > **Navigation :** [← security.md](security.md) | [↑ plugins/](README.md)
13
+
14
+ Le plugin CSRF implémente une protection complète contre les attaques Cross-Site Request Forgery avec deux modes opérationnels et une détection automatique du type de client.
15
+
16
+ ## Architecture
17
+
18
+ ```
19
+ source/framework/plugins/security/csrf.ts
20
+ │
21
+ ├── double-submit mode
22
+ │ └── CsrfUtil.generateDoubleSubmitToken(secret)
23
+ │ └── CsrfUtil.validateDoubleSubmitToken(secret, token, ttl)
24
+ │
25
+ ├── synchronizer mode
26
+ │ └── CsrfUtil.createTokenStore(ttl)
27
+ │ ├── .create() → string
28
+ │ ├── .validate(token) → boolean
29
+ │ ├── .revoke(token) → boolean
30
+ │ └── .destroy() → void
31
+ │
32
+ └── client detection
33
+ └── CsrfUtil.isBrowserClient(headers, config)
34
+ ```
35
+
36
+ ## Types
37
+
38
+ ```typescript
39
+ // source/framework/enums/csrf.enum.ts
40
+
41
+ export enum CSRFModeEnum {
42
+ DOUBLE_SUBMIT = 'double-submit',
43
+ SYNCHRONIZER = 'synchronizer',
44
+ }
45
+ ```
46
+
47
+ ```typescript
48
+ // source/types/csrf.ts
49
+
50
+ interface CsrfOptions {
51
+ mode?: CSRFModeEnum
52
+ secret?: string
53
+ cookieName?: string
54
+ headerName?: string
55
+ ttl?: number
56
+ methods?: string[]
57
+ skipPaths?: string[]
58
+ clientDetection?: CsrfClientDetectionConfig
59
+ cookieOptions?: CsrfCookieOptions
60
+ }
61
+
62
+ interface CsrfClientDetectionConfig {
63
+ headerName?: string // Défaut: 'X-Client-Type'
64
+ skipClients?: string[] // Défaut: ['mobile', 'desktop']
65
+ }
66
+
67
+ interface CsrfCookieOptions {
68
+ httpOnly?: boolean
69
+ secure?: boolean
70
+ sameSite?: 'strict' | 'lax' | 'none'
71
+ path?: string
72
+ domain?: string
73
+ maxAge?: number
74
+ }
75
+
76
+ interface CsrfGuardOptions {
77
+ mode?: CSRFModeEnum
78
+ methods?: string[]
79
+ skipPaths?: string[]
80
+ }
81
+ ```
82
+
83
+ ## Utilitaire CSRF
84
+
85
+ ### `CsrfUtil.generateDoubleSubmitToken(secret)`
86
+
87
+ Génère un token HMAC-SHA256 signé.
88
+
89
+ ```
90
+ Format: timestamp.nonce.signature
91
+ Exemple: m1a2b3.c4d5e6f7g8h9i0j1k2l3m4n5o6p7q8r9s0t1u2v3w4.a1b2c3d4...
92
+ ```
93
+
94
+ - `timestamp` : Base36 du timestamp actuel
95
+ - `nonce` : 16 bytes aléatoires en hex (32 caractères)
96
+ - `signature` : HMAC-SHA256 du payload avec le secret
97
+
98
+ ### `CsrfUtil.validateDoubleSubmitToken(secret, token, maxAge?)`
99
+
100
+ Valide un token double-submit :
101
+ 1. Vérifie le format (3 parties séparées par `.`)
102
+ 2. Recalcule la signature HMAC
103
+ 3. Compare avec `timingSafeEqual` (résistant au timing attack)
104
+ 4. Vérifie l'âge si `maxAge` est défini
105
+
106
+ ### `CsrfUtil.createTokenStore(ttl)`
107
+
108
+ Crée un store en mémoire pour le mode synchronizer :
109
+ - `create()` : Génère un token aléatoire et le stocke
110
+ - `validate(token)` : Vérifie l'existence et la validité
111
+ - `revoke(token)` : Supprime un token
112
+ - Nettoyage automatique des tokens expirés (interval)
113
+
114
+ ### `CsrfUtil.isBrowserClient(headers, config?)`
115
+
116
+ Détermine si la requête vient d'un navigateur :
117
+ - Si header `X-Client-Type` est dans `skipClients` → `false`
118
+ - Si header `Authorization` présent ET pas de cookie CSRF → `false`
119
+ - Sinon → `true`
120
+
121
+ ### `CsrfUtil.serializeCookie(name, value, options?)`
122
+
123
+ Sérialise un cookie avec les attributs de sécurité.
124
+
125
+ ### `CsrfUtil.extractCookieValue(cookieHeader, name)`
126
+
127
+ Extrait la valeur d'un cookie spécifique depuis l'en-tête `Cookie`.
128
+ - Retourne `undefined` si le cookie n'est pas trouvé
129
+ - Partagé entre le plugin et le decorator `@CsrfGuard`
130
+
131
+ ### `CsrfUtil.timingSafeEqual(a, b)`
132
+
133
+ Compare deux chaînes de manière résistante aux attaques par timing.
134
+ - Utilise `crypto.timingSafeEqual` de Node.js
135
+ - Retourne `false` immédiatement si les longueurs diffèrent
136
+ - Partagé entre le plugin et le decorator `@CsrfGuard`
137
+
138
+ ## Plugin Middleware
139
+
140
+ ### Pipeline d'exécution
141
+
142
+ ```
143
+ 1. Request entrante
144
+ │
145
+ ├── GET/HEAD/OPTIONS
146
+ │ └── Générer token → Set-Cookie → next()
147
+ │
148
+ ├── Méthode non protégée (GET par défaut)
149
+ │ └── next()
150
+ │
151
+ ├── Skip path (ex: /health)
152
+ │ └── next()
153
+ │
154
+ ├── Client non-navigateur (mobile/desktop)
155
+ │ └── next()
156
+ │
157
+ └── Méthode protégée (POST/PUT/PATCH/DELETE)
158
+ │
159
+ ├── Cookie présent + Header présent
160
+ │ ├── Token valide → next()
161
+ │ └── Token invalide → 403 Forbidden
162
+ │
163
+ └── Cookie OU Header manquant
164
+ └── 403 Forbidden (CSRF token missing)
165
+ ```
166
+
167
+ ### Hooks
168
+
169
+ Le plugin enregistre un hook `onResponse` qui ajoute le token CSRF dans un cookie `Set-Cookie` pour les requêtes state-changing.
170
+
171
+ ### Stockage du token
172
+
173
+ Le token est disponible dans `context.state.csrfToken` après le middleware CSRF.
174
+
175
+ ## Decorators
176
+
177
+ ### `@CsrfGuard(options?)`
178
+
179
+ Decorator qui wrappe le middleware CSRF comme middleware de contrôleur.
180
+
181
+ **Fichier :** `source/framework/decorators/csrf-guard.decorator.ts`
182
+
183
+ ```typescript
184
+ // Utilisation basique
185
+ @CsrfGuard()
186
+ @Controllable('/api/users')
187
+ export class UserController { ... }
188
+
189
+ // Avec options
190
+ @CsrfGuard({
191
+ methods: ['POST', 'DELETE'],
192
+ skipPaths: ['/api/public'],
193
+ })
194
+ ```
195
+
196
+ ### `@CsrfToken()`
197
+
198
+ Decorator qui ajoute un middleware pour injecter le token CSRF dans le header de réponse.
199
+
200
+ **Fichier :** `source/framework/decorators/csrf-token.decorator.ts`
201
+
202
+ ```typescript
203
+ @CsrfToken()
204
+ @Get('/csrf-token')
205
+ getCsrfToken() {
206
+ return { message: 'Token injected via header X-CSRF-Token' }
207
+ }
208
+ ```
209
+
210
+ ## Intégration avec le système de plugins
211
+
212
+ Le plugin suit le pattern `definePlugin` de Raiton :
213
+
214
+ ```typescript
215
+ // source/framework/plugins/security/csrf.ts
216
+ export const secureCsrf = (opts: CsrfOptions = {}) => {
217
+ return definePlugin((scope) => {
218
+ // 1. Initialiser le store (synchronizer mode)
219
+ // 2. Enregistrer le hook onResponse
220
+ // 3. Enregistrer le middleware CSRF
221
+ }, 'csrf')
222
+ }
223
+ ```
224
+
225
+ ## Intégration avec Security
226
+
227
+ ```typescript
228
+ // source/framework/plugins/security/index.ts
229
+ export class Security {
230
+ // ...
231
+ static csrf = secureCsrf
232
+ }
233
+ ```
234
+
235
+ ## Dépendances
236
+
237
+ | Module | Utilisation |
238
+ |--------|------------|
239
+ | `node:crypto` | HMAC-SHA256, randomBytes, timingSafeEqual |
240
+ | `definePlugin` | Création du plugin |
241
+ | `RaitonResponses` | Formatage des réponses d'erreur |
242
+ | `HttpStatus` | Codes de statut HTTP |
243
+
244
+ ## Ordre d'enregistrement recommandé
245
+
246
+ ```
247
+ 1. Security.cors → CORS preflight
248
+ 2. Security.methodGuard → Méthodes autorisées
249
+ 3. Security.csrf → Protection CSRF (NOVEAU)
250
+ 4. Security.bodyLimit → Taille max
251
+ 5. Security.rateLimit → Rate limiting
252
+ 6. Security.headers → En-têtes de sécurité (automatique)
253
+ 7. bodyParserPlugin → Parsing body (automatique)
254
+ 8. Middleware personnalisés
255
+ ```
256
+
257
+ ## Notes d'implémentation
258
+
259
+ ### Timing-safe comparison
260
+
261
+ La comparaison des tokens utilise `crypto.timingSafeEqual` pour éviter les attaques par timing. Si les tokens ont des longueurs différentes, la comparaison retourne `false` immédiatement.
262
+
263
+ ### Nettoyage automatique (synchronizer mode)
264
+
265
+ Le `TokenStore` utilise un `setInterval` pour nettoyer les tokens expirés. L'interval est configuré avec `unref()` pour ne pas empêcher la fermeture du processus.
266
+
267
+ ### Cookie HttpOnly=false
268
+
269
+ Le cookie CSRF doit être lisible par le JavaScript côté client pour pouvoir être inclus dans le header `X-CSRF-Token`. C'est pourquoi `httpOnly` est `false` par défaut.
270
+
271
+ ### Secret auto-généré
272
+
273
+ Si aucun secret n'est fourni, un secret aléatoire de 32 bytes est généré. Ceci est déconseillé en production car le secret change à chaque redémarrage, invalidant tous les tokens existants.
274
+
275
+ ---
276
+
277
+ [← security.md](security.md) | [↑ plugins/](README.md)
@@ -5,12 +5,13 @@
5
5
 
6
6
  > **Navigation :** [← openapi.md](openapi.md) | [↑ plugins/](README.md)
7
7
 
8
- La classe `Security` regroupe 5 middlewares de sécurité.
8
+ La classe `Security` regroupe 6 middlewares de sécurité.
9
9
 
10
10
  ```typescript
11
11
  class Security {
12
12
  static headers // secureHeaders (activé automatiquement)
13
13
  static cors // secureCors(options?)
14
+ static csrf // secureCsrf(options?) — [Documentation CSRF](csrf.md)
14
15
  static rateLimit // secureRateLimit(options?)
15
16
  static bodyLimit // secureBodyLimit(options?)
16
17
  static methodGuard // secureMethodGuard(options?)
@@ -83,6 +84,33 @@ Access-Control-Allow-Methods: GET, POST, PUT, DELETE, PATCH
83
84
  Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With
84
85
  ```
85
86
 
87
+ ## `Security.csrf(options?)`
88
+
89
+ Middleware de protection CSRF. Supporte deux modes : `double-submit` (stateless) et `synchronizer` (stateful).
90
+
91
+ ```typescript
92
+ app.use(Security.csrf({
93
+ mode: CSRFModeEnum.DOUBLE_SUBMIT, // CSRFModeEnum.DOUBLE_SUBMIT | CSRFModeEnum.SYNCHRONIZER
94
+ secret: process.env.CSRF_SECRET, // Secret HMAC (min 32 chars)
95
+ cookieName: '_csrf', // Nom du cookie
96
+ headerName: 'X-CSRF-Token', // Nom du header
97
+ ttl: 3600_000, // TTL en ms (défaut: 1h)
98
+ methods: ['POST', 'PUT', 'PATCH', 'DELETE'],
99
+ skipPaths: ['/health'],
100
+ clientDetection: {
101
+ headerName: 'X-Client-Type',
102
+ skipClients: ['mobile', 'desktop'],
103
+ },
104
+ }))
105
+ ```
106
+
107
+ **Fichiers associés :**
108
+ - `source/framework/plugins/security/csrf.ts` — Plugin principal
109
+ - `source/framework/utilities/csrf.util.ts` — Utilitaire tokens
110
+ - `source/framework/decorators/csrf-guard.decorator.ts` — Decorator `@CsrfGuard`
111
+ - `source/framework/decorators/csrf-token.decorator.ts` — Decorator `@CsrfToken`
112
+ - [Documentation CSRF complète](csrf.md)
113
+
86
114
  ## `Security.bodyLimit(options?)`
87
115
 
88
116
  Limite la taille du corps des requêtes.
@@ -132,6 +160,11 @@ app
132
160
  origin: "https://frontend.example.com",
133
161
  credentials: true,
134
162
  }))
163
+ .use(Security.csrf({
164
+ mode: CSRFModeEnum.DOUBLE_SUBMIT,
165
+ secret: process.env.CSRF_SECRET,
166
+ cookieOptions: { secure: true, sameSite: 'strict' }
167
+ }))
135
168
  .use(Security.bodyLimit({ maxSize: "5MB" }))
136
169
  .use(Security.rateLimit({
137
170
  windowMs: 60_000,
@@ -147,11 +180,12 @@ app
147
180
  ```
148
181
  1. Security.cors → CORS preflight
149
182
  2. Security.methodGuard → Méthodes autorisées
150
- 3. Security.bodyLimit → Taille max
151
- 4. Security.rateLimit → Rate limiting
152
- 5. Security.headers → En-têtes de sécurité (automatique)
153
- 6. bodyParserPlugin → Parsing body (automatique)
154
- 7. Middleware personnalisés
183
+ 3. Security.csrf → Protection CSRF
184
+ 4. Security.bodyLimit → Taille max
185
+ 5. Security.rateLimit → Rate limiting
186
+ 6. Security.headers → En-têtes de sécurité (automatique)
187
+ 7. bodyParserPlugin → Parsing body (automatique)
188
+ 8. Middleware personnalisés
155
189
  ```
156
190
 
157
191
  ---
@@ -19,6 +19,7 @@ Ce dossier décrit comment utiliser Raiton pour créer un serveur d'API.
19
19
  | [responses.md](responses.md) | Structurer les réponses et les erreurs |
20
20
  | [body-parser.md](body-parser.md) | Lire JSON, formulaires et fichiers |
21
21
  | [security.md](security.md) | Sécurité HTTP, CORS, rate-limit, body-limit |
22
+ | [health-check.md](health-check.md) | Endpoint de contrôle et vérifications de santé |
22
23
  | [https.md](https.md) | HTTPS, certificats et environnements |
23
24
  | [openapi/README.md](openapi/README.md) | Générer et documenter l'API |
24
25
  | [sockets.md](sockets.md) | Déclarer et gérer les sockets |
@@ -48,10 +49,11 @@ Ce dossier décrit comment utiliser Raiton pour créer un serveur d'API.
48
49
  15. lire [openapi/README.md](openapi/README.md)
49
50
  16. lire [sockets.md](sockets.md)
50
51
  17. lire [mcp.md](mcp.md)
51
- 18. lire [types.md](types.md)
52
- 19. lire [tutorial.md](tutorial.md)
53
- 20. lire [plugins.md](plugins.md)
54
- 21. lire [cli.md](cli.md)
52
+ 18. lire [health-check.md](health-check.md)
53
+ 19. lire [types.md](types.md)
54
+ 20. lire [tutorial.md](tutorial.md)
55
+ 21. lire [plugins.md](plugins.md)
56
+ 22. lire [cli.md](cli.md)
55
57
 
56
58
  ## Ce que couvre ce guide
57
59
 
@@ -62,6 +64,7 @@ Ce dossier décrit comment utiliser Raiton pour créer un serveur d'API.
62
64
  - l'injection de services
63
65
  - les plugins de sécurité et de documentation
64
66
  - le protocole HTTPS et la gestion des certificats
67
+ - les endpoints et vérifications de santé (health-check)
65
68
  - le cycle local `dev` / `build` / `start`
66
69
 
67
70
  > **Navigation :** [← docs/](../README.md) | [← contributeurs](../contributors/README.md)
@@ -12,6 +12,7 @@ Dans un projet Raiton, gardez ces règles simples :
12
12
  - activez les plugins de sécurité dès que l’API est exposée publiquement
13
13
  - centralisez les conventions par domaine
14
14
  - utilisez une structure modulaire quand plusieurs fonctionnalités métier cohabitent
15
+ - importez les interfaces et types avec `import type` (ou `import {type X}` en inline pour un mélange) quand ils ne servent qu’à la compilation : avec Bun et `emitDecoratorMetadata`, un import de valeur d’un symbole type-only lève `SyntaxError: Export named '…' not found` au démarrage — laissez les entités/classes runtime en import de valeur
15
16
 
16
17
  ## Exemple de découpage
17
18