@naman_deep_singh/server-utils 1.3.0 → 1.4.1
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 +19 -5
- package/dist/cjs/core/health.d.ts +5 -0
- package/dist/cjs/{health.js → core/health.js} +4 -4
- package/dist/cjs/{periodic-health.d.ts → core/periodic-health.d.ts} +1 -1
- package/dist/cjs/{periodic-health.js → core/periodic-health.js} +4 -4
- package/dist/{types → cjs/core}/server.d.ts +8 -7
- package/dist/cjs/{server.js → core/server.js} +70 -25
- package/dist/cjs/{shutdown.d.ts → core/shutdown.d.ts} +2 -2
- package/dist/cjs/{shutdown.js → core/shutdown.js} +2 -1
- package/dist/cjs/index.d.ts +14 -14
- package/dist/cjs/index.js +10 -10
- package/dist/cjs/middleware/auth.middleware.d.ts +7 -0
- package/dist/cjs/middleware/auth.middleware.js +41 -0
- package/dist/cjs/middleware/cache.middleware.d.ts +2 -0
- package/dist/cjs/middleware/cache.middleware.js +58 -0
- package/dist/cjs/middleware/errorHandler.middleware.d.ts +2 -0
- package/dist/cjs/middleware/errorHandler.middleware.js +30 -0
- package/dist/cjs/middleware/index.d.ts +10 -0
- package/dist/cjs/middleware/index.js +40 -0
- package/dist/cjs/middleware/logging.middleware.d.ts +2 -0
- package/dist/cjs/middleware/logging.middleware.js +19 -0
- package/dist/cjs/middleware/plugins.middleware.d.ts +14 -0
- package/dist/cjs/middleware/plugins.middleware.js +58 -0
- package/dist/cjs/middleware/rateLimiter.middleware.d.ts +8 -0
- package/dist/cjs/middleware/rateLimiter.middleware.js +35 -0
- package/dist/cjs/middleware/requestId.middleware.d.ts +2 -0
- package/dist/cjs/middleware/requestId.middleware.js +12 -0
- package/dist/cjs/middleware/session.middleware.d.ts +2 -0
- package/dist/cjs/middleware/session.middleware.js +53 -0
- package/dist/cjs/middleware/validation.middleware.d.ts +11 -0
- package/dist/cjs/middleware/validation.middleware.js +67 -0
- package/dist/{esm/types.d.ts → cjs/types/index.d.ts} +1 -1
- package/dist/cjs/{utils.js → utils/utils.js} +2 -2
- package/dist/esm/core/health.d.ts +5 -0
- package/dist/esm/{health.js → core/health.js} +4 -4
- package/dist/esm/{periodic-health.d.ts → core/periodic-health.d.ts} +1 -1
- package/dist/esm/{periodic-health.js → core/periodic-health.js} +4 -4
- package/dist/esm/{server.d.ts → core/server.d.ts} +8 -7
- package/dist/esm/{server.js → core/server.js} +36 -24
- package/dist/esm/{shutdown.d.ts → core/shutdown.d.ts} +2 -2
- package/dist/esm/{shutdown.js → core/shutdown.js} +2 -1
- package/dist/esm/index.d.ts +14 -14
- package/dist/esm/index.js +12 -12
- package/dist/esm/middleware/auth.middleware.d.ts +7 -0
- package/dist/esm/middleware/auth.middleware.js +38 -0
- package/dist/esm/middleware/cache.middleware.d.ts +2 -0
- package/dist/esm/middleware/cache.middleware.js +55 -0
- package/dist/esm/middleware/errorHandler.middleware.d.ts +2 -0
- package/dist/esm/middleware/errorHandler.middleware.js +27 -0
- package/dist/esm/middleware/index.d.ts +10 -0
- package/dist/esm/middleware/index.js +20 -0
- package/dist/esm/middleware/logging.middleware.d.ts +2 -0
- package/dist/esm/middleware/logging.middleware.js +16 -0
- package/dist/esm/middleware/plugins.middleware.d.ts +14 -0
- package/dist/esm/middleware/plugins.middleware.js +47 -0
- package/dist/esm/middleware/rateLimiter.middleware.d.ts +8 -0
- package/dist/esm/middleware/rateLimiter.middleware.js +32 -0
- package/dist/esm/middleware/requestId.middleware.d.ts +2 -0
- package/dist/esm/middleware/requestId.middleware.js +9 -0
- package/dist/esm/middleware/session.middleware.d.ts +2 -0
- package/dist/esm/middleware/session.middleware.js +50 -0
- package/dist/esm/middleware/validation.middleware.d.ts +11 -0
- package/dist/esm/middleware/validation.middleware.js +64 -0
- package/dist/{types/types.d.ts → esm/types/index.d.ts} +1 -1
- package/dist/esm/{utils.js → utils/utils.js} +2 -2
- package/dist/types/core/health.d.ts +5 -0
- package/dist/types/{periodic-health.d.ts → core/periodic-health.d.ts} +1 -1
- package/dist/{cjs → types/core}/server.d.ts +8 -7
- package/dist/types/{shutdown.d.ts → core/shutdown.d.ts} +2 -2
- package/dist/types/index.d.ts +14 -14
- package/dist/types/middleware/auth.middleware.d.ts +7 -0
- package/dist/types/middleware/cache.middleware.d.ts +2 -0
- package/dist/types/middleware/errorHandler.middleware.d.ts +2 -0
- package/dist/types/middleware/index.d.ts +10 -0
- package/dist/types/middleware/logging.middleware.d.ts +2 -0
- package/dist/types/middleware/plugins.middleware.d.ts +14 -0
- package/dist/types/middleware/rateLimiter.middleware.d.ts +8 -0
- package/dist/types/middleware/requestId.middleware.d.ts +2 -0
- package/dist/types/middleware/session.middleware.d.ts +2 -0
- package/dist/types/middleware/validation.middleware.d.ts +11 -0
- package/dist/{cjs/types.d.ts → types/types/index.d.ts} +1 -1
- package/package.json +4 -2
- package/dist/cjs/health.d.ts +0 -5
- package/dist/cjs/middleware.d.ts +0 -39
- package/dist/cjs/middleware.js +0 -348
- package/dist/esm/health.d.ts +0 -5
- package/dist/esm/middleware.d.ts +0 -39
- package/dist/esm/middleware.js +0 -329
- package/dist/types/health.d.ts +0 -5
- package/dist/types/middleware.d.ts +0 -39
- /package/dist/cjs/{types.js → types/index.js} +0 -0
- /package/dist/cjs/{utils.d.ts → utils/utils.d.ts} +0 -0
- /package/dist/esm/{types.js → types/index.js} +0 -0
- /package/dist/esm/{utils.d.ts → utils/utils.d.ts} +0 -0
- /package/dist/types/{utils.d.ts → utils/utils.d.ts} +0 -0
|
@@ -1,8 +1,9 @@
|
|
|
1
|
-
import express from 'express';
|
|
2
|
-
import { createGracefulShutdown } from './shutdown';
|
|
3
|
-
import { PeriodicHealthMonitor } from './periodic-health';
|
|
4
1
|
import crypto from 'crypto';
|
|
5
2
|
import { CacheFactory, SessionStore } from '@naman_deep_singh/cache';
|
|
3
|
+
import express, { json, raw } from 'express';
|
|
4
|
+
import { PeriodicHealthMonitor } from './periodic-health';
|
|
5
|
+
import { createGracefulShutdown } from './shutdown';
|
|
6
|
+
import { useSession } from '../middleware';
|
|
6
7
|
export class ExpressServer {
|
|
7
8
|
constructor(name = 'Express Server', version = '1.0.0', config = {}) {
|
|
8
9
|
this.status = 'stopped';
|
|
@@ -24,7 +25,7 @@ export class ExpressServer {
|
|
|
24
25
|
socketIO: config.socketIO,
|
|
25
26
|
periodicHealthCheck: config.periodicHealthCheck || { enabled: false },
|
|
26
27
|
cache: config.cache || { enabled: false },
|
|
27
|
-
session: config.session || { enabled: false }
|
|
28
|
+
session: config.session || { enabled: false },
|
|
28
29
|
};
|
|
29
30
|
// Initialize locals for cache/session
|
|
30
31
|
this.app.locals.cache = undefined;
|
|
@@ -59,7 +60,7 @@ export class ExpressServer {
|
|
|
59
60
|
}
|
|
60
61
|
// Apply JSON parser if enabled
|
|
61
62
|
if (this.config.json) {
|
|
62
|
-
this.app.use(
|
|
63
|
+
this.app.use(json());
|
|
63
64
|
}
|
|
64
65
|
// Apply cookie parser if enabled
|
|
65
66
|
if (this.config.cookieParser) {
|
|
@@ -72,21 +73,24 @@ export class ExpressServer {
|
|
|
72
73
|
}
|
|
73
74
|
}
|
|
74
75
|
// Apply custom middleware
|
|
75
|
-
if (this.config.customMiddleware &&
|
|
76
|
-
this.config.customMiddleware.
|
|
76
|
+
if (this.config.customMiddleware &&
|
|
77
|
+
this.config.customMiddleware.length > 0) {
|
|
78
|
+
this.config.customMiddleware.forEach((middleware) => {
|
|
77
79
|
this.app.use(middleware);
|
|
78
80
|
});
|
|
79
81
|
}
|
|
80
82
|
// Add health check if enabled
|
|
81
83
|
if (this.config.healthCheck) {
|
|
82
|
-
const healthPath = typeof this.config.healthCheck === 'string'
|
|
84
|
+
const healthPath = typeof this.config.healthCheck === 'string'
|
|
85
|
+
? this.config.healthCheck
|
|
86
|
+
: '/health';
|
|
83
87
|
this.app.get(healthPath, async (req, res) => {
|
|
84
88
|
const base = {
|
|
85
89
|
status: 'healthy',
|
|
86
90
|
service: this.config.name,
|
|
87
91
|
version: this.config.version,
|
|
88
92
|
uptime: Date.now() - this.config.startTime.getTime(),
|
|
89
|
-
timestamp: new Date().toISOString()
|
|
93
|
+
timestamp: new Date().toISOString(),
|
|
90
94
|
};
|
|
91
95
|
// If cache is enabled, include its health
|
|
92
96
|
const cache = req.app.locals.cache;
|
|
@@ -95,7 +99,12 @@ export class ExpressServer {
|
|
|
95
99
|
base.cache = await cache.isAlive();
|
|
96
100
|
}
|
|
97
101
|
catch (e) {
|
|
98
|
-
base.cache = {
|
|
102
|
+
base.cache = {
|
|
103
|
+
isAlive: false,
|
|
104
|
+
adapter: 'unknown',
|
|
105
|
+
timestamp: new Date(),
|
|
106
|
+
error: e.message,
|
|
107
|
+
};
|
|
99
108
|
}
|
|
100
109
|
}
|
|
101
110
|
res.status(200).json(base);
|
|
@@ -114,7 +123,11 @@ export class ExpressServer {
|
|
|
114
123
|
}
|
|
115
124
|
console.log(`🔄 [${serverName}] Initializing cache adapter: ${config.cache.adapter || 'memory'}...`);
|
|
116
125
|
// Use createWithFallback to prefer primary and fall back to memory when configured
|
|
117
|
-
const cfg = {
|
|
126
|
+
const cfg = {
|
|
127
|
+
...(cacheConfig || {}),
|
|
128
|
+
ttl: cacheConfig?.ttl ??
|
|
129
|
+
config.cache?.defaultTTL,
|
|
130
|
+
};
|
|
118
131
|
const cache = await CacheFactory.createWithFallback(cfg);
|
|
119
132
|
this.app.locals.cache = cache;
|
|
120
133
|
this.cache = cache;
|
|
@@ -124,7 +137,7 @@ export class ExpressServer {
|
|
|
124
137
|
req.cache = cache;
|
|
125
138
|
next();
|
|
126
139
|
});
|
|
127
|
-
console.log(`✅ [${serverName}] Cache initialized successfully (adapter: ${
|
|
140
|
+
console.log(`✅ [${serverName}] Cache initialized successfully (adapter: ${cacheConfig.adapter || 'memory'})`);
|
|
128
141
|
}
|
|
129
142
|
catch (err) {
|
|
130
143
|
console.error(`❌ [${serverName}] Failed to initialize cache (fallback to memory if enabled):`, err instanceof Error ? err.message : err);
|
|
@@ -133,7 +146,8 @@ export class ExpressServer {
|
|
|
133
146
|
}
|
|
134
147
|
// Initialize session if enabled
|
|
135
148
|
if (config.session && config.session.enabled) {
|
|
136
|
-
const cookieName = config.session.cookieName ||
|
|
149
|
+
const cookieName = config.session.cookieName ||
|
|
150
|
+
`${serverName.replace(/\s+/g, '_').toLowerCase()}.sid`;
|
|
137
151
|
const ttl = config.session.ttl ?? 3600;
|
|
138
152
|
let cache = this.app.locals.cache;
|
|
139
153
|
if (!cache) {
|
|
@@ -161,8 +175,6 @@ export class ExpressServer {
|
|
|
161
175
|
this.sessionStore = store;
|
|
162
176
|
// attach session middleware globally so req.sessionStore is available
|
|
163
177
|
try {
|
|
164
|
-
// eslint-disable-next-line @typescript-eslint/no-var-requires
|
|
165
|
-
const { useSession } = require('./middleware');
|
|
166
178
|
this.app.use(useSession(cookieName));
|
|
167
179
|
console.log(`✅ [${serverName}] Session middleware enabled (cookie: ${cookieName}, TTL: ${ttl}s)`);
|
|
168
180
|
}
|
|
@@ -217,7 +229,7 @@ export class ExpressServer {
|
|
|
217
229
|
catch (e) {
|
|
218
230
|
// SessionStore may not have close; ignore
|
|
219
231
|
}
|
|
220
|
-
}
|
|
232
|
+
},
|
|
221
233
|
});
|
|
222
234
|
}
|
|
223
235
|
// Start periodic health monitoring after server is running
|
|
@@ -267,7 +279,7 @@ export class ExpressServer {
|
|
|
267
279
|
port: this.config.port,
|
|
268
280
|
uptime: Date.now() - this.config.startTime.getTime(),
|
|
269
281
|
status: this.status,
|
|
270
|
-
startTime: this.config.startTime
|
|
282
|
+
startTime: this.config.startTime,
|
|
271
283
|
};
|
|
272
284
|
}
|
|
273
285
|
addGrpcService(service, implementation, port = 50051) {
|
|
@@ -275,7 +287,6 @@ export class ExpressServer {
|
|
|
275
287
|
// Lazy load gRPC to avoid dependency issues
|
|
276
288
|
if (!this.grpcServer) {
|
|
277
289
|
try {
|
|
278
|
-
// eslint-disable-next-line @typescript-eslint/no-var-requires
|
|
279
290
|
const grpc = require('@grpc/grpc-js');
|
|
280
291
|
this.grpcServer = new grpc.Server();
|
|
281
292
|
// Add all services
|
|
@@ -295,7 +306,6 @@ export class ExpressServer {
|
|
|
295
306
|
addRpcMethods(methods, path = '/rpc') {
|
|
296
307
|
Object.assign(this.rpcMethods, methods);
|
|
297
308
|
try {
|
|
298
|
-
// eslint-disable-next-line @typescript-eslint/no-var-requires
|
|
299
309
|
const jayson = require('jayson');
|
|
300
310
|
const rpcServer = jayson.server(this.rpcMethods);
|
|
301
311
|
this.app.use(path, rpcServer.middleware());
|
|
@@ -306,17 +316,20 @@ export class ExpressServer {
|
|
|
306
316
|
}
|
|
307
317
|
}
|
|
308
318
|
addWebhook(config) {
|
|
309
|
-
this.app.post(config.path,
|
|
319
|
+
this.app.post(config.path, raw({ type: 'application/json' }), async (req, res) => {
|
|
310
320
|
try {
|
|
311
321
|
// Verify signature if secret provided
|
|
312
322
|
if (config.secret) {
|
|
313
|
-
const signature = req.headers['x-hub-signature-256'] ||
|
|
323
|
+
const signature = req.headers['x-hub-signature-256'] ||
|
|
324
|
+
req.headers['x-signature-256'];
|
|
314
325
|
if (signature) {
|
|
315
326
|
const expectedSignature = crypto
|
|
316
327
|
.createHmac('sha256', config.secret)
|
|
317
328
|
.update(req.body)
|
|
318
329
|
.digest('hex');
|
|
319
|
-
const providedSignature = Array.isArray(signature)
|
|
330
|
+
const providedSignature = Array.isArray(signature)
|
|
331
|
+
? signature[0]
|
|
332
|
+
: signature;
|
|
320
333
|
if (!providedSignature.includes(expectedSignature)) {
|
|
321
334
|
return res.status(401).json({ error: 'Invalid signature' });
|
|
322
335
|
}
|
|
@@ -340,7 +353,6 @@ export class ExpressServer {
|
|
|
340
353
|
throw new Error(`${this.config.name}: Server must be started before adding Socket.IO`);
|
|
341
354
|
}
|
|
342
355
|
try {
|
|
343
|
-
// eslint-disable-next-line @typescript-eslint/no-var-requires
|
|
344
356
|
const { Server } = require('socket.io');
|
|
345
357
|
// Configure CORS
|
|
346
358
|
const corsConfig = config.cors === true
|
|
@@ -349,7 +361,7 @@ export class ExpressServer {
|
|
|
349
361
|
// Create Socket.IO server
|
|
350
362
|
const io = new Server(this.server, {
|
|
351
363
|
cors: config.cors ? corsConfig : undefined,
|
|
352
|
-
path: config.path || '/socket.io'
|
|
364
|
+
path: config.path || '/socket.io',
|
|
353
365
|
});
|
|
354
366
|
// Store reference for cleanup
|
|
355
367
|
this.socketIO = io;
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { Server } from 'http';
|
|
2
|
-
import { GracefulShutdownConfig, ServerPlugin } from '
|
|
1
|
+
import type { Server } from 'http';
|
|
2
|
+
import type { GracefulShutdownConfig, ServerPlugin } from '../types';
|
|
3
3
|
export declare function createGracefulShutdown(server: Server, config?: GracefulShutdownConfig): void;
|
|
4
4
|
export declare function withGracefulShutdown(config?: GracefulShutdownConfig): ServerPlugin;
|
|
5
5
|
export declare function startServerWithShutdown(app: import('express').Application, port: number, shutdownConfig?: GracefulShutdownConfig, serverName?: string, serverVersion?: string): Server;
|
|
@@ -32,6 +32,7 @@ export function withGracefulShutdown(config = {}) {
|
|
|
32
32
|
return (app, serverConfig) => {
|
|
33
33
|
// This plugin needs to be applied after server.listen()
|
|
34
34
|
// Store config for later use
|
|
35
|
+
;
|
|
35
36
|
app.__gracefulShutdownConfig = config;
|
|
36
37
|
};
|
|
37
38
|
}
|
|
@@ -45,7 +46,7 @@ export function startServerWithShutdown(app, port, shutdownConfig = {}, serverNa
|
|
|
45
46
|
const enhancedConfig = {
|
|
46
47
|
...config,
|
|
47
48
|
serverName,
|
|
48
|
-
serverVersion
|
|
49
|
+
serverVersion,
|
|
49
50
|
};
|
|
50
51
|
createGracefulShutdown(server, enhancedConfig);
|
|
51
52
|
return server;
|
package/dist/esm/index.d.ts
CHANGED
|
@@ -1,19 +1,19 @@
|
|
|
1
|
-
export { ExpressServer, createServer } from './server';
|
|
2
|
-
export type { ServerInstance, ServerInfo, GrpcService, RpcMethod, WebhookConfig } from './server';
|
|
1
|
+
export { ExpressServer, createServer } from './core/server';
|
|
2
|
+
export type { ServerInstance, ServerInfo, GrpcService, RpcMethod, WebhookConfig, } from './core/server';
|
|
3
3
|
export { Request, Response, NextFunction, Router, Application } from 'express';
|
|
4
4
|
export type { RequestHandler, ErrorRequestHandler } from 'express';
|
|
5
|
-
export { createHealthCheck, withHealthCheck, addHealthCheck } from './health';
|
|
6
|
-
export { createGracefulShutdown, withGracefulShutdown, startServerWithShutdown } from './shutdown';
|
|
7
|
-
export { createLoggingMiddleware, createErrorHandler, createRequestIdMiddleware, createValidationMiddleware, createRateLimitMiddleware, createAuthMiddleware, withLogging, withErrorHandler, withRequestId, withValidation, withRateLimit, withAuth, validateFields, rateLimit, requireAuth, cacheResponse, useSession, type ValidationRule, type RateLimitConfig, type AuthConfig } from './middleware';
|
|
8
|
-
export { getEnv, getEnvNumber, getEnvBoolean } from './utils';
|
|
9
|
-
export { PeriodicHealthMonitor } from './periodic-health';
|
|
10
|
-
export type { ServerConfig, HealthCheckConfig, HealthCheck, GracefulShutdownConfig, ServerPlugin, SocketIOConfig, SocketInstance, PeriodicHealthCheckConfig, HealthCheckService } from './types';
|
|
11
|
-
import {
|
|
12
|
-
import {
|
|
13
|
-
import {
|
|
14
|
-
import {
|
|
15
|
-
import {
|
|
16
|
-
import {
|
|
5
|
+
export { createHealthCheck, withHealthCheck, addHealthCheck, } from './core/health';
|
|
6
|
+
export { createGracefulShutdown, withGracefulShutdown, startServerWithShutdown, } from './core/shutdown';
|
|
7
|
+
export { createLoggingMiddleware, createErrorHandler, createRequestIdMiddleware, createValidationMiddleware, createRateLimitMiddleware, createAuthMiddleware, withLogging, withErrorHandler, withRequestId, withValidation, withRateLimit, withAuth, validateFields, rateLimit, requireAuth, cacheResponse, useSession, type ValidationRule, type RateLimitConfig, type AuthConfig, } from './middleware';
|
|
8
|
+
export { getEnv, getEnvNumber, getEnvBoolean, } from './utils/utils';
|
|
9
|
+
export { PeriodicHealthMonitor } from './core/periodic-health';
|
|
10
|
+
export type { ServerConfig, HealthCheckConfig, HealthCheck, GracefulShutdownConfig, ServerPlugin, SocketIOConfig, SocketInstance, PeriodicHealthCheckConfig, HealthCheckService, } from './types';
|
|
11
|
+
import { addHealthCheck, createHealthCheck, withHealthCheck } from './core/health';
|
|
12
|
+
import { PeriodicHealthMonitor } from './core/periodic-health';
|
|
13
|
+
import { ExpressServer, createServer } from './core/server';
|
|
14
|
+
import { createGracefulShutdown, startServerWithShutdown, withGracefulShutdown } from './core/shutdown';
|
|
15
|
+
import { createAuthMiddleware, createErrorHandler, createLoggingMiddleware, createRateLimitMiddleware, createRequestIdMiddleware, createValidationMiddleware, rateLimit, requireAuth, validateFields, withAuth, withErrorHandler, withLogging, withRateLimit, withRequestId, withValidation } from './middleware';
|
|
16
|
+
import { getEnv, getEnvBoolean, getEnvNumber } from './utils/utils';
|
|
17
17
|
declare const ServerUtils: {
|
|
18
18
|
createServer: typeof createServer;
|
|
19
19
|
ExpressServer: typeof ExpressServer;
|
package/dist/esm/index.js
CHANGED
|
@@ -1,24 +1,24 @@
|
|
|
1
1
|
// Core server utilities
|
|
2
|
-
export { ExpressServer, createServer } from './server';
|
|
2
|
+
export { ExpressServer, createServer } from './core/server';
|
|
3
3
|
// Express re-exports (to avoid direct Express dependency in services)
|
|
4
4
|
export { Router } from 'express';
|
|
5
5
|
// Health check utilities
|
|
6
|
-
export { createHealthCheck, withHealthCheck, addHealthCheck } from './health';
|
|
6
|
+
export { createHealthCheck, withHealthCheck, addHealthCheck, } from './core/health';
|
|
7
7
|
// Graceful shutdown utilities
|
|
8
|
-
export { createGracefulShutdown, withGracefulShutdown, startServerWithShutdown } from './shutdown';
|
|
8
|
+
export { createGracefulShutdown, withGracefulShutdown, startServerWithShutdown, } from './core/shutdown';
|
|
9
9
|
// Middleware utilities
|
|
10
|
-
export { createLoggingMiddleware, createErrorHandler, createRequestIdMiddleware, createValidationMiddleware, createRateLimitMiddleware, createAuthMiddleware, withLogging, withErrorHandler, withRequestId, withValidation, withRateLimit, withAuth, validateFields, rateLimit, requireAuth, cacheResponse, useSession } from './middleware';
|
|
10
|
+
export { createLoggingMiddleware, createErrorHandler, createRequestIdMiddleware, createValidationMiddleware, createRateLimitMiddleware, createAuthMiddleware, withLogging, withErrorHandler, withRequestId, withValidation, withRateLimit, withAuth, validateFields, rateLimit, requireAuth, cacheResponse, useSession, } from './middleware';
|
|
11
11
|
// Utility functions
|
|
12
|
-
export { getEnv, getEnvNumber, getEnvBoolean } from './utils';
|
|
12
|
+
export { getEnv, getEnvNumber, getEnvBoolean, } from './utils/utils';
|
|
13
13
|
// Periodic health monitoring
|
|
14
|
-
export { PeriodicHealthMonitor } from './periodic-health';
|
|
14
|
+
export { PeriodicHealthMonitor } from './core/periodic-health';
|
|
15
|
+
import { addHealthCheck, createHealthCheck, withHealthCheck, } from './core/health';
|
|
16
|
+
import { PeriodicHealthMonitor } from './core/periodic-health';
|
|
15
17
|
// Import all exports for default export
|
|
16
|
-
import { ExpressServer, createServer } from './server';
|
|
17
|
-
import {
|
|
18
|
-
import {
|
|
19
|
-
import {
|
|
20
|
-
import { getEnv, getEnvNumber, getEnvBoolean } from './utils';
|
|
21
|
-
import { PeriodicHealthMonitor } from './periodic-health';
|
|
18
|
+
import { ExpressServer, createServer } from './core/server';
|
|
19
|
+
import { createGracefulShutdown, startServerWithShutdown, withGracefulShutdown, } from './core/shutdown';
|
|
20
|
+
import { createAuthMiddleware, createErrorHandler, createLoggingMiddleware, createRateLimitMiddleware, createRequestIdMiddleware, createValidationMiddleware, rateLimit, requireAuth, validateFields, withAuth, withErrorHandler, withLogging, withRateLimit, withRequestId, withValidation, } from './middleware';
|
|
21
|
+
import { getEnv, getEnvBoolean, getEnvNumber } from './utils/utils';
|
|
22
22
|
// Default export for namespace usage
|
|
23
23
|
const ServerUtils = {
|
|
24
24
|
// Server creation
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { Request, RequestHandler } from 'node_modules/@types/express';
|
|
2
|
+
export interface AuthConfig {
|
|
3
|
+
secret: string;
|
|
4
|
+
unauthorizedMessage?: string;
|
|
5
|
+
tokenExtractor?: (req: Request) => string | null;
|
|
6
|
+
}
|
|
7
|
+
export declare function createAuthMiddleware(config: AuthConfig): RequestHandler;
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { UnauthorizedError } from '@naman_deep_singh/errors-utils';
|
|
2
|
+
import { extractToken, safeVerifyToken } from '@naman_deep_singh/security';
|
|
3
|
+
export function createAuthMiddleware(config) {
|
|
4
|
+
const { secret, unauthorizedMessage = 'Unauthorized access', tokenExtractor = (req) => extractToken({
|
|
5
|
+
header: req.headers.authorization || undefined,
|
|
6
|
+
cookies: req.cookies,
|
|
7
|
+
query: req.query,
|
|
8
|
+
body: req.body,
|
|
9
|
+
}), } = config;
|
|
10
|
+
return async (req, res, next) => {
|
|
11
|
+
try {
|
|
12
|
+
// Extract token from request
|
|
13
|
+
const token = tokenExtractor(req);
|
|
14
|
+
if (!token) {
|
|
15
|
+
const error = new UnauthorizedError(unauthorizedMessage, {
|
|
16
|
+
reason: 'No token provided',
|
|
17
|
+
});
|
|
18
|
+
return next(error);
|
|
19
|
+
}
|
|
20
|
+
// Use safe verify token from security package
|
|
21
|
+
const result = safeVerifyToken(token, secret);
|
|
22
|
+
if (!result.valid) {
|
|
23
|
+
const error = new UnauthorizedError(unauthorizedMessage, {
|
|
24
|
+
reason: 'Invalid or expired token',
|
|
25
|
+
originalError: result.error?.message,
|
|
26
|
+
});
|
|
27
|
+
return next(error);
|
|
28
|
+
}
|
|
29
|
+
// Attach the verified payload as user
|
|
30
|
+
req.user = result.payload;
|
|
31
|
+
next();
|
|
32
|
+
}
|
|
33
|
+
catch (error) {
|
|
34
|
+
const unauthorizedError = new UnauthorizedError(unauthorizedMessage, error instanceof Error ? { originalError: error.message } : error);
|
|
35
|
+
return next(unauthorizedError);
|
|
36
|
+
}
|
|
37
|
+
};
|
|
38
|
+
}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
// Cache response middleware (per-route opt-in)
|
|
2
|
+
export function cacheResponse(ttl) {
|
|
3
|
+
return async (req, res, next) => {
|
|
4
|
+
try {
|
|
5
|
+
if (req.method !== 'GET')
|
|
6
|
+
return next();
|
|
7
|
+
const cache = (req.cache ?? req.app.locals.cache);
|
|
8
|
+
const defaultTTL = req.app.locals.cacheDefaultTTL;
|
|
9
|
+
if (!cache || typeof cache.get !== 'function')
|
|
10
|
+
return next();
|
|
11
|
+
const key = `${req.originalUrl}`;
|
|
12
|
+
try {
|
|
13
|
+
const cached = await cache.get(key);
|
|
14
|
+
if (cached !== null && cached !== undefined) {
|
|
15
|
+
res.setHeader('X-Cache', 'HIT');
|
|
16
|
+
return res.json(cached);
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
catch (cacheErr) {
|
|
20
|
+
console.error(`[Cache] Failed to retrieve key "${key}":`, cacheErr);
|
|
21
|
+
// Continue without cache hit
|
|
22
|
+
}
|
|
23
|
+
const originalJson = res.json.bind(res);
|
|
24
|
+
res.json = (body) => {
|
|
25
|
+
try {
|
|
26
|
+
const expiry = ttl ?? defaultTTL;
|
|
27
|
+
if (expiry && cache && typeof cache.set === 'function') {
|
|
28
|
+
;
|
|
29
|
+
cache.set(key, body, expiry).catch((err) => {
|
|
30
|
+
console.error(`[Cache] Failed to set key "${key}" with TTL ${expiry}:`, err);
|
|
31
|
+
});
|
|
32
|
+
}
|
|
33
|
+
else if (cache) {
|
|
34
|
+
if (typeof cache.set === 'function') {
|
|
35
|
+
;
|
|
36
|
+
cache.set(key, body).catch((err) => {
|
|
37
|
+
console.error(`[Cache] Failed to set key "${key}":`, err);
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
catch (e) {
|
|
43
|
+
console.error(`[Cache] Error during cache.set operation:`, e);
|
|
44
|
+
}
|
|
45
|
+
res.setHeader('X-Cache', 'MISS');
|
|
46
|
+
return originalJson(body);
|
|
47
|
+
};
|
|
48
|
+
next();
|
|
49
|
+
}
|
|
50
|
+
catch (err) {
|
|
51
|
+
console.error('[Cache] Unexpected error in cacheResponse middleware:', err);
|
|
52
|
+
next();
|
|
53
|
+
}
|
|
54
|
+
};
|
|
55
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
// Error handling middleware
|
|
2
|
+
export function createErrorHandler() {
|
|
3
|
+
return (err, req, res, next) => {
|
|
4
|
+
console.error('Error:', err);
|
|
5
|
+
if (res.headersSent) {
|
|
6
|
+
return next(err);
|
|
7
|
+
}
|
|
8
|
+
// Type guard for error objects
|
|
9
|
+
const errorObj = err;
|
|
10
|
+
const status = errorObj.status || errorObj.statusCode || 500;
|
|
11
|
+
const message = process.env.NODE_ENV === 'production'
|
|
12
|
+
? 'Internal Server Error'
|
|
13
|
+
: errorObj.message || 'Unknown error';
|
|
14
|
+
res.status(status).json({
|
|
15
|
+
success: false,
|
|
16
|
+
message,
|
|
17
|
+
data: undefined,
|
|
18
|
+
error: {
|
|
19
|
+
message,
|
|
20
|
+
...(process.env.NODE_ENV !== 'production' && {
|
|
21
|
+
details: { stack: errorObj.stack },
|
|
22
|
+
}),
|
|
23
|
+
},
|
|
24
|
+
meta: null,
|
|
25
|
+
});
|
|
26
|
+
};
|
|
27
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
export { AuthConfig, createAuthMiddleware } from './auth.middleware';
|
|
2
|
+
export { cacheResponse } from './cache.middleware';
|
|
3
|
+
export { createErrorHandler } from './errorHandler.middleware';
|
|
4
|
+
export { createLoggingMiddleware } from './logging.middleware';
|
|
5
|
+
export { RateLimitConfig, createRateLimitMiddleware, } from './rateLimiter.middleware';
|
|
6
|
+
export { createRequestIdMiddleware } from './requestId.middleware';
|
|
7
|
+
export { useSession } from './session.middleware';
|
|
8
|
+
export { ValidationRule, createValidationMiddleware, } from './validation.middleware';
|
|
9
|
+
export { withLogging, withErrorHandler, withRequestId, withValidation, withRateLimit, withAuth, } from './plugins.middleware';
|
|
10
|
+
export { validateFields, rateLimit, requireAuth, } from './plugins.middleware';
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
// Authentication Middleware
|
|
2
|
+
export { createAuthMiddleware } from './auth.middleware';
|
|
3
|
+
// Cache Middleware
|
|
4
|
+
export { cacheResponse } from './cache.middleware';
|
|
5
|
+
// Error Handler Middleware
|
|
6
|
+
export { createErrorHandler } from './errorHandler.middleware';
|
|
7
|
+
// Logging Middleware
|
|
8
|
+
export { createLoggingMiddleware } from './logging.middleware';
|
|
9
|
+
// Rate Limiter Middleware
|
|
10
|
+
export { createRateLimitMiddleware, } from './rateLimiter.middleware';
|
|
11
|
+
// Request ID Middleware
|
|
12
|
+
export { createRequestIdMiddleware } from './requestId.middleware';
|
|
13
|
+
// Session Middleware
|
|
14
|
+
export { useSession } from './session.middleware';
|
|
15
|
+
// Validation Middleware
|
|
16
|
+
export { createValidationMiddleware, } from './validation.middleware';
|
|
17
|
+
// Plugin middleware functions (for application-level middleware)
|
|
18
|
+
export { withLogging, withErrorHandler, withRequestId, withValidation, withRateLimit, withAuth, } from './plugins.middleware';
|
|
19
|
+
// Convenience middleware functions (for route-level middleware)
|
|
20
|
+
export { validateFields, rateLimit, requireAuth, } from './plugins.middleware';
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
// Logging middleware
|
|
2
|
+
export function createLoggingMiddleware(format = 'simple') {
|
|
3
|
+
return (req, res, next) => {
|
|
4
|
+
const start = Date.now();
|
|
5
|
+
res.on('finish', () => {
|
|
6
|
+
const duration = Date.now() - start;
|
|
7
|
+
if (format === 'detailed') {
|
|
8
|
+
console.log(`${req.method} ${req.url} - ${res.statusCode} - ${duration}ms - ${req.ip}`);
|
|
9
|
+
}
|
|
10
|
+
else {
|
|
11
|
+
console.log(`${req.method} ${req.url} - ${res.statusCode}`);
|
|
12
|
+
}
|
|
13
|
+
});
|
|
14
|
+
next();
|
|
15
|
+
};
|
|
16
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { RequestHandler } from 'express';
|
|
2
|
+
import type { ServerPlugin } from '../types';
|
|
3
|
+
import type { AuthConfig } from './auth.middleware';
|
|
4
|
+
import type { RateLimitConfig } from './rateLimiter.middleware';
|
|
5
|
+
import type { ValidationRule } from './validation.middleware';
|
|
6
|
+
export declare function withLogging(format?: 'simple' | 'detailed'): ServerPlugin;
|
|
7
|
+
export declare function withErrorHandler(): ServerPlugin;
|
|
8
|
+
export declare function withRequestId(): ServerPlugin;
|
|
9
|
+
export declare function withValidation(rules: ValidationRule[]): ServerPlugin;
|
|
10
|
+
export declare function withRateLimit(config?: RateLimitConfig): ServerPlugin;
|
|
11
|
+
export declare function withAuth(config: AuthConfig): ServerPlugin;
|
|
12
|
+
export declare function validateFields(rules: ValidationRule[]): RequestHandler;
|
|
13
|
+
export declare function rateLimit(config?: RateLimitConfig): RequestHandler;
|
|
14
|
+
export declare function requireAuth(config: AuthConfig): RequestHandler;
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { createAuthMiddleware } from './auth.middleware';
|
|
2
|
+
import { createErrorHandler } from './errorHandler.middleware';
|
|
3
|
+
import { createLoggingMiddleware } from './logging.middleware';
|
|
4
|
+
import { createRateLimitMiddleware } from './rateLimiter.middleware';
|
|
5
|
+
import { createRequestIdMiddleware } from './requestId.middleware';
|
|
6
|
+
import { createValidationMiddleware } from './validation.middleware';
|
|
7
|
+
// Plugin versions
|
|
8
|
+
export function withLogging(format = 'simple') {
|
|
9
|
+
return (app) => {
|
|
10
|
+
app.use(createLoggingMiddleware(format));
|
|
11
|
+
};
|
|
12
|
+
}
|
|
13
|
+
export function withErrorHandler() {
|
|
14
|
+
return (app) => {
|
|
15
|
+
app.use(createErrorHandler());
|
|
16
|
+
};
|
|
17
|
+
}
|
|
18
|
+
export function withRequestId() {
|
|
19
|
+
return (app) => {
|
|
20
|
+
app.use(createRequestIdMiddleware());
|
|
21
|
+
};
|
|
22
|
+
}
|
|
23
|
+
export function withValidation(rules) {
|
|
24
|
+
return (app) => {
|
|
25
|
+
app.use(createValidationMiddleware(rules));
|
|
26
|
+
};
|
|
27
|
+
}
|
|
28
|
+
export function withRateLimit(config = {}) {
|
|
29
|
+
return (app) => {
|
|
30
|
+
app.use(createRateLimitMiddleware(config));
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
export function withAuth(config) {
|
|
34
|
+
return (app) => {
|
|
35
|
+
app.use(createAuthMiddleware(config));
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
// Convenience functions for route-specific middleware
|
|
39
|
+
export function validateFields(rules) {
|
|
40
|
+
return createValidationMiddleware(rules);
|
|
41
|
+
}
|
|
42
|
+
export function rateLimit(config = {}) {
|
|
43
|
+
return createRateLimitMiddleware(config);
|
|
44
|
+
}
|
|
45
|
+
export function requireAuth(config) {
|
|
46
|
+
return createAuthMiddleware(config);
|
|
47
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { Request, RequestHandler } from 'node_modules/@types/express';
|
|
2
|
+
export interface RateLimitConfig {
|
|
3
|
+
windowMs?: number;
|
|
4
|
+
maxRequests?: number;
|
|
5
|
+
message?: string;
|
|
6
|
+
keyGenerator?: (req: Request) => string;
|
|
7
|
+
}
|
|
8
|
+
export declare function createRateLimitMiddleware(config?: RateLimitConfig): RequestHandler;
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
const rateLimitStore = new Map();
|
|
2
|
+
export function createRateLimitMiddleware(config = {}) {
|
|
3
|
+
const { windowMs = 15 * 60 * 1000, maxRequests = 100, message = 'Too many requests, please try again later', keyGenerator = (req) => req.ip || 'unknown', } = config;
|
|
4
|
+
return (req, res, next) => {
|
|
5
|
+
const key = keyGenerator(req);
|
|
6
|
+
const now = Date.now();
|
|
7
|
+
const record = rateLimitStore.get(key);
|
|
8
|
+
if (!record || now > record.resetTime) {
|
|
9
|
+
rateLimitStore.set(key, {
|
|
10
|
+
count: 1,
|
|
11
|
+
resetTime: now + windowMs,
|
|
12
|
+
});
|
|
13
|
+
return next();
|
|
14
|
+
}
|
|
15
|
+
if (record.count >= maxRequests) {
|
|
16
|
+
return res.status(429).json({
|
|
17
|
+
success: false,
|
|
18
|
+
message,
|
|
19
|
+
data: undefined,
|
|
20
|
+
error: {
|
|
21
|
+
message,
|
|
22
|
+
details: {
|
|
23
|
+
retryAfter: Math.ceil((record.resetTime - now) / 1000),
|
|
24
|
+
},
|
|
25
|
+
},
|
|
26
|
+
meta: null,
|
|
27
|
+
});
|
|
28
|
+
}
|
|
29
|
+
record.count++;
|
|
30
|
+
next();
|
|
31
|
+
};
|
|
32
|
+
}
|