raiton 6.5.0-beta.13 → 6.7.0-beta.15

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 (166) hide show
  1. package/CHANGELOG.md +31 -0
  2. package/README.md +16 -9
  3. package/build/bin/index.mjs +10288 -6059
  4. package/deno.json +4 -1
  5. package/docs/contributors/framework/README.md +2 -0
  6. package/docs/contributors/framework/cache/README.md +55 -0
  7. package/docs/contributors/framework/cache/cache.md +86 -0
  8. package/docs/contributors/framework/cache/etag.md +82 -0
  9. package/docs/contributors/framework/decorators/README.md +1 -0
  10. package/docs/contributors/framework/plugins/csrf.md +277 -0
  11. package/docs/contributors/framework/plugins/security.md +40 -6
  12. package/docs/contributors/framework/runtime.md +13 -3
  13. package/docs/user-guide/README.md +8 -4
  14. package/docs/user-guide/best-practices.md +1 -0
  15. package/docs/user-guide/cache.md +79 -0
  16. package/docs/user-guide/cli.md +35 -3
  17. package/docs/user-guide/csrf.md +557 -0
  18. package/docs/user-guide/decorators/README.md +3 -0
  19. package/docs/user-guide/decorators/cache.md +79 -0
  20. package/docs/user-guide/decorators/health-check.md +125 -0
  21. package/docs/user-guide/health-check.md +117 -0
  22. package/docs/user-guide/runtime.md +2 -1
  23. package/docs/user-guide/security.md +8 -2
  24. package/package.json +8 -3
  25. package/source/bin/bootstrapper.ts +4 -4
  26. package/source/bin/cli-tools.ts +27 -3
  27. package/source/bin/cli.ts +2 -2
  28. package/source/bin/commands.registry.ts +17 -0
  29. package/source/bin/constants.ts +1 -0
  30. package/source/bin/index.ts +2 -2
  31. package/source/commands/artifact.command.ts +2 -2
  32. package/source/commands/build.command.ts +2 -2
  33. package/source/commands/develop.command.ts +4 -5
  34. package/source/commands/grafts.command.ts +1 -1
  35. package/source/commands/start.command.ts +2 -2
  36. package/source/core/application.ts +10 -10
  37. package/source/core/artifacts/artifact.ts +1 -1
  38. package/source/core/artifacts/index.ts +1 -1
  39. package/source/core/builder.ts +69 -15
  40. package/source/core/bytes.util.ts +1 -1
  41. package/source/core/commands.ts +24 -14
  42. package/source/core/config/config.ts +2 -2
  43. package/source/core/config/define.ts +2 -2
  44. package/source/core/config/index.ts +2 -2
  45. package/source/core/context.ts +1 -1
  46. package/source/core/controller/builder.ts +31 -8
  47. package/source/core/controller/compiler.ts +6 -6
  48. package/source/core/controller/index.ts +4 -4
  49. package/source/core/controller/metadata.ts +2 -2
  50. package/source/core/controller/tracker.ts +1 -1
  51. package/source/core/directories.ts +3 -2
  52. package/source/core/guards.ts +1 -1
  53. package/source/core/helpers/index.ts +1 -1
  54. package/source/core/hooks.ts +1 -1
  55. package/source/core/index.ts +16 -16
  56. package/source/core/injection/index.ts +1 -1
  57. package/source/core/injection/injection.ts +3 -3
  58. package/source/core/mcp/builder.ts +8 -8
  59. package/source/core/mcp/index.ts +3 -3
  60. package/source/core/mcp/metadata.ts +2 -2
  61. package/source/core/mcp/tracker.ts +1 -1
  62. package/source/core/middleware/compose.ts +2 -2
  63. package/source/core/middleware/index.ts +2 -2
  64. package/source/core/middleware/pipeline.ts +2 -2
  65. package/source/core/plugins/index.ts +2 -2
  66. package/source/core/plugins/plugin.ts +1 -1
  67. package/source/core/plugins/scope.ts +4 -4
  68. package/source/core/raiton.ts +1 -1
  69. package/source/core/router/handler.ts +30 -6
  70. package/source/core/router/handler.utils.ts +3 -3
  71. package/source/core/router/index.ts +4 -4
  72. package/source/core/router/matcher.ts +1 -1
  73. package/source/core/router/route.ts +1 -1
  74. package/source/core/router/router.ts +4 -4
  75. package/source/core/server.ts +1 -1
  76. package/source/core/socket/builder.ts +2 -2
  77. package/source/core/socket/index.ts +2 -2
  78. package/source/core/socket/metadata.ts +2 -2
  79. package/source/core/thread.ts +53 -20
  80. package/source/framework/artifacts.ts +8 -5
  81. package/source/framework/cache/cache.decorator.ts +35 -0
  82. package/source/framework/cache/cache.ts +197 -0
  83. package/source/framework/cache/etag.ts +174 -0
  84. package/source/framework/cache/index.ts +4 -0
  85. package/source/framework/cache/types.ts +111 -0
  86. package/source/framework/constants/decorators.constant.ts +4 -0
  87. package/source/framework/constants/index.ts +2 -2
  88. package/source/framework/decorators/access-guard.decorator.ts +2 -2
  89. package/source/framework/decorators/api-response.decorator.ts +1 -1
  90. package/source/framework/decorators/api.decorator.ts +1 -1
  91. package/source/framework/decorators/controllable.decorator.ts +3 -3
  92. package/source/framework/decorators/csrf-guard.decorator.ts +60 -0
  93. package/source/framework/decorators/csrf-token.decorator.ts +20 -0
  94. package/source/framework/decorators/guard.decorator.ts +4 -4
  95. package/source/framework/decorators/health-check.decorator.ts +50 -0
  96. package/source/framework/decorators/index.ts +14 -11
  97. package/source/framework/decorators/injection.decorator.ts +3 -3
  98. package/source/framework/decorators/mcp.decorator.ts +4 -4
  99. package/source/framework/decorators/middleware.decorator.ts +2 -2
  100. package/source/framework/decorators/parametrable.decorator.ts +2 -2
  101. package/source/framework/decorators/routable.decorator.ts +3 -3
  102. package/source/framework/decorators/route-interaction.decorator.ts +4 -4
  103. package/source/framework/decorators/socket.decorator.ts +3 -3
  104. package/source/framework/encryption.ts +2 -2
  105. package/source/framework/enums/csrf.enum.ts +4 -0
  106. package/source/framework/enums/index.ts +8 -7
  107. package/source/framework/enums/runtime.enum.ts +1 -2
  108. package/source/framework/env.ts +2 -2
  109. package/source/framework/exceptions/http-exception.ts +3 -3
  110. package/source/framework/exceptions/index.ts +2 -2
  111. package/source/framework/health-check.ts +137 -0
  112. package/source/framework/index.ts +18 -16
  113. package/source/framework/mcp/handler.ts +3 -3
  114. package/source/framework/mcp/index.ts +3 -3
  115. package/source/framework/mcp/protocol.ts +1 -1
  116. package/source/framework/mcp/streamable-http.ts +3 -3
  117. package/source/framework/parameter-bag.ts +2 -2
  118. package/source/framework/plugins/body-parser.plugin.ts +3 -3
  119. package/source/framework/plugins/index.ts +4 -4
  120. package/source/framework/plugins/mcp.plugin.ts +5 -5
  121. package/source/framework/plugins/openapi.plugin.ts +4 -4
  122. package/source/framework/plugins/security/body-limit.ts +3 -3
  123. package/source/framework/plugins/security/cors.ts +2 -2
  124. package/source/framework/plugins/security/csrf.ts +145 -0
  125. package/source/framework/plugins/security/headers.ts +2 -2
  126. package/source/framework/plugins/security/index.ts +7 -5
  127. package/source/framework/plugins/security/method-guard.ts +3 -3
  128. package/source/framework/plugins/security/rate-limit.ts +3 -3
  129. package/source/framework/repositories.ts +1 -1
  130. package/source/framework/responses/error.ts +2 -2
  131. package/source/framework/responses/helpers.ts +3 -3
  132. package/source/framework/responses/http-throwable.ts +3 -3
  133. package/source/framework/responses/http.ts +3 -3
  134. package/source/framework/responses/index.ts +4 -4
  135. package/source/framework/runtime/bun/server.ts +5 -5
  136. package/source/framework/runtime/deno/server.ts +156 -96
  137. package/source/framework/runtime/index.ts +11 -17
  138. package/source/framework/runtime/node/reply.ts +1 -1
  139. package/source/framework/runtime/node/request.ts +2 -2
  140. package/source/framework/runtime/node/server.ts +3 -3
  141. package/source/framework/runtime/web/server.ts +2 -2
  142. package/source/framework/services.ts +1 -1
  143. package/source/framework/utilities/artifact.util.ts +4 -0
  144. package/source/framework/utilities/csrf.util.ts +162 -0
  145. package/source/framework/utilities/index.ts +10 -9
  146. package/source/framework/utilities/openapi.utils.ts +7 -7
  147. package/source/framework/utilities/utilities.util.ts +1 -1
  148. package/source/types/application.ts +2 -2
  149. package/source/types/builder.ts +1 -1
  150. package/source/types/config.ts +1 -1
  151. package/source/types/controller.ts +3 -3
  152. package/source/types/core.ts +1 -1
  153. package/source/types/csrf.ts +38 -0
  154. package/source/types/guard.ts +1 -1
  155. package/source/types/http-responses.ts +1 -1
  156. package/source/types/index.ts +26 -25
  157. package/source/types/injection.ts +1 -1
  158. package/source/types/middleware.ts +1 -1
  159. package/source/types/plugin.ts +1 -1
  160. package/source/types/raiton.ts +1 -1
  161. package/source/types/responses.ts +2 -2
  162. package/source/types/router.ts +2 -2
  163. package/source/types/runtime.ts +3 -5
  164. package/source/types/thread.ts +4 -4
  165. /package/source/framework/utilities/{https.ts → https.util.ts} +0 -0
  166. /package/source/framework/utilities/{url.ts → url.util.ts} +0 -0
package/deno.json CHANGED
@@ -4,6 +4,9 @@
4
4
  "@/": "./source/"
5
5
  },
6
6
  "tasks": {
7
- "start": "deno run --allow-all source/bin/bootstrapper.ts"
7
+ "dev": "deno run --allow-all --watch source/bin/index.ts dev",
8
+ "build": "deno run --allow-all source/bin/index.ts build",
9
+ "start": "deno run --allow-all source/bin/index.ts start",
10
+ "compile": "deno compile --no-check --allow-all --output build/bin/raiton source/bin/index.ts"
8
11
  }
9
12
  }
@@ -14,6 +14,7 @@ Le dossier `source/framework/` regroupe les briques publiques du framework: déc
14
14
  | [env.md](env.md) | Variables d’environnement |
15
15
  | [base-classes.md](base-classes.md) | DTO, ViewModel, services, repositories, bag de paramètres |
16
16
  | [decorators/](decorators/README.md) | Décorateurs du framework |
17
+ | [cache/](cache/README.md) | ETag et cache de routes |
17
18
  | [plugins/](plugins/README.md) | Body parser, OpenAPI, sécurité |
18
19
 
19
20
  ## Ce que fournit ce module
@@ -38,6 +39,7 @@ framework/
38
39
  ├── parameter-bag.ts
39
40
  ├── artifacts.ts
40
41
  ├── env.ts
42
+ ├── cache/
41
43
  ├── decorators/
42
44
  ├── plugins/
43
45
  ├── runtime/
@@ -0,0 +1,55 @@
1
+ # Module Cache & ETag
2
+
3
+ **Fichiers :** `source/framework/cache/`
4
+ **Import :** `import { Cache, etag, Etagger, CacheManager } from "raiton/framework"`
5
+
6
+ > **Navigation :** [← framework/](../README.md) | [↑ framework/](../README.md) | [etag.md →](etag.md)
7
+
8
+ Le module `cache/` regroupe deux mécanismes complémentaires de performance HTTP :
9
+ les **ETag** (validation) et le **cache de routes** (expiration).
10
+
11
+ ## Table des matières
12
+
13
+ | Fichier | Description |
14
+ |---------|-------------|
15
+ | [etag.md](etag.md) | Gestion complète et personnalisable des ETag |
16
+ | [cache.md](cache.md) | Cache de réponses sur les routes via décorateur |
17
+
18
+ ## Vue d'ensemble des exports
19
+
20
+ ```text
21
+ cache/
22
+ ├── index.ts → Réexporte le module
23
+ ├── types.ts → Options ETag & Cache
24
+ ├── etag.ts → Etagger (manager) + etag() (middleware)
25
+ ├── cache.ts → MemoryCacheStore + CacheManager + createCacheMiddleware
26
+ └── cache.decorator.ts → @Cache (décorateur de route)
27
+ ```
28
+
29
+ ## Les deux stratégies
30
+
31
+ | Mécanisme | Objectif | Déclencheur | Coût du handler |
32
+ |-----------|----------|-------------|-----------------|
33
+ | `etag()` / `Etagger` | Validation (`304 Not Modified`) | En-tête `If-None-Match` | Exécuté |
34
+ | `@Cache()` | Expiration (« fresh », pas d'exécution) | TTL | Évité |
35
+
36
+ Les deux mécanismes s'empilent : un `@Cache()` réduit le travail du handler,
37
+ tandis qu'un `etag()` en amont (global) permet au client de valider sa copie.
38
+
39
+ ## Activation
40
+
41
+ L'ETag et le cache **ne sont pas activés par défaut** — contrairement aux
42
+ en-têtes de sécurité — afin de ne pas modifier le comportement des applications
43
+ existantes. Le développeur les branche explicitement.
44
+
45
+ ```typescript
46
+ import { etag } from "raiton/framework"
47
+
48
+ const app = new Application({ port: 3000 })
49
+
50
+ app.use(etag({ weak: false, cacheControl: { maxAge: 60 } }))
51
+ ```
52
+
53
+ ---
54
+
55
+ [← framework/](../README.md) | [↑ framework/](../README.md) | [etag.md →](etag.md)
@@ -0,0 +1,86 @@
1
+ # Cache de routes — `@Cache()`, `CacheManager`
2
+
3
+ **Fichiers :** `source/framework/cache/cache.ts`, `source/framework/cache/cache.decorator.ts`
4
+ **Import :** `import { Cache, CacheManager, MemoryCacheStore } from "raiton/framework"`
5
+
6
+ > **Navigation :** [← etag.md](etag.md) | [↑ README](README.md) | [framework/](../README.md)
7
+
8
+ Le cache de routes évite complètement d'exécuter le handler tant que la réponse
9
+ est **fraîche** (dans la fenêtre de TTL). C'est une stratégie d'**expiration**,
10
+ à distinguer de la **validation** apportée par les ETag.
11
+
12
+ ## `@Cache(options)` — décorateur de route
13
+
14
+ ```typescript
15
+ import { Controllable, Get, Cache } from "raiton/framework"
16
+
17
+ @Controllable("/products")
18
+ export class ProductController {
19
+ @Get("/featured")
20
+ @Cache({ ttl: 60_000 })
21
+ featured() {
22
+ return this.products.findFeatured()
23
+ }
24
+ }
25
+ ```
26
+
27
+ Le décorateur enregistre un middleware sur la route. Tant que l'entrée est
28
+ fraîche, la réponse est servie depuis le store **sans** appeler le handler.
29
+ À expiration, le handler s'exécute à nouveau et la réponse est stockée.
30
+
31
+ ## `CacheOptions`
32
+
33
+ | Option | Type | défaut | Description |
34
+ |--------|------|--------|-------------|
35
+ | `ttl` | `number` | `60_000` | durée de validité (ms) |
36
+ | `enabled` | `boolean` | `true` | active le cache de la route |
37
+ | `maxEntries` | `number` | `1000` | taille max du store en mémoire |
38
+ | `key` | `(context, route?) => string` | méthode + pathname + params | clé personnalisée |
39
+ | `vary` | `string[]` | `[]` | en-têtes participant à la clé (segmentation) |
40
+ | `methods` | `string[]` | `['GET', 'HEAD']` | méthodes HTTP mises en cache |
41
+
42
+ ### Segmenter par en-tête
43
+
44
+ ```typescript
45
+ @Cache({ ttl: 30_000, vary: ["accept-language"] })
46
+ list() { /* ... */ }
47
+ ```
48
+
49
+ Deux langues différentes produiront deux entrées de cache distinctes.
50
+
51
+ ## `CacheManager` — configuration globale
52
+
53
+ Comme les autres managers du framework, `CacheManager` configure le comportement
54
+ par défaut et le store partagé.
55
+
56
+ ```typescript
57
+ CacheManager.configure({ ttl: 30_000, maxEntries: 5000 })
58
+ CacheManager.setStore(redisStore) // store alternatif, p.ex. Redis
59
+ CacheManager.clear() // vide le cache
60
+ ```
61
+
62
+ ## `MemoryCacheStore` & `CacheStore`
63
+
64
+ Le store par défaut est un `MemoryCacheStore` borné (TTL + taille max). Un store
65
+ alternatif doit implémenter l'interface `CacheStore` :
66
+
67
+ ```typescript
68
+ interface CacheStore {
69
+ get<T>(key: string): CacheEntry<T> | undefined
70
+ set<T>(key: string, entry: CacheEntry<T>, ttl?: number): void
71
+ has(key: string): boolean
72
+ delete(key: string): boolean
73
+ clear(): void
74
+ size(): number
75
+ }
76
+ ```
77
+
78
+ ## Combinaison avec les ETag
79
+
80
+ Le middleware `etag()` (global) s'exécute avant le middleware `@Cache()` (route).
81
+ Sur une réponse servie depuis le cache, l'ETag est calculé sur le corps mis en
82
+ cache : le client peut donc **valider** une réponse déjà **fraîche**.
83
+
84
+ ---
85
+
86
+ [← etag.md](etag.md) | [↑ README](README.md) | [framework/](../README.md)
@@ -0,0 +1,82 @@
1
+ # ETag — `Etagger`, `etag()`
2
+
3
+ **Fichiers :** `source/framework/cache/etag.ts`
4
+ **Import :** `import { Etagger, etag, defaultEtagger } from "raiton/framework"`
5
+
6
+ > **Navigation :** [← README](README.md) | [↑ README](README.md) | [cache.md →](cache.md)
7
+
8
+ Système **complet et personnalisable** de gestion des ETag. Il permet de :
9
+
10
+ - calculer un ETag stable depuis le corps sérialisé de la réponse (hachage FNV-1a par défaut) ;
11
+ - répondre `304 Not Modified` quand le client déclare posséder la représentation (`If-None-Match`) ;
12
+ - choisir un ETag **fort** ou **faible** (`W/"..."`) ;
13
+ - remplacer l'algorithme de hachage par un algorithme **personnalisé** ;
14
+ - piloter l'en-tête `Cache-Control` automatiquement ;
15
+ - exclure certaines requêtes/réponses du calcul.
16
+
17
+ ## `etag(options?)` — middleware prêt à l'emploi
18
+
19
+ ```typescript
20
+ app.use(etag({
21
+ weak: false,
22
+ cacheControl: { maxAge: 60 },
23
+ }))
24
+ ```
25
+
26
+ Le middleware intercepte `context.reply.send`, calcule l'ETag du corps,
27
+ pose l'en-tête `ETag`, applique `Cache-Control` et, si `If-None-Match` matche,
28
+ répond `304` sans corps.
29
+
30
+ ## `ETagOptions`
31
+
32
+ | Option | Type | défaut | Description |
33
+ |--------|------|--------|-------------|
34
+ | `enabled` | `boolean` | `true` | active la génération |
35
+ | `weak` | `boolean` | `false` | ETag faible (`W/"..."`) |
36
+ | `algorithm` | `(body: string) => string \| Promise<string>` | FNV-1a | hasher personnalisé |
37
+ | `cacheControl` | `boolean \| { ... }` | `false` | en-têtes `Cache-Control` automatiques |
38
+ | `headerName` | `string` | `'ETag'` | nom de l'en-tête de réponse |
39
+ | `skip` | `(context, body) => boolean` | – | exclure une requête/réponse |
40
+
41
+ ### `cacheControl`
42
+
43
+ - `true` → `no-cache`
44
+ - `{ public: true, maxAge: 60 }` → `public, max-age=60`
45
+ - `{ noStore: true }` → `private, no-store`
46
+
47
+ ## `Etagger` — utilisation programmatique
48
+
49
+ ```typescript
50
+ const etagger = new Etagger({ weak: true, cacheControl: { maxAge: 300 } })
51
+
52
+ const { tag, body, notModified } = await etagger.evaluate(context, payload)
53
+ if (notModified) {
54
+ context.reply.status(304)
55
+ context.reply.send(null)
56
+ } else {
57
+ context.reply.send(body)
58
+ }
59
+ ```
60
+
61
+ ### API de `Etagger`
62
+
63
+ | Méthode | Description |
64
+ |---------|-------------|
65
+ | `generate(body)` | calcule la valeur d'ETag (`"..."` ou `W/"..."`) |
66
+ | `matches(clientTags, tag)` | teste `If-None-Match` (`*` accepté) |
67
+ | `evaluate(context, body)` | applique en-têtes + décision 304, renvoie `{ tag, body, notModified }` |
68
+ | `static apply(context, body, options?)` | raccourci un seul appel |
69
+
70
+ ## Exemple — hachage personnalisé
71
+
72
+ ```typescript
73
+ app.use(etag({ algorithm: async (body) => {
74
+ const bytes = new TextEncoder().encode(body)
75
+ const digest = await crypto.subtle.digest("SHA-1", bytes)
76
+ return [...new Uint8Array(digest)].map(b => b.toString(16).padStart(2, "0")).join("")
77
+ }}))
78
+ ```
79
+
80
+ ---
81
+
82
+ [← README](README.md) | [↑ README](README.md) | [cache.md →](cache.md)
@@ -28,6 +28,7 @@ Les décorateurs utilisent `reflect-metadata` et `experimentalDecorators: true`
28
28
  | `@Injectable` | Classe | Enregistrement DI | [Voir](injection.md) |
29
29
  | `@Inject` | Constructeur/propriété | Injection de dépendance | [Voir](injection.md) |
30
30
  | `@Middleware` | Classe/méthode | Middleware sur contrôleur/route | [Voir](middleware.md) |
31
+ | `@Cache` | Méthode | Cache de réponse de route | [Voir](../cache/cache.md) |
31
32
  | `@Socket` | Classe | Handler socket | [Voir](socket.md) |
32
33
  | `@OnSocket*` | Méthode | Événement socket | [Voir](socket.md) |
33
34
  | `@ApiTags` | Classe/méthode | Tag OpenAPI | [Voir](openapi.md) |
@@ -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
  ---
@@ -14,6 +14,7 @@ class Runtime {
14
14
  constructor(public readonly type: RuntimeType)
15
15
 
16
16
  get isNode(): boolean
17
+ get isDeno(): boolean
17
18
  get isBun(): boolean
18
19
 
19
20
  adapter(): RuntimeAdapterInterface
@@ -25,11 +26,15 @@ class Runtime {
25
26
 
26
27
  ```typescript
27
28
  // Détection automatique (dans RaitonThread.setup) :
28
- const defaultRuntime = typeof Bun !== 'undefined' ? RuntimeType.Bun : RuntimeType.Node
29
+ // Bun si présent, sinon Deno si présent, sinon Node
30
+ const defaultRuntime = isBunUsed
31
+ ? RuntimeType.Bun
32
+ : (isDenoUsed ? RuntimeType.Deno : RuntimeType.Node)
29
33
 
30
34
  // Manuel :
31
35
  const runtime = new Runtime(RuntimeType.Bun)
32
36
  const runtime = new Runtime(RuntimeType.Node)
37
+ const runtime = new Runtime(RuntimeType.Deno)
33
38
  ```
34
39
 
35
40
  ### Création du serveur
@@ -77,11 +82,16 @@ node/
77
82
  - `NodeRequest` : wrapper autour de `IncomingMessage` avec interface `RequestInterface`
78
83
  - `NodeReply` : wrapper autour de `ServerResponse` avec interface `ReplyInterface`
79
84
 
80
- ### `denoRuntime` (stub)
85
+ ### `denoRuntime` (Deno.serve)
81
86
 
82
87
  **Fichier :** `source/framework/runtime/deno/server.ts`
83
88
 
84
- Non implémenté — stub uniquement.
89
+ Utilise `Deno.serve()` et `Deno.upgradeWebSocket()` pour les sockets.
90
+
91
+ - **Serveur** : `Deno.serve({ port, hostname })`
92
+ - **Requêtes** : Native `Request` / `Response`
93
+ - **Sockets** : `Deno.upgradeWebSocket()`
94
+ - **Recommandé** pour une production stable et rapide sur Deno
85
95
 
86
96
  ## Interface `RuntimeAdapterInterface`
87
97