navis.js 3.1.0 → 5.0.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.
- package/README.md +30 -2
- package/examples/v4-features-demo.js +171 -0
- package/examples/v5-features-demo.js +167 -0
- package/package.json +1 -1
- package/src/auth/authenticator.js +223 -0
- package/src/cache/cache.js +157 -0
- package/src/cache/redis-cache.js +174 -0
- package/src/core/advanced-router.js +186 -0
- package/src/core/app.js +264 -176
- package/src/core/graceful-shutdown.js +77 -0
- package/src/errors/error-handler.js +157 -0
- package/src/health/health-checker.js +120 -0
- package/src/index.js +69 -0
- package/src/middleware/cache-middleware.js +105 -0
- package/src/middleware/compression.js +97 -0
- package/src/middleware/cors.js +86 -0
- package/src/middleware/rate-limiter.js +159 -0
- package/src/middleware/security.js +107 -0
- package/src/validation/validator.js +301 -0
package/README.md
CHANGED
|
@@ -112,7 +112,7 @@ navis metrics
|
|
|
112
112
|
- ✅ **Distributed tracing** - Trace and span management
|
|
113
113
|
- ✅ **Enhanced CLI** - Test and metrics commands
|
|
114
114
|
|
|
115
|
-
### v3.1
|
|
115
|
+
### v3.1
|
|
116
116
|
|
|
117
117
|
- ✅ **Lambda cold start optimization** - Connection pooling, lazy initialization
|
|
118
118
|
- ✅ **ServiceClientPool** - Reuse HTTP connections across invocations
|
|
@@ -120,6 +120,24 @@ navis metrics
|
|
|
120
120
|
- ✅ **LambdaHandler** - Optimized handler with warm-up support
|
|
121
121
|
- ✅ **Cold start tracking** - Monitor and log cold start metrics
|
|
122
122
|
|
|
123
|
+
### v4
|
|
124
|
+
|
|
125
|
+
- ✅ **Advanced routing** - Route parameters (`:id`), nested routes, PATCH method
|
|
126
|
+
- ✅ **Request validation** - Schema-based validation with comprehensive rules
|
|
127
|
+
- ✅ **Authentication** - JWT and API Key authentication
|
|
128
|
+
- ✅ **Authorization** - Role-based access control
|
|
129
|
+
- ✅ **Rate limiting** - In-memory rate limiting with configurable windows
|
|
130
|
+
- ✅ **Enhanced error handling** - Custom error classes and error handler middleware
|
|
131
|
+
|
|
132
|
+
### v5 (Current)
|
|
133
|
+
|
|
134
|
+
- ✅ **Caching layer** - In-memory cache with TTL and Redis adapter
|
|
135
|
+
- ✅ **CORS support** - Cross-Origin Resource Sharing middleware
|
|
136
|
+
- ✅ **Security headers** - Protection against common attacks
|
|
137
|
+
- ✅ **Response compression** - Gzip and Brotli compression
|
|
138
|
+
- ✅ **Health checks** - Liveness and readiness probes
|
|
139
|
+
- ✅ **Graceful shutdown** - Clean shutdown handling
|
|
140
|
+
|
|
123
141
|
## API Reference
|
|
124
142
|
|
|
125
143
|
### NavisApp
|
|
@@ -304,6 +322,8 @@ See the `examples/` directory:
|
|
|
304
322
|
- `server.js` - Node.js HTTP server example
|
|
305
323
|
- `lambda.js` - AWS Lambda handler example
|
|
306
324
|
- `lambda-optimized.js` - Optimized Lambda handler with cold start optimizations (v3.1)
|
|
325
|
+
- `v4-features-demo.js` - v4 features demonstration (routing, validation, auth, rate limiting, etc.)
|
|
326
|
+
- `v5-features-demo.js` - v5 features demonstration (caching, CORS, security, compression, health checks, etc.)
|
|
307
327
|
- `service-client-demo.js` - ServiceClient usage example
|
|
308
328
|
- `v2-features-demo.js` - v2 features demonstration (retry, circuit breaker, etc.)
|
|
309
329
|
- `v3-features-demo.js` - v3 features demonstration (messaging, observability, etc.)
|
|
@@ -316,13 +336,21 @@ Core functionality: routing, middleware, Lambda support, ServiceClient
|
|
|
316
336
|
### v2 ✅
|
|
317
337
|
Resilience patterns: retry, circuit breaker, service discovery, CLI generators
|
|
318
338
|
|
|
319
|
-
### v3 ✅
|
|
339
|
+
### v3 ✅
|
|
320
340
|
Advanced features: async messaging (SQS/Kafka/NATS), observability, enhanced CLI
|
|
321
341
|
|
|
342
|
+
### v4 ✅
|
|
343
|
+
Production-ready: advanced routing, validation, authentication, rate limiting, error handling
|
|
344
|
+
|
|
345
|
+
### v5 ✅ (Current)
|
|
346
|
+
Enterprise-grade: caching, CORS, security headers, compression, health checks, graceful shutdown
|
|
347
|
+
|
|
322
348
|
## Documentation
|
|
323
349
|
|
|
324
350
|
- [V2 Features Guide](./V2_FEATURES.md) - Complete v2 features documentation
|
|
325
351
|
- [V3 Features Guide](./V3_FEATURES.md) - Complete v3 features documentation
|
|
352
|
+
- [V4 Features Guide](./V4_FEATURES.md) - Complete v4 features documentation
|
|
353
|
+
- [V5 Features Guide](./V5_FEATURES.md) - Complete v5 features documentation
|
|
326
354
|
- [Lambda Optimization Guide](./LAMBDA_OPTIMIZATION.md) - Lambda cold start optimization guide (v3.1)
|
|
327
355
|
- [Verification Guide v2](./VERIFY_V2.md) - How to verify v2 features
|
|
328
356
|
- [Verification Guide v3](./VERIFY_V3.md) - How to verify v3 features
|
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Navis.js v4 Features Demo
|
|
3
|
+
* Demonstrates advanced routing, validation, auth, rate limiting, and error handling
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
const {
|
|
7
|
+
NavisApp,
|
|
8
|
+
response,
|
|
9
|
+
validate,
|
|
10
|
+
authenticateJWT,
|
|
11
|
+
authorize,
|
|
12
|
+
rateLimit,
|
|
13
|
+
errorHandler,
|
|
14
|
+
asyncHandler,
|
|
15
|
+
NotFoundError,
|
|
16
|
+
BadRequestError,
|
|
17
|
+
} = require('../src/index');
|
|
18
|
+
|
|
19
|
+
const app = new NavisApp();
|
|
20
|
+
|
|
21
|
+
// Set error handler
|
|
22
|
+
app.setErrorHandler(errorHandler({
|
|
23
|
+
includeStack: true,
|
|
24
|
+
logErrors: true,
|
|
25
|
+
}));
|
|
26
|
+
|
|
27
|
+
// Global rate limiting
|
|
28
|
+
app.use(rateLimit({
|
|
29
|
+
windowMs: 60000, // 1 minute
|
|
30
|
+
max: 100, // 100 requests per minute
|
|
31
|
+
}));
|
|
32
|
+
|
|
33
|
+
// Example 1: Route Parameters
|
|
34
|
+
console.log('\n=== Route Parameters (v4) ===\n');
|
|
35
|
+
|
|
36
|
+
app.get('/users/:id', (req, res) => {
|
|
37
|
+
console.log('User ID:', req.params.id);
|
|
38
|
+
response.success(res, {
|
|
39
|
+
message: `Fetching user ${req.params.id}`,
|
|
40
|
+
userId: req.params.id,
|
|
41
|
+
});
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
app.get('/users/:id/posts/:postId', (req, res) => {
|
|
45
|
+
console.log('User ID:', req.params.id);
|
|
46
|
+
console.log('Post ID:', req.params.postId);
|
|
47
|
+
response.success(res, {
|
|
48
|
+
userId: req.params.id,
|
|
49
|
+
postId: req.params.postId,
|
|
50
|
+
});
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
// Example 2: Request Validation
|
|
54
|
+
console.log('\n=== Request Validation (v4) ===\n');
|
|
55
|
+
|
|
56
|
+
const createUserSchema = {
|
|
57
|
+
body: {
|
|
58
|
+
name: {
|
|
59
|
+
type: 'string',
|
|
60
|
+
required: true,
|
|
61
|
+
minLength: 3,
|
|
62
|
+
maxLength: 50,
|
|
63
|
+
},
|
|
64
|
+
email: {
|
|
65
|
+
type: 'string',
|
|
66
|
+
required: true,
|
|
67
|
+
format: 'email',
|
|
68
|
+
},
|
|
69
|
+
age: {
|
|
70
|
+
type: 'number',
|
|
71
|
+
min: 18,
|
|
72
|
+
max: 100,
|
|
73
|
+
},
|
|
74
|
+
},
|
|
75
|
+
};
|
|
76
|
+
|
|
77
|
+
app.post('/users', validate(createUserSchema), (req, res) => {
|
|
78
|
+
console.log('Validated body:', req.body);
|
|
79
|
+
response.success(res, {
|
|
80
|
+
message: 'User created',
|
|
81
|
+
user: req.body,
|
|
82
|
+
}, 201);
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
// Example 3: Authentication (Mock JWT)
|
|
86
|
+
console.log('\n=== Authentication (v4) ===\n');
|
|
87
|
+
|
|
88
|
+
// Mock JWT secret (in production, use environment variable)
|
|
89
|
+
process.env.JWT_SECRET = 'your-secret-key';
|
|
90
|
+
|
|
91
|
+
// Protected route
|
|
92
|
+
app.get('/profile', authenticateJWT(), (req, res) => {
|
|
93
|
+
response.success(res, {
|
|
94
|
+
message: 'Protected route',
|
|
95
|
+
user: req.user,
|
|
96
|
+
});
|
|
97
|
+
});
|
|
98
|
+
|
|
99
|
+
// Role-based authorization
|
|
100
|
+
app.get('/admin', authenticateJWT(), authorize(['admin']), (req, res) => {
|
|
101
|
+
response.success(res, {
|
|
102
|
+
message: 'Admin area',
|
|
103
|
+
user: req.user,
|
|
104
|
+
});
|
|
105
|
+
});
|
|
106
|
+
|
|
107
|
+
// Example 4: Error Handling
|
|
108
|
+
console.log('\n=== Error Handling (v4) ===\n');
|
|
109
|
+
|
|
110
|
+
app.get('/error-test', asyncHandler(async (req, res) => {
|
|
111
|
+
throw new BadRequestError('This is a bad request');
|
|
112
|
+
}));
|
|
113
|
+
|
|
114
|
+
app.get('/not-found-test', asyncHandler(async (req, res) => {
|
|
115
|
+
throw new NotFoundError('Resource not found');
|
|
116
|
+
}));
|
|
117
|
+
|
|
118
|
+
// Example 5: Rate Limiting per Route
|
|
119
|
+
console.log('\n=== Rate Limiting (v4) ===\n');
|
|
120
|
+
|
|
121
|
+
app.post('/login', rateLimit({ max: 5, windowMs: 60000 }), (req, res) => {
|
|
122
|
+
response.success(res, {
|
|
123
|
+
message: 'Login endpoint (5 requests per minute)',
|
|
124
|
+
});
|
|
125
|
+
});
|
|
126
|
+
|
|
127
|
+
// Example 6: Query Parameters
|
|
128
|
+
app.get('/search', (req, res) => {
|
|
129
|
+
console.log('Query params:', req.query);
|
|
130
|
+
response.success(res, {
|
|
131
|
+
query: req.query.q,
|
|
132
|
+
filters: req.query,
|
|
133
|
+
});
|
|
134
|
+
});
|
|
135
|
+
|
|
136
|
+
// Example 7: PATCH Method (v4)
|
|
137
|
+
app.patch('/users/:id', validate({
|
|
138
|
+
body: {
|
|
139
|
+
name: { type: 'string', required: false },
|
|
140
|
+
email: { type: 'string', required: false, format: 'email' },
|
|
141
|
+
},
|
|
142
|
+
}), (req, res) => {
|
|
143
|
+
response.success(res, {
|
|
144
|
+
message: `Updating user ${req.params.id}`,
|
|
145
|
+
updates: req.body,
|
|
146
|
+
});
|
|
147
|
+
});
|
|
148
|
+
|
|
149
|
+
// Start server
|
|
150
|
+
const PORT = 3000;
|
|
151
|
+
app.listen(PORT, () => {
|
|
152
|
+
console.log(`\n🚀 Navis.js v4 Features Demo Server`);
|
|
153
|
+
console.log(`📡 Listening on http://localhost:${PORT}\n`);
|
|
154
|
+
console.log('Available endpoints:');
|
|
155
|
+
console.log(' GET /users/:id');
|
|
156
|
+
console.log(' GET /users/:id/posts/:postId');
|
|
157
|
+
console.log(' POST /users (with validation)');
|
|
158
|
+
console.log(' GET /profile (requires JWT)');
|
|
159
|
+
console.log(' GET /admin (requires admin role)');
|
|
160
|
+
console.log(' GET /error-test');
|
|
161
|
+
console.log(' GET /not-found-test');
|
|
162
|
+
console.log(' POST /login (rate limited)');
|
|
163
|
+
console.log(' GET /search?q=test');
|
|
164
|
+
console.log(' PATCH /users/:id');
|
|
165
|
+
console.log('\n💡 Test with:');
|
|
166
|
+
console.log(' curl http://localhost:3000/users/123');
|
|
167
|
+
console.log(' curl -X POST http://localhost:3000/users -H "Content-Type: application/json" -d \'{"name":"John","email":"john@example.com","age":25}\'');
|
|
168
|
+
});
|
|
169
|
+
|
|
170
|
+
module.exports = app;
|
|
171
|
+
|
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Navis.js v5 Features Demo
|
|
3
|
+
* Demonstrates caching, CORS, security, compression, health checks, and graceful shutdown
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
const {
|
|
7
|
+
NavisApp,
|
|
8
|
+
response,
|
|
9
|
+
Cache,
|
|
10
|
+
cache,
|
|
11
|
+
cors,
|
|
12
|
+
security,
|
|
13
|
+
compress,
|
|
14
|
+
createHealthChecker,
|
|
15
|
+
gracefulShutdown,
|
|
16
|
+
} = require('../src/index');
|
|
17
|
+
|
|
18
|
+
const app = new NavisApp();
|
|
19
|
+
|
|
20
|
+
// ============================================
|
|
21
|
+
// CORS Middleware
|
|
22
|
+
// ============================================
|
|
23
|
+
app.use(cors({
|
|
24
|
+
origin: ['http://localhost:3000', 'https://example.com'],
|
|
25
|
+
methods: ['GET', 'POST', 'PUT', 'DELETE'],
|
|
26
|
+
credentials: true,
|
|
27
|
+
}));
|
|
28
|
+
|
|
29
|
+
// ============================================
|
|
30
|
+
// Security Headers
|
|
31
|
+
// ============================================
|
|
32
|
+
app.use(security({
|
|
33
|
+
helmet: true,
|
|
34
|
+
hsts: true,
|
|
35
|
+
noSniff: true,
|
|
36
|
+
xssFilter: true,
|
|
37
|
+
frameOptions: 'DENY',
|
|
38
|
+
referrerPolicy: 'no-referrer',
|
|
39
|
+
}));
|
|
40
|
+
|
|
41
|
+
// ============================================
|
|
42
|
+
// Response Compression
|
|
43
|
+
// ============================================
|
|
44
|
+
app.use(compress({
|
|
45
|
+
level: 6,
|
|
46
|
+
threshold: 1024,
|
|
47
|
+
algorithm: 'gzip',
|
|
48
|
+
}));
|
|
49
|
+
|
|
50
|
+
// ============================================
|
|
51
|
+
// Caching
|
|
52
|
+
// ============================================
|
|
53
|
+
const cacheStore = new Cache({
|
|
54
|
+
maxSize: 1000,
|
|
55
|
+
defaultTTL: 3600000, // 1 hour
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
// Cached route
|
|
59
|
+
app.get('/users/:id', cache({
|
|
60
|
+
cacheStore,
|
|
61
|
+
ttl: 1800, // 30 minutes
|
|
62
|
+
keyGenerator: (req) => `user:${req.params.id}`,
|
|
63
|
+
}), (req, res) => {
|
|
64
|
+
// Simulate database query
|
|
65
|
+
const user = {
|
|
66
|
+
id: req.params.id,
|
|
67
|
+
name: 'John Doe',
|
|
68
|
+
email: 'john@example.com',
|
|
69
|
+
};
|
|
70
|
+
|
|
71
|
+
response.success(res, user);
|
|
72
|
+
});
|
|
73
|
+
|
|
74
|
+
// Non-cached route
|
|
75
|
+
app.get('/users/:id/posts', (req, res) => {
|
|
76
|
+
response.success(res, {
|
|
77
|
+
userId: req.params.id,
|
|
78
|
+
posts: [],
|
|
79
|
+
});
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
// ============================================
|
|
83
|
+
// Health Checks
|
|
84
|
+
// ============================================
|
|
85
|
+
const healthChecker = createHealthChecker({
|
|
86
|
+
livenessPath: '/health/live',
|
|
87
|
+
readinessPath: '/health/ready',
|
|
88
|
+
checks: {
|
|
89
|
+
database: async () => {
|
|
90
|
+
// Simulate database check
|
|
91
|
+
return true;
|
|
92
|
+
},
|
|
93
|
+
cache: async () => {
|
|
94
|
+
// Check cache
|
|
95
|
+
return cacheStore.size() >= 0;
|
|
96
|
+
},
|
|
97
|
+
},
|
|
98
|
+
});
|
|
99
|
+
|
|
100
|
+
app.use(healthChecker.middleware());
|
|
101
|
+
|
|
102
|
+
// ============================================
|
|
103
|
+
// Routes
|
|
104
|
+
// ============================================
|
|
105
|
+
app.get('/', (req, res) => {
|
|
106
|
+
response.success(res, {
|
|
107
|
+
message: 'Navis.js v5 Features Demo',
|
|
108
|
+
features: [
|
|
109
|
+
'Caching',
|
|
110
|
+
'CORS',
|
|
111
|
+
'Security Headers',
|
|
112
|
+
'Compression',
|
|
113
|
+
'Health Checks',
|
|
114
|
+
'Graceful Shutdown',
|
|
115
|
+
],
|
|
116
|
+
});
|
|
117
|
+
});
|
|
118
|
+
|
|
119
|
+
app.get('/cache-stats', (req, res) => {
|
|
120
|
+
response.success(res, {
|
|
121
|
+
size: cacheStore.size(),
|
|
122
|
+
keys: cacheStore.keys().slice(0, 10), // First 10 keys
|
|
123
|
+
});
|
|
124
|
+
});
|
|
125
|
+
|
|
126
|
+
app.post('/cache/clear', (req, res) => {
|
|
127
|
+
cacheStore.clear();
|
|
128
|
+
response.success(res, { message: 'Cache cleared' });
|
|
129
|
+
});
|
|
130
|
+
|
|
131
|
+
// ============================================
|
|
132
|
+
// Start Server
|
|
133
|
+
// ============================================
|
|
134
|
+
const PORT = 3000;
|
|
135
|
+
const server = app.listen(PORT, () => {
|
|
136
|
+
console.log(`\n🚀 Navis.js v5 Features Demo Server`);
|
|
137
|
+
console.log(`📡 Listening on http://localhost:${PORT}\n`);
|
|
138
|
+
console.log('Available endpoints:');
|
|
139
|
+
console.log(' GET /');
|
|
140
|
+
console.log(' GET /users/:id (cached)');
|
|
141
|
+
console.log(' GET /users/:id/posts');
|
|
142
|
+
console.log(' GET /health/live (liveness)');
|
|
143
|
+
console.log(' GET /health/ready (readiness)');
|
|
144
|
+
console.log(' GET /cache-stats');
|
|
145
|
+
console.log(' POST /cache/clear');
|
|
146
|
+
console.log('\n💡 Test with:');
|
|
147
|
+
console.log(' curl http://localhost:3000/');
|
|
148
|
+
console.log(' curl http://localhost:3000/users/123');
|
|
149
|
+
console.log(' curl http://localhost:3000/health/ready');
|
|
150
|
+
});
|
|
151
|
+
|
|
152
|
+
// ============================================
|
|
153
|
+
// Graceful Shutdown
|
|
154
|
+
// ============================================
|
|
155
|
+
gracefulShutdown(server, {
|
|
156
|
+
timeout: 10000,
|
|
157
|
+
onShutdown: async () => {
|
|
158
|
+
console.log('Cleaning up...');
|
|
159
|
+
// Close database connections
|
|
160
|
+
// Close cache connections
|
|
161
|
+
cacheStore.destroy();
|
|
162
|
+
console.log('Cleanup complete');
|
|
163
|
+
},
|
|
164
|
+
});
|
|
165
|
+
|
|
166
|
+
module.exports = app;
|
|
167
|
+
|
package/package.json
CHANGED
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Authentication and Authorization Middleware
|
|
3
|
+
* v4: JWT, API Key, and role-based access control
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
const crypto = require('crypto');
|
|
7
|
+
|
|
8
|
+
class AuthenticationError extends Error {
|
|
9
|
+
constructor(message, statusCode = 401) {
|
|
10
|
+
super(message);
|
|
11
|
+
this.name = 'AuthenticationError';
|
|
12
|
+
this.statusCode = statusCode;
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
class AuthorizationError extends Error {
|
|
17
|
+
constructor(message, statusCode = 403) {
|
|
18
|
+
super(message);
|
|
19
|
+
this.name = 'AuthorizationError';
|
|
20
|
+
this.statusCode = statusCode;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* JWT Authentication Middleware
|
|
26
|
+
* @param {Object} options - JWT options
|
|
27
|
+
* @returns {Function} - Middleware function
|
|
28
|
+
*/
|
|
29
|
+
function authenticateJWT(options = {}) {
|
|
30
|
+
const {
|
|
31
|
+
secret = process.env.JWT_SECRET,
|
|
32
|
+
algorithms = ['HS256'],
|
|
33
|
+
header = 'authorization',
|
|
34
|
+
extractToken = (req) => {
|
|
35
|
+
const authHeader = req.headers[header] || req.headers[header.toLowerCase()];
|
|
36
|
+
if (!authHeader) return null;
|
|
37
|
+
|
|
38
|
+
// Support "Bearer <token>" format
|
|
39
|
+
const parts = authHeader.split(' ');
|
|
40
|
+
return parts.length === 2 && parts[0].toLowerCase() === 'bearer'
|
|
41
|
+
? parts[1]
|
|
42
|
+
: authHeader;
|
|
43
|
+
},
|
|
44
|
+
} = options;
|
|
45
|
+
|
|
46
|
+
if (!secret) {
|
|
47
|
+
throw new Error('JWT secret is required');
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
return async (req, res, next) => {
|
|
51
|
+
try {
|
|
52
|
+
const token = extractToken(req);
|
|
53
|
+
|
|
54
|
+
if (!token) {
|
|
55
|
+
throw new AuthenticationError('No authentication token provided');
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
// Simple JWT decode and verify (for HS256)
|
|
59
|
+
// In production, use a proper JWT library like jsonwebtoken
|
|
60
|
+
const decoded = verifyJWT(token, secret);
|
|
61
|
+
|
|
62
|
+
if (!decoded) {
|
|
63
|
+
throw new AuthenticationError('Invalid or expired token');
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
// Attach user info to request
|
|
67
|
+
req.user = decoded;
|
|
68
|
+
req.token = token;
|
|
69
|
+
|
|
70
|
+
next();
|
|
71
|
+
} catch (error) {
|
|
72
|
+
if (error instanceof AuthenticationError) {
|
|
73
|
+
res.statusCode = error.statusCode;
|
|
74
|
+
res.body = { error: error.message };
|
|
75
|
+
return;
|
|
76
|
+
}
|
|
77
|
+
throw error;
|
|
78
|
+
}
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* Simple JWT verification (HS256 only)
|
|
84
|
+
* For production, use jsonwebtoken library
|
|
85
|
+
* @private
|
|
86
|
+
*/
|
|
87
|
+
function verifyJWT(token, secret) {
|
|
88
|
+
try {
|
|
89
|
+
const parts = token.split('.');
|
|
90
|
+
if (parts.length !== 3) {
|
|
91
|
+
return null;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
const [headerB64, payloadB64, signatureB64] = parts;
|
|
95
|
+
|
|
96
|
+
// Verify signature
|
|
97
|
+
const signature = Buffer.from(signatureB64, 'base64url').toString('hex');
|
|
98
|
+
const expectedSignature = crypto
|
|
99
|
+
.createHmac('sha256', secret)
|
|
100
|
+
.update(`${headerB64}.${payloadB64}`)
|
|
101
|
+
.digest('hex');
|
|
102
|
+
|
|
103
|
+
if (signature !== expectedSignature) {
|
|
104
|
+
return null;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
// Decode payload
|
|
108
|
+
const payload = JSON.parse(Buffer.from(payloadB64, 'base64url').toString());
|
|
109
|
+
|
|
110
|
+
// Check expiration
|
|
111
|
+
if (payload.exp && Date.now() >= payload.exp * 1000) {
|
|
112
|
+
return null;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
return payload;
|
|
116
|
+
} catch (error) {
|
|
117
|
+
return null;
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* API Key Authentication Middleware
|
|
123
|
+
* @param {Object} options - API Key options
|
|
124
|
+
* @returns {Function} - Middleware function
|
|
125
|
+
*/
|
|
126
|
+
function authenticateAPIKey(options = {}) {
|
|
127
|
+
const {
|
|
128
|
+
header = 'x-api-key',
|
|
129
|
+
keys = process.env.API_KEYS ? process.env.API_KEYS.split(',') : [],
|
|
130
|
+
validateKey = (key) => keys.includes(key),
|
|
131
|
+
} = options;
|
|
132
|
+
|
|
133
|
+
return async (req, res, next) => {
|
|
134
|
+
try {
|
|
135
|
+
const apiKey = req.headers[header] || req.headers[header.toLowerCase()];
|
|
136
|
+
|
|
137
|
+
if (!apiKey) {
|
|
138
|
+
throw new AuthenticationError('API key is required');
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
const isValid = await validateKey(apiKey);
|
|
142
|
+
|
|
143
|
+
if (!isValid) {
|
|
144
|
+
throw new AuthenticationError('Invalid API key');
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
req.apiKey = apiKey;
|
|
148
|
+
next();
|
|
149
|
+
} catch (error) {
|
|
150
|
+
if (error instanceof AuthenticationError) {
|
|
151
|
+
res.statusCode = error.statusCode;
|
|
152
|
+
res.body = { error: error.message };
|
|
153
|
+
return;
|
|
154
|
+
}
|
|
155
|
+
throw error;
|
|
156
|
+
}
|
|
157
|
+
};
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/**
|
|
161
|
+
* Role-based Authorization Middleware
|
|
162
|
+
* @param {string|Array} allowedRoles - Allowed roles
|
|
163
|
+
* @returns {Function} - Middleware function
|
|
164
|
+
*/
|
|
165
|
+
function authorize(allowedRoles) {
|
|
166
|
+
const roles = Array.isArray(allowedRoles) ? allowedRoles : [allowedRoles];
|
|
167
|
+
|
|
168
|
+
return async (req, res, next) => {
|
|
169
|
+
try {
|
|
170
|
+
if (!req.user) {
|
|
171
|
+
throw new AuthenticationError('Authentication required');
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
const userRoles = req.user.roles || req.user.role ? [req.user.role] : [];
|
|
175
|
+
|
|
176
|
+
const hasRole = roles.some(role => userRoles.includes(role));
|
|
177
|
+
|
|
178
|
+
if (!hasRole) {
|
|
179
|
+
throw new AuthorizationError('Insufficient permissions');
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
next();
|
|
183
|
+
} catch (error) {
|
|
184
|
+
if (error instanceof AuthenticationError || error instanceof AuthorizationError) {
|
|
185
|
+
res.statusCode = error.statusCode;
|
|
186
|
+
res.body = { error: error.message };
|
|
187
|
+
return;
|
|
188
|
+
}
|
|
189
|
+
throw error;
|
|
190
|
+
}
|
|
191
|
+
};
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/**
|
|
195
|
+
* Optional authentication (doesn't fail if no token)
|
|
196
|
+
* @param {Object} options - JWT options
|
|
197
|
+
* @returns {Function} - Middleware function
|
|
198
|
+
*/
|
|
199
|
+
function optionalAuth(options = {}) {
|
|
200
|
+
const jwtAuth = authenticateJWT(options);
|
|
201
|
+
|
|
202
|
+
return async (req, res, next) => {
|
|
203
|
+
try {
|
|
204
|
+
await jwtAuth(req, res, () => {
|
|
205
|
+
// Continue even if auth fails
|
|
206
|
+
next();
|
|
207
|
+
});
|
|
208
|
+
} catch (error) {
|
|
209
|
+
// If auth fails, continue without user
|
|
210
|
+
next();
|
|
211
|
+
}
|
|
212
|
+
};
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
module.exports = {
|
|
216
|
+
authenticateJWT,
|
|
217
|
+
authenticateAPIKey,
|
|
218
|
+
authorize,
|
|
219
|
+
optionalAuth,
|
|
220
|
+
AuthenticationError,
|
|
221
|
+
AuthorizationError,
|
|
222
|
+
};
|
|
223
|
+
|