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.
- package/CHANGELOG.md +31 -0
- package/README.md +16 -9
- package/build/bin/index.mjs +10288 -6059
- package/deno.json +4 -1
- package/docs/contributors/framework/README.md +2 -0
- package/docs/contributors/framework/cache/README.md +55 -0
- package/docs/contributors/framework/cache/cache.md +86 -0
- package/docs/contributors/framework/cache/etag.md +82 -0
- package/docs/contributors/framework/decorators/README.md +1 -0
- package/docs/contributors/framework/plugins/csrf.md +277 -0
- package/docs/contributors/framework/plugins/security.md +40 -6
- package/docs/contributors/framework/runtime.md +13 -3
- package/docs/user-guide/README.md +8 -4
- package/docs/user-guide/best-practices.md +1 -0
- package/docs/user-guide/cache.md +79 -0
- package/docs/user-guide/cli.md +35 -3
- package/docs/user-guide/csrf.md +557 -0
- package/docs/user-guide/decorators/README.md +3 -0
- package/docs/user-guide/decorators/cache.md +79 -0
- package/docs/user-guide/decorators/health-check.md +125 -0
- package/docs/user-guide/health-check.md +117 -0
- package/docs/user-guide/runtime.md +2 -1
- package/docs/user-guide/security.md +8 -2
- package/package.json +8 -3
- package/source/bin/bootstrapper.ts +4 -4
- package/source/bin/cli-tools.ts +27 -3
- package/source/bin/cli.ts +2 -2
- package/source/bin/commands.registry.ts +17 -0
- package/source/bin/constants.ts +1 -0
- package/source/bin/index.ts +2 -2
- package/source/commands/artifact.command.ts +2 -2
- package/source/commands/build.command.ts +2 -2
- package/source/commands/develop.command.ts +4 -5
- package/source/commands/grafts.command.ts +1 -1
- package/source/commands/start.command.ts +2 -2
- package/source/core/application.ts +10 -10
- package/source/core/artifacts/artifact.ts +1 -1
- package/source/core/artifacts/index.ts +1 -1
- package/source/core/builder.ts +69 -15
- package/source/core/bytes.util.ts +1 -1
- package/source/core/commands.ts +24 -14
- package/source/core/config/config.ts +2 -2
- package/source/core/config/define.ts +2 -2
- package/source/core/config/index.ts +2 -2
- package/source/core/context.ts +1 -1
- package/source/core/controller/builder.ts +31 -8
- package/source/core/controller/compiler.ts +6 -6
- package/source/core/controller/index.ts +4 -4
- package/source/core/controller/metadata.ts +2 -2
- package/source/core/controller/tracker.ts +1 -1
- package/source/core/directories.ts +3 -2
- package/source/core/guards.ts +1 -1
- package/source/core/helpers/index.ts +1 -1
- package/source/core/hooks.ts +1 -1
- package/source/core/index.ts +16 -16
- package/source/core/injection/index.ts +1 -1
- package/source/core/injection/injection.ts +3 -3
- package/source/core/mcp/builder.ts +8 -8
- package/source/core/mcp/index.ts +3 -3
- package/source/core/mcp/metadata.ts +2 -2
- package/source/core/mcp/tracker.ts +1 -1
- package/source/core/middleware/compose.ts +2 -2
- package/source/core/middleware/index.ts +2 -2
- package/source/core/middleware/pipeline.ts +2 -2
- package/source/core/plugins/index.ts +2 -2
- package/source/core/plugins/plugin.ts +1 -1
- package/source/core/plugins/scope.ts +4 -4
- package/source/core/raiton.ts +1 -1
- package/source/core/router/handler.ts +30 -6
- package/source/core/router/handler.utils.ts +3 -3
- package/source/core/router/index.ts +4 -4
- package/source/core/router/matcher.ts +1 -1
- package/source/core/router/route.ts +1 -1
- package/source/core/router/router.ts +4 -4
- package/source/core/server.ts +1 -1
- package/source/core/socket/builder.ts +2 -2
- package/source/core/socket/index.ts +2 -2
- package/source/core/socket/metadata.ts +2 -2
- package/source/core/thread.ts +53 -20
- package/source/framework/artifacts.ts +8 -5
- package/source/framework/cache/cache.decorator.ts +35 -0
- package/source/framework/cache/cache.ts +197 -0
- package/source/framework/cache/etag.ts +174 -0
- package/source/framework/cache/index.ts +4 -0
- package/source/framework/cache/types.ts +111 -0
- package/source/framework/constants/decorators.constant.ts +4 -0
- package/source/framework/constants/index.ts +2 -2
- package/source/framework/decorators/access-guard.decorator.ts +2 -2
- package/source/framework/decorators/api-response.decorator.ts +1 -1
- package/source/framework/decorators/api.decorator.ts +1 -1
- package/source/framework/decorators/controllable.decorator.ts +3 -3
- package/source/framework/decorators/csrf-guard.decorator.ts +60 -0
- package/source/framework/decorators/csrf-token.decorator.ts +20 -0
- package/source/framework/decorators/guard.decorator.ts +4 -4
- package/source/framework/decorators/health-check.decorator.ts +50 -0
- package/source/framework/decorators/index.ts +14 -11
- package/source/framework/decorators/injection.decorator.ts +3 -3
- package/source/framework/decorators/mcp.decorator.ts +4 -4
- package/source/framework/decorators/middleware.decorator.ts +2 -2
- package/source/framework/decorators/parametrable.decorator.ts +2 -2
- package/source/framework/decorators/routable.decorator.ts +3 -3
- package/source/framework/decorators/route-interaction.decorator.ts +4 -4
- package/source/framework/decorators/socket.decorator.ts +3 -3
- package/source/framework/encryption.ts +2 -2
- package/source/framework/enums/csrf.enum.ts +4 -0
- package/source/framework/enums/index.ts +8 -7
- package/source/framework/enums/runtime.enum.ts +1 -2
- package/source/framework/env.ts +2 -2
- package/source/framework/exceptions/http-exception.ts +3 -3
- package/source/framework/exceptions/index.ts +2 -2
- package/source/framework/health-check.ts +137 -0
- package/source/framework/index.ts +18 -16
- package/source/framework/mcp/handler.ts +3 -3
- package/source/framework/mcp/index.ts +3 -3
- package/source/framework/mcp/protocol.ts +1 -1
- package/source/framework/mcp/streamable-http.ts +3 -3
- package/source/framework/parameter-bag.ts +2 -2
- package/source/framework/plugins/body-parser.plugin.ts +3 -3
- package/source/framework/plugins/index.ts +4 -4
- package/source/framework/plugins/mcp.plugin.ts +5 -5
- package/source/framework/plugins/openapi.plugin.ts +4 -4
- package/source/framework/plugins/security/body-limit.ts +3 -3
- package/source/framework/plugins/security/cors.ts +2 -2
- package/source/framework/plugins/security/csrf.ts +145 -0
- package/source/framework/plugins/security/headers.ts +2 -2
- package/source/framework/plugins/security/index.ts +7 -5
- package/source/framework/plugins/security/method-guard.ts +3 -3
- package/source/framework/plugins/security/rate-limit.ts +3 -3
- package/source/framework/repositories.ts +1 -1
- package/source/framework/responses/error.ts +2 -2
- package/source/framework/responses/helpers.ts +3 -3
- package/source/framework/responses/http-throwable.ts +3 -3
- package/source/framework/responses/http.ts +3 -3
- package/source/framework/responses/index.ts +4 -4
- package/source/framework/runtime/bun/server.ts +5 -5
- package/source/framework/runtime/deno/server.ts +156 -96
- package/source/framework/runtime/index.ts +11 -17
- package/source/framework/runtime/node/reply.ts +1 -1
- package/source/framework/runtime/node/request.ts +2 -2
- package/source/framework/runtime/node/server.ts +3 -3
- package/source/framework/runtime/web/server.ts +2 -2
- package/source/framework/services.ts +1 -1
- package/source/framework/utilities/artifact.util.ts +4 -0
- package/source/framework/utilities/csrf.util.ts +162 -0
- package/source/framework/utilities/index.ts +10 -9
- package/source/framework/utilities/openapi.utils.ts +7 -7
- package/source/framework/utilities/utilities.util.ts +1 -1
- package/source/types/application.ts +2 -2
- package/source/types/builder.ts +1 -1
- package/source/types/config.ts +1 -1
- package/source/types/controller.ts +3 -3
- package/source/types/core.ts +1 -1
- package/source/types/csrf.ts +38 -0
- package/source/types/guard.ts +1 -1
- package/source/types/http-responses.ts +1 -1
- package/source/types/index.ts +26 -25
- package/source/types/injection.ts +1 -1
- package/source/types/middleware.ts +1 -1
- package/source/types/plugin.ts +1 -1
- package/source/types/raiton.ts +1 -1
- package/source/types/responses.ts +2 -2
- package/source/types/router.ts +2 -2
- package/source/types/runtime.ts +3 -5
- package/source/types/thread.ts +4 -4
- /package/source/framework/utilities/{https.ts → https.util.ts} +0 -0
- /package/source/framework/utilities/{url.ts → url.util.ts} +0 -0
|
@@ -0,0 +1,557 @@
|
|
|
1
|
+
# Protection CSRF
|
|
2
|
+
|
|
3
|
+
> **Navigation :** [← security](security.md) | [middleware →](middleware.md)
|
|
4
|
+
|
|
5
|
+
La protection CSRF (Cross-Site Request Forgery) empêche les attaques où un site malveillant exploite les cookies de session d'un utilisateur pour effectuer des actions non autorisées en son nom.
|
|
6
|
+
|
|
7
|
+
## Table des matières
|
|
8
|
+
|
|
9
|
+
- [Pourquoi CSRF ?](#pourquoi-csrf)
|
|
10
|
+
- [Comment ça fonctionne](#comment-ça-fonctionne)
|
|
11
|
+
- [Modes de protection](#modes-de-protection)
|
|
12
|
+
- [Configuration](#configuration)
|
|
13
|
+
- [Intégration frontend (Navigateur)](#intégration-frontend-navigateur)
|
|
14
|
+
- [Intégration Mobile / Desktop](#intégration-mobile--desktop)
|
|
15
|
+
- [Decorators](#decorators)
|
|
16
|
+
- [Sécurité](#sécurité)
|
|
17
|
+
- [Dépannage](#dépannage)
|
|
18
|
+
|
|
19
|
+
---
|
|
20
|
+
|
|
21
|
+
## Pourquoi CSRF ?
|
|
22
|
+
|
|
23
|
+
Une attaque CSRF fonctionne ainsi :
|
|
24
|
+
|
|
25
|
+
1. L'utilisateur se connecte à `https://monapp.com` → le navigateur stocke un cookie de session
|
|
26
|
+
2. L'utilisateur visite `https://site-malveillant.com`
|
|
27
|
+
3. Ce site contient du code qui envoie une requête à `https://monapp.com/api/transfer`
|
|
28
|
+
4. Le navigateur envoie **automatiquement** le cookie de session avec cette requête
|
|
29
|
+
5. Le serveur traite la requête comme légitime
|
|
30
|
+
|
|
31
|
+
La protection CSRF empêche cette attaque en exigeant un **token secret** que le site malveillant ne peut pas lire (grâce à la politique Same-Origin).
|
|
32
|
+
|
|
33
|
+
---
|
|
34
|
+
|
|
35
|
+
## Comment ça fonctionne
|
|
36
|
+
|
|
37
|
+
Raiton utilise un mécanisme de **Double Submit Cookie** ou **Synchronizer Token** :
|
|
38
|
+
|
|
39
|
+
```
|
|
40
|
+
1. Le serveur génère un token CSRF
|
|
41
|
+
2. Le token est placé dans un cookie (SameSite=Strict)
|
|
42
|
+
3. Le client doit renvoyer le même token dans le header X-CSRF-Token
|
|
43
|
+
4. Le serveur compare le cookie et le header
|
|
44
|
+
5. Si correspondent → requête traitée
|
|
45
|
+
6. Sinon → 403 Forbidden
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
### Pourquoi ça marche ?
|
|
49
|
+
|
|
50
|
+
Un site malveillant **peut** forcer le navigateur à envoyer des cookies cross-origin, mais il **ne peut PAS** lire les cookies ( Same-Origin Policy ). Sans pouvoir lire le token, il ne peut pas le placer dans le header `X-CSRF-Token`.
|
|
51
|
+
|
|
52
|
+
---
|
|
53
|
+
|
|
54
|
+
## Modes de protection
|
|
55
|
+
|
|
56
|
+
### Mode `double-submit` (Recommandé — Stateless)
|
|
57
|
+
|
|
58
|
+
Le token est un HMAC-SHA256 signé par le serveur :
|
|
59
|
+
|
|
60
|
+
```
|
|
61
|
+
Token = HMAC-SHA256(secret, timestamp.nonce).signature
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
**Avantages :**
|
|
65
|
+
- Pas de stockage côté serveur
|
|
66
|
+
- Scalable sur plusieurs instances
|
|
67
|
+
- Compatible avec les architectures distribuées
|
|
68
|
+
|
|
69
|
+
**Inconvénients :**
|
|
70
|
+
- Le token est valide pendant toute sa durée de vie (TTL)
|
|
71
|
+
- Pas de révocation individuelle possible
|
|
72
|
+
|
|
73
|
+
### Mode `synchronizer` (Stateful)
|
|
74
|
+
|
|
75
|
+
Le token est un aléatoire stocké en mémoire côté serveur avec un TTL :
|
|
76
|
+
|
|
77
|
+
```
|
|
78
|
+
Token = randomBytes(32).hex()
|
|
79
|
+
Stocké en mémoire avec expiresAt = now + ttl
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
**Avantages :**
|
|
83
|
+
- Token unique et jetable
|
|
84
|
+
- Révocation possible
|
|
85
|
+
- Plus résistant aux attaques par replay
|
|
86
|
+
|
|
87
|
+
**Inconvénients :**
|
|
88
|
+
- Nécessite un stockage en mémoire
|
|
89
|
+
- Non distribué (un seul serveur)
|
|
90
|
+
- Nettoyage automatique des tokens expirés
|
|
91
|
+
|
|
92
|
+
---
|
|
93
|
+
|
|
94
|
+
## Configuration
|
|
95
|
+
|
|
96
|
+
### Import
|
|
97
|
+
|
|
98
|
+
```typescript
|
|
99
|
+
import { Security } from "raiton/framework"
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
### Configuration minimale
|
|
103
|
+
|
|
104
|
+
```typescript
|
|
105
|
+
app.register(Security.csrf())
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
### Configuration complète
|
|
109
|
+
|
|
110
|
+
```typescript
|
|
111
|
+
app.register(Security.csrf({
|
|
112
|
+
mode: CSRFModeEnum.DOUBLE_SUBMIT, // CSRFModeEnum.DOUBLE_SUBMIT | CSRFModeEnum.SYNCHRONIZER
|
|
113
|
+
secret: 'mon-secret-ultra-long', // Secret HMAC (min 32 caractères)
|
|
114
|
+
cookieName: '_csrf', // Nom du cookie (défaut: '_csrf')
|
|
115
|
+
headerName: 'X-CSRF-Token', // Nom du header (défaut: 'X-CSRF-Token')
|
|
116
|
+
ttl: 3600_000, // Durée de vie en ms (défaut: 1 heure)
|
|
117
|
+
methods: ['POST', 'PUT', 'PATCH', 'DELETE'], // Méthodes protégées
|
|
118
|
+
skipPaths: ['/health', '/auth/login'], // Chemins exclus
|
|
119
|
+
clientDetection: {
|
|
120
|
+
headerName: 'X-Client-Type', // Header de détection client
|
|
121
|
+
skipClients: ['mobile', 'desktop'], // Clients exemptés
|
|
122
|
+
},
|
|
123
|
+
cookieOptions: {
|
|
124
|
+
httpOnly: false, // false = JS peut lire le cookie
|
|
125
|
+
secure: true, // true = HTTPS uniquement
|
|
126
|
+
sameSite: 'lax', // 'strict' | 'lax' | 'none'
|
|
127
|
+
path: '/',
|
|
128
|
+
maxAge: 3600, // Durée du cookie en secondes
|
|
129
|
+
}
|
|
130
|
+
}))
|
|
131
|
+
```
|
|
132
|
+
|
|
133
|
+
### Import de l'enum
|
|
134
|
+
|
|
135
|
+
```typescript
|
|
136
|
+
import { CSRFModeEnum, Security } from "raiton/framework"
|
|
137
|
+
|
|
138
|
+
// Utilisation
|
|
139
|
+
app.register(Security.csrf({
|
|
140
|
+
mode: CSRFModeEnum.DOUBLE_SUBMIT,
|
|
141
|
+
}))
|
|
142
|
+
```
|
|
143
|
+
|
|
144
|
+
### Options détaillées
|
|
145
|
+
|
|
146
|
+
| Option | Type | Défaut | Description |
|
|
147
|
+
|--------|------|--------|-------------|
|
|
148
|
+
| `mode` | `CSRFModeEnum` | `CSRFModeEnum.DOUBLE_SUBMIT` | Stratégie CSRF utilisée |
|
|
149
|
+
| `secret` | `string` | aléatoire | Secret HMAC pour le mode double-submit |
|
|
150
|
+
| `cookieName` | `string` | `'_csrf'` | Nom du cookie contenant le token |
|
|
151
|
+
| `headerName` | `string` | `'X-CSRF-Token'` | Nom du header contenant le token |
|
|
152
|
+
| `ttl` | `number` | `3600000` | Durée de vie du token en millisecondes |
|
|
153
|
+
| `methods` | `string[]` | `['POST','PUT','PATCH','DELETE']` | Méthodes HTTP protégées |
|
|
154
|
+
| `skip` | `string[]` | `[]` | Chemins exclus de la protection |
|
|
155
|
+
| `client` | `CsrfClientDetectionConfig` | `{}` | Configuration de détection client |
|
|
156
|
+
| `cookieOptions` | `CsrfCookieOptions` | voir ci-dessous | Options du cookie |
|
|
157
|
+
|
|
158
|
+
### Options du cookie
|
|
159
|
+
|
|
160
|
+
| Option | Type | Défaut | Description |
|
|
161
|
+
|--------|------|--------|-------------|
|
|
162
|
+
| `httpOnly` | `boolean` | `false` | Cookie inaccessible au JavaScript |
|
|
163
|
+
| `secure` | `boolean` | `false` | Cookie envoyé uniquement en HTTPS |
|
|
164
|
+
| `sameSite` | `'strict' \| 'lax' \| 'none'` | `'lax'` | Politique SameSite |
|
|
165
|
+
| `path` | `string` | `'/'` | chemin du cookie |
|
|
166
|
+
| `domain` | `string` | — | Domaine du cookie |
|
|
167
|
+
| `maxAge` | `number` | — | Durée de vie en secondes |
|
|
168
|
+
|
|
169
|
+
---
|
|
170
|
+
|
|
171
|
+
## Intégration frontend (Navigateur)
|
|
172
|
+
|
|
173
|
+
### Étape 1 : Récupérer le token
|
|
174
|
+
|
|
175
|
+
Le token est automatiquement placé dans le cookie `_csrf` par le serveur. Vous pouvez aussi le récupérer via le header `X-CSRF-Token` dans la réponse.
|
|
176
|
+
|
|
177
|
+
#### Avec JavaScript natif
|
|
178
|
+
|
|
179
|
+
```javascript
|
|
180
|
+
// Fonction pour lire un cookie
|
|
181
|
+
function getCookie(name) {
|
|
182
|
+
const match = document.cookie.match(new RegExp('(^| )' + name + '=([^;]+)'))
|
|
183
|
+
return match ? match[2] : null
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
// Récupérer le token CSRF
|
|
187
|
+
const csrfToken = getCookie('_csrf')
|
|
188
|
+
```
|
|
189
|
+
|
|
190
|
+
#### Avec React
|
|
191
|
+
|
|
192
|
+
```typescript
|
|
193
|
+
// Hook personnalisé
|
|
194
|
+
function useCsrfToken() {
|
|
195
|
+
const getCookie = (name: string) => {
|
|
196
|
+
const match = document.cookie.match(new RegExp('(^| )' + name + '=([^;]+)'))
|
|
197
|
+
return match ? match[2] : null
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
return getCookie('_csrf')
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
// Utilisation
|
|
204
|
+
const csrfToken = useCsrfToken()
|
|
205
|
+
```
|
|
206
|
+
|
|
207
|
+
### Étape 2 : Envoyer le token
|
|
208
|
+
|
|
209
|
+
#### Avec Fetch API
|
|
210
|
+
|
|
211
|
+
```typescript
|
|
212
|
+
const response = await fetch('/api/data', {
|
|
213
|
+
method: 'POST',
|
|
214
|
+
headers: {
|
|
215
|
+
'Content-Type': 'application/json',
|
|
216
|
+
'X-CSRF-Token': getCookie('_csrf'),
|
|
217
|
+
},
|
|
218
|
+
body: JSON.stringify({ name: 'test' })
|
|
219
|
+
})
|
|
220
|
+
```
|
|
221
|
+
|
|
222
|
+
#### Avec Axios
|
|
223
|
+
|
|
224
|
+
```typescript
|
|
225
|
+
import axios from 'axios'
|
|
226
|
+
|
|
227
|
+
// Intercepteur automatique
|
|
228
|
+
axios.interceptors.request.use(config => {
|
|
229
|
+
const csrfToken = document.cookie
|
|
230
|
+
.match(new RegExp('(^| )_csrf=([^;]+)'))?.[2]
|
|
231
|
+
|
|
232
|
+
if (csrfToken && config.method !== 'get') {
|
|
233
|
+
config.headers['X-CSRF-Token'] = csrfToken
|
|
234
|
+
}
|
|
235
|
+
return config
|
|
236
|
+
})
|
|
237
|
+
```
|
|
238
|
+
|
|
239
|
+
#### Avec jQuery
|
|
240
|
+
|
|
241
|
+
```typescript
|
|
242
|
+
// Configuration globale
|
|
243
|
+
$.ajaxSetup({
|
|
244
|
+
beforeSend: function(xhr) {
|
|
245
|
+
const csrfToken = document.cookie
|
|
246
|
+
.match(new RegExp('(^| )_csrf=([^;]+)'))?.[2]
|
|
247
|
+
if (csrfToken) {
|
|
248
|
+
xhr.setRequestHeader('X-CSRF-Token', csrfToken)
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
})
|
|
252
|
+
```
|
|
253
|
+
|
|
254
|
+
### Exemple complet avec SPA
|
|
255
|
+
|
|
256
|
+
```typescript
|
|
257
|
+
// app.ts
|
|
258
|
+
async function apiCall(url: string, options: RequestInit = {}) {
|
|
259
|
+
const csrfToken = document.cookie
|
|
260
|
+
.match(new RegExp('(^| )_csrf=([^;]+)'))?.[2]
|
|
261
|
+
|
|
262
|
+
return fetch(url, {
|
|
263
|
+
...options,
|
|
264
|
+
headers: {
|
|
265
|
+
'Content-Type': 'application/json',
|
|
266
|
+
'X-CSRF-Token': csrfToken ?? '',
|
|
267
|
+
...options.headers,
|
|
268
|
+
}
|
|
269
|
+
})
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
// Utilisation
|
|
273
|
+
await apiCall('/api/users', {
|
|
274
|
+
method: 'POST',
|
|
275
|
+
body: JSON.stringify({ name: 'Alice' })
|
|
276
|
+
})
|
|
277
|
+
```
|
|
278
|
+
|
|
279
|
+
---
|
|
280
|
+
|
|
281
|
+
## Intégration Mobile / Desktop
|
|
282
|
+
|
|
283
|
+
Les applications mobiles et desktop utilisent généralement des **Bearer tokens (JWT)** au lieu de cookies. Elles sont automatiquement exemptées de la protection CSRF si elles envoient le header `X-Client-Type`.
|
|
284
|
+
|
|
285
|
+
### Configuration côté client
|
|
286
|
+
|
|
287
|
+
#### Application mobile (React Native, Flutter, etc.)
|
|
288
|
+
|
|
289
|
+
```typescript
|
|
290
|
+
// Pas besoin de gérer CSRF !
|
|
291
|
+
// Envoyez simplement le JWT dans le header Authorization
|
|
292
|
+
|
|
293
|
+
const response = await fetch('https://api.monapp.com/data', {
|
|
294
|
+
method: 'POST',
|
|
295
|
+
headers: {
|
|
296
|
+
'Content-Type': 'application/json',
|
|
297
|
+
'Authorization': 'Bearer eyJhbGciOiJIUzI1NiIs...',
|
|
298
|
+
'X-Client-Type': 'mobile', // ← Indique au serveur que c'est un client mobile
|
|
299
|
+
},
|
|
300
|
+
body: JSON.stringify({ name: 'test' })
|
|
301
|
+
})
|
|
302
|
+
```
|
|
303
|
+
|
|
304
|
+
#### Application Tauri Desktop
|
|
305
|
+
|
|
306
|
+
```typescript
|
|
307
|
+
// Tauri peut utiliser soit JWT soit cookies
|
|
308
|
+
|
|
309
|
+
// Option 1 : JWT (recommandé pour Tauri)
|
|
310
|
+
const response = await fetch('https://api.monapp.com/data', {
|
|
311
|
+
method: 'POST',
|
|
312
|
+
headers: {
|
|
313
|
+
'Authorization': `Bearer ${jwtToken}`,
|
|
314
|
+
'X-Client-Type': 'desktop',
|
|
315
|
+
},
|
|
316
|
+
body: JSON.stringify({ name: 'test' })
|
|
317
|
+
})
|
|
318
|
+
|
|
319
|
+
// Option 2 : Cookies (si Tauri gère des cookies)
|
|
320
|
+
// Dans ce cas, envoyez aussi le header X-CSRF-Token
|
|
321
|
+
const csrfToken = await invoke('get_csrf_token') // depuis le backend Rust
|
|
322
|
+
const response = await fetch('https://api.monapp.com/data', {
|
|
323
|
+
method: 'POST',
|
|
324
|
+
headers: {
|
|
325
|
+
'Content-Type': 'application/json',
|
|
326
|
+
'X-CSRF-Token': csrfToken,
|
|
327
|
+
},
|
|
328
|
+
body: JSON.stringify({ name: 'test' })
|
|
329
|
+
})
|
|
330
|
+
```
|
|
331
|
+
|
|
332
|
+
### Logique de détection côté serveur
|
|
333
|
+
|
|
334
|
+
Le middleware CSRF détecte automatiquement le type de client :
|
|
335
|
+
|
|
336
|
+
```
|
|
337
|
+
Requête avec cookie + header X-CSRF-Token → Navigation browser → Valider CSRF
|
|
338
|
+
Requête avec Authorization + X-Client-Type: mobile → App mobile → Skip CSRF
|
|
339
|
+
Requête avec Authorization + X-Client-Type: desktop → App desktop → Skip CSRF
|
|
340
|
+
Requête avec cookie mais sans header CSRF → Faille potentielle → 403
|
|
341
|
+
```
|
|
342
|
+
|
|
343
|
+
---
|
|
344
|
+
|
|
345
|
+
## Decorators
|
|
346
|
+
|
|
347
|
+
### `@CsrfGuard()`
|
|
348
|
+
|
|
349
|
+
Applique la protection CSRF sur une classe ou une méthode de contrôleur.
|
|
350
|
+
|
|
351
|
+
```typescript
|
|
352
|
+
import { CsrfGuard, Controllable, Post } from "raiton/framework"
|
|
353
|
+
|
|
354
|
+
// Protection sur toute la classe
|
|
355
|
+
@CsrfGuard()
|
|
356
|
+
@Controllable('/api/users')
|
|
357
|
+
export class UserController {
|
|
358
|
+
@Post('/')
|
|
359
|
+
create(@Body() data: any) {
|
|
360
|
+
return { created: true }
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
@Get('/')
|
|
364
|
+
list() {
|
|
365
|
+
return [] // GET n'est pas protégé par défaut
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
```
|
|
369
|
+
|
|
370
|
+
#### Options du decorator
|
|
371
|
+
|
|
372
|
+
```typescript
|
|
373
|
+
@CsrfGuard({
|
|
374
|
+
methods: ['POST', 'PUT'], // Méthodes spécifiques
|
|
375
|
+
skipPaths: ['/api/public'], // Chemins exclus
|
|
376
|
+
})
|
|
377
|
+
```
|
|
378
|
+
|
|
379
|
+
### `@CsrfToken()`
|
|
380
|
+
|
|
381
|
+
Injecte le token CSRF dans la réponse pour les routes GET.
|
|
382
|
+
|
|
383
|
+
```typescript
|
|
384
|
+
import { CsrfToken, Controllable, Get } from "raiton/framework"
|
|
385
|
+
|
|
386
|
+
@Controllable('/api/auth')
|
|
387
|
+
export class AuthController {
|
|
388
|
+
@CsrfToken()
|
|
389
|
+
@Get('/csrf-token')
|
|
390
|
+
getCsrfToken() {
|
|
391
|
+
// Le token CSRF sera automatiquement ajouté au header X-CSRF-Token
|
|
392
|
+
return { message: 'Token injected via header' }
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
```
|
|
396
|
+
|
|
397
|
+
### Utilisation combinée
|
|
398
|
+
|
|
399
|
+
```typescript
|
|
400
|
+
@CsrfGuard()
|
|
401
|
+
@Controllable('/api/admin')
|
|
402
|
+
export class AdminController {
|
|
403
|
+
@CsrfToken()
|
|
404
|
+
@Get('/token')
|
|
405
|
+
getToken() {
|
|
406
|
+
return { message: 'Use this token for state-changing requests' }
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
@Post('/settings')
|
|
410
|
+
updateSettings(@Body() data: any) {
|
|
411
|
+
return { updated: true }
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
```
|
|
415
|
+
|
|
416
|
+
---
|
|
417
|
+
|
|
418
|
+
## Sécurité
|
|
419
|
+
|
|
420
|
+
### Bonnes pratiques
|
|
421
|
+
|
|
422
|
+
1. **Utilisez HTTPS en production** et activez `secure: true` sur les cookies
|
|
423
|
+
2. **Configurez SameSite=Strict** si votre app est mono-domaine
|
|
424
|
+
3. **Utilisez un secret fort** (minimum 32 caractères) pour le mode double-submit
|
|
425
|
+
4. **Ne désactivez pas CSRF** pour les routes qui modifient des données
|
|
426
|
+
5. **Exemptez uniquement** les clients qui utilisent des Bearer tokens (JWT)
|
|
427
|
+
|
|
428
|
+
### Headers de sécurité recommandés
|
|
429
|
+
|
|
430
|
+
```typescript
|
|
431
|
+
// Combiner avec les autres plugins de sécurité
|
|
432
|
+
app.register(Security.headers())
|
|
433
|
+
app.register(Security.cors({
|
|
434
|
+
origin: 'https://monapp.com',
|
|
435
|
+
credentials: true,
|
|
436
|
+
}))
|
|
437
|
+
app.register(Security.csrf({
|
|
438
|
+
mode: CSRFModeEnum.DOUBLE_SUBMIT,
|
|
439
|
+
secret: process.env.CSRF_SECRET,
|
|
440
|
+
cookieOptions: {
|
|
441
|
+
secure: true,
|
|
442
|
+
sameSite: 'strict',
|
|
443
|
+
}
|
|
444
|
+
}))
|
|
445
|
+
app.register(Security.rateLimit({ max: 100, windowMs: 60000 }))
|
|
446
|
+
```
|
|
447
|
+
|
|
448
|
+
### Attaques courantes et protections
|
|
449
|
+
|
|
450
|
+
| Attaque | Protection Raiton |
|
|
451
|
+
|---------|-------------------|
|
|
452
|
+
| Cross-Site Request Forgery | Token CSRF dans cookie + header |
|
|
453
|
+
| Token theft via XSS | SameSite=Strict empêche l'envoi cross-origin |
|
|
454
|
+
| Replay attack | TTL configurable + nonce aléatoire |
|
|
455
|
+
| Brute force token | Token de 64 caractères hexadécimaux |
|
|
456
|
+
| Man-in-the-middle | Secure=true (HTTPS uniquement) |
|
|
457
|
+
|
|
458
|
+
---
|
|
459
|
+
|
|
460
|
+
## Dépannage
|
|
461
|
+
|
|
462
|
+
### Erreur 403 "CSRF token missing"
|
|
463
|
+
|
|
464
|
+
**Cause :** Le client envoie un cookie de session mais pas le header `X-CSRF-Token`.
|
|
465
|
+
|
|
466
|
+
**Solution :**
|
|
467
|
+
```javascript
|
|
468
|
+
// Ajouter le header à chaque requête POST/PUT/PATCH/DELETE
|
|
469
|
+
fetch('/api/data', {
|
|
470
|
+
method: 'POST',
|
|
471
|
+
headers: {
|
|
472
|
+
'X-CSRF-Token': getCookie('_csrf'),
|
|
473
|
+
}
|
|
474
|
+
})
|
|
475
|
+
```
|
|
476
|
+
|
|
477
|
+
### Erreur 403 "CSRF token invalid"
|
|
478
|
+
|
|
479
|
+
**Cause :** Le token dans le cookie ne correspond pas au token dans le header.
|
|
480
|
+
|
|
481
|
+
**Solutions possibles :**
|
|
482
|
+
1. Le token a expiré → Rafraîchissez la page pour obtenir un nouveau token
|
|
483
|
+
2. Le cookie a été modifié → Vérifiez que votre JS lit le bon cookie
|
|
484
|
+
3. Le header n'est pas envoyé → Vérifiez le nom du header (défaut: `X-CSRF-Token`)
|
|
485
|
+
|
|
486
|
+
### Erreur 403 sur les apps mobiles
|
|
487
|
+
|
|
488
|
+
**Cause :** Le client mobile n'envoie pas le header `X-Client-Type`.
|
|
489
|
+
|
|
490
|
+
**Solution :**
|
|
491
|
+
```typescript
|
|
492
|
+
// Ajouter le header pour indiquer que c'est un client mobile/desktop
|
|
493
|
+
headers: {
|
|
494
|
+
'X-Client-Type': 'mobile',
|
|
495
|
+
'Authorization': `Bearer ${token}`,
|
|
496
|
+
}
|
|
497
|
+
```
|
|
498
|
+
|
|
499
|
+
### Le token n'est pas rafraîchitt
|
|
500
|
+
|
|
501
|
+
**Cause :** Le middleware CSRF ne s'exécute que sur les requêtes GET/HEAD/OPTIONS.
|
|
502
|
+
|
|
503
|
+
**Solution :** Le token est automatiquement rafraîchi à chaque requête GET. Si vous avez besoin d'un token pour une requête POST, faites d'abord un GET.
|
|
504
|
+
|
|
505
|
+
### Cookies multiples
|
|
506
|
+
|
|
507
|
+
**Cause :** Plusieurs middlewares CSRF définissent le même cookie.
|
|
508
|
+
|
|
509
|
+
**Solution :** Utilisez un seul `Security.csrf()` dans votre application.
|
|
510
|
+
|
|
511
|
+
---
|
|
512
|
+
|
|
513
|
+
## Exemple complet
|
|
514
|
+
|
|
515
|
+
```typescript
|
|
516
|
+
import { Application } from "raiton/application"
|
|
517
|
+
import { Security, CsrfGuard, CsrfToken, CSRFModeEnum } from "raiton/framework"
|
|
518
|
+
|
|
519
|
+
const app = new Application({
|
|
520
|
+
port: 3000,
|
|
521
|
+
hostname: '0.0.0.0',
|
|
522
|
+
})
|
|
523
|
+
|
|
524
|
+
// 1. Activer la protection CSRF
|
|
525
|
+
app.register(Security.csrf({
|
|
526
|
+
mode: CSRFModeEnum.DOUBLE_SUBMIT,
|
|
527
|
+
secret: process.env.CSRF_SECRET ?? 'change-moi-en-production',
|
|
528
|
+
methods: ['POST', 'PUT', 'PATCH', 'DELETE'],
|
|
529
|
+
skipPaths: ['/health'],
|
|
530
|
+
clientDetection: {
|
|
531
|
+
headerName: 'X-Client-Type',
|
|
532
|
+
skipClients: ['mobile', 'desktop'],
|
|
533
|
+
},
|
|
534
|
+
cookieOptions: {
|
|
535
|
+
secure: process.env.NODE_ENV === 'production',
|
|
536
|
+
sameSite: 'lax',
|
|
537
|
+
}
|
|
538
|
+
}))
|
|
539
|
+
|
|
540
|
+
// 2. Route publique pour obtenir le token
|
|
541
|
+
app.get('/csrf-token', (ctx) => {
|
|
542
|
+
return {
|
|
543
|
+
token: ctx.state.csrfToken
|
|
544
|
+
}
|
|
545
|
+
})
|
|
546
|
+
|
|
547
|
+
// 3. Route protégée
|
|
548
|
+
app.post('/api/data', (ctx) => {
|
|
549
|
+
return { success: true, data: ctx.state }
|
|
550
|
+
})
|
|
551
|
+
|
|
552
|
+
app.listen(3000)
|
|
553
|
+
```
|
|
554
|
+
|
|
555
|
+
---
|
|
556
|
+
|
|
557
|
+
[← security](security.md) | [middleware →](middleware.md)
|
|
@@ -11,6 +11,7 @@ Cette section regroupe les décorateurs que vous utilisez pour définir vos cont
|
|
|
11
11
|
- [parameters.md](parameters.md)
|
|
12
12
|
- [injection.md](injection.md)
|
|
13
13
|
- [middleware.md](middleware.md)
|
|
14
|
+
- [cache.md](cache.md)
|
|
14
15
|
- [socket.md](socket.md)
|
|
15
16
|
- [api-tags.md](api-tags.md)
|
|
16
17
|
- [api-operation.md](api-operation.md)
|
|
@@ -21,6 +22,7 @@ Cette section regroupe les décorateurs que vous utilisez pour définir vos cont
|
|
|
21
22
|
- [api-query.md](api-query.md)
|
|
22
23
|
- [route-interaction.md](route-interaction.md)
|
|
23
24
|
- [guard.md](guard.md)
|
|
25
|
+
- [health-check.md](health-check.md)
|
|
24
26
|
- [mcp.md](mcp.md)
|
|
25
27
|
|
|
26
28
|
## Comment lire cette section
|
|
@@ -28,6 +30,7 @@ Cette section regroupe les décorateurs que vous utilisez pour définir vos cont
|
|
|
28
30
|
- commencez par `controllable.md` et `routes.md`
|
|
29
31
|
- utilisez ensuite `parameters.md`, `injection.md` et `middleware.md`
|
|
30
32
|
- documentez vos endpoints temps réel et IA avec `socket.md` et `mcp.md`
|
|
33
|
+
- qualifiez un endpoint de santé avec `health-check.md`
|
|
31
34
|
- terminez par les décorateurs OpenAPI si vous documentez votre API
|
|
32
35
|
|
|
33
36
|
---
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
# `@Cache()`
|
|
2
|
+
|
|
3
|
+
> **Navigation :** [← middleware](middleware.md) | [health-check →](health-check.md)
|
|
4
|
+
|
|
5
|
+
`@Cache()` met en cache la réponse d'une route pendant une durée de vie (`ttl`).
|
|
6
|
+
Tant qu'une entrée est fraîche, le handler **n'est pas re-exécuté** : la réponse
|
|
7
|
+
est servie depuis le cache.
|
|
8
|
+
|
|
9
|
+
## Pourquoi l'utiliser
|
|
10
|
+
|
|
11
|
+
- alléger des endpoints coûteux (lectures DB, calculs, appels externes)
|
|
12
|
+
- réduire la latence perçue sur les données peu volatiles
|
|
13
|
+
- économiser les ressources serveur sur les pics de lecture
|
|
14
|
+
|
|
15
|
+
## Comment l'utiliser
|
|
16
|
+
|
|
17
|
+
- placez `@Cache(options)` sur la méthode d'un contrôleur, après le décorateur de route
|
|
18
|
+
- définissez un `ttl` adapté à la volatilité de vos données
|
|
19
|
+
- segmentez éventuellement le cache avec `vary`
|
|
20
|
+
|
|
21
|
+
## Exemple
|
|
22
|
+
|
|
23
|
+
```typescript
|
|
24
|
+
import { Controllable, Get, Cache } from "raiton/framework"
|
|
25
|
+
|
|
26
|
+
@Controllable("/products")
|
|
27
|
+
export class ProductController {
|
|
28
|
+
@Get("/featured")
|
|
29
|
+
@Cache({ ttl: 60_000 })
|
|
30
|
+
featured() {
|
|
31
|
+
// coûteux : n'est exécuté qu'une fois par minute
|
|
32
|
+
return this.catalogue.featured()
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
## Options
|
|
38
|
+
|
|
39
|
+
| Option | Type | défaut | Description |
|
|
40
|
+
|--------|------|--------|-------------|
|
|
41
|
+
| `ttl` | `number` | `60000` | durée de validité (ms) |
|
|
42
|
+
| `enabled` | `boolean` | `true` | désactiver le cache de la route |
|
|
43
|
+
| `key` | `(context, route?) => string` | auto | clé personnalisée |
|
|
44
|
+
| `vary` | `string[]` | `[]` | en-têtes participant à la clé |
|
|
45
|
+
| `methods` | `string[]` | `['GET', 'HEAD']` | méthodes mises en cache |
|
|
46
|
+
|
|
47
|
+
### Exemple avec `vary`
|
|
48
|
+
|
|
49
|
+
```typescript
|
|
50
|
+
@Get("/")
|
|
51
|
+
@Cache({ ttl: 30_000, vary: ["accept-language"] })
|
|
52
|
+
list() { /* ... */ }
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
## Configuration globale
|
|
56
|
+
|
|
57
|
+
Utilisez `CacheManager` pour les réglages par défaut ou un store alternatif.
|
|
58
|
+
|
|
59
|
+
```typescript
|
|
60
|
+
import { CacheManager } from "raiton/framework"
|
|
61
|
+
|
|
62
|
+
CacheManager.configure({ ttl: 30_000, maxEntries: 5000 })
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
## Avantages
|
|
66
|
+
|
|
67
|
+
- simple : un décorateur, aucun code de cache à écrire
|
|
68
|
+
- personnalisable (TTL, clé, vary, store)
|
|
69
|
+
- se combine avec les ETag pour la validation
|
|
70
|
+
|
|
71
|
+
## Inconvénients
|
|
72
|
+
|
|
73
|
+
- un `ttl` trop long peut servir des données obsolètes
|
|
74
|
+
- le cache est en mémoire par défaut (non partagé entre processus)
|
|
75
|
+
- à n'utiliser que sur des données compatibles avec un léger retard
|
|
76
|
+
|
|
77
|
+
---
|
|
78
|
+
|
|
79
|
+
[← middleware](middleware.md) | [health-check →](health-check.md)
|