yinzerflow 0.4.4 → 0.5.0

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.
@@ -0,0 +1,369 @@
1
+ # 📖 CORS Security
2
+
3
+ YinzerFlow provides built-in CORS support to handle cross-origin requests securely and efficiently. CORS is **disabled by default** for security - enable it only when you need cross-origin access.
4
+
5
+ For detailed configuration examples and patterns, see [Configuration Guide](../configuration/configuration.md).
6
+
7
+ # ⚙️ Usage
8
+
9
+ ## 🎛️ Settings
10
+
11
+ ### enabled — @default <span style="color: #e74c3c">`false`</span>
12
+
13
+ Enable/disable CORS protection.
14
+
15
+ ```typescript
16
+ const app = new YinzerFlow({
17
+ cors: {
18
+ enabled: true // ⚠️ Explicitly enable when needed
19
+ }
20
+ });
21
+ ```
22
+
23
+ <aside>
24
+
25
+ Options: `boolean`
26
+
27
+ - `false`: CORS disabled (default, most secure)
28
+ - `true`: CORS enabled with validation
29
+ </aside>
30
+
31
+ ### origin — @default <span style="color: #f39c12">`'*'`</span>
32
+
33
+ Allowed origins for cross-origin requests.
34
+
35
+ ```typescript
36
+ const app = new YinzerFlow({
37
+ cors: {
38
+ enabled: true,
39
+ origin: 'https://myapp.com' // Single domain
40
+ }
41
+ });
42
+ ```
43
+
44
+ <aside>
45
+
46
+ Options: `string | string[] | RegExp | function | '*'`
47
+
48
+ - `'*'`: Allow all origins (⚠️ cannot use with credentials)
49
+ - `'https://myapp.com'`: Single specific domain
50
+ - `['https://myapp.com', 'https://admin.myapp.com']`: Multiple domains
51
+ - `/^https:\/\/.*\.myapp\.com$/`: RegExp pattern for subdomains
52
+ - `(origin, request) => boolean`: Custom validation function
53
+ </aside>
54
+
55
+ ### methods — @default <span style="color: #2ecc71">`['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS']`</span>
56
+
57
+ Allowed HTTP methods for cross-origin requests.
58
+
59
+ ```typescript
60
+ const app = new YinzerFlow({
61
+ cors: {
62
+ enabled: true,
63
+ methods: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH']
64
+ }
65
+ });
66
+ ```
67
+
68
+ <aside>
69
+
70
+ Options: `string[]`
71
+
72
+ - `['GET', 'POST']`: Minimal methods
73
+ - `['GET', 'POST', 'PUT', 'DELETE']`: Standard REST methods
74
+ - `['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS']`: Extended methods
75
+ </aside>
76
+
77
+ ### allowedHeaders — @default <span style="color: #2ecc71">`['*']`</span>
78
+
79
+ Allowed request headers for cross-origin requests.
80
+
81
+ ```typescript
82
+ const app = new YinzerFlow({
83
+ cors: {
84
+ enabled: true,
85
+ allowedHeaders: ['Content-Type', 'Authorization', 'X-CSRF-Token']
86
+ }
87
+ });
88
+ ```
89
+
90
+ <aside>
91
+
92
+ Options: `string | string[]`
93
+
94
+ - `'Content-Type'`: Single header
95
+ - `['Content-Type', 'Authorization']`: Multiple headers
96
+ - `'*'`: Allow all headers (less secure)
97
+ </aside>
98
+
99
+ ### exposedHeaders — @default <span style="color: #2ecc71">`[]`</span>
100
+
101
+ Headers exposed to the client in CORS responses.
102
+
103
+ ```typescript
104
+ const app = new YinzerFlow({
105
+ cors: {
106
+ enabled: true,
107
+ exposedHeaders: ['X-Total-Count', 'X-Page-Count']
108
+ }
109
+ });
110
+ ```
111
+
112
+ <aside>
113
+
114
+ Options: `string[]`
115
+
116
+ - `[]`: No exposed headers (default)
117
+ - `['X-Total-Count']`: Custom pagination headers
118
+ - `['X-Total-Count', 'X-Page-Count', 'X-Rate-Limit']`: Multiple custom headers
119
+ </aside>
120
+
121
+ ### credentials — @default <span style="color: #e74c3c">`false`</span>
122
+
123
+ Allow credentials (cookies, authorization headers) in cross-origin requests.
124
+
125
+ ```typescript
126
+ const app = new YinzerFlow({
127
+ cors: {
128
+ enabled: true,
129
+ origin: ['https://myapp.com'],
130
+ credentials: true // ✅ Safe with specific origins
131
+ }
132
+ });
133
+ ```
134
+
135
+ <aside>
136
+
137
+ Options: `boolean`
138
+
139
+ - `false`: No credentials allowed (default)
140
+ - `true`: Allow credentials (requires specific origins, not '*')
141
+ </aside>
142
+
143
+ ### maxAge — @default <span style="color: #2ecc71">`86400`</span> (24 hours)
144
+
145
+ Maximum age (in seconds) for preflight cache.
146
+
147
+ ```typescript
148
+ const app = new YinzerFlow({
149
+ cors: {
150
+ enabled: true,
151
+ maxAge: 86400 // 24 hours preflight cache
152
+ }
153
+ });
154
+ ```
155
+
156
+ <aside>
157
+
158
+ Options: `number` (in seconds)
159
+
160
+ - `0`: No preflight caching
161
+ - `3600`: 1 hour cache
162
+ - `86400`: 24 hours cache (default)
163
+ - `604800`: 7 days cache
164
+ </aside>
165
+
166
+ ### preflightContinue — @default <span style="color: #2ecc71">`false`</span>
167
+
168
+ Continue to route handler after preflight.
169
+
170
+ ```typescript
171
+ const app = new YinzerFlow({
172
+ cors: {
173
+ enabled: true,
174
+ preflightContinue: false // ✅ Recommended: handle preflight completely
175
+ }
176
+ });
177
+ ```
178
+
179
+ <aside>
180
+
181
+ Options: `boolean`
182
+
183
+ - `false`: Handle preflight completely in CORS system (recommended)
184
+ - `true`: Pass preflight to route handlers (requires manual OPTIONS routes)
185
+ </aside>
186
+
187
+ ### optionsSuccessStatus — @default <span style="color: #2ecc71">`204`</span>
188
+
189
+ Status code for successful OPTIONS requests.
190
+
191
+ ```typescript
192
+ const app = new YinzerFlow({
193
+ cors: {
194
+ enabled: true,
195
+ optionsSuccessStatus: 204 // No Content
196
+ }
197
+ });
198
+ ```
199
+
200
+ <aside>
201
+
202
+ Options: `number`
203
+
204
+ - `200`: OK (some older clients expect this)
205
+ - `204`: No Content (default, recommended)
206
+ - `204`: Most common and recommended
207
+ </aside>
208
+
209
+ # ✨ Best Practices
210
+
211
+ - **Use specific origins** instead of wildcards when possible
212
+ - **Enable credentials only when needed** and with specific origins
213
+ - **Restrict methods** to only those your API actually uses
214
+ - **Limit allowed headers** to prevent unnecessary exposure
215
+ - **Set appropriate maxAge** for preflight caching
216
+ - **Test CORS configuration** thoroughly before deployment
217
+ - **Monitor CORS errors** in production logs
218
+
219
+ # 💻 Examples
220
+
221
+ ### Production API
222
+
223
+ **Use Case:** Secure web application with authenticated cross-origin requests
224
+
225
+ **Description:** Production-ready CORS configuration with specific origins, credentials support, and restricted methods/headers for maximum security.
226
+
227
+ ```typescript
228
+ import { YinzerFlow } from 'yinzerflow';
229
+
230
+ const app = new YinzerFlow({
231
+ port: 3000,
232
+ cors: {
233
+ enabled: true,
234
+ origin: ['https://myapp.com', 'https://admin.myapp.com'], // Specific domains
235
+ credentials: true, // Allow cookies/auth headers
236
+ methods: ['GET', 'POST', 'PUT', 'DELETE'], // Standard REST methods
237
+ allowedHeaders: ['Content-Type', 'Authorization', 'X-CSRF-Token'], // Essential headers
238
+ exposedHeaders: ['X-Total-Count'], // Headers exposed to client
239
+ maxAge: 86400, // Preflight cache duration (24h)
240
+ optionsSuccessStatus: 204, // Status code for successful OPTIONS
241
+ preflightContinue: false // Stop after preflight (recommended)
242
+ }
243
+ });
244
+
245
+ app.get('/api/users', ({ request }) => {
246
+ // CORS validation happens automatically
247
+ return { users: [] };
248
+ });
249
+
250
+ await app.listen();
251
+ ```
252
+
253
+ ### Dev API
254
+
255
+ **Use Case:** Development server with permissive CORS for local development
256
+
257
+ **Description:** Development configuration with multiple localhost origins and relaxed settings for easier debugging and testing.
258
+
259
+ ```typescript
260
+ import { YinzerFlow } from 'yinzerflow';
261
+
262
+ const app = new YinzerFlow({
263
+ port: 3000,
264
+ cors: {
265
+ enabled: true,
266
+ origin: [
267
+ 'http://localhost:3000',
268
+ 'http://localhost:3001',
269
+ 'http://127.0.0.1:3000'
270
+ ], // Multiple localhost origins
271
+ credentials: true,
272
+ methods: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS'], // All methods for dev
273
+ allowedHeaders: ['*'], // Allow all headers in dev
274
+ exposedHeaders: [], // No exposed headers in dev
275
+ maxAge: 0, // No preflight caching in dev
276
+ optionsSuccessStatus: 204,
277
+ preflightContinue: false
278
+ }
279
+ });
280
+
281
+ app.get('/api/test', ({ request }) => {
282
+ return { message: 'Development mode' };
283
+ });
284
+
285
+ await app.listen();
286
+ ```
287
+
288
+ ## 🚀 Performance Notes
289
+
290
+ - **Preflight caching**: `maxAge` setting reduces OPTIONS requests
291
+ - **Origin validation**: O(1) constant time for string/array origins
292
+ - **Header processing**: Minimal overhead for standard headers
293
+ - **Memory usage**: Negligible impact on request processing
294
+
295
+ ## 🔒 Security Notes
296
+
297
+ YinzerFlow implements several security measures to prevent common CORS vulnerabilities:
298
+
299
+ ### 🛡️ Origin Validation Enforcement
300
+ - **Problem**: Many frameworks validate origins but don't enforce the validation result
301
+ - **YinzerFlow Solution**: Origin validation results are actually used - unauthorized requests get 403 Forbidden
302
+
303
+ ### 🛡️ Spec Compliance Enforcement
304
+ - **Problem**: CORS spec forbids `origin: '*'` with `credentials: true`, but many frameworks allow this dangerous combination
305
+ - **YinzerFlow Solution**: This combination throws a security error at startup, preventing deployment of vulnerable configurations
306
+
307
+ ### 🛡️ No Origin Echo-back for Wildcards
308
+ - **Problem**: Some implementations echo back the request origin when using wildcards, defeating CORS protection
309
+ - **YinzerFlow Solution**: Wildcard origins always return literal `'*'`, never echo back request origins
310
+
311
+ ### 🛡️ Proper Preflight Rejection
312
+ - **Problem**: Some frameworks set CORS headers even for rejected requests, or let request handlers override CORS rejections
313
+ - **YinzerFlow Solution**: Unauthorized preflight requests get 403 with no CORS headers, and the rejection cannot be overridden
314
+
315
+ ### 🛡️ Case-Insensitive Origin Matching
316
+ - **Problem**: Inconsistent case handling can lead to bypass attempts
317
+ - **YinzerFlow Solution**: All origin validation is case-insensitive but preserves original case in responses
318
+
319
+ ## 🔧 Troubleshooting
320
+
321
+ ### CORS Error: "Origin not allowed"
322
+ - **Problem**: Request origin not in allowed list
323
+ - **Fix**: Add origin to configuration or check for typos
324
+
325
+ ```typescript
326
+ // ❌ Wrong
327
+ cors: { origin: 'https://myapp.com' } // Missing 's' in https
328
+
329
+ // ✅ Correct
330
+ cors: { origin: 'https://myapp.com' } // Exact match required
331
+ ```
332
+
333
+ ### CORS Error: "credentials: true with origin: '*'"
334
+ - **Problem**: Wildcard origin with credentials violates CORS spec
335
+ - **Fix**: Use specific origins or disable credentials
336
+
337
+ ```typescript
338
+ // ❌ Wrong
339
+ cors: { origin: '*', credentials: true }
340
+
341
+ // ✅ Correct
342
+ cors: { origin: ['https://myapp.com'], credentials: true }
343
+ // or
344
+ cors: { origin: '*', credentials: false }
345
+ ```
346
+
347
+ ### Preflight Request Fails
348
+ - **Problem**: Method or header not allowed
349
+ - **Fix**: Add method/header to configuration
350
+
351
+ ```typescript
352
+ // ❌ Request uses PATCH but not allowed
353
+ cors: { methods: ['GET', 'POST'] }
354
+
355
+ // ✅ Add PATCH to allowed methods
356
+ cors: { methods: ['GET', 'POST', 'PATCH'] }
357
+ ```
358
+
359
+ ### Credentials Not Sent
360
+ - **Problem**: Server doesn't allow credentials or client doesn't send them
361
+ - **Fix**: Enable credentials on both sides
362
+
363
+ ```typescript
364
+ // Server side
365
+ cors: { credentials: true }
366
+
367
+ // Client side
368
+ fetch(url, { credentials: 'include' })
369
+ ```
@@ -0,0 +1,125 @@
1
+ # 📦 Modules
2
+
3
+ YinzerFlow's modular architecture provides built-in modules for common web development needs. Each module is self-contained and can be configured independently.
4
+
5
+ ## Available Modules
6
+
7
+ ### 🛡️ Security Modules
8
+
9
+ #### [Rate Limiting](rate-limiting.md)
10
+ Protect your API from abuse and DoS attacks with configurable rate limiting.
11
+
12
+ - **Sliding Window Counter** algorithm for accurate rate limiting
13
+ - **Global and per-route** limits
14
+ - **Custom key generators** for authenticated users
15
+ - **Memory efficient** with automatic cleanup
16
+ - **Standard headers** for client feedback
17
+
18
+ #### [CORS](cors.md)
19
+ Handle cross-origin requests securely with comprehensive CORS support.
20
+
21
+ - **Origin validation** with wildcard and regex support
22
+ - **Preflight handling** for complex requests
23
+ - **Credential support** for authenticated requests
24
+ - **Custom headers** and methods configuration
25
+ - **Security-first defaults** (disabled by default)
26
+
27
+ #### [IP Security](ip-security.md)
28
+ Advanced IP address validation and security features.
29
+
30
+ - **Private IP detection** and handling
31
+ - **Trusted proxy support** for load balancers
32
+ - **Spoofing detection** with pattern analysis
33
+ - **Configurable chain length** limits
34
+ - **Security logging** for suspicious activity
35
+
36
+ #### [Body Parsing](body-parsing.md)
37
+ Secure and efficient request body parsing with comprehensive validation.
38
+
39
+ - **JSON parsing** with size limits and validation
40
+ - **Form data handling** with file upload support
41
+ - **URL-encoded data** parsing
42
+ - **Text content** processing
43
+ - **Security protections** against common attacks
44
+
45
+ ## Module Configuration
46
+
47
+ All modules can be configured through the main YinzerFlow constructor:
48
+
49
+ ```typescript
50
+ import { YinzerFlow } from 'yinzerflow';
51
+
52
+ const app = new YinzerFlow({
53
+ // Rate limiting configuration
54
+ rateLimit: {
55
+ enabled: true,
56
+ windowMs: 900000, // 15 minutes
57
+ max: 100 // 100 requests per window
58
+ },
59
+
60
+ // CORS configuration
61
+ cors: {
62
+ enabled: true,
63
+ origin: ['https://app.example.com'],
64
+ credentials: true
65
+ },
66
+
67
+ // IP security configuration
68
+ ipSecurity: {
69
+ enabled: true,
70
+ trustProxy: true,
71
+ maxChainLength: 5
72
+ },
73
+
74
+ // Body parsing configuration
75
+ bodyParser: {
76
+ json: {
77
+ maxSize: 262144 // 256KB
78
+ },
79
+ form: {
80
+ maxFields: 1000
81
+ }
82
+ }
83
+ });
84
+ ```
85
+
86
+ ## Module Features
87
+
88
+ ### 🔧 Easy Configuration
89
+ - **Sensible defaults** - Works out of the box
90
+ - **Type-safe options** - Full TypeScript support
91
+ - **Validation** - Built-in configuration validation
92
+ - **Warnings** - Helpful warnings for misconfigurations
93
+
94
+ ### 🚀 Performance Optimized
95
+ - **Memory efficient** - Minimal overhead
96
+ - **Fast execution** - Optimized algorithms
97
+ - **Automatic cleanup** - No memory leaks
98
+ - **Scalable** - Handles high traffic
99
+
100
+ ### 🛡️ Security First
101
+ - **Built-in protections** - Common vulnerabilities covered
102
+ - **Secure defaults** - Safe out of the box
103
+ - **Validation** - Input validation and sanitization
104
+ - **Logging** - Security event logging
105
+
106
+ ### 📚 Comprehensive Documentation
107
+ - **Detailed guides** - Step-by-step instructions
108
+ - **Examples** - Real-world usage patterns
109
+ - **Troubleshooting** - Common issues and solutions
110
+ - **Best practices** - Recommended configurations
111
+
112
+ ## Getting Started with Modules
113
+
114
+ 1. **Choose your modules** - Select the modules you need for your application
115
+ 2. **Configure options** - Set up module-specific configuration
116
+ 3. **Test thoroughly** - Verify module behavior in your environment
117
+ 4. **Monitor performance** - Use built-in logging and metrics
118
+ 5. **Scale as needed** - Adjust configuration for production loads
119
+
120
+ ## Need Help?
121
+
122
+ - **Module-specific guides** - Each module has detailed documentation
123
+ - **Configuration examples** - See [Configuration Guide](../configuration/configuration.md)
124
+ - **Troubleshooting** - Check individual module troubleshooting sections
125
+ - **Best practices** - Follow security and performance recommendations