-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsecurity-hardened.ts
More file actions
786 lines (739 loc) Β· 25.6 KB
/
security-hardened.ts
File metadata and controls
786 lines (739 loc) Β· 25.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
/**
* Comprehensive Security Hardening Example
*
* This example demonstrates ALL security features available in Bungate for a
* production-ready API gateway with maximum security hardening and defense-in-depth.
*
* βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
* SECURITY LAYERS DEMONSTRATED:
* βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
*
* π TRANSPORT LAYER SECURITY
* - TLS 1.3 enforcement with strong cipher suites
* - HTTP to HTTPS automatic redirect
* - HSTS with preload for browser security
*
* π‘οΈ INPUT VALIDATION & SANITIZATION
* - Path length and character validation
* - Header size and count limits
* - Blocked patterns (XSS, SQL injection, traversal)
* - Header sanitization
*
* π AUTHENTICATION & AUTHORIZATION
* - JWT authentication with key rotation
* - API key authentication
* - Role-based access control (RBAC)
* - Multi-secret support with graceful rotation
*
* π¦ RATE LIMITING & ABUSE PREVENTION
* - Per-user rate limiting with JWT context
* - Per-endpoint rate limit policies
* - API key-based rate limiting
*
* π SECURITY HEADERS
* - Strict-Transport-Security (HSTS)
* - Content-Security-Policy (CSP)
* - X-Frame-Options (clickjacking protection)
* - X-Content-Type-Options (MIME sniffing prevention)
* - Referrer-Policy
* - Permissions-Policy
*
* π REQUEST/RESPONSE MONITORING
* - Request size limits (body, headers, URL)
* - Response payload monitoring
* - Comprehensive error handling
* - Secure error messages (no stack traces in prod)
*
* π NETWORK SECURITY
* - Trusted proxy validation (Cloudflare, AWS, etc.)
* - IP whitelist/blacklist support
* - X-Forwarded-For depth limiting
* - CORS validation with credentials support
*
* πΎ SESSION MANAGEMENT
* - High-entropy session IDs (128+ bits)
* - Secure cookie configuration
* - HTTPOnly and SameSite flags
* - Session timeout and rotation
*
* π CIRCUIT BREAKER & RESILIENCE
* - Backend failure detection
* - Automatic circuit opening/closing
* - Timeout configuration
* - Fallback responses
*
* π οΈ CSRF PROTECTION
* - Token-based CSRF prevention
* - Double-submit cookie pattern
* - Path and method exclusions
*
* Run this example:
* bun run examples/security-hardened.ts
*
* Test endpoints:
* # Health check (public)
* curl -k https://localhost:3443/health
*
* # API with key
* curl -k -H "x-api-key: public-key-1" https://localhost:3443/api/public/test
*
* # Generate JWT for testing
* # Use: https://jwt.io with secret: primary-secret-key
*
* # Protected endpoint
* curl -k -H "Authorization: Bearer YOUR_JWT_TOKEN" https://localhost:3443/api/users/123
*
* # Admin endpoint (requires admin role in JWT)
* curl -k -H "Authorization: Bearer YOUR_ADMIN_JWT_TOKEN" https://localhost:3443/api/admin/settings
*
* # View security headers
* curl -I -k https://localhost:3443/health
*
* # Test HTTP redirect
* curl -L http://localhost:3080/health
*/
import { BunGateway } from '../src/index'
import { BunGateLogger } from '../src/logger/pino-logger'
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
// ENVIRONMENT CONFIGURATION
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
/**
* Load secrets from environment variables in production
* Never hardcode secrets in your code!
*/
const config = {
// TLS Certificates
tlsCert: process.env.TLS_CERT_PATH || './examples/cert.pem',
tlsKey: process.env.TLS_KEY_PATH || './examples/key.pem',
// JWT Secrets (use strong, random keys in production)
jwtPrimary: process.env.JWT_SECRET_PRIMARY || 'primary-secret-key',
jwtOld: process.env.JWT_SECRET_OLD || 'old-secret-key',
// API Keys
publicApiKeys: (process.env.PUBLIC_API_KEYS || '').split(',').filter(Boolean)
.length
? process.env.PUBLIC_API_KEYS!.split(',')
: ['public-key-1', 'public-key-2', 'public-key-3'],
metricsApiKey: process.env.METRICS_API_KEY || 'metrics-secret-key',
// Server Ports
httpsPort: parseInt(process.env.HTTPS_PORT || '3443'),
httpPort: parseInt(process.env.HTTP_PORT || '3080'),
// CORS Origins
corsOrigins: process.env.CORS_ORIGINS?.split(',') || [
'https://app.example.com',
'https://admin.example.com',
],
// Backend Targets
backendTargets: process.env.BACKEND_TARGETS?.split(',') || [
'http://localhost:8080',
'http://localhost:8081',
],
}
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
// LOGGER CONFIGURATION
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
// Create structured logger with request correlation
const logger = new BunGateLogger({
level: 'info',
format: 'pretty',
enableRequestLogging: true,
})
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
// GATEWAY CONFIGURATION
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
// Create gateway with comprehensive security configuration
const gateway = new BunGateway({
server: {
port: config.httpsPort,
development: false,
},
logger,
// Security configuration
security: {
// TLS/HTTPS configuration
tls: {
enabled: true,
cert: config.tlsCert,
key: config.tlsKey,
minVersion: 'TLSv1.3', // Enforce TLS 1.3 only (most secure)
cipherSuites: [
'TLS_AES_256_GCM_SHA384', // AES-256 with GCM
'TLS_CHACHA20_POLY1305_SHA256', // ChaCha20 (faster on mobile)
],
redirectHTTP: true,
redirectPort: config.httpPort,
},
// Input validation
inputValidation: {
maxPathLength: 2048,
maxHeaderSize: 16384,
maxHeaderCount: 100,
allowedPathChars: /^[a-zA-Z0-9\/_\-\.~%]+$/,
blockedPatterns: [
/\.\./, // Directory traversal
/%00/, // Null byte injection
/<script>/i, // XSS attempts
/javascript:/i, // JavaScript protocol
],
sanitizeHeaders: true,
},
// Secure error handling
errorHandling: {
production: true,
includeStackTrace: false,
logErrors: true,
sanitizeBackendErrors: true,
customMessages: {
500: 'An internal error occurred',
502: 'Service temporarily unavailable',
503: 'Service unavailable',
504: 'Request timeout',
},
},
// Session management
sessions: {
entropyBits: 128,
ttl: 3600000, // 1 hour
cookieOptions: {
secure: true,
httpOnly: true,
sameSite: 'strict',
},
},
// Trusted proxy configuration
trustedProxies: {
enabled: true,
trustedIPs: ['10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16'],
trustedNetworks: ['cloudflare'],
maxForwardedDepth: 2,
},
// Security headers
securityHeaders: {
enabled: true,
hsts: {
maxAge: 31536000, // 1 year
includeSubDomains: true,
preload: true,
},
contentSecurityPolicy: {
directives: {
'default-src': ["'self'"],
'script-src': ["'self'"],
'style-src': ["'self'"],
'img-src': ["'self'", 'https:'],
'connect-src': ["'self'"],
'font-src': ["'self'"],
'object-src': ["'none'"],
'frame-ancestors': ["'none'"],
'base-uri': ["'self'"],
'form-action': ["'self'"],
},
reportOnly: false,
},
xFrameOptions: 'DENY',
xContentTypeOptions: true,
referrerPolicy: 'strict-origin-when-cross-origin',
permissionsPolicy: {
camera: [],
microphone: [],
geolocation: ["'self'"],
payment: ["'self'"],
},
},
// Request size limits
sizeLimits: {
maxBodySize: 10 * 1024 * 1024, // 10 MB
maxHeaderSize: 16 * 1024, // 16 KB
maxHeaderCount: 100,
maxUrlLength: 2048,
maxQueryParams: 100,
},
// NOTE: JWT Key Rotation Configuration
// The security.jwtKeyRotation config exists but is NOT automatically integrated
// into the gateway. For key rotation, you need to manually use JWTKeyRotationManager
// or implement multiple secrets per route. See src/security/jwt-key-rotation.ts
//
// TODO: Future enhancement - integrate JWTKeyRotationManager into gateway
// to automatically apply key rotation from security.jwtKeyRotation config
// CSRF protection
csrf: {
enabled: true,
tokenLength: 32,
cookieName: 'bungate_csrf',
headerName: 'X-CSRF-Token',
excludeMethods: ['GET', 'HEAD', 'OPTIONS'],
excludePaths: ['/health', '/api/public/*'],
sameSiteStrict: true,
},
// CORS validation (strict mode)
corsValidation: {
strictMode: true,
allowWildcardWithCredentials: false,
maxOrigins: 10,
requireHttps: true,
},
// Payload monitoring
payloadMonitor: {
maxResponseSize: 100 * 1024 * 1024, // 100 MB
trackMetrics: true,
abortOnLimit: true,
warnThreshold: 0.8, // Warn at 80% of limit
},
},
// CORS configuration (Cross-Origin Resource Sharing)
cors: {
origin: config.corsOrigins, // Explicitly allowed origins
credentials: true, // Allow cookies/auth headers
methods: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH'],
allowedHeaders: ['Content-Type', 'Authorization', 'X-CSRF-Token'],
exposedHeaders: ['X-Request-ID', 'X-RateLimit-Remaining'],
maxAge: 86400, // Cache preflight for 24 hours
},
// Routes configuration
routes: [
// Public health check endpoint (no authentication)
{
pattern: '/health',
handler: async () => {
return new Response(
JSON.stringify({
status: 'healthy',
timestamp: new Date().toISOString(),
}),
{
headers: { 'Content-Type': 'application/json' },
},
)
},
},
// Protected API endpoints with JWT authentication
{
pattern: '/api/users/*',
handler: async (req) => {
// In a real application, this would proxy to a backend service
const user = (req as any).jwt
return new Response(
JSON.stringify({
message: 'User endpoint',
user: {
id: user?.userId,
role: user?.role,
},
}),
{
headers: { 'Content-Type': 'application/json' },
},
)
},
auth: {
secret: config.jwtPrimary,
jwtOptions: {
algorithms: ['HS256'],
issuer: 'https://auth.example.com',
audience: 'https://api.example.com',
},
},
rateLimit: {
max: 100,
windowMs: 60000,
keyGenerator: (req) => {
return (
(req as any).jwt?.userId ||
req.headers.get('x-forwarded-for') ||
'unknown'
)
},
},
},
// Admin endpoints with stricter rate limiting
{
pattern: '/api/admin/*',
handler: async (req) => {
const user = (req as any).jwt
// Check admin role
if (user?.role !== 'admin') {
return new Response(JSON.stringify({ error: 'Forbidden' }), {
status: 403,
headers: { 'Content-Type': 'application/json' },
})
}
return new Response(
JSON.stringify({
message: 'Admin endpoint',
user: {
id: user.userId,
role: user.role,
},
}),
{
headers: { 'Content-Type': 'application/json' },
},
)
},
auth: {
secret: config.jwtPrimary,
jwtOptions: {
algorithms: ['HS256'],
issuer: 'https://auth.example.com',
audience: 'https://api.example.com',
},
},
rateLimit: {
max: 50,
windowMs: 60000,
},
},
// Public API endpoint with API key authentication
{
pattern: '/api/public/*',
handler: async (req) => {
return new Response(
JSON.stringify({
message: 'Public API endpoint',
timestamp: new Date().toISOString(),
path: new URL(req.url).pathname,
}),
{
headers: { 'Content-Type': 'application/json' },
},
)
},
auth: {
apiKeys: config.publicApiKeys,
apiKeyHeader: 'x-api-key',
},
rateLimit: {
max: 1000,
windowMs: 60000,
},
},
// Load-balanced backend with circuit breaker
{
pattern: '/api/backend/*',
loadBalancer: {
strategy: 'least-connections', // Route to least busy server
targets: config.backendTargets.map((url, index) => ({
url,
weight: index === 0 ? 2 : 1, // First server gets 2x traffic
})),
healthCheck: {
enabled: true,
interval: 5000,
timeout: 2000,
path: '/health',
expectedStatus: 200,
},
},
circuitBreaker: {
enabled: true,
failureThreshold: 5,
resetTimeout: 30000,
timeout: 5000,
},
proxy: {
pathRewrite: (path) => path.replace('/api/backend', ''),
headers: {
'X-Gateway-Version': '1.0',
'X-Forwarded-Proto': 'https',
},
},
rateLimit: {
max: 200,
windowMs: 60000,
},
hooks: {
afterCircuitBreakerExecution: async (req, result) => {
if (!result.success) {
logger.warn(
`Circuit breaker failed for ${req.url}: ${result.error}`,
)
}
},
},
},
// File upload endpoint with size validation
{
pattern: '/api/upload',
handler: async (req) => {
const contentLength = req.headers.get('content-length')
const maxSize = 5 * 1024 * 1024 // 5 MB
if (contentLength && parseInt(contentLength) > maxSize) {
return new Response(
JSON.stringify({
error: 'File too large',
maxSize: '5MB',
}),
{
status: 413,
headers: { 'Content-Type': 'application/json' },
},
)
}
// Handle file upload
return new Response(
JSON.stringify({
message: 'File uploaded successfully',
size: contentLength,
}),
{
headers: { 'Content-Type': 'application/json' },
},
)
},
auth: {
secret: config.jwtPrimary,
},
rateLimit: {
max: 10, // 10 uploads per minute
windowMs: 60000,
},
},
// WebSocket upgrade endpoint (example)
{
pattern: '/ws',
handler: async (req) => {
// WebSocket upgrade logic would go here
return new Response(
JSON.stringify({
message: 'WebSocket endpoint',
note: 'Use appropriate WebSocket client',
}),
{
headers: { 'Content-Type': 'application/json' },
},
)
},
rateLimit: {
max: 100,
windowMs: 60000,
},
},
// Metrics endpoint (protected with API key)
{
pattern: '/metrics',
handler: async (req) => {
// In production, this would return Prometheus metrics
return new Response(
JSON.stringify({
metrics: {
requests_total: 12345,
requests_per_second: 42,
active_connections: 15,
circuit_breakers_open: 0,
},
}),
{
headers: { 'Content-Type': 'application/json' },
},
)
},
auth: {
apiKeys: [config.metricsApiKey],
apiKeyHeader: 'x-metrics-key',
},
},
],
})
// Start the gateway
const server = await gateway.listen()
// Display comprehensive startup information
logger.info('')
logger.info('βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ')
logger.info('π SECURITY-HARDENED GATEWAY STARTED')
logger.info('βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ')
logger.info('')
logger.info('π‘ Server Configuration:')
logger.info(' β’ HTTPS: https://localhost:3443')
logger.info(' β’ HTTP Redirect: http://localhost:3080 β https://localhost:3443')
logger.info('')
logger.info('π‘οΈ Security Features Active:')
logger.info(' β TLS 1.3 with AES-256-GCM & ChaCha20-Poly1305')
logger.info(' β HTTP Strict Transport Security (HSTS) - 1 year')
logger.info(' β Content Security Policy (CSP)')
logger.info(' β Input validation & sanitization')
logger.info(' β Request size limits (10MB body, 16KB headers)')
logger.info(' β Security headers (X-Frame, X-Content-Type, Referrer)')
logger.info(' β JWT authentication with key rotation')
logger.info(' β CSRF protection (token-based)')
logger.info(' β Rate limiting (per-user & per-endpoint)')
logger.info(' β Session management (secure cookies)')
logger.info(' β Trusted proxy validation (Cloudflare, RFC1918)')
logger.info(' β CORS validation (strict mode)')
logger.info(' β Payload monitoring (100MB limit)')
logger.info(' β Circuit breaker pattern')
logger.info(' β Secure error handling (no stack traces)')
logger.info('')
logger.info('π Available Endpoints:')
logger.info(' Public:')
logger.info(' GET /health - Health check')
logger.info(
' * /api/public/* - Public API (requires x-api-key)',
)
logger.info(' Protected (JWT):')
logger.info(' * /api/users/* - User endpoints')
logger.info(' POST /api/upload - File upload (5MB max)')
logger.info(' Admin Only (JWT + role):')
logger.info(' * /api/admin/* - Admin endpoints')
logger.info(' Infrastructure:')
logger.info(' * /api/backend/* - Load balanced backend')
logger.info(' GET /ws - WebSocket endpoint')
logger.info(
' GET /metrics - Metrics (requires x-metrics-key)',
)
logger.info('')
logger.info('π§ͺ Testing Commands:')
logger.info('')
logger.info(' # Check health & security headers')
logger.info(' curl -I -k https://localhost:3443/health')
logger.info('')
logger.info(' # Test HTTP β HTTPS redirect')
logger.info(' curl -L http://localhost:3080/health')
logger.info('')
logger.info(' # Public API with API key')
logger.info(
' curl -k -H "x-api-key: public-key-1" https://localhost:3443/api/public/test',
)
logger.info('')
logger.info(' # Generate JWT token for testing:')
logger.info(' # Go to https://jwt.io and create a token with:')
logger.info(' # Secret: primary-secret-key')
logger.info(' # Payload: { "userId": "123", "role": "user" }')
logger.info('')
logger.info(' # Protected endpoint with JWT')
logger.info(
' curl -k -H "Authorization: Bearer YOUR_JWT" https://localhost:3443/api/users/profile',
)
logger.info('')
logger.info(' # Admin endpoint (requires role: admin)')
logger.info(
' curl -k -H "Authorization: Bearer ADMIN_JWT" https://localhost:3443/api/admin/settings',
)
logger.info('')
logger.info(' # View metrics')
logger.info(
' curl -k -H "x-metrics-key: metrics-secret-key" https://localhost:3443/metrics',
)
logger.info('')
logger.info('βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ')
logger.info('Press Ctrl+C to shutdown gracefully')
logger.info('βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ')
logger.info('')
// Graceful shutdown handlers
const shutdown = async (signal: string) => {
logger.info('')
logger.info(`Received ${signal}, initiating graceful shutdown...`)
try {
// Close the gateway gracefully
await gateway.close()
logger.info('β Gateway closed successfully')
logger.info('β All connections drained')
logger.info('β Cleanup completed')
logger.info('')
logger.info('Goodbye! π')
process.exit(0)
} catch (error) {
logger.error('Error during shutdown', error as Error)
process.exit(1)
}
}
process.on('SIGINT', () => shutdown('SIGINT'))
process.on('SIGTERM', () => shutdown('SIGTERM'))
// Handle uncaught exceptions
process.on('uncaughtException', (error) => {
logger.error('Uncaught Exception', error)
shutdown('uncaughtException')
})
// Handle unhandled promise rejections
process.on('unhandledRejection', (reason) => {
logger.error('Unhandled Rejection', reason as Error)
shutdown('unhandledRejection')
})
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
// PRODUCTION DEPLOYMENT CHECKLIST
// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
/**
* Before deploying to production, ensure you:
*
* 1. CERTIFICATES & SECRETS
* β Replace self-signed certificates with CA-signed certificates
* β Use Let's Encrypt or commercial CA (DigiCert, GlobalSign)
* β Store secrets in environment variables or secret manager
* β Generate strong, random JWT secrets (256+ bits)
* β Set proper file permissions (600 for keys, 644 for certs)
* β Never commit secrets to version control
* β Implement certificate rotation strategy
* β Monitor certificate expiration dates
*
* 2. SECURITY CONFIGURATION
* β Enable TLS 1.3 (or minimum TLS 1.2)
* β Use strong cipher suites only
* β Enable HSTS with preload
* β Configure strict CSP policies
* β Enable CSRF protection
* β Set appropriate CORS origins (no wildcards with credentials)
* β Configure trusted proxy IPs/networks
* β Set appropriate rate limits
* β Enable payload monitoring
*
* 3. ERROR HANDLING
* β Set production: true in errorHandling config
* β Disable stack traces in responses
* β Sanitize backend errors
* β Configure custom error messages
* β Set up error logging/monitoring
*
* 4. AUTHENTICATION & AUTHORIZATION
* β Implement proper JWT validation
* β Set up key rotation schedule
* β Use different secrets per environment
* β Implement role-based access control
* β Validate JWT issuer and audience
* β Set appropriate token expiration times
*
* 5. MONITORING & LOGGING
* β Configure structured logging
* β Set up log aggregation (ELK, Datadog, etc.)
* β Enable request correlation IDs
* β Monitor rate limit violations
* β Track circuit breaker events
* β Set up alerts for security events
* β Monitor certificate expiration
*
* 6. PERFORMANCE & SCALING
* β Enable cluster mode for multi-core utilization
* β Configure appropriate worker count
* β Set up load balancing health checks
* β Configure circuit breaker thresholds
* β Optimize rate limit windows
* β Set appropriate timeout values
*
* 7. INFRASTRUCTURE
* β Run behind a load balancer (AWS ALB, Nginx, etc.)
* β Configure WAF rules
* β Set up DDoS protection (Cloudflare, AWS Shield)
* β Enable auto-scaling
* β Configure health check endpoints
* β Set up backup and disaster recovery
*
* 8. TESTING
* β Test with SSL Labs (https://www.ssllabs.com/ssltest/)
* β Run security headers test (https://securityheaders.com/)
* β Perform penetration testing
* β Load test with realistic traffic
* β Test certificate rotation process
* β Test graceful shutdown
* β Test failover scenarios
*
* 9. COMPLIANCE
* β Review GDPR/CCPA requirements
* β Implement data retention policies
* β Set up audit logging
* β Document security controls
* β Review PCI DSS if handling payments
*
* 10. DOCUMENTATION
* β Document security architecture
* β Create incident response plan
* β Document key rotation procedures
* β Create runbooks for common issues
* β Document API authentication flows
*/